book.tex 333 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860
  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. \definecolor{lightgray}{gray}{1}
  53. \newcommand{\black}[1]{{\color{black} #1}}
  54. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  55. \newcommand{\gray}[1]{{\color{gray} #1}}
  56. %% For pictures
  57. \usepackage{tikz}
  58. \usetikzlibrary{arrows.meta}
  59. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  60. % Computer Modern is already the default. -Jeremy
  61. %\renewcommand{\ttdefault}{cmtt}
  62. \definecolor{comment-red}{rgb}{0.8,0,0}
  63. \if01
  64. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  65. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  66. \else
  67. \newcommand{\rn}[1]{}
  68. \newcommand{\margincomment}[1]{}
  69. \fi
  70. \lstset{%
  71. language=Lisp,
  72. basicstyle=\ttfamily\small,
  73. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  74. deletekeywords={read},
  75. escapechar=|,
  76. columns=flexible,
  77. moredelim=[is][\color{red}]{~}{~}
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge An Incremental Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. The tradition of compiler writing at Indiana University goes back to
  147. research and courses about programming languages by Daniel Friedman in
  148. the 1970's and 1980's. Dan conducted research on lazy
  149. evaluation~\citep{Friedman:1976aa} in the context of
  150. Lisp~\citep{McCarthy:1960dz} and then studied
  151. continuations~\citep{Felleisen:kx} and
  152. macros~\citep{Kohlbecker:1986dk} in the context of the
  153. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  154. of those courses, Kent Dybvig, went on to build Chez
  155. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  156. compiler for Scheme. After completing his Ph.D. at the University of
  157. North Carolina, Kent returned to teach at Indiana University.
  158. Throughout the 1990's and 2000's, Kent continued development of Chez
  159. Scheme and taught the compiler course.
  160. The compiler course evolved to incorporate novel pedagogical ideas
  161. while also including elements of effective real-world compilers. One
  162. of Dan's ideas was to split the compiler into many small ``passes'' so
  163. that the code for each pass would be easy to understood in isolation.
  164. (In contrast, most compilers of the time were organized into only a
  165. few monolithic passes for reasons of compile-time efficiency.) Kent,
  166. with later help from his students Dipanwita Sarkar and Andrew Keep,
  167. developed infrastructure to support this approach and evolved the
  168. course, first to use micro-sized passes and then into even smaller
  169. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  170. student in this compiler course in the early 2000's, as part of his
  171. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  172. the course immensely!
  173. During that time, another student named Abdulaziz Ghuloum observed
  174. that the front-to-back organization of the course made it difficult
  175. for students to understand the rationale for the compiler
  176. design. Abdulaziz proposed an incremental approach in which the
  177. students build the compiler in stages; they start by implementing a
  178. complete compiler for a very small subset of the input language and in
  179. each subsequent stage they add a language feature and add or modify
  180. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  181. the students see how the language features motivate aspects of the
  182. compiler design.
  183. After graduating from Indiana University in 2005, Jeremy went on to
  184. teach at the University of Colorado. He adapted the nano pass and
  185. incremental approaches to compiling a subset of the Python
  186. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  187. on the surface but there is a large overlap in the compiler techniques
  188. required for the two languages. Thus, Jeremy was able to teach much of
  189. the same content from the Indiana compiler course. He very much
  190. enjoyed teaching the course organized in this way, and even better,
  191. many of the students learned a lot and got excited about compilers.
  192. Jeremy returned to teach at Indiana University in 2013. In his
  193. absence the compiler course had switched from the front-to-back
  194. organization to a back-to-front organization. Seeing how well the
  195. incremental approach worked at Colorado, he started porting and
  196. adapting the structure of the Colorado course back into the land of
  197. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  198. the course is now about compiling a subset of Racket (and Typed
  199. Racket) to the x86 assembly language. The compiler is implemented in
  200. Racket 7.1~\citep{plt-tr}.
  201. This is the textbook for the incremental version of the compiler
  202. course at Indiana University (Spring 2016 - present) and it is the
  203. first open textbook for an Indiana compiler course. With this book we
  204. hope to make the Indiana compiler course available to people that have
  205. not had the chance to study in Bloomington in person. Many of the
  206. compiler design decisions in this book are drawn from the assignment
  207. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  208. are the most important topics from \cite{Dybvig:2010aa} but we have
  209. omitted topics that we think are less interesting conceptually and we
  210. have made simplifications to reduce complexity. In this way, this
  211. book leans more towards pedagogy than towards the efficiency of the
  212. generated code. Also, the book differs in places where we saw the
  213. opportunity to make the topics more fun, such as in relating register
  214. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  215. \section*{Prerequisites}
  216. The material in this book is challenging but rewarding. It is meant to
  217. prepare students for a lifelong career in programming languages.
  218. The book uses the Racket language both for the implementation of the
  219. compiler and for the language that is compiled, so a student should be
  220. proficient with Racket (or Scheme) prior to reading this book. There
  221. are many excellent resources for learning Scheme and
  222. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  223. is helpful but not necessary for the student to have prior exposure to
  224. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  225. obtain from a computer systems
  226. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  227. parts of x86-64 assembly language that are needed.
  228. %\section*{Structure of book}
  229. % You might want to add short description about each chapter in this book.
  230. %\section*{About the companion website}
  231. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  232. %\begin{itemize}
  233. % \item A link to (freely downlodable) latest version of this document.
  234. % \item Link to download LaTeX source for this document.
  235. % \item Miscellaneous material (e.g. suggested readings etc).
  236. %\end{itemize}
  237. \section*{Acknowledgments}
  238. Many people have contributed to the ideas, techniques, organization,
  239. and teaching of the materials in this book. We especially thank the
  240. following people.
  241. \begin{itemize}
  242. \item Bor-Yuh Evan Chang
  243. \item Kent Dybvig
  244. \item Daniel P. Friedman
  245. \item Ronald Garcia
  246. \item Abdulaziz Ghuloum
  247. \item Jay McCarthy
  248. \item Dipanwita Sarkar
  249. \item Andrew Keep
  250. \item Oscar Waddell
  251. \item Michael Wollowski
  252. \end{itemize}
  253. \mbox{}\\
  254. \noindent Jeremy G. Siek \\
  255. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  256. %\noindent Spring 2016
  257. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  258. \chapter{Preliminaries}
  259. \label{ch:trees-recur}
  260. In this chapter we review the basic tools that are needed to implement
  261. a compiler. Programs are typically input by a programmer as text,
  262. i.e., a sequence of characters. The program-as-text representation is
  263. called \emph{concrete syntax}. We use concrete syntax to concisely
  264. write down and talk about programs. Inside the compiler, we use
  265. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  266. that efficiently supports the operations that the compiler needs to
  267. perform.
  268. %
  269. The translation from concrete syntax to abstract syntax is a process
  270. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  271. and implementation of parsing in this book. A parser is provided in
  272. the supporting materials for translating from concrete syntax to
  273. abstract syntax for the languages used in this book.
  274. ASTs can be represented in many different ways inside the compiler,
  275. depending on the programming language used to write the compiler.
  276. %
  277. We use Racket's \code{struct} feature to represent ASTs
  278. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  279. of programming languages (Section~\ref{sec:grammar}) and pattern
  280. matching to inspect individual nodes in an AST
  281. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  282. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  283. chapter provides an brief introduction to these ideas.
  284. \section{Abstract Syntax Trees and Racket Structures}
  285. \label{sec:ast}
  286. Compilers use abstract syntax trees to represent programs because
  287. compilers often need to ask questions like: for a given part of a
  288. program, what kind of language feature is it? What are the sub-parts
  289. of this part of the program? Consider the program on the left and its
  290. AST on the right. This program is an addition and it has two
  291. sub-parts, a read operation and a negation. The negation has another
  292. sub-part, the integer constant \code{8}. By using a tree to represent
  293. the program, we can easily follow the links to go from one part of a
  294. program to its sub-parts.
  295. \begin{center}
  296. \begin{minipage}{0.4\textwidth}
  297. \begin{lstlisting}
  298. (+ (read) (- 8))
  299. \end{lstlisting}
  300. \end{minipage}
  301. \begin{minipage}{0.4\textwidth}
  302. \begin{equation}
  303. \begin{tikzpicture}
  304. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  305. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  306. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  307. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  308. \draw[->] (plus) to (read);
  309. \draw[->] (plus) to (minus);
  310. \draw[->] (minus) to (8);
  311. \end{tikzpicture}
  312. \label{eq:arith-prog}
  313. \end{equation}
  314. \end{minipage}
  315. \end{center}
  316. We use the standard terminology for trees to describe ASTs: each
  317. circle above is called a \emph{node}. The arrows connect a node to its
  318. \emph{children} (which are also nodes). The top-most node is the
  319. \emph{root}. Every node except for the root has a \emph{parent} (the
  320. node it is the child of). If a node has no children, it is a
  321. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  322. %% Recall that an \emph{symbolic expression} (S-expression) is either
  323. %% \begin{enumerate}
  324. %% \item an atom, or
  325. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  326. %% where $e_1$ and $e_2$ are each an S-expression.
  327. %% \end{enumerate}
  328. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  329. %% null value \code{'()}, etc. We can create an S-expression in Racket
  330. %% simply by writing a backquote (called a quasi-quote in Racket)
  331. %% followed by the textual representation of the S-expression. It is
  332. %% quite common to use S-expressions to represent a list, such as $a, b
  333. %% ,c$ in the following way:
  334. %% \begin{lstlisting}
  335. %% `(a . (b . (c . ())))
  336. %% \end{lstlisting}
  337. %% Each element of the list is in the first slot of a pair, and the
  338. %% second slot is either the rest of the list or the null value, to mark
  339. %% the end of the list. Such lists are so common that Racket provides
  340. %% special notation for them that removes the need for the periods
  341. %% and so many parenthesis:
  342. %% \begin{lstlisting}
  343. %% `(a b c)
  344. %% \end{lstlisting}
  345. %% The following expression creates an S-expression that represents AST
  346. %% \eqref{eq:arith-prog}.
  347. %% \begin{lstlisting}
  348. %% `(+ (read) (- 8))
  349. %% \end{lstlisting}
  350. %% When using S-expressions to represent ASTs, the convention is to
  351. %% represent each AST node as a list and to put the operation symbol at
  352. %% the front of the list. The rest of the list contains the children. So
  353. %% in the above case, the root AST node has operation \code{`+} and its
  354. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  355. %% diagram \eqref{eq:arith-prog}.
  356. %% To build larger S-expressions one often needs to splice together
  357. %% several smaller S-expressions. Racket provides the comma operator to
  358. %% splice an S-expression into a larger one. For example, instead of
  359. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  360. %% we could have first created an S-expression for AST
  361. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  362. %% S-expression.
  363. %% \begin{lstlisting}
  364. %% (define ast1.4 `(- 8))
  365. %% (define ast1.1 `(+ (read) ,ast1.4))
  366. %% \end{lstlisting}
  367. %% In general, the Racket expression that follows the comma (splice)
  368. %% can be any expression that produces an S-expression.
  369. We define a Racket \code{struct} for each kind of node. For this
  370. chapter we require just two kinds of nodes: one for integer constants
  371. and one for primitive operations. The following is the \code{struct}
  372. definition for integer constants.
  373. \begin{lstlisting}
  374. (struct Int (value))
  375. \end{lstlisting}
  376. An integer node includes just one thing: the integer value.
  377. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  378. \begin{lstlisting}
  379. (define eight (Int 8))
  380. \end{lstlisting}
  381. We say that the value created by \code{(Int 8)} is an
  382. \emph{instance} of the \code{Int} structure.
  383. The following is the \code{struct} definition for primitives operations.
  384. \begin{lstlisting}
  385. (struct Prim (op arg*))
  386. \end{lstlisting}
  387. A primitive operation node includes an operator symbol \code{op}
  388. and a list of children \code{arg*}. For example, to create
  389. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  390. \begin{lstlisting}
  391. (define neg-eight (Prim '- (list eight)))
  392. \end{lstlisting}
  393. Primitive operations may have zero or more children. The \code{read}
  394. operator has zero children:
  395. \begin{lstlisting}
  396. (define rd (Prim 'read '()))
  397. \end{lstlisting}
  398. whereas the addition operator has two children:
  399. \begin{lstlisting}
  400. (define ast1.1 (Prim '+ (list rd neg-eight)))
  401. \end{lstlisting}
  402. We have made a design choice regarding the \code{Prim} structure.
  403. Instead of using one structure for many different operations
  404. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  405. structure for each operation, as follows.
  406. \begin{lstlisting}
  407. (struct Read ())
  408. (struct Add (left right))
  409. (struct Neg (value))
  410. \end{lstlisting}
  411. The reason we choose to use just one structure is that in many parts
  412. of the compiler the code for the different primitive operators is the
  413. same, so we might as well just write that code once, which is enabled
  414. by using a single structure.
  415. When compiling a program such as \eqref{eq:arith-prog}, we need to
  416. know that the operation associated with the root node is addition and
  417. we need to be able to access its two children. Racket provides pattern
  418. matching over structures to support these kinds of queries, as we
  419. shall see in Section~\ref{sec:pattern-matching}.
  420. In this book, we often write down the concrete syntax of a program
  421. even when we really have in mind the AST because the concrete syntax
  422. is more concise. We recommend that, in your mind, you always think of
  423. programs as abstract syntax trees.
  424. \section{Grammars}
  425. \label{sec:grammar}
  426. A programming language can be thought of as a \emph{set} of programs.
  427. The set is typically infinite (one can always create larger and larger
  428. programs), so one cannot simply describe a language by listing all of
  429. the programs in the language. Instead we write down a set of rules, a
  430. \emph{grammar}, for building programs. Grammars are often used to
  431. define the concrete syntax of a language, but they can also be used to
  432. describe the abstract syntax. We shall write our rules in a variant of
  433. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  434. example, we describe a small language, named $R_0$, that consists of
  435. integers and arithmetic operations.
  436. The first grammar rule for the abstract syntax of $R_0$ says that an
  437. instance of the \code{Int} structure is an expression:
  438. \begin{equation}
  439. \Exp ::= \INT{\Int} \label{eq:arith-int}
  440. \end{equation}
  441. %
  442. Each rule has a left-hand-side and a right-hand-side. The way to read
  443. a rule is that if you have all the program parts on the
  444. right-hand-side, then you can create an AST node and categorize it
  445. according to the left-hand-side.
  446. %
  447. A name such as $\Exp$ that is
  448. defined by the grammar rules is a \emph{non-terminal}.
  449. %
  450. The name $\Int$ is a also a non-terminal, but instead of defining it
  451. with a grammar rule, we define it with the following explanation. We
  452. make the simplifying design decision that all of the languages in this
  453. book only handle machine-representable integers. On most modern
  454. machines this corresponds to integers represented with 64-bits, i.e.,
  455. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  456. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  457. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  458. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  459. that the sequence of decimals represent an integer in range $-2^{62}$
  460. to $2^{62}-1$.
  461. The second grammar rule is the \texttt{read} operation that receives
  462. an input integer from the user of the program.
  463. \begin{equation}
  464. \Exp ::= \READ{} \label{eq:arith-read}
  465. \end{equation}
  466. The third rule says that, given an $\Exp$ node, you can build another
  467. $\Exp$ node by negating it.
  468. \begin{equation}
  469. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  470. \end{equation}
  471. Symbols in typewriter font such as \key{-} and \key{read} are
  472. \emph{terminal} symbols and must literally appear in the program for
  473. the rule to be applicable.
  474. We can apply the rules to build ASTs in the $R_0$
  475. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  476. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  477. an $\Exp$.
  478. \begin{center}
  479. \begin{minipage}{0.4\textwidth}
  480. \begin{lstlisting}
  481. (Prim '- (list (Int 8)))
  482. \end{lstlisting}
  483. \end{minipage}
  484. \begin{minipage}{0.25\textwidth}
  485. \begin{equation}
  486. \begin{tikzpicture}
  487. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  488. \node[draw, circle] (8) at (0, -1.2) {$8$};
  489. \draw[->] (minus) to (8);
  490. \end{tikzpicture}
  491. \label{eq:arith-neg8}
  492. \end{equation}
  493. \end{minipage}
  494. \end{center}
  495. The next grammar rule defines addition expressions:
  496. \begin{equation}
  497. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  498. \end{equation}
  499. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  500. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  501. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  502. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  503. to show that
  504. \begin{lstlisting}
  505. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  506. \end{lstlisting}
  507. is an $\Exp$ in the $R_0$ language.
  508. If you have an AST for which the above rules do not apply, then the
  509. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  510. is not in $R_0$ because there are no rules for \code{+} with only one
  511. argument, nor for \key{-} with two arguments. Whenever we define a
  512. language with a grammar, the language only includes those programs
  513. that are justified by the rules.
  514. The last grammar rule for $R_0$ states that there is a \code{Program}
  515. node to mark the top of the whole program:
  516. \[
  517. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  518. \]
  519. The \code{Program} structure is defined as follows
  520. \begin{lstlisting}
  521. (struct Program (info body))
  522. \end{lstlisting}
  523. where \code{body} is an expression. In later chapters, the \code{info}
  524. part will be used to store auxiliary information but for now it is
  525. just the empty list.
  526. It is common to have many grammar rules with the same left-hand side
  527. but different right-hand sides, such as the rules for $\Exp$ in the
  528. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  529. combine several right-hand-sides into a single rule.
  530. We collect all of the grammar rules for the abstract syntax of $R_0$
  531. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  532. defined in Figure~\ref{fig:r0-concrete-syntax}.
  533. The \code{read-program} function provided in \code{utilities.rkt} of
  534. the support materials reads a program in from a file (the sequence of
  535. characters in the concrete syntax of Racket) and parses it into an
  536. abstract syntax tree. See the description of \code{read-program} in
  537. Appendix~\ref{appendix:utilities} for more details.
  538. \begin{figure}[tp]
  539. \fbox{
  540. \begin{minipage}{0.96\textwidth}
  541. \[
  542. \begin{array}{rcl}
  543. \begin{array}{rcl}
  544. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  545. R_0 &::=& \Exp
  546. \end{array}
  547. \end{array}
  548. \]
  549. \end{minipage}
  550. }
  551. \caption{The concrete syntax of $R_0$.}
  552. \label{fig:r0-concrete-syntax}
  553. \end{figure}
  554. \begin{figure}[tp]
  555. \fbox{
  556. \begin{minipage}{0.96\textwidth}
  557. \[
  558. \begin{array}{rcl}
  559. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  560. &\mid& \ADD{\Exp}{\Exp} \\
  561. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  562. \end{array}
  563. \]
  564. \end{minipage}
  565. }
  566. \caption{The abstract syntax of $R_0$.}
  567. \label{fig:r0-syntax}
  568. \end{figure}
  569. \section{Pattern Matching}
  570. \label{sec:pattern-matching}
  571. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  572. the parts of an AST node. Racket provides the \texttt{match} form to
  573. access the parts of a structure. Consider the following example and
  574. the output on the right.
  575. \begin{center}
  576. \begin{minipage}{0.5\textwidth}
  577. \begin{lstlisting}
  578. (match ast1.1
  579. [(Prim op (list child1 child2))
  580. (print op)])
  581. \end{lstlisting}
  582. \end{minipage}
  583. \vrule
  584. \begin{minipage}{0.25\textwidth}
  585. \begin{lstlisting}
  586. '+
  587. \end{lstlisting}
  588. \end{minipage}
  589. \end{center}
  590. In the above example, the \texttt{match} form takes the AST
  591. \eqref{eq:arith-prog} and binds its parts to the three pattern
  592. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  593. general, a match clause consists of a \emph{pattern} and a
  594. \emph{body}. Patterns are recursively defined to be either a pattern
  595. variable, a structure name followed by a pattern for each of the
  596. structure's arguments, or an S-expression (symbols, lists, etc.).
  597. (See Chapter 12 of The Racket
  598. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  599. and Chapter 9 of The Racket
  600. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  601. for a complete description of \code{match}.)
  602. %
  603. The body of a match clause may contain arbitrary Racket code. The
  604. pattern variables can be used in the scope of the body.
  605. A \code{match} form may contain several clauses, as in the following
  606. function \code{leaf?} that recognizes when an $R_0$ node is
  607. a leaf. The \code{match} proceeds through the clauses in order,
  608. checking whether the pattern can match the input AST. The
  609. body of the first clause that matches is executed. The output of
  610. \code{leaf?} for several ASTs is shown on the right.
  611. \begin{center}
  612. \begin{minipage}{0.6\textwidth}
  613. \begin{lstlisting}
  614. (define (leaf? arith)
  615. (match arith
  616. [(Int n) #t]
  617. [(Prim 'read '()) #t]
  618. [(Prim '- (list c1)) #f]
  619. [(Prim '+ (list c1 c2)) #f]))
  620. (leaf? (Prim 'read '()))
  621. (leaf? (Prim '- (list (Int 8))))
  622. (leaf? (Int 8))
  623. \end{lstlisting}
  624. \end{minipage}
  625. \vrule
  626. \begin{minipage}{0.25\textwidth}
  627. \begin{lstlisting}
  628. #t
  629. #f
  630. #t
  631. \end{lstlisting}
  632. \end{minipage}
  633. \end{center}
  634. When writing a \code{match}, we refer to the grammar definition to
  635. identify which non-terminal we are expecting to match against, then we
  636. make sure that 1) we have one clause for each alternative of that
  637. non-terminal and 2) that the pattern in each clause corresponds to the
  638. corresponding right-hand side of a grammar rule. For the \code{match}
  639. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  640. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  641. alternatives, so the \code{match} has 4 clauses. The pattern in each
  642. clause corresponds to the right-hand side of a grammar rule. For
  643. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  644. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  645. patterns, replace non-terminals such as $\Exp$ with pattern variables
  646. of your choice (e.g. \code{c1} and \code{c2}).
  647. \section{Recursion}
  648. \label{sec:recursion}
  649. Programs are inherently recursive. For example, an $R_0$ expression is
  650. often made of smaller expressions. Thus, the natural way to process an
  651. entire program is with a recursive function. As a first example of
  652. such a recursive function, we define \texttt{exp?} below, which takes
  653. an arbitrary value and determines whether or not it is an $R_0$
  654. expression.
  655. %
  656. When a recursive function is defined using a sequence of match clauses
  657. that correspond to a grammar, and the body of each clause makes a
  658. recursive call on each child node, then we say the function is defined
  659. by \emph{structural recursion}\footnote{This principle of structuring
  660. code according to the data definition is advocated in the book
  661. \emph{How to Design Programs}
  662. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  663. define a second function, named \code{R0?}, that determines whether a
  664. value is an $R_0$ program. In general we can expect to write one
  665. recursive function to handle each non-terminal in a grammar.
  666. %
  667. \begin{center}
  668. \begin{minipage}{0.7\textwidth}
  669. \begin{lstlisting}
  670. (define (exp? ast)
  671. (match ast
  672. [(Int n) #t]
  673. [(Prim 'read '()) #t]
  674. [(Prim '- (list e)) (exp? e)]
  675. [(Prim '+ (list e1 e2))
  676. (and (exp? e1) (exp? e2))]
  677. [else #f]))
  678. (define (R0? ast)
  679. (match ast
  680. [(Program '() e) (exp? e)]
  681. [else #f]))
  682. (R0? (Program '() ast1.1)
  683. (R0? (Program '()
  684. (Prim '- (list (Prim 'read '())
  685. (Prim '+ (list (Num 8)))))))
  686. \end{lstlisting}
  687. \end{minipage}
  688. \vrule
  689. \begin{minipage}{0.25\textwidth}
  690. \begin{lstlisting}
  691. #t
  692. #f
  693. \end{lstlisting}
  694. \end{minipage}
  695. \end{center}
  696. You may be tempted to merge the two functions into one, like this:
  697. \begin{center}
  698. \begin{minipage}{0.5\textwidth}
  699. \begin{lstlisting}
  700. (define (R0? ast)
  701. (match ast
  702. [(Int n) #t]
  703. [(Prim 'read '()) #t]
  704. [(Prim '- (list e)) (R0? e)]
  705. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  706. [(Program '() e) (R0? e)]
  707. [else #f]))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \end{center}
  711. %
  712. Sometimes such a trick will save a few lines of code, especially when
  713. it comes to the \code{Program} wrapper. Yet this style is generally
  714. \emph{not} recommended because it can get you into trouble.
  715. %
  716. For example, the above function is subtly wrong:
  717. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  718. will return true, when it should return false.
  719. %% NOTE FIXME - must check for consistency on this issue throughout.
  720. \section{Interpreters}
  721. \label{sec:interp-R0}
  722. The meaning, or semantics, of a program is typically defined in the
  723. specification of the language. For example, the Scheme language is
  724. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  725. defined in its reference manual~\citep{plt-tr}. In this book we use an
  726. interpreter to define the meaning of each language that we consider,
  727. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  728. interpreter that is designated (by some people) as the definition of a
  729. language is called a \emph{definitional interpreter}. We warm up by
  730. creating a definitional interpreter for the $R_0$ language, which
  731. serves as a second example of structural recursion. The
  732. \texttt{interp-R0} function is defined in
  733. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  734. input program followed by a call to the \lstinline{interp-exp} helper
  735. function, which in turn has one match clause per grammar rule for
  736. $R_0$ expressions.
  737. \begin{figure}[tp]
  738. \begin{lstlisting}
  739. (define (interp-exp e)
  740. (match e
  741. [(Int n) n]
  742. [(Prim 'read '())
  743. (define r (read))
  744. (cond [(fixnum? r) r]
  745. [else (error 'interp-R0 "expected an integer" r)])]
  746. [(Prim '- (list e))
  747. (define v (interp-exp e))
  748. (fx- 0 v)]
  749. [(Prim '+ (list e1 e2))
  750. (define v1 (interp-exp e1))
  751. (define v2 (interp-exp e2))
  752. (fx+ v1 v2)]
  753. ))
  754. (define (interp-R0 p)
  755. (match p
  756. [(Program '() e) (interp-exp e)]
  757. ))
  758. \end{lstlisting}
  759. \caption{Interpreter for the $R_0$ language.}
  760. \label{fig:interp-R0}
  761. \end{figure}
  762. Let us consider the result of interpreting a few $R_0$ programs. The
  763. following program adds two integers.
  764. \begin{lstlisting}
  765. (+ 10 32)
  766. \end{lstlisting}
  767. The result is \key{42}. We wrote the above program in concrete syntax,
  768. whereas the parsed abstract syntax is:
  769. \begin{lstlisting}
  770. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  771. \end{lstlisting}
  772. The next example demonstrates that expressions may be nested within
  773. each other, in this case nesting several additions and negations.
  774. \begin{lstlisting}
  775. (+ 10 (- (+ 12 20)))
  776. \end{lstlisting}
  777. What is the result of the above program?
  778. As mentioned previously, the $R_0$ language does not support
  779. arbitrarily-large integers, but only $63$-bit integers, so we
  780. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  781. in Racket.
  782. Suppose
  783. \[
  784. n = 999999999999999999
  785. \]
  786. which indeed fits in $63$-bits. What happens when we run the
  787. following program in our interpreter?
  788. \begin{lstlisting}
  789. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  790. \end{lstlisting}
  791. It produces an error:
  792. \begin{lstlisting}
  793. fx+: result is not a fixnum
  794. \end{lstlisting}
  795. We establish the convention that if running the definitional
  796. interpreter on a program produces an error, then the meaning of that
  797. program is \emph{unspecified}. That means a compiler for the language
  798. is under no obligations regarding that program; it may or may not
  799. produce an executable, and if it does, that executable can do
  800. anything. This convention applies to the languages defined in this
  801. book, as a way to simplify the student's task of implementing them,
  802. but this convention is not applicable to all programming languages.
  803. Moving on to the last feature of the $R_0$ language, the \key{read}
  804. operation prompts the user of the program for an integer. Recall that
  805. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  806. \code{8}. So if we run
  807. \begin{lstlisting}
  808. (interp-R0 (Program '() ast1.1))
  809. \end{lstlisting}
  810. and if the input is \code{50}, then we get the answer to life, the
  811. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  812. Guide to the Galaxy} by Douglas Adams.}
  813. We include the \key{read} operation in $R_0$ so a clever student
  814. cannot implement a compiler for $R_0$ that simply runs the interpreter
  815. during compilation to obtain the output and then generates the trivial
  816. code to produce the output. (Yes, a clever student did this in the
  817. first instance of this course.)
  818. The job of a compiler is to translate a program in one language into a
  819. program in another language so that the output program behaves the
  820. same way as the input program does according to its definitional
  821. interpreter. This idea is depicted in the following diagram. Suppose
  822. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  823. interpreter for each language. Suppose that the compiler translates
  824. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  825. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  826. respective interpreters with input $i$ should yield the same output
  827. $o$.
  828. \begin{equation} \label{eq:compile-correct}
  829. \begin{tikzpicture}[baseline=(current bounding box.center)]
  830. \node (p1) at (0, 0) {$P_1$};
  831. \node (p2) at (3, 0) {$P_2$};
  832. \node (o) at (3, -2.5) {$o$};
  833. \path[->] (p1) edge [above] node {compile} (p2);
  834. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  835. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  836. \end{tikzpicture}
  837. \end{equation}
  838. In the next section we see our first example of a compiler.
  839. \section{Example Compiler: a Partial Evaluator}
  840. \label{sec:partial-evaluation}
  841. In this section we consider a compiler that translates $R_0$ programs
  842. into $R_0$ programs that may be more efficient, that is, this compiler
  843. is an optimizer. This optimizer eagerly computes the parts of the
  844. program that do not depend on any inputs, a process known as
  845. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  846. following program
  847. \begin{lstlisting}
  848. (+ (read) (- (+ 5 3)))
  849. \end{lstlisting}
  850. our compiler will translate it into the program
  851. \begin{lstlisting}
  852. (+ (read) -8)
  853. \end{lstlisting}
  854. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  855. evaluator for the $R_0$ language. The output of the partial evaluator
  856. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  857. recursion over $\Exp$ is captured in the \code{pe-exp} function
  858. whereas the code for partially evaluating the negation and addition
  859. operations is factored into two separate helper functions:
  860. \code{pe-neg} and \code{pe-add}. The input to these helper
  861. functions is the output of partially evaluating the children.
  862. \begin{figure}[tp]
  863. \begin{lstlisting}
  864. (define (pe-neg r)
  865. (match r
  866. [(Int n) (Int (fx- 0 n))]
  867. [else (Prim '- (list r))]))
  868. (define (pe-add r1 r2)
  869. (match* (r1 r2)
  870. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  871. [(_ _) (Prim '+ (list r1 r2))]))
  872. (define (pe-exp e)
  873. (match e
  874. [(Int n) (Int n)]
  875. [(Prim 'read '()) (Prim 'read '())]
  876. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  877. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  878. ))
  879. (define (pe-R0 p)
  880. (match p
  881. [(Program '() e) (Program '() (pe-exp e))]
  882. ))
  883. \end{lstlisting}
  884. \caption{A partial evaluator for $R_0$ expressions.}
  885. \label{fig:pe-arith}
  886. \end{figure}
  887. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  888. arguments are integers and if they are, perform the appropriate
  889. arithmetic. Otherwise, they create an AST node for the operation
  890. (either negation or addition).
  891. To gain some confidence that the partial evaluator is correct, we can
  892. test whether it produces programs that get the same result as the
  893. input programs. That is, we can test whether it satisfies Diagram
  894. \eqref{eq:compile-correct}. The following code runs the partial
  895. evaluator on several examples and tests the output program. The
  896. \texttt{parse-program} and \texttt{assert} functions are defined in
  897. Appendix~\ref{appendix:utilities}.\\
  898. \begin{minipage}{1.0\textwidth}
  899. \begin{lstlisting}
  900. (define (test-pe p)
  901. (assert "testing pe-R0"
  902. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  903. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  904. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  905. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  906. \end{lstlisting}
  907. \end{minipage}
  908. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  909. \chapter{Integers and Variables}
  910. \label{ch:int-exp}
  911. This chapter is about compiling the subset of Racket that includes
  912. integer arithmetic and local variable binding, which we name $R_1$, to
  913. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  914. to x86-64 simply as x86. The chapter begins with a description of the
  915. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  916. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  917. discuss only what is needed for compiling $R_1$. We introduce more of
  918. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  919. reflect on their differences and come up with a plan to break down the
  920. translation from $R_1$ to x86 into a handful of steps
  921. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  922. chapter give detailed hints regarding each step
  923. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  924. to give enough hints that the well-prepared reader, together with a
  925. few friends, can implement a compiler from $R_1$ to x86 in a couple
  926. weeks while at the same time leaving room for some fun and creativity.
  927. To give the reader a feeling for the scale of this first compiler, the
  928. instructor solution for the $R_1$ compiler is less than 500 lines of
  929. code.
  930. \section{The $R_1$ Language}
  931. \label{sec:s0}
  932. The $R_1$ language extends the $R_0$ language with variable
  933. definitions. The concrete syntax of the $R_1$ language is defined by
  934. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  935. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  936. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  937. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  938. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  939. \key{Program} struct to mark the top of the program.
  940. %% The $\itm{info}$
  941. %% field of the \key{Program} structure contains an \emph{association
  942. %% list} (a list of key-value pairs) that is used to communicate
  943. %% auxiliary data from one compiler pass the next.
  944. Despite the simplicity of the $R_1$ language, it is rich enough to
  945. exhibit several compilation techniques.
  946. \begin{figure}[tp]
  947. \centering
  948. \fbox{
  949. \begin{minipage}{0.96\textwidth}
  950. \[
  951. \begin{array}{rcl}
  952. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  953. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  954. R_1 &::=& \Exp
  955. \end{array}
  956. \]
  957. \end{minipage}
  958. }
  959. \caption{The concrete syntax of $R_1$.}
  960. \label{fig:r1-concrete-syntax}
  961. \end{figure}
  962. \begin{figure}[tp]
  963. \centering
  964. \fbox{
  965. \begin{minipage}{0.96\textwidth}
  966. \[
  967. \begin{array}{rcl}
  968. \Exp &::=& \INT{\Int} \mid \READ{} \\
  969. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  970. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  971. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  972. \end{array}
  973. \]
  974. \end{minipage}
  975. }
  976. \caption{The abstract syntax of $R_1$.}
  977. \label{fig:r1-syntax}
  978. \end{figure}
  979. Let us dive further into the syntax and semantics of the $R_1$
  980. language. The \key{Let} feature defines a variable for use within its
  981. body and initializes the variable with the value of an expression.
  982. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  983. The concrete syntax for \key{Let} is
  984. \begin{lstlisting}
  985. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  986. \end{lstlisting}
  987. For example, the following program initializes \code{x} to $32$ and then
  988. evaluates the body \code{(+ 10 x)}, producing $42$.
  989. \begin{lstlisting}
  990. (let ([x (+ 12 20)]) (+ 10 x))
  991. \end{lstlisting}
  992. When there are multiple \key{let}'s for the same variable, the closest
  993. enclosing \key{let} is used. That is, variable definitions overshadow
  994. prior definitions. Consider the following program with two \key{let}'s
  995. that define variables named \code{x}. Can you figure out the result?
  996. \begin{lstlisting}
  997. (let ([x 32]) (+ (let ([x 10]) x) x))
  998. \end{lstlisting}
  999. For the purposes of depicting which variable uses correspond to which
  1000. definitions, the following shows the \code{x}'s annotated with
  1001. subscripts to distinguish them. Double check that your answer for the
  1002. above is the same as your answer for this annotated version of the
  1003. program.
  1004. \begin{lstlisting}
  1005. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1006. \end{lstlisting}
  1007. The initializing expression is always evaluated before the body of the
  1008. \key{let}, so in the following, the \key{read} for \code{x} is
  1009. performed before the \key{read} for \code{y}. Given the input
  1010. $52$ then $10$, the following produces $42$ (not $-42$).
  1011. \begin{lstlisting}
  1012. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1013. \end{lstlisting}
  1014. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1015. \small
  1016. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1017. An \emph{association list} (alist) is a list of key-value pairs.
  1018. For example, we can map people to their ages with an alist.
  1019. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1020. (define ages
  1021. '((jane . 25) (sam . 24) (kate . 45)))
  1022. \end{lstlisting}
  1023. The \emph{dictionary} interface is for mapping keys to values.
  1024. Every alist implements this interface. The package
  1025. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1026. provides many functions for working with dictionaries. Here
  1027. are a few of them:
  1028. \begin{description}
  1029. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1030. returns the value associated with the given $\itm{key}$.
  1031. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1032. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1033. but otherwise is the same as $\itm{dict}$.
  1034. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1035. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1036. of keys and values in $\itm{dict}$. For example, the following
  1037. creates a new alist in which the ages are incremented.
  1038. \end{description}
  1039. \vspace{-10pt}
  1040. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1041. (for/list ([(k v) (in-dict ages)])
  1042. (cons k (add1 v)))
  1043. \end{lstlisting}
  1044. \end{tcolorbox}
  1045. \end{wrapfigure}
  1046. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1047. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1048. \key{match} clauses for variables and for \key{let}. For \key{let},
  1049. we need a way to communicate the value of a variable to all the uses
  1050. of a variable. To accomplish this, we maintain a mapping from
  1051. variables to values. Throughout the compiler we often need to map
  1052. variables to information about them. We refer to these mappings as
  1053. \emph{environments}
  1054. \footnote{Another common term for environment in the compiler
  1055. literature is \emph{symbol table}.}. For simplicity, we use an
  1056. association list (alist) to represent the environment. The sidebar to
  1057. the right gives a brief introduction to alists and the
  1058. \code{racket/dict} package. The \code{interp-R1} function takes the
  1059. current environment, \code{env}, as an extra parameter. When the
  1060. interpreter encounters a variable, it finds the corresponding value
  1061. using the \code{dict-ref} function. When the interpreter encounters a
  1062. \key{Let}, it evaluates the initializing expression, extends the
  1063. environment with the result value bound to the variable, using
  1064. \code{dict-set}, then evaluates the body of the \key{Let}.
  1065. \begin{figure}[tp]
  1066. \begin{lstlisting}
  1067. (define (interp-exp env)
  1068. (lambda (e)
  1069. (match e
  1070. [(Int n) n]
  1071. [(Prim 'read '())
  1072. (define r (read))
  1073. (cond [(fixnum? r) r]
  1074. [else (error 'interp-R1 "expected an integer" r)])]
  1075. [(Prim '- (list e))
  1076. (define v ((interp-exp env) e))
  1077. (fx- 0 v)]
  1078. [(Prim '+ (list e1 e2))
  1079. (define v1 ((interp-exp env) e1))
  1080. (define v2 ((interp-exp env) e2))
  1081. (fx+ v1 v2)]
  1082. [(Var x) (dict-ref env x)]
  1083. [(Let x e body)
  1084. (define new-env (dict-set env x ((interp-exp env) e)))
  1085. ((interp-exp new-env) body)]
  1086. )))
  1087. (define (interp-R1 p)
  1088. (match p
  1089. [(Program '() e) ((interp-exp '()) e)]
  1090. ))
  1091. \end{lstlisting}
  1092. \caption{Interpreter for the $R_1$ language.}
  1093. \label{fig:interp-R1}
  1094. \end{figure}
  1095. The goal for this chapter is to implement a compiler that translates
  1096. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1097. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1098. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1099. is, they both output the same integer $n$. We depict this correctness
  1100. criteria in the following diagram.
  1101. \[
  1102. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1103. \node (p1) at (0, 0) {$P_1$};
  1104. \node (p2) at (4, 0) {$P_2$};
  1105. \node (o) at (4, -2) {$n$};
  1106. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1107. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1108. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1109. \end{tikzpicture}
  1110. \]
  1111. In the next section we introduce enough of the x86 assembly
  1112. language to compile $R_1$.
  1113. \section{The x86$_0$ Assembly Language}
  1114. \label{sec:x86}
  1115. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1116. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1117. %
  1118. An x86 program begins with a \code{main} label followed by a sequence
  1119. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1120. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1121. instructions.
  1122. %
  1123. An x86 program is stored in the computer's memory and the computer has
  1124. a \emph{program counter} that points to the address of the next
  1125. instruction to be executed. For most instructions, once the
  1126. instruction is executed, the program counter is incremented to point
  1127. to the immediately following instruction in memory. Most x86
  1128. instructions take two operands, where each operand is either an
  1129. integer constant (called \emph{immediate value}), a \emph{register},
  1130. or a memory location. A register is a special kind of variable. Each
  1131. one holds a 64-bit value; there are 16 registers in the computer and
  1132. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1133. as a mapping of 64-bit addresses to 64-bit values%
  1134. \footnote{This simple story suffices for describing how sequential
  1135. programs access memory but is not sufficient for multi-threaded
  1136. programs. However, multi-threaded execution is beyond the scope of
  1137. this book.}.
  1138. %
  1139. We use the AT\&T syntax expected by the GNU assembler, which comes
  1140. with the \key{gcc} compiler that we use for compiling assembly code to
  1141. machine code.
  1142. %
  1143. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1144. the x86 instructions used in this book.
  1145. % to do: finish treatment of imulq
  1146. % it's needed for vector's in R6/R7
  1147. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1148. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1149. && \key{r8} \mid \key{r9} \mid \key{r10}
  1150. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1151. \mid \key{r14} \mid \key{r15}}
  1152. \begin{figure}[tp]
  1153. \fbox{
  1154. \begin{minipage}{0.96\textwidth}
  1155. \[
  1156. \begin{array}{lcl}
  1157. \Reg &::=& \allregisters{} \\
  1158. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1159. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1160. \key{subq} \; \Arg\key{,} \Arg \mid
  1161. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1162. && \key{callq} \; \mathit{label} \mid
  1163. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1164. && \itm{label}\key{:}\; \Instr \\
  1165. x86_0 &::= & \key{.globl main}\\
  1166. & & \key{main:} \; \Instr\ldots
  1167. \end{array}
  1168. \]
  1169. \end{minipage}
  1170. }
  1171. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1172. \label{fig:x86-0-concrete}
  1173. \end{figure}
  1174. An immediate value is written using the notation \key{\$}$n$ where $n$
  1175. is an integer.
  1176. %
  1177. A register is written with a \key{\%} followed by the register name,
  1178. such as \key{\%rax}.
  1179. %
  1180. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1181. which obtains the address stored in register $r$ and then adds $n$
  1182. bytes to the address. The resulting address is used to either load or
  1183. store to memory depending on whether it occurs as a source or
  1184. destination argument of an instruction.
  1185. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1186. source $s$ and destination $d$, applies the arithmetic operation, then
  1187. writes the result back to the destination $d$.
  1188. %
  1189. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1190. stores the result in $d$.
  1191. %
  1192. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1193. specified by the label and $\key{retq}$ returns from a procedure to
  1194. its caller. We discuss procedure calls in more detail later in this
  1195. chapter and in Chapter~\ref{ch:functions}. The
  1196. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1197. the address of the instruction after the specified label.
  1198. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1199. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1200. \key{main} procedure is externally visible, which is necessary so
  1201. that the operating system can call it. The label \key{main:}
  1202. indicates the beginning of the \key{main} procedure which is where
  1203. the operating system starts executing this program. The instruction
  1204. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1205. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1206. $10$ in \key{rax} and puts the result, $42$, back into
  1207. \key{rax}.
  1208. %
  1209. The last instruction, \key{retq}, finishes the \key{main} function by
  1210. returning the integer in \key{rax} to the operating system. The
  1211. operating system interprets this integer as the program's exit
  1212. code. By convention, an exit code of 0 indicates that a program
  1213. completed successfully, and all other exit codes indicate various
  1214. errors. Nevertheless, we return the result of the program as the exit
  1215. code.
  1216. %\begin{wrapfigure}{r}{2.25in}
  1217. \begin{figure}[tbp]
  1218. \begin{lstlisting}
  1219. .globl main
  1220. main:
  1221. movq $10, %rax
  1222. addq $32, %rax
  1223. retq
  1224. \end{lstlisting}
  1225. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1226. \label{fig:p0-x86}
  1227. %\end{wrapfigure}
  1228. \end{figure}
  1229. Unfortunately, x86 varies in a couple ways depending on what operating
  1230. system it is assembled in. The code examples shown here are correct on
  1231. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1232. labels like \key{main} must be prefixed with an underscore, as in
  1233. \key{\_main}.
  1234. We exhibit the use of memory for storing intermediate results in the
  1235. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1236. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1237. memory called the \emph{procedure call stack} (or \emph{stack} for
  1238. short). The stack consists of a separate \emph{frame} for each
  1239. procedure call. The memory layout for an individual frame is shown in
  1240. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1241. \emph{stack pointer} and points to the item at the top of the
  1242. stack. The stack grows downward in memory, so we increase the size of
  1243. the stack by subtracting from the stack pointer. In the context of a
  1244. procedure call, the \emph{return address} is the next instruction
  1245. after the call instruction on the caller side. During a function call,
  1246. the return address is pushed onto the stack. The register \key{rbp}
  1247. is the \emph{base pointer} and is used to access variables associated
  1248. with the current procedure call. The base pointer of the caller is
  1249. pushed onto the stack after the return address. We number the
  1250. variables from $1$ to $n$. Variable $1$ is stored at address
  1251. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1252. \begin{figure}[tbp]
  1253. \begin{lstlisting}
  1254. start:
  1255. movq $10, -8(%rbp)
  1256. negq -8(%rbp)
  1257. movq -8(%rbp), %rax
  1258. addq $52, %rax
  1259. jmp conclusion
  1260. .globl main
  1261. main:
  1262. pushq %rbp
  1263. movq %rsp, %rbp
  1264. subq $16, %rsp
  1265. jmp start
  1266. conclusion:
  1267. addq $16, %rsp
  1268. popq %rbp
  1269. retq
  1270. \end{lstlisting}
  1271. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1272. \label{fig:p1-x86}
  1273. \end{figure}
  1274. \begin{figure}[tbp]
  1275. \centering
  1276. \begin{tabular}{|r|l|} \hline
  1277. Position & Contents \\ \hline
  1278. 8(\key{\%rbp}) & return address \\
  1279. 0(\key{\%rbp}) & old \key{rbp} \\
  1280. -8(\key{\%rbp}) & variable $1$ \\
  1281. -16(\key{\%rbp}) & variable $2$ \\
  1282. \ldots & \ldots \\
  1283. 0(\key{\%rsp}) & variable $n$\\ \hline
  1284. \end{tabular}
  1285. \caption{Memory layout of a frame.}
  1286. \label{fig:frame}
  1287. \end{figure}
  1288. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1289. control is transfered from the operating system to the \code{main}
  1290. function. The operating system issues a \code{callq main} instruction
  1291. which pushes its return address on the stack and then jumps to
  1292. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1293. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1294. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1295. alignment (because the \code{callq} pushed the return address). The
  1296. first three instructions are the typical \emph{prelude} for a
  1297. procedure. The instruction \code{pushq \%rbp} saves the base pointer
  1298. for the caller onto the stack and subtracts $8$ from the stack
  1299. pointer. At this point the stack pointer is back to being 16-byte
  1300. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1301. base pointer so that it points the location of the old base
  1302. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1303. pointer down to make enough room for storing variables. This program
  1304. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1305. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1306. we are ready to make calls to other functions. The last instruction of
  1307. the prelude is \code{jmp start}, which transfers control to the
  1308. instructions that were generated from the Racket expression \code{(+
  1309. 10 32)}.
  1310. The four instructions under the label \code{start} carry out the work
  1311. of computing \code{(+ 52 (- 10)))}. The first instruction
  1312. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1313. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1314. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1315. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1316. \code{rax}, at which point \code{rax} contains $42$.
  1317. The three instructions under the label \code{conclusion} are the
  1318. typical \emph{conclusion} of a procedure. The first two instructions
  1319. are necessary to get the state of the machine back to where it was at
  1320. the beginning of the procedure. The instruction \key{addq \$16,
  1321. \%rsp} moves the stack pointer back to point at the old base
  1322. pointer. The amount added here needs to match the amount that was
  1323. subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1324. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1325. pointer. The last instruction, \key{retq}, jumps back to the
  1326. procedure that called this one and adds 8 to the stack pointer, which
  1327. returns the stack pointer to where it was prior to the procedure call.
  1328. The compiler needs a convenient representation for manipulating x86
  1329. programs, so we define an abstract syntax for x86 in
  1330. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1331. a subscript $0$ because later we introduce extended versions of this
  1332. assembly language. The main difference compared to the concrete syntax
  1333. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow labeled
  1334. instructions to appear anywhere, but instead organizes instructions
  1335. into groups called \emph{blocks} and associates a label with every
  1336. block, which is why the \key{CFG} struct (for control-flow graph)
  1337. includes an alist mapping labels to blocks. The reason for this
  1338. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1339. introduce conditional branching. The \code{Block} structure includes
  1340. an $\itm{info}$ field that is not needed for this chapter, but will
  1341. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1342. the $\itm{info}$ field should just contain an empty list.
  1343. \begin{figure}[tp]
  1344. \fbox{
  1345. \begin{minipage}{0.96\textwidth}
  1346. \small
  1347. \[
  1348. \begin{array}{lcl}
  1349. \Reg &::=& \allregisters{} \\
  1350. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1351. \mid \DEREF{\Reg}{\Int} \\
  1352. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1353. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1354. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1355. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1356. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1357. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1358. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1359. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1360. \end{array}
  1361. \]
  1362. \end{minipage}
  1363. }
  1364. \caption{The abstract syntax of x86$_0$ assembly.}
  1365. \label{fig:x86-0-ast}
  1366. \end{figure}
  1367. \section{Planning the trip to x86 via the $C_0$ language}
  1368. \label{sec:plan-s0-x86}
  1369. To compile one language to another it helps to focus on the
  1370. differences between the two languages because the compiler will need
  1371. to bridge those differences. What are the differences between $R_1$
  1372. and x86 assembly? Here are some of the most important ones:
  1373. \begin{enumerate}
  1374. \item[(a)] x86 arithmetic instructions typically have two arguments
  1375. and update the second argument in place. In contrast, $R_1$
  1376. arithmetic operations take two arguments and produce a new value.
  1377. An x86 instruction may have at most one memory-accessing argument.
  1378. Furthermore, some instructions place special restrictions on their
  1379. arguments.
  1380. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1381. whereas x86 instructions restrict their arguments to be integers
  1382. constants, registers, and memory locations.
  1383. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1384. sequence of instructions and jumps to labeled positions, whereas in
  1385. $R_1$ the order of evaluation is a left-to-right depth-first
  1386. traversal of the abstract syntax tree.
  1387. \item[(d)] An $R_1$ program can have any number of variables whereas
  1388. x86 has 16 registers and the procedure calls stack.
  1389. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1390. same name. The registers and memory locations of x86 all have unique
  1391. names or addresses.
  1392. \end{enumerate}
  1393. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1394. the problem into several steps, dealing with the above differences one
  1395. at a time. Each of these steps is called a \emph{pass} of the
  1396. compiler.
  1397. %
  1398. This terminology comes from each step traverses (i.e. passes over) the
  1399. AST of the program.
  1400. %
  1401. We begin by sketching how we might implement each pass, and give them
  1402. names. We then figure out an ordering of the passes and the
  1403. input/output language for each pass. The very first pass has $R_1$ as
  1404. its input language and the last pass has x86 as its output
  1405. language. In between we can choose whichever language is most
  1406. convenient for expressing the output of each pass, whether that be
  1407. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1408. Finally, to implement each pass we write one recursive function per
  1409. non-terminal in the grammar of the input language of the pass.
  1410. \begin{description}
  1411. \item[Pass \key{select-instructions}] To handle the difference between
  1412. $R_1$ operations and x86 instructions we convert each $R_1$
  1413. operation to a short sequence of instructions that accomplishes the
  1414. same task.
  1415. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1416. subexpression (i.e. operator and operand, and hence the name
  1417. \key{opera*}) is an \emph{atomic} expression (a variable or
  1418. integer), we introduce temporary variables to hold the results
  1419. of subexpressions.
  1420. \item[Pass \key{explicate-control}] To make the execution order of the
  1421. program explicit, we convert from the abstract syntax tree
  1422. representation into a \emph{control-flow graph} in which each node
  1423. contains a sequence of statements and the edges between nodes say
  1424. where to go at the end of the sequence.
  1425. \item[Pass \key{assign-homes}] To handle the difference between the
  1426. variables in $R_1$ versus the registers and stack locations in x86,
  1427. we map each variable to a register or stack location.
  1428. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1429. by renaming every variable to a unique name, so that shadowing no
  1430. longer occurs.
  1431. \end{description}
  1432. The next question is: in what order should we apply these passes? This
  1433. question can be challenging because it is difficult to know ahead of
  1434. time which orders will be better (easier to implement, produce more
  1435. efficient code, etc.) so oftentimes trial-and-error is
  1436. involved. Nevertheless, we can try to plan ahead and make educated
  1437. choices regarding the ordering.
  1438. Let us consider the ordering of \key{uniquify} and
  1439. \key{remove-complex-opera*}. The assignment of subexpressions to
  1440. temporary variables involves introducing new variables and moving
  1441. subexpressions, which might change the shadowing of variables and
  1442. inadvertently change the behavior of the program. But if we apply
  1443. \key{uniquify} first, this will not be an issue. Of course, this means
  1444. that in \key{remove-complex-opera*}, we need to ensure that the
  1445. temporary variables that it creates are unique.
  1446. What should be the ordering of \key{explicate-control} with respect to
  1447. \key{uniquify}? The \key{uniquify} pass should come first because
  1448. \key{explicate-control} changes all the \key{let}-bound variables to
  1449. become local variables whose scope is the entire program, which would
  1450. confuse variables with the same name.
  1451. %
  1452. Likewise, we place \key{explicate-control} after
  1453. \key{remove-complex-opera*} because \key{explicate-control} removes
  1454. the \key{let} form, but it is convenient to use \key{let} in the
  1455. output of \key{remove-complex-opera*}.
  1456. %
  1457. Regarding \key{assign-homes}, it is helpful to place
  1458. \key{explicate-control} first because \key{explicate-control} changes
  1459. \key{let}-bound variables into program-scope variables. This means
  1460. that the \key{assign-homes} pass can read off the variables from the
  1461. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1462. entire program in search of \key{let}-bound variables.
  1463. Last, we need to decide on the ordering of \key{select-instructions}
  1464. and \key{assign-homes}. These two passes are intertwined, creating a
  1465. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1466. have already determined which instructions will be used, because x86
  1467. instructions have restrictions about which of their arguments can be
  1468. registers versus stack locations. One might want to give preferential
  1469. treatment to variables that occur in register-argument positions. On
  1470. the other hand, it may turn out to be impossible to make sure that all
  1471. such variables are assigned to registers, and then one must redo the
  1472. selection of instructions. Some compilers handle this problem by
  1473. iteratively repeating these two passes until a good solution is found.
  1474. We shall use a simpler approach in which \key{select-instructions}
  1475. comes first, followed by the \key{assign-homes}, then a third
  1476. pass named \key{patch-instructions} that uses a reserved register to
  1477. patch-up outstanding problems regarding instructions with too many
  1478. memory accesses. The disadvantage of this approach is some programs
  1479. may not execute as efficiently as they would if we used the iterative
  1480. approach and used all of the registers for variables.
  1481. \begin{figure}[tbp]
  1482. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1483. \node (R1) at (0,2) {\large $R_1$};
  1484. \node (R1-2) at (3,2) {\large $R_1$};
  1485. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1486. %\node (C0-1) at (6,0) {\large $C_0$};
  1487. \node (C0-2) at (3,0) {\large $C_0$};
  1488. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1489. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1490. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1491. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1492. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1493. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1494. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1495. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1496. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1497. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1498. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1499. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1500. \end{tikzpicture}
  1501. \caption{Overview of the passes for compiling $R_1$. }
  1502. \label{fig:R1-passes}
  1503. \end{figure}
  1504. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1505. passes in the form of a graph. Each pass is an edge and the
  1506. input/output language of each pass is a node in the graph. The output
  1507. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1508. are still in the $R_1$ language, but the output of the pass
  1509. \key{explicate-control} is in a different language $C_0$ that is
  1510. designed to make the order of evaluation explicit in its syntax, which
  1511. we introduce in the next section. The \key{select-instruction} pass
  1512. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1513. \key{patch-instructions} passes input and output variants of x86
  1514. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1515. \key{print-x86}, which converts from the abstract syntax of
  1516. $\text{x86}_0$ to the concrete syntax of x86.
  1517. In the next sections we discuss the $C_0$ language and the
  1518. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1519. remainder of this chapter gives hints regarding the implementation of
  1520. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1521. \subsection{The $C_0$ Intermediate Language}
  1522. The output of \key{explicate-control} is similar to the $C$
  1523. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1524. categories for expressions and statements, so we name it $C_0$. The
  1525. concrete syntax for $C_0$ is defined in
  1526. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1527. is defined in Figure~\ref{fig:c0-syntax}.
  1528. %
  1529. The $C_0$ language supports the same operators as $R_1$ but the
  1530. arguments of operators are restricted to atomic expressions (variables
  1531. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1532. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1533. executed in sequence using the \key{Seq} form. A sequence of
  1534. statements always ends with \key{Return}, a guarantee that is baked
  1535. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1536. this non-terminal comes from the term \emph{tail position}, which
  1537. refers to an expression that is the last one to execute within a
  1538. function. (A expression in tail position may contain subexpressions,
  1539. and those may or may not be in tail position depending on the kind of
  1540. expression.)
  1541. A $C_0$ program consists of a control-flow graph (represented as an
  1542. alist mapping labels to tails). This is more general than
  1543. necessary for the present chapter, as we do not yet need to introduce
  1544. \key{goto} for jumping to labels, but it saves us from having to
  1545. change the syntax of the program construct in
  1546. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1547. \key{start}, and the whole program is its tail.
  1548. %
  1549. The $\itm{info}$ field of the \key{Program} form, after the
  1550. \key{explicate-control} pass, contains a mapping from the symbol
  1551. \key{locals} to a list of variables, that is, a list of all the
  1552. variables used in the program. At the start of the program, these
  1553. variables are uninitialized; they become initialized on their first
  1554. assignment.
  1555. \begin{figure}[tbp]
  1556. \fbox{
  1557. \begin{minipage}{0.96\textwidth}
  1558. \[
  1559. \begin{array}{lcl}
  1560. \Atm &::=& \Int \mid \Var \\
  1561. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1562. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1563. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1564. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1565. \end{array}
  1566. \]
  1567. \end{minipage}
  1568. }
  1569. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1570. \label{fig:c0-concrete-syntax}
  1571. \end{figure}
  1572. \begin{figure}[tbp]
  1573. \fbox{
  1574. \begin{minipage}{0.96\textwidth}
  1575. \[
  1576. \begin{array}{lcl}
  1577. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1578. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1579. &\mid& \ADD{\Atm}{\Atm}\\
  1580. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1581. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1582. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1583. \end{array}
  1584. \]
  1585. \end{minipage}
  1586. }
  1587. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1588. \label{fig:c0-syntax}
  1589. \end{figure}
  1590. %% The \key{select-instructions} pass is optimistic in the sense that it
  1591. %% treats variables as if they were all mapped to registers. The
  1592. %% \key{select-instructions} pass generates a program that consists of
  1593. %% x86 instructions but that still uses variables, so it is an
  1594. %% intermediate language that is technically different than x86, which
  1595. %% explains the asterisks in the diagram above.
  1596. %% In this Chapter we shall take the easy road to implementing
  1597. %% \key{assign-homes} and simply map all variables to stack locations.
  1598. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1599. %% smarter approach in which we make a best-effort to map variables to
  1600. %% registers, resorting to the stack only when necessary.
  1601. %% Once variables have been assigned to their homes, we can finalize the
  1602. %% instruction selection by dealing with an idiosyncrasy of x86
  1603. %% assembly. Many x86 instructions have two arguments but only one of the
  1604. %% arguments may be a memory reference (and the stack is a part of
  1605. %% memory). Because some variables may get mapped to stack locations,
  1606. %% some of our generated instructions may violate this restriction. The
  1607. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1608. %% replacing every violating instruction with a short sequence of
  1609. %% instructions that use the \key{rax} register. Once we have implemented
  1610. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1611. %% need to patch instructions will be relatively rare.
  1612. \subsection{The dialects of x86}
  1613. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1614. the pass \key{select-instructions}. It extends x86$_0$ with an
  1615. unbounded number of program-scope variables and has looser rules
  1616. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1617. output of \key{print-x86}, is the concrete syntax for x86.
  1618. \section{Uniquify Variables}
  1619. \label{sec:uniquify-s0}
  1620. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1621. programs in which every \key{let} uses a unique variable name. For
  1622. example, the \code{uniquify} pass should translate the program on the
  1623. left into the program on the right. \\
  1624. \begin{tabular}{lll}
  1625. \begin{minipage}{0.4\textwidth}
  1626. \begin{lstlisting}
  1627. (let ([x 32])
  1628. (+ (let ([x 10]) x) x))
  1629. \end{lstlisting}
  1630. \end{minipage}
  1631. &
  1632. $\Rightarrow$
  1633. &
  1634. \begin{minipage}{0.4\textwidth}
  1635. \begin{lstlisting}
  1636. (let ([x.1 32])
  1637. (+ (let ([x.2 10]) x.2) x.1))
  1638. \end{lstlisting}
  1639. \end{minipage}
  1640. \end{tabular} \\
  1641. %
  1642. The following is another example translation, this time of a program
  1643. with a \key{let} nested inside the initializing expression of another
  1644. \key{let}.\\
  1645. \begin{tabular}{lll}
  1646. \begin{minipage}{0.4\textwidth}
  1647. \begin{lstlisting}
  1648. (let ([x (let ([x 4])
  1649. (+ x 1))])
  1650. (+ x 2))
  1651. \end{lstlisting}
  1652. \end{minipage}
  1653. &
  1654. $\Rightarrow$
  1655. &
  1656. \begin{minipage}{0.4\textwidth}
  1657. \begin{lstlisting}
  1658. (let ([x.2 (let ([x.1 4])
  1659. (+ x.1 1))])
  1660. (+ x.2 2))
  1661. \end{lstlisting}
  1662. \end{minipage}
  1663. \end{tabular}
  1664. We recommend implementing \code{uniquify} by creating a function named
  1665. \code{uniquify-exp} that is structurally recursive function and mostly
  1666. just copies the input program. However, when encountering a \key{let},
  1667. it should generate a unique name for the variable (the Racket function
  1668. \code{gensym} is handy for this) and associate the old name with the
  1669. new unique name in an alist. The \code{uniquify-exp}
  1670. function will need to access this alist when it gets to a
  1671. variable reference, so we add another parameter to \code{uniquify-exp}
  1672. for the alist.
  1673. The skeleton of the \code{uniquify-exp} function is shown in
  1674. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1675. convenient to partially apply it to a symbol table and then apply it
  1676. to different expressions, as in the last clause for primitive
  1677. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1678. is useful for applying a function to each element of a list to produce
  1679. a new list.
  1680. \begin{exercise}
  1681. \normalfont % I don't like the italics for exercises. -Jeremy
  1682. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1683. implement the clauses for variables and for the \key{let} form.
  1684. \end{exercise}
  1685. \begin{figure}[tbp]
  1686. \begin{lstlisting}
  1687. (define (uniquify-exp symtab)
  1688. (lambda (e)
  1689. (match e
  1690. [(Var x) ___]
  1691. [(Int n) (Int n)]
  1692. [(Let x e body) ___]
  1693. [(Prim op es)
  1694. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1695. )))
  1696. (define (uniquify p)
  1697. (match p
  1698. [(Program '() e)
  1699. (Program '() ((uniquify-exp '()) e))]
  1700. )))
  1701. \end{lstlisting}
  1702. \caption{Skeleton for the \key{uniquify} pass.}
  1703. \label{fig:uniquify-s0}
  1704. \end{figure}
  1705. \begin{exercise}
  1706. \normalfont % I don't like the italics for exercises. -Jeremy
  1707. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1708. and checking whether the output programs produce the same result as
  1709. the input programs. The $R_1$ programs should be designed to test the
  1710. most interesting parts of the \key{uniquify} pass, that is, the
  1711. programs should include \key{let} forms, variables, and variables
  1712. that overshadow each other. The five programs should be in a
  1713. subdirectory named \key{tests} and they should have the same file name
  1714. except for a different integer at the end of the name, followed by the
  1715. ending \key{.rkt}. Use the \key{interp-tests} function
  1716. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1717. your \key{uniquify} pass on the example programs. See the
  1718. \key{run-tests.rkt} script in the student support code for an example
  1719. of how to use \key{interp-tests}.
  1720. \end{exercise}
  1721. \section{Remove Complex Operands}
  1722. \label{sec:remove-complex-opera-R1}
  1723. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1724. $R_1$ programs in which the arguments of operations are atomic
  1725. expressions. Put another way, this pass removes complex operands,
  1726. such as the expression \code{(- 10)} in the program below. This is
  1727. accomplished by introducing a new \key{let}-bound variable, binding
  1728. the complex operand to the new variable, and then using the new
  1729. variable in place of the complex operand, as shown in the output of
  1730. \code{remove-complex-opera*} on the right.\\
  1731. \begin{tabular}{lll}
  1732. \begin{minipage}{0.4\textwidth}
  1733. % s0_19.rkt
  1734. \begin{lstlisting}
  1735. (+ 52 (- 10))
  1736. \end{lstlisting}
  1737. \end{minipage}
  1738. &
  1739. $\Rightarrow$
  1740. &
  1741. \begin{minipage}{0.4\textwidth}
  1742. \begin{lstlisting}
  1743. (let ([tmp.1 (- 10)])
  1744. (+ 52 tmp.1))
  1745. \end{lstlisting}
  1746. \end{minipage}
  1747. \end{tabular}
  1748. \begin{figure}[tp]
  1749. \centering
  1750. \fbox{
  1751. \begin{minipage}{0.96\textwidth}
  1752. \[
  1753. \begin{array}{rcl}
  1754. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1755. \Exp &::=& \Atm \mid \READ{} \\
  1756. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1757. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1758. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1759. \end{array}
  1760. \]
  1761. \end{minipage}
  1762. }
  1763. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1764. \label{fig:r1-anf-syntax}
  1765. \end{figure}
  1766. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1767. this pass, language $R_1^{\dagger}$. The main difference is that
  1768. operator arguments are required to be atomic expressions. In the
  1769. literature this is called \emph{administrative normal form}, or ANF
  1770. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1771. We recommend implementing this pass with two mutually recursive
  1772. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1773. \code{rco-atom} to subexpressions that are required to be atomic and
  1774. to apply \code{rco-exp} to subexpressions that can be atomic or
  1775. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1776. $R_1$ expression as input. The \code{rco-exp} function returns an
  1777. expression. The \code{rco-atom} function returns two things: an
  1778. atomic expression and alist mapping temporary variables to complex
  1779. subexpressions. You can return multiple things from a function using
  1780. Racket's \key{values} form and you can receive multiple things from a
  1781. function call using the \key{define-values} form. If you are not
  1782. familiar with these features, review the Racket documentation. Also,
  1783. the \key{for/lists} form is useful for applying a function to each
  1784. element of a list, in the case where the function returns multiple
  1785. values.
  1786. The following shows the output of \code{rco-atom} on the expression
  1787. \code{(- 10)} (using concrete syntax to be concise).
  1788. \begin{tabular}{lll}
  1789. \begin{minipage}{0.4\textwidth}
  1790. \begin{lstlisting}
  1791. (- 10)
  1792. \end{lstlisting}
  1793. \end{minipage}
  1794. &
  1795. $\Rightarrow$
  1796. &
  1797. \begin{minipage}{0.4\textwidth}
  1798. \begin{lstlisting}
  1799. tmp.1
  1800. ((tmp.1 . (- 10)))
  1801. \end{lstlisting}
  1802. \end{minipage}
  1803. \end{tabular}
  1804. Take special care of programs such as the next one that \key{let}-bind
  1805. variables with integers or other variables. You should leave them
  1806. unchanged, as shown in to the program on the right \\
  1807. \begin{tabular}{lll}
  1808. \begin{minipage}{0.4\textwidth}
  1809. % s0_20.rkt
  1810. \begin{lstlisting}
  1811. (let ([a 42])
  1812. (let ([b a])
  1813. b))
  1814. \end{lstlisting}
  1815. \end{minipage}
  1816. &
  1817. $\Rightarrow$
  1818. &
  1819. \begin{minipage}{0.4\textwidth}
  1820. \begin{lstlisting}
  1821. (let ([a 42])
  1822. (let ([b a])
  1823. b))
  1824. \end{lstlisting}
  1825. \end{minipage}
  1826. \end{tabular} \\
  1827. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1828. produce the following output.\\
  1829. \begin{minipage}{0.4\textwidth}
  1830. \begin{lstlisting}
  1831. (let ([tmp.1 42])
  1832. (let ([a tmp.1])
  1833. (let ([tmp.2 a])
  1834. (let ([b tmp.2])
  1835. b))))
  1836. \end{lstlisting}
  1837. \end{minipage}
  1838. \begin{exercise}
  1839. \normalfont Implement the \code{remove-complex-opera*} pass.
  1840. 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}} looping form in Racket may come in handy.
  1841. Test the new pass on all of the example programs that you created to test the
  1842. \key{uniquify} pass and create three new example programs that are
  1843. designed to exercise the interesting code in the
  1844. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1845. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1846. your passes on the example programs.
  1847. \end{exercise}
  1848. \section{Explicate Control}
  1849. \label{sec:explicate-control-r1}
  1850. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1851. programs that make the order of execution explicit in their
  1852. syntax. For now this amounts to flattening \key{let} constructs into a
  1853. sequence of assignment statements. For example, consider the following
  1854. $R_1$ program.\\
  1855. % s0_11.rkt
  1856. \begin{minipage}{0.96\textwidth}
  1857. \begin{lstlisting}
  1858. (let ([y (let ([x 20])
  1859. (+ x (let ([x 22]) x)))])
  1860. y)
  1861. \end{lstlisting}
  1862. \end{minipage}\\
  1863. %
  1864. The output of the previous pass and of \code{explicate-control} is
  1865. shown below. Recall that the right-hand-side of a \key{let} executes
  1866. before its body, so the order of evaluation for this program is to
  1867. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1868. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1869. output of \code{explicate-control} makes this ordering explicit.\\
  1870. \begin{tabular}{lll}
  1871. \begin{minipage}{0.4\textwidth}
  1872. \begin{lstlisting}
  1873. (let ([y (let ([x.1 20])
  1874. (let ([x.2 22])
  1875. (+ x.1 x.2)))])
  1876. y)
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. &
  1880. $\Rightarrow$
  1881. &
  1882. \begin{minipage}{0.4\textwidth}
  1883. \begin{lstlisting}
  1884. locals: y x.1 x.2
  1885. start:
  1886. x.1 = 20;
  1887. x.2 = 22;
  1888. y = (+ x.1 x.2);
  1889. return y;
  1890. \end{lstlisting}
  1891. \end{minipage}
  1892. \end{tabular}
  1893. We recommend implementing \code{explicate-control} using two mutually
  1894. recursive functions: \code{explicate-tail} and
  1895. \code{explicate-assign}. The first function should be applied to
  1896. expressions in tail position whereas the second should be applied to
  1897. expressions that occur on the right-hand-side of a \key{let}.
  1898. %
  1899. The \code{explicate-tail} function takes an $R_1$ expression as input
  1900. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1901. list of formerly \key{let}-bound variables.
  1902. %
  1903. The \code{explicate-assign} function takes an $R_1$ expression, the
  1904. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1905. should come after the assignment (e.g., the code generated for the
  1906. body of the \key{let}). It returns a $\Tail$ and a list of
  1907. variables. The \code{explicate-assign} function is in
  1908. accumulator-passing style in that its third parameter is some $C_0$
  1909. code which it then adds to and returns. The reader might be tempted to
  1910. instead organize \code{explicate-assign} in a more direct fashion,
  1911. without the third parameter and perhaps using \code{append} to combine
  1912. statements. We warn against that alternative because the
  1913. accumulator-passing style is key to how we generate high-quality code
  1914. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1915. The top-level \code{explicate-control} function should invoke
  1916. \code{explicate-tail} on the body of the \key{program} and then
  1917. associate the \code{locals} symbol with the resulting list of
  1918. variables in the $\itm{info}$ field, as in the above example.
  1919. \section{Select Instructions}
  1920. \label{sec:select-r1}
  1921. In the \code{select-instructions} pass we begin the work of
  1922. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1923. this pass is a variant of x86 that still uses variables, so we add an
  1924. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1925. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1926. \code{select-instructions} in terms of three auxiliary functions, one
  1927. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1928. The cases for $\Atm$ are straightforward, variables stay
  1929. the same and integer constants are changed to immediates:
  1930. $\INT{n}$ changes to $\IMM{n}$.
  1931. Next we consider the cases for $\Stmt$, starting with arithmetic
  1932. operations. For example, in $C_0$ an addition operation can take the
  1933. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1934. need to use the \key{addq} instruction which does an in-place
  1935. update. So we must first move \code{10} to \code{x}. \\
  1936. \begin{tabular}{lll}
  1937. \begin{minipage}{0.4\textwidth}
  1938. \begin{lstlisting}
  1939. x = (+ 10 32);
  1940. \end{lstlisting}
  1941. \end{minipage}
  1942. &
  1943. $\Rightarrow$
  1944. &
  1945. \begin{minipage}{0.4\textwidth}
  1946. \begin{lstlisting}
  1947. movq $10, x
  1948. addq $32, x
  1949. \end{lstlisting}
  1950. \end{minipage}
  1951. \end{tabular} \\
  1952. %
  1953. There are cases that require special care to avoid generating
  1954. needlessly complicated code. If one of the arguments of the addition
  1955. is the same as the left-hand side of the assignment, then there is no
  1956. need for the extra move instruction. For example, the following
  1957. assignment statement can be translated into a single \key{addq}
  1958. instruction.\\
  1959. \begin{tabular}{lll}
  1960. \begin{minipage}{0.4\textwidth}
  1961. \begin{lstlisting}
  1962. x = (+ 10 x);
  1963. \end{lstlisting}
  1964. \end{minipage}
  1965. &
  1966. $\Rightarrow$
  1967. &
  1968. \begin{minipage}{0.4\textwidth}
  1969. \begin{lstlisting}
  1970. addq $10, x
  1971. \end{lstlisting}
  1972. \end{minipage}
  1973. \end{tabular} \\
  1974. The \key{read} operation does not have a direct counterpart in x86
  1975. assembly, so we have instead implemented this functionality in the C
  1976. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  1977. in the file \code{runtime.c}. In general, we refer to all of the
  1978. functionality in this file as the \emph{runtime system}, or simply the
  1979. \emph{runtime} for short. When compiling your generated x86 assembly
  1980. code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  1981. ``object file'', using \code{gcc} option \code{-c}) and link it into
  1982. the executable. For our purposes of code generation, all you need to
  1983. do is translate an assignment of \key{read} into some variable
  1984. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  1985. function followed by a move from \code{rax} to the left-hand side.
  1986. The move from \code{rax} is needed because the return value from
  1987. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1988. \begin{tabular}{lll}
  1989. \begin{minipage}{0.3\textwidth}
  1990. \begin{lstlisting}
  1991. |$\itm{var}$| = (read);
  1992. \end{lstlisting}
  1993. \end{minipage}
  1994. &
  1995. $\Rightarrow$
  1996. &
  1997. \begin{minipage}{0.3\textwidth}
  1998. \begin{lstlisting}
  1999. callq read_int
  2000. movq %rax, |$\itm{var}$|
  2001. \end{lstlisting}
  2002. \end{minipage}
  2003. \end{tabular} \\
  2004. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2005. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2006. assignment to the \key{rax} register followed by a jump to the
  2007. conclusion of the program (so the conclusion needs to be labeled).
  2008. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2009. recursively and append the resulting instructions.
  2010. \begin{exercise}
  2011. \normalfont
  2012. Implement the \key{select-instructions} pass and test it on all of the
  2013. example programs that you created for the previous passes and create
  2014. three new example programs that are designed to exercise all of the
  2015. interesting code in this pass. Use the \key{interp-tests} function
  2016. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2017. your passes on the example programs.
  2018. \end{exercise}
  2019. \section{Assign Homes}
  2020. \label{sec:assign-r1}
  2021. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2022. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2023. Thus, the \key{assign-homes} pass is responsible for placing all of
  2024. the program variables in registers or on the stack. For runtime
  2025. efficiency, it is better to place variables in registers, but as there
  2026. are only 16 registers, some programs must necessarily resort to
  2027. placing some variables on the stack. In this chapter we focus on the
  2028. mechanics of placing variables on the stack. We study an algorithm for
  2029. placing variables in registers in
  2030. Chapter~\ref{ch:register-allocation-r1}.
  2031. Consider again the following $R_1$ program.
  2032. % s0_20.rkt
  2033. \begin{lstlisting}
  2034. (let ([a 42])
  2035. (let ([b a])
  2036. b))
  2037. \end{lstlisting}
  2038. For reference, we repeat the output of \code{select-instructions} on
  2039. the left and show the output of \code{assign-homes} on the right.
  2040. Recall that \key{explicate-control} associated the list of
  2041. variables with the \code{locals} symbol in the program's $\itm{info}$
  2042. field, so \code{assign-homes} has convenient access to the them. In
  2043. this example, we assign variable \code{a} to stack location
  2044. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2045. \begin{tabular}{l}
  2046. \begin{minipage}{0.4\textwidth}
  2047. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2048. locals: a b
  2049. start:
  2050. movq $42, a
  2051. movq a, b
  2052. movq b, %rax
  2053. jmp conclusion
  2054. \end{lstlisting}
  2055. \end{minipage}
  2056. {$\Rightarrow$}
  2057. \begin{minipage}{0.4\textwidth}
  2058. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2059. stack-space: 16
  2060. start:
  2061. movq $42, -8(%rbp)
  2062. movq -8(%rbp), -16(%rbp)
  2063. movq -16(%rbp), %rax
  2064. jmp conclusion
  2065. \end{lstlisting}
  2066. \end{minipage}
  2067. \end{tabular} \\
  2068. In the process of assigning variables to stack locations, it is
  2069. convenient to compute and store the size of the frame (in bytes) in
  2070. the $\itm{info}$ field of the \key{Program} node, with the key
  2071. \code{stack-space}, which will be needed later to generate the
  2072. procedure conclusion. Some operating systems place restrictions on
  2073. the frame size. For example, Mac OS X requires the frame size to be a
  2074. multiple of 16 bytes.
  2075. \begin{exercise}
  2076. \normalfont Implement the \key{assign-homes} pass and test it on all
  2077. of the example programs that you created for the previous passes pass.
  2078. We recommend that \key{assign-homes} take an extra parameter that is a
  2079. mapping of variable names to homes (stack locations for now). Use the
  2080. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2081. \key{utilities.rkt} to test your passes on the example programs.
  2082. \end{exercise}
  2083. \section{Patch Instructions}
  2084. \label{sec:patch-s0}
  2085. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2086. programs to $\text{x86}_0$ programs by making sure that each
  2087. instruction adheres to the restrictions of the x86 assembly language.
  2088. In particular, at most one argument of an instruction may be a memory
  2089. reference.
  2090. We return to the following running example.
  2091. % s0_20.rkt
  2092. \begin{lstlisting}
  2093. (let ([a 42])
  2094. (let ([b a])
  2095. b))
  2096. \end{lstlisting}
  2097. After the \key{assign-homes} pass, the above program has been translated to
  2098. the following. \\
  2099. \begin{minipage}{0.5\textwidth}
  2100. \begin{lstlisting}
  2101. stack-space: 16
  2102. start:
  2103. movq $42, -8(%rbp)
  2104. movq -8(%rbp), -16(%rbp)
  2105. movq -16(%rbp), %rax
  2106. jmp conclusion
  2107. \end{lstlisting}
  2108. \end{minipage}\\
  2109. The second \key{movq} instruction is problematic because both
  2110. arguments are stack locations. We suggest fixing this problem by
  2111. moving from the source location to the register \key{rax} and then
  2112. from \key{rax} to the destination location, as follows.
  2113. \begin{lstlisting}
  2114. movq -8(%rbp), %rax
  2115. movq %rax, -16(%rbp)
  2116. \end{lstlisting}
  2117. \begin{exercise}
  2118. \normalfont
  2119. Implement the \key{patch-instructions} pass and test it on all of the
  2120. example programs that you created for the previous passes and create
  2121. three new example programs that are designed to exercise all of the
  2122. interesting code in this pass. Use the \key{interp-tests} function
  2123. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2124. your passes on the example programs.
  2125. \end{exercise}
  2126. \section{Print x86}
  2127. \label{sec:print-x86}
  2128. The last step of the compiler from $R_1$ to x86 is to convert the
  2129. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2130. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2131. \key{format} and \key{string-append} functions are useful in this
  2132. regard. The main work that this step needs to perform is to create the
  2133. \key{main} function and the standard instructions for its prelude and
  2134. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2135. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2136. variables, so we suggest computing it in the \key{assign-homes} pass
  2137. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2138. of the \key{program} node.
  2139. %% Your compiled code should print the result of the program's execution
  2140. %% by using the \code{print\_int} function provided in
  2141. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2142. %% far, this final result should be stored in the \key{rax} register.
  2143. %% We'll talk more about how to perform function calls with arguments in
  2144. %% general later on, but for now, place the following after the compiled
  2145. %% code for the $R_1$ program but before the conclusion:
  2146. %% \begin{lstlisting}
  2147. %% movq %rax, %rdi
  2148. %% callq print_int
  2149. %% \end{lstlisting}
  2150. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2151. %% stores the first argument to be passed into \key{print\_int}.
  2152. If you want your program to run on Mac OS X, your code needs to
  2153. determine whether or not it is running on a Mac, and prefix
  2154. underscores to labels like \key{main}. You can determine the platform
  2155. with the Racket call \code{(system-type 'os)}, which returns
  2156. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2157. %% In addition to
  2158. %% placing underscores on \key{main}, you need to put them in front of
  2159. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2160. %% \_print\_int}).
  2161. \begin{exercise}
  2162. \normalfont Implement the \key{print-x86} pass and test it on all of
  2163. the example programs that you created for the previous passes. Use the
  2164. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2165. \key{utilities.rkt} to test your complete compiler on the example
  2166. programs. See the \key{run-tests.rkt} script in the student support
  2167. code for an example of how to use \key{compiler-tests}. Also, remember
  2168. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2169. \key{gcc}.
  2170. \end{exercise}
  2171. \section{Challenge: Partial Evaluator for $R_1$}
  2172. \label{sec:pe-R1}
  2173. This section describes optional challenge exercises that involve
  2174. adapting and improving the partial evaluator for $R_0$ that was
  2175. introduced in Section~\ref{sec:partial-evaluation}.
  2176. \begin{exercise}\label{ex:pe-R1}
  2177. \normalfont
  2178. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2179. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2180. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2181. and variables to the $R_0$ language, so you will need to add cases for
  2182. them in the \code{pe-exp} function. Also, note that the \key{program}
  2183. form changes slightly to include an $\itm{info}$ field. Once
  2184. complete, add the partial evaluation pass to the front of your
  2185. compiler and make sure that your compiler still passes all of the
  2186. tests.
  2187. \end{exercise}
  2188. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2189. \begin{exercise}
  2190. \normalfont
  2191. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2192. \code{pe-add} auxiliary functions with functions that know more about
  2193. arithmetic. For example, your partial evaluator should translate
  2194. \begin{lstlisting}
  2195. (+ 1 (+ (read) 1))
  2196. \end{lstlisting}
  2197. into
  2198. \begin{lstlisting}
  2199. (+ 2 (read))
  2200. \end{lstlisting}
  2201. To accomplish this, the \code{pe-exp} function should produce output
  2202. in the form of the $\itm{residual}$ non-terminal of the following
  2203. grammar.
  2204. \[
  2205. \begin{array}{lcl}
  2206. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2207. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2208. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2209. \end{array}
  2210. \]
  2211. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2212. that their inputs are $\itm{residual}$ expressions and they should
  2213. return $\itm{residual}$ expressions. Once the improvements are
  2214. complete, make sure that your compiler still passes all of the tests.
  2215. After all, fast code is useless if it produces incorrect results!
  2216. \end{exercise}
  2217. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2218. \chapter{Register Allocation}
  2219. \label{ch:register-allocation-r1}
  2220. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2221. make our life easier. However, we can improve the performance of the
  2222. generated code if we instead place some variables into registers. The
  2223. CPU can access a register in a single cycle, whereas accessing the
  2224. stack takes many cycles if the relevant data is in cache or many more
  2225. to access main memory if the data is not in cache.
  2226. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2227. serves as a running example. We show the source program and also the
  2228. output of instruction selection. At that point the program is almost
  2229. x86 assembly but not quite; it still contains variables instead of
  2230. stack locations or registers.
  2231. \begin{figure}
  2232. \begin{minipage}{0.45\textwidth}
  2233. Example $R_1$ program:
  2234. % s0_28.rkt
  2235. \begin{lstlisting}
  2236. (let ([v 1])
  2237. (let ([w 42])
  2238. (let ([x (+ v 7)])
  2239. (let ([y x])
  2240. (let ([z (+ x w)])
  2241. (+ z (- y)))))))
  2242. \end{lstlisting}
  2243. \end{minipage}
  2244. \begin{minipage}{0.45\textwidth}
  2245. After instruction selection:
  2246. \begin{lstlisting}
  2247. locals: (v w x y z t)
  2248. start:
  2249. movq $1, v
  2250. movq $42, w
  2251. movq v, x
  2252. addq $7, x
  2253. movq x, y
  2254. movq x, z
  2255. addq w, z
  2256. movq y, t
  2257. negq t
  2258. movq z, %rax
  2259. addq t, %rax
  2260. jmp conclusion
  2261. \end{lstlisting}
  2262. \end{minipage}
  2263. \caption{An example program for register allocation.}
  2264. \label{fig:reg-eg}
  2265. \end{figure}
  2266. The goal of register allocation is to fit as many variables into
  2267. registers as possible. A program sometimes has more variables than
  2268. registers, so we cannot map each variable to a different
  2269. register. Fortunately, it is common for different variables to be
  2270. needed during different periods of time during program execution, and
  2271. in such cases several variables can be mapped to the same register.
  2272. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2273. After the variable \code{x} is moved to \code{z} it is no longer
  2274. needed. Variable \code{y}, on the other hand, is used only after this
  2275. point, so \code{x} and \code{y} could share the same register. The
  2276. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2277. where a variable is needed. Once we have that information, we compute
  2278. which variables are needed at the same time, i.e., which ones
  2279. \emph{interfere} with each other, and represent this relation as an
  2280. undirected graph whose vertices are variables and edges indicate when
  2281. two variables interfere (Section~\ref{sec:build-interference}). We
  2282. then model register allocation as a graph coloring problem, which we
  2283. discuss in Section~\ref{sec:graph-coloring}.
  2284. In the event that we run out of registers despite these efforts, we
  2285. place the remaining variables on the stack, similar to what we did in
  2286. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2287. for assigning a variable to a stack location. The process of spilling
  2288. variables is handled as part of the graph coloring process described
  2289. in \ref{sec:graph-coloring}.
  2290. We make the simplifying assumption that each variable is assigned to
  2291. one location (a register or stack address). A more sophisticated
  2292. approach is to assign a variable to one or more locations in different
  2293. regions of the program. For example, if a variable is used many times
  2294. in short sequence and then only used again after many other
  2295. instructions, it could be more efficient to assign the variable to a
  2296. register during the intial sequence and then move it to the stack for
  2297. the rest of its lifetime. We refer the interested reader to
  2298. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2299. about this approach.
  2300. % discuss prioritizing variables based on how much they are used.
  2301. \section{Registers and Calling Conventions}
  2302. \label{sec:calling-conventions}
  2303. As we perform register allocation, we need to be aware of the
  2304. conventions that govern the way in which registers interact with
  2305. function calls, such as calls to the \code{read\_int} function in our
  2306. generated code and even the call that the operating system makes to
  2307. execute our \code{main} function. The convention for x86 is that the
  2308. caller is responsible for freeing up some registers, the
  2309. \emph{caller-saved registers}, prior to the function call, and the
  2310. callee is responsible for preserving the values in some other
  2311. registers, the \emph{callee-saved registers}. The caller-saved
  2312. registers are
  2313. \begin{lstlisting}
  2314. rax rcx rdx rsi rdi r8 r9 r10 r11
  2315. \end{lstlisting}
  2316. while the callee-saved registers are
  2317. \begin{lstlisting}
  2318. rsp rbp rbx r12 r13 r14 r15
  2319. \end{lstlisting}
  2320. We can think about this caller/callee convention from two points of
  2321. view, the caller view and the callee view:
  2322. \begin{itemize}
  2323. \item The caller should assume that all the caller-saved registers get
  2324. overwritten with arbitrary values by the callee. On the other hand,
  2325. the caller can safely assume that all the callee-saved registers
  2326. contain the same values after the call that they did before the
  2327. call.
  2328. \item The callee can freely use any of the caller-saved registers.
  2329. However, if the callee wants to use a callee-saved register, the
  2330. callee must arrange to put the original value back in the register
  2331. prior to returning to the caller, which is usually accomplished by
  2332. saving the value to the stack in the prelude of the function and
  2333. restoring the value in the conclusion of the function.
  2334. \end{itemize}
  2335. The next question is how these calling conventions impact register
  2336. allocation. Consider the $R_1$ program in
  2337. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2338. example from the caller point of view and then from the callee point
  2339. of view.
  2340. The program makes two calls to the \code{read} function. Also, the
  2341. variable \code{x} is in-use during the second call to \code{read}, so
  2342. we need to make sure that the value in \code{x} does not get
  2343. accidentally wiped out by the call to \code{read}. One obvious
  2344. approach is to save all the values in caller-saved registers to the
  2345. stack prior to each function call, and restore them after each
  2346. call. That way, if the register allocator chooses to assign \code{x}
  2347. to a caller-saved register, its value will be preserved accross the
  2348. call to \code{read}. However, the disadvantage of this approach is
  2349. that saving and restoring to the stack is relatively slow. If \code{x}
  2350. is not used many times, it may be better to assign \code{x} to a stack
  2351. location in the first place. Or better yet, if we can arrange for
  2352. \code{x} to be placed in a callee-saved register, then it won't need
  2353. to be saved and restored during function calls.
  2354. The approach that we recommend is to treat variables differently
  2355. depending on whether they are in-use during a function call. If a
  2356. variable is in-use during a function call, then we never assign it to
  2357. a caller-saved register: we either assign it to a callee-saved
  2358. register or we spill it to the stack. If a variable is not in-use
  2359. during any function call, then we try the following alternatives in
  2360. order 1) look for an available caller-saved register (to leave room
  2361. for other variables in the callee-saved register), 2) look for a
  2362. callee-saved register, and 3) spill the variable to the stack.
  2363. It is straightforward to implement this approach in a graph coloring
  2364. register allocator. First, we know which variables are in-use during
  2365. every function call because we compute that information for every
  2366. instruciton (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2367. build the interference graph (Section~\ref{sec:build-interference}),
  2368. we can place an edge between each of these variables and the
  2369. caller-saved registers in the interference graph. This will prevent
  2370. the graph coloring algorithm from assigning those variables to
  2371. caller-saved registers.
  2372. Returning to the example in
  2373. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2374. generated x86 code on the right-hand side, focusing on the
  2375. \code{start} block. Notice that variable \code{x} is assigned to
  2376. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2377. place during the second call to \code{read\_int}. Next, notice that
  2378. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2379. because there are no function calls in the remainder of the block.
  2380. Next we analyze the example from the callee point of view, focusing on
  2381. the prelude and conclusion of the \code{main} function. As usual the
  2382. prelude begins with saving the \code{rbp} register to the stack and
  2383. setting the \code{rbp} to the current stack pointer. We now know why
  2384. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2385. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2386. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2387. variable (\code{x}). There are several more callee-saved register that
  2388. are not saved in the prelude because they were not assigned to
  2389. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2390. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2391. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2392. from the stack with a \code{popq} instruction.
  2393. \begin{figure}[tp]
  2394. \begin{minipage}{0.45\textwidth}
  2395. Example $R_1$ program:
  2396. %s0_14.rkt
  2397. \begin{lstlisting}
  2398. (let ([x (read)])
  2399. (let ([y (read)])
  2400. (+ (+ x y) 42)))
  2401. \end{lstlisting}
  2402. \end{minipage}
  2403. \begin{minipage}{0.45\textwidth}
  2404. Generated x86 assembly:
  2405. \begin{lstlisting}
  2406. start:
  2407. callq read_int
  2408. movq %rax, %rbx
  2409. callq read_int
  2410. movq %rax, %rcx
  2411. addq %rcx, %rbx
  2412. movq %rbx, %rax
  2413. addq $42, %rax
  2414. jmp _conclusion
  2415. .globl main
  2416. main:
  2417. pushq %rbp
  2418. movq %rsp, %rbp
  2419. pushq %rbx
  2420. subq $8, %rsp
  2421. jmp start
  2422. conclusion:
  2423. addq $8, %rsp
  2424. popq %rbx
  2425. popq %rbp
  2426. retq
  2427. \end{lstlisting}
  2428. \end{minipage}
  2429. \caption{An example with function calls.}
  2430. \label{fig:example-calling-conventions}
  2431. \end{figure}
  2432. \section{Liveness Analysis}
  2433. \label{sec:liveness-analysis-r1}
  2434. A variable is \emph{live} if the variable is used at some later point
  2435. in the program and there is not an intervening assignment to the
  2436. variable.
  2437. %
  2438. To understand the latter condition, consider the following code
  2439. fragment in which there are two writes to \code{b}. Are \code{a} and
  2440. \code{b} both live at the same time?
  2441. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2442. movq $5, a
  2443. movq $30, b
  2444. movq a, c
  2445. movq $10, b
  2446. addq b, c
  2447. \end{lstlisting}
  2448. The answer is no because the integer \code{30} written to \code{b} on
  2449. line 2 is never used. The variable \code{b} is read on line 5 and
  2450. there is an intervening write to \code{b} on line 4, so the read on
  2451. line 5 receives the value written on line 4, not line 2.
  2452. \begin{wrapfigure}[21]{l}[1.0in]{0.6\textwidth}
  2453. \small
  2454. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2455. A \emph{set} is an unordered collection of elements that does not
  2456. contain duplicates.
  2457. \begin{description}
  2458. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2459. \item[$\LP\code{set-union}\,s_1\,s_2\RP$] returns the union of the two sets.
  2460. \item[$\LP\code{set-subtract}\,s_1\,s_2\RP$] returns the difference of the two sets.
  2461. \item[$\LP\code{set-member?}\,s\,v\RP$] is element $v$ in set $s$?
  2462. \item[$\LP\code{set-count}\,s\RP$] how many unique elements are in set $s$?
  2463. \item[$\LP\code{set-add}\,s\,v\RP$] returns a set with all the
  2464. elements of $s$ plus the element $v$.
  2465. \item[$\LP\code{set->list}\,s\RP$] converts the set $s$ to a list.
  2466. \end{description}
  2467. \end{tcolorbox}
  2468. \end{wrapfigure}
  2469. The live variables can be computed by traversing the instruction
  2470. sequence back to front (i.e., backwards in execution order). Let
  2471. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2472. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2473. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2474. variables before instruction $I_k$. The live variables after an
  2475. instruction are always the same as the live variables before the next
  2476. instruction.
  2477. \begin{equation} \label{eq:live-after-before-next}
  2478. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2479. \end{equation}
  2480. To start things off, there are no live variables after the last
  2481. instruction, so
  2482. \begin{equation}\label{eq:live-last-empty}
  2483. L_{\mathsf{after}}(n) = \emptyset
  2484. \end{equation}
  2485. We then apply the following rule repeatedly, traversing the
  2486. instruction sequence back to front.
  2487. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2488. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2489. \end{equation}
  2490. where $W(k)$ are the variables written to by instruction $I_k$ and
  2491. $R(k)$ are the variables read by instruction $I_k$.
  2492. Let us walk through the above example, applying these formulas
  2493. starting with the instruction on line 5. We collect the answers in the
  2494. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2495. instruction is $\emptyset$ because it is the last instruction
  2496. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2497. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2498. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2499. is
  2500. \[
  2501. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2502. \]
  2503. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2504. the live-before set from line 5 to be the live-after set for this
  2505. instruction (formula~\ref{eq:live-after-before-next}).
  2506. \[
  2507. L_{\mathsf{after}}(4) = \{ b, c \}
  2508. \]
  2509. This move instruction writes to $b$ and does not read from any
  2510. variables, so we have the following live-before set
  2511. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2512. \[
  2513. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2514. \]
  2515. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2516. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2517. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2518. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2519. variable that is not live and does not read from a variable.
  2520. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2521. because it writes to variable $a$.
  2522. \begin{center}
  2523. \begin{minipage}{0.45\textwidth}
  2524. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2525. movq $5, a
  2526. movq $30, b
  2527. movq a, c
  2528. movq $10, b
  2529. addq b, c
  2530. \end{lstlisting}
  2531. \end{minipage}
  2532. \vrule\hspace{10pt}
  2533. \begin{minipage}{0.45\textwidth}
  2534. \begin{align*}
  2535. L_{\mathsf{before}}(1)= \emptyset,
  2536. L_{\mathsf{after}}(1)= \{a\}\\
  2537. L_{\mathsf{before}}(2)= \{a\},
  2538. L_{\mathsf{after}}(2)= \{a\}\\
  2539. L_{\mathsf{before}}(3)= \{a\},
  2540. L_{\mathsf{after}}(2)= \{c\}\\
  2541. L_{\mathsf{before}}(4)= \{c\},
  2542. L_{\mathsf{after}}(4)= \{b,c\}\\
  2543. L_{\mathsf{before}}(5)= \{b,c\},
  2544. L_{\mathsf{after}}(5)= \emptyset
  2545. \end{align*}
  2546. \end{minipage}
  2547. \end{center}
  2548. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2549. for the running example program, with the live-before and live-after
  2550. sets shown between each instruction to make the figure easy to read.
  2551. \begin{figure}[tp]
  2552. \hspace{20pt}
  2553. \begin{minipage}{0.45\textwidth}
  2554. \begin{lstlisting}
  2555. |$\{\}$|
  2556. movq $1, v
  2557. |$\{v\}$|
  2558. movq $42, w
  2559. |$\{v,w\}$|
  2560. movq v, x
  2561. |$\{w,x\}$|
  2562. addq $7, x
  2563. |$\{w,x\}$|
  2564. movq x, y
  2565. |$\{w,x,y\}$|
  2566. movq x, z
  2567. |$\{w,y,z\}$|
  2568. addq w, z
  2569. |$\{y,z\}$|
  2570. movq y, t
  2571. |$\{t,z\}$|
  2572. negq t
  2573. |$\{t,z\}$|
  2574. movq z, %rax
  2575. |$\{t\}$|
  2576. addq t, %rax
  2577. |$\{\}$|
  2578. jmp conclusion
  2579. |$\{\}$|
  2580. \end{lstlisting}
  2581. \end{minipage}
  2582. \caption{The running example annotated with live-after sets.}
  2583. \label{fig:live-eg}
  2584. \end{figure}
  2585. \begin{exercise}\normalfont
  2586. Implement the compiler pass named \code{uncover-live} that computes
  2587. the live-after sets. We recommend storing the live-after sets (a list
  2588. of a set of variables) in the $\itm{info}$ field of the \key{Block}
  2589. structure. We recommend using the
  2590. \href{https://docs.racket-lang.org/reference/sets.html}{\code{racket/set}}
  2591. package for representing sets of variables.
  2592. %
  2593. We recommend organizing your code to use a helper function that takes
  2594. a list of instructions and an initial live-after set (typically empty)
  2595. and returns the list of live-after sets.
  2596. %
  2597. We recommend creating helper functions to 1) compute the set of
  2598. variables that appear in an argument (of an instruction), 2) compute
  2599. the variables read by an instruction which corresponds to the $R$
  2600. function discussed above, and 3) the variables written by an
  2601. instruction which corresponds to $W$.
  2602. \end{exercise}
  2603. \section{Building the Interference Graph}
  2604. \label{sec:build-interference}
  2605. Based on the liveness analysis, we know where each variable is needed.
  2606. However, during register allocation, we need to answer questions of
  2607. the specific form: are variables $u$ and $v$ live at the same time?
  2608. (And therefore cannot be assigned to the same register.) To make this
  2609. question easier to answer, we create an explicit data structure, an
  2610. \emph{interference graph}. An interference graph is an undirected
  2611. graph that has an edge between two variables if they are live at the
  2612. same time, that is, if they interfere with each other.
  2613. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2614. \small
  2615. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2616. A \emph{graph} is a collection of vertices and edges where each
  2617. edge connects two vertices. A graph is \emph{directed} if each
  2618. edge points from a source to a target. Otherwise the graph is
  2619. \emph{undirected}.
  2620. \begin{description}
  2621. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2622. directed graph from a list of edges. Each edge is a list
  2623. containing the source and target vertex.
  2624. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2625. undirected graph from a list of edges. Each edge is represented by
  2626. a list containing two vertices.
  2627. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2628. inserts a vertex into the graph.
  2629. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2630. inserts an edge between the two vertices into the graph.
  2631. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2632. returns a sequence of all the neighbors of the given vertex.
  2633. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2634. returns a sequence of all the vertices in the graph.
  2635. \end{description}
  2636. \end{tcolorbox}
  2637. \end{wrapfigure}
  2638. The most obvious way to compute the interference graph is to look at
  2639. the set of live variables between each statement in the program and
  2640. add an edge to the graph for every pair of variables in the same set.
  2641. This approach is less than ideal for two reasons. First, it can be
  2642. expensive because it takes $O(n^2)$ time to look at every pair in a
  2643. set of $n$ live variables. Second, there is a special case in which
  2644. two variables that are live at the same time do not actually interfere
  2645. with each other: when they both contain the same value because we have
  2646. assigned one to the other.
  2647. A better way to compute the interference graph is to focus on the
  2648. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2649. instruction to overwrite something in a live variable. So for each
  2650. instruction, we create an edge between the variable being written to
  2651. and all the \emph{other} live variables. (One should not create self
  2652. edges.) For a \key{callq} instruction, think of all caller-saved
  2653. registers as being written to, so an edge must be added between every
  2654. live variable and every caller-saved register. For \key{movq}, we deal
  2655. with the above-mentioned special case by not adding an edge between a
  2656. live variable $v$ and destination $d$ if $v$ matches the source of the
  2657. move. So we have the following three rules.
  2658. \begin{enumerate}
  2659. \item If instruction $I_k$ is an arithmetic instruction such as
  2660. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2661. L_{\mathsf{after}}(k)$ unless $v = d$.
  2662. \item If instruction $I_k$ is of the form \key{callq}
  2663. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2664. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2665. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2666. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2667. d$ or $v = s$.
  2668. \end{enumerate}
  2669. Working from the top to bottom of Figure~\ref{fig:live-eg}, apply the
  2670. above rules to each instruction. We highlight a few of the
  2671. instructions and then refer the reader to
  2672. Figure~\ref{fig:interference-results} all the interference results.
  2673. The first instruction is \lstinline{movq $1, v}, so rule 3 applies,
  2674. and the live-after set is $\{v\}$. We do not add any interference
  2675. edges because the one live variable $v$ is also the destination of
  2676. this instruction.
  2677. %
  2678. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2679. again, and the live-after set is $\{v,w\}$. So the target $w$ of
  2680. \key{movq} interferes with $v$.
  2681. %
  2682. Next we skip forward to the instruction \lstinline{movq x, y}.
  2683. \begin{figure}[tbp]
  2684. \begin{quote}
  2685. \begin{tabular}{ll}
  2686. \lstinline!movq $1, v!& no interference by rule 3,\\
  2687. \lstinline!movq $42, w!& $w$ interferes with $v$ by rule 3,\\
  2688. \lstinline!movq v, x!& $x$ interferes with $w$ by rule 3,\\
  2689. \lstinline!addq $7, x!& $x$ interferes with $w$ by rule 1,\\
  2690. \lstinline!movq x, y!& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2691. \lstinline!movq x, z!& $z$ interferes with $w$ and $y$ by rule 3,\\
  2692. \lstinline!addq w, z!& $z$ interferes with $y$ by rule 1, \\
  2693. \lstinline!movq y, t!& $t$ interferes with $z$ by rule 3, \\
  2694. \lstinline!negq t!& $t$ interferes with $z$ by rule 1, \\
  2695. \lstinline!movq z, %rax! & no interference (ignore rax), \\
  2696. \lstinline!addq t, %rax! & no interference (ignore rax). \\
  2697. \lstinline!jmp conclusion!& no interference.
  2698. \end{tabular}
  2699. \end{quote}
  2700. \caption{Interference results for the running example.}
  2701. \label{fig:interference-results}
  2702. \end{figure}
  2703. The resulting interference graph is shown in
  2704. Figure~\ref{fig:interfere}.
  2705. \begin{figure}[tbp]
  2706. \large
  2707. \[
  2708. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2709. \node (t1) at (0,2) {$t$};
  2710. \node (z) at (3,2) {$z$};
  2711. \node (x) at (6,2) {$x$};
  2712. \node (y) at (3,0) {$y$};
  2713. \node (w) at (6,0) {$w$};
  2714. \node (v) at (9,0) {$v$};
  2715. \draw (t1) to (z);
  2716. \draw (z) to (y);
  2717. \draw (z) to (w);
  2718. \draw (x) to (w);
  2719. \draw (y) to (w);
  2720. \draw (v) to (w);
  2721. \end{tikzpicture}
  2722. \]
  2723. \caption{The interference graph of the example program.}
  2724. \label{fig:interfere}
  2725. \end{figure}
  2726. %% Our next concern is to choose a data structure for representing the
  2727. %% interference graph. There are many choices for how to represent a
  2728. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2729. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2730. %% data structure is to study the algorithm that uses the data structure,
  2731. %% determine what operations need to be performed, and then choose the
  2732. %% data structure that provide the most efficient implementations of
  2733. %% those operations. Often times the choice of data structure can have an
  2734. %% effect on the time complexity of the algorithm, as it does here. If
  2735. %% you skim the next section, you will see that the register allocation
  2736. %% algorithm needs to ask the graph for all of its vertices and, given a
  2737. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2738. %% correct choice of graph representation is that of an adjacency
  2739. %% list. There are helper functions in \code{utilities.rkt} for
  2740. %% representing graphs using the adjacency list representation:
  2741. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2742. %% (Appendix~\ref{appendix:utilities}).
  2743. %% %
  2744. %% \margincomment{\footnotesize To do: change to use the
  2745. %% Racket graph library. \\ --Jeremy}
  2746. %% %
  2747. %% In particular, those functions use a hash table to map each vertex to
  2748. %% the set of adjacent vertices, and the sets are represented using
  2749. %% Racket's \key{set}, which is also a hash table.
  2750. \begin{exercise}\normalfont
  2751. Implement the compiler pass named \code{build-interference} according
  2752. to the algorithm suggested above. We recommend using the \code{graph}
  2753. package to create and inspect the interference graph. The output
  2754. graph of this pass should be stored in the $\itm{info}$ field of the
  2755. program, under the key \code{conflicts}.
  2756. \end{exercise}
  2757. \section{Graph Coloring via Sudoku}
  2758. \label{sec:graph-coloring}
  2759. We come to the main event, mapping variables to registers (or to stack
  2760. locations in the event that we run out of registers). We need to make
  2761. sure that two variables do not get mapped to the same register if the
  2762. two variables interfere with each other. Thinking about the
  2763. interference graph, this means that adjacent vertices must be mapped
  2764. to different registers. If we think of registers as colors, the
  2765. register allocation problem becomes the widely-studied graph coloring
  2766. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2767. The reader may be more familiar with the graph coloring problem than he
  2768. or she realizes; the popular game of Sudoku is an instance of the
  2769. graph coloring problem. The following describes how to build a graph
  2770. out of an initial Sudoku board.
  2771. \begin{itemize}
  2772. \item There is one vertex in the graph for each Sudoku square.
  2773. \item There is an edge between two vertices if the corresponding squares
  2774. are in the same row, in the same column, or if the squares are in
  2775. the same $3\times 3$ region.
  2776. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2777. \item Based on the initial assignment of numbers to squares in the
  2778. Sudoku board, assign the corresponding colors to the corresponding
  2779. vertices in the graph.
  2780. \end{itemize}
  2781. If you can color the remaining vertices in the graph with the nine
  2782. colors, then you have also solved the corresponding game of Sudoku.
  2783. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2784. the corresponding graph with colored vertices. We map the Sudoku
  2785. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2786. sampling of the vertices (the colored ones) because showing edges for
  2787. all of the vertices would make the graph unreadable.
  2788. \begin{figure}[tbp]
  2789. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2790. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2791. \caption{A Sudoku game board and the corresponding colored graph.}
  2792. \label{fig:sudoku-graph}
  2793. \end{figure}
  2794. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2795. strategies to come up with an algorithm for allocating registers. For
  2796. example, one of the basic techniques for Sudoku is called Pencil
  2797. Marks. The idea is to use a process of elimination to determine what
  2798. numbers no longer make sense for a square and write down those
  2799. numbers in the square (writing very small). For example, if the number
  2800. $1$ is assigned to a square, then by process of elimination, you can
  2801. write the pencil mark $1$ in all the squares in the same row, column,
  2802. and region. Many Sudoku computer games provide automatic support for
  2803. Pencil Marks.
  2804. %
  2805. The Pencil Marks technique corresponds to the notion of
  2806. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2807. vertex, in Sudoku terms, is the set of numbers that are no longer
  2808. available. In graph terminology, we have the following definition:
  2809. \begin{equation*}
  2810. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2811. \text{ and } \mathrm{color}(v) = c \}
  2812. \end{equation*}
  2813. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2814. edge with $u$.
  2815. Using the Pencil Marks technique leads to a simple strategy for
  2816. filling in numbers: if there is a square with only one possible number
  2817. left, then choose that number! But what if there are no squares with
  2818. only one possibility left? One brute-force approach is to try them
  2819. all: choose the first and if it ultimately leads to a solution,
  2820. great. If not, backtrack and choose the next possibility. One good
  2821. thing about Pencil Marks is that it reduces the degree of branching in
  2822. the search tree. Nevertheless, backtracking can be horribly time
  2823. consuming. One way to reduce the amount of backtracking is to use the
  2824. most-constrained-first heuristic. That is, when choosing a square,
  2825. always choose one with the fewest possibilities left (the vertex with
  2826. the highest saturation). The idea is that choosing highly constrained
  2827. squares earlier rather than later is better because later on there may
  2828. not be any possibilities left for those squares.
  2829. However, register allocation is easier than Sudoku because the
  2830. register allocator can map variables to stack locations when the
  2831. registers run out. Thus, it makes sense to drop backtracking in favor
  2832. of greedy search, that is, make the best choice at the time and keep
  2833. going. We still wish to minimize the number of colors needed, so
  2834. keeping the most-constrained-first heuristic is a good idea.
  2835. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2836. algorithm for register allocation based on saturation and the
  2837. most-constrained-first heuristic. It is roughly equivalent to the
  2838. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2839. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2840. Sudoku, the algorithm represents colors with integers. The first $k$
  2841. colors corresponding to the $k$ registers in a given machine and the
  2842. rest of the integers corresponding to stack locations.
  2843. \begin{figure}[btp]
  2844. \centering
  2845. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2846. Algorithm: DSATUR
  2847. Input: a graph |$G$|
  2848. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2849. |$W \gets \mathit{vertices}(G)$|
  2850. while |$W \neq \emptyset$| do
  2851. pick a vertex |$u$| from |$W$| with the highest saturation,
  2852. breaking ties randomly
  2853. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2854. |$\mathrm{color}[u] \gets c$|
  2855. |$W \gets W - \{u\}$|
  2856. \end{lstlisting}
  2857. \caption{The saturation-based greedy graph coloring algorithm.}
  2858. \label{fig:satur-algo}
  2859. \end{figure}
  2860. With this algorithm in hand, let us return to the running example and
  2861. consider how to color the interference graph in
  2862. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2863. colored and they are unsaturated, so we annotate each of them with a
  2864. dash for their color and an empty set for the saturation.
  2865. \[
  2866. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2867. \node (t1) at (0,2) {$t:-,\{\}$};
  2868. \node (z) at (3,2) {$z:-,\{\}$};
  2869. \node (x) at (6,2) {$x:-,\{\}$};
  2870. \node (y) at (3,0) {$y:-,\{\}$};
  2871. \node (w) at (6,0) {$w:-,\{\}$};
  2872. \node (v) at (9,0) {$v:-,\{\}$};
  2873. \draw (t1) to (z);
  2874. \draw (z) to (y);
  2875. \draw (z) to (w);
  2876. \draw (x) to (w);
  2877. \draw (y) to (w);
  2878. \draw (v) to (w);
  2879. \end{tikzpicture}
  2880. \]
  2881. The algorithm says to select a maximally saturated vertex and color it
  2882. $0$. In this case we have a 6-way tie, so we arbitrarily pick
  2883. $t$. We then mark color $0$ as no longer available for $z$ because
  2884. it interferes with $t$.
  2885. \[
  2886. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2887. \node (t1) at (0,2) {$t:0,\{\}$};
  2888. \node (z) at (3,2) {$z:-,\{0\}$};
  2889. \node (x) at (6,2) {$x:-,\{\}$};
  2890. \node (y) at (3,0) {$y:-,\{\}$};
  2891. \node (w) at (6,0) {$w:-,\{\}$};
  2892. \node (v) at (9,0) {$v:-,\{\}$};
  2893. \draw (t1) to (z);
  2894. \draw (z) to (y);
  2895. \draw (z) to (w);
  2896. \draw (x) to (w);
  2897. \draw (y) to (w);
  2898. \draw (v) to (w);
  2899. \end{tikzpicture}
  2900. \]
  2901. Next we repeat the process, selecting another maximally saturated
  2902. vertex, which is $z$, and color it with the first available number,
  2903. which is $1$.
  2904. \[
  2905. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2906. \node (t1) at (0,2) {$t:0,\{1\}$};
  2907. \node (z) at (3,2) {$z:1,\{0\}$};
  2908. \node (x) at (6,2) {$x:-,\{\}$};
  2909. \node (y) at (3,0) {$y:-,\{1\}$};
  2910. \node (w) at (6,0) {$w:-,\{1\}$};
  2911. \node (v) at (9,0) {$v:-,\{\}$};
  2912. \draw (t1) to (z);
  2913. \draw (z) to (y);
  2914. \draw (z) to (w);
  2915. \draw (x) to (w);
  2916. \draw (y) to (w);
  2917. \draw (v) to (w);
  2918. \end{tikzpicture}
  2919. \]
  2920. The most saturated vertices are now $w$ and $y$. We color $w$ with the
  2921. first available color, which is $0$.
  2922. \[
  2923. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2924. \node (t1) at (0,2) {$t:0,\{1\}$};
  2925. \node (z) at (3,2) {$z:1,\{0\}$};
  2926. \node (x) at (6,2) {$x:-,\{0\}$};
  2927. \node (y) at (3,0) {$y:-,\{0,1\}$};
  2928. \node (w) at (6,0) {$w:0,\{1\}$};
  2929. \node (v) at (9,0) {$v:-,\{0\}$};
  2930. \draw (t1) to (z);
  2931. \draw (z) to (y);
  2932. \draw (z) to (w);
  2933. \draw (x) to (w);
  2934. \draw (y) to (w);
  2935. \draw (v) to (w);
  2936. \end{tikzpicture}
  2937. \]
  2938. Vertex $y$ is now the most highly saturated, so we color $y$ with $2$.
  2939. We cannot choose $0$ or $1$ because those numbers are in $y$'s
  2940. saturation set. Indeed, $y$ interferes with $w$ and $z$, whose colors
  2941. are $0$ and $1$ respectively.
  2942. \[
  2943. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2944. \node (t1) at (0,2) {$t:0,\{1\}$};
  2945. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2946. \node (x) at (6,2) {$x:-,\{0\}$};
  2947. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2948. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2949. \node (v) at (9,0) {$v:-,\{0\}$};
  2950. \draw (t1) to (z);
  2951. \draw (z) to (y);
  2952. \draw (z) to (w);
  2953. \draw (x) to (w);
  2954. \draw (y) to (w);
  2955. \draw (v) to (w);
  2956. \end{tikzpicture}
  2957. \]
  2958. Now $x$ and $v$ are the most saturated, so we color $v$ it $1$.
  2959. \[
  2960. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2961. \node (t1) at (0,2) {$t:0,\{1\}$};
  2962. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2963. \node (x) at (6,2) {$x:-,\{0\}$};
  2964. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2965. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2966. \node (v) at (9,0) {$v:1,\{0\}$};
  2967. \draw (t1) to (z);
  2968. \draw (z) to (y);
  2969. \draw (z) to (w);
  2970. \draw (x) to (w);
  2971. \draw (y) to (w);
  2972. \draw (v) to (w);
  2973. \end{tikzpicture}
  2974. \]
  2975. In the last step of the algorithm, we color $x$ with $1$.
  2976. \[
  2977. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2978. \node (t1) at (0,2) {$t:0,\{1,\}$};
  2979. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2980. \node (x) at (6,2) {$x:1,\{0\}$};
  2981. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2982. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2983. \node (v) at (9,0) {$v:1,\{0\}$};
  2984. \draw (t1) to (z);
  2985. \draw (z) to (y);
  2986. \draw (z) to (w);
  2987. \draw (x) to (w);
  2988. \draw (y) to (w);
  2989. \draw (v) to (w);
  2990. \end{tikzpicture}
  2991. \]
  2992. With the coloring complete, we finalize the assignment of variables to
  2993. registers and stack locations. Recall that if we have $k$ registers,
  2994. we map the first $k$ colors to registers and the rest to stack
  2995. locations. Suppose for the moment that we have just one register to
  2996. use for register allocation, \key{rcx}. Then the following is the
  2997. mapping of colors to registers and stack allocations.
  2998. \[
  2999. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3000. \]
  3001. Putting this mapping together with the above coloring of the
  3002. variables, we arrive at the following assignment of variables to
  3003. registers and stack locations.
  3004. \begin{gather*}
  3005. \{ v \mapsto \key{\%rcx}, \,
  3006. w \mapsto \key{\%rcx}, \,
  3007. x \mapsto \key{-8(\%rbp)}, \\
  3008. y \mapsto \key{-16(\%rbp)}, \,
  3009. z\mapsto \key{-8(\%rbp)},
  3010. t\mapsto \key{\%rcx} \}
  3011. \end{gather*}
  3012. Applying this assignment to our running example, on the left, yields
  3013. the program on the right.
  3014. % why frame size of 32? -JGS
  3015. \begin{center}
  3016. \begin{minipage}{0.3\textwidth}
  3017. \begin{lstlisting}
  3018. movq $1, v
  3019. movq $42, w
  3020. movq v, x
  3021. addq $7, x
  3022. movq x, y
  3023. movq x, z
  3024. addq w, z
  3025. movq y, t
  3026. negq t
  3027. movq z, %rax
  3028. addq t, %rax
  3029. jmp conclusion
  3030. \end{lstlisting}
  3031. \end{minipage}
  3032. $\Rightarrow\qquad$
  3033. \begin{minipage}{0.45\textwidth}
  3034. \begin{lstlisting}
  3035. movq $1, %rcx
  3036. movq $42, %rcx
  3037. movq %rcx, -8(%rbp)
  3038. addq $7, -8(%rbp)
  3039. movq -8(%rbp), -16(%rbp)
  3040. movq -8(%rbp), -8(%rbp)
  3041. addq %rcx, -8(%rbp)
  3042. movq -16(%rbp), %rcx
  3043. negq %rcx
  3044. movq -8(%rbp), %rax
  3045. addq %rcx, %rax
  3046. jmp conclusion
  3047. \end{lstlisting}
  3048. \end{minipage}
  3049. \end{center}
  3050. The resulting program is almost an x86 program. The remaining step is
  3051. the patch instructions pass. In this example, the trivial move of
  3052. \code{-8(\%rbp)} to itself is deleted and the addition of
  3053. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3054. \code{rax} as follows.
  3055. \begin{lstlisting}
  3056. movq -8(%rbp), %rax
  3057. addq %rax, -16(%rbp)
  3058. \end{lstlisting}
  3059. An overview of all of the passes involved in register allocation is
  3060. shown in Figure~\ref{fig:reg-alloc-passes}.
  3061. \begin{figure}[tbp]
  3062. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3063. \node (R1) at (0,2) {\large $R_1$};
  3064. \node (R1-2) at (3,2) {\large $R_1$};
  3065. \node (R1-3) at (6,2) {\large $R_1$};
  3066. \node (C0-1) at (3,0) {\large $C_0$};
  3067. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3068. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3069. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3070. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3071. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3072. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3073. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3074. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3075. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3076. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3077. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3078. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3079. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3080. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3081. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3082. \end{tikzpicture}
  3083. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3084. \label{fig:reg-alloc-passes}
  3085. \end{figure}
  3086. \begin{exercise}\normalfont
  3087. Implement the pass \code{allocate-registers}, which should come
  3088. after the \code{build-interference} pass. The three new passes,
  3089. \code{uncover-live}, \code{build-interference}, and
  3090. \code{allocate-registers} replace the \code{assign-homes} pass of
  3091. Section~\ref{sec:assign-r1}.
  3092. We recommend that you create a helper function named
  3093. \code{color-graph} that takes an interference graph and a list of
  3094. all the variables in the program. This function should return a
  3095. mapping of variables to their colors (represented as natural
  3096. numbers). By creating this helper function, you will be able to
  3097. reuse it in Chapter~\ref{ch:functions} when you add support for
  3098. functions. The support code includes an implementation of the
  3099. priority queue data structure in the file
  3100. \code{priority\_queue.rkt}, which might come in handy for
  3101. prioritizing highly saturated nodes inside your \code{color-graph}
  3102. function.
  3103. Once you have obtained the coloring from \code{color-graph}, you can
  3104. assign the variables to registers or stack locations and then reuse
  3105. code from the \code{assign-homes} pass from
  3106. Section~\ref{sec:assign-r1} to replace the variables with their
  3107. assigned location.
  3108. Test your updated compiler by creating new example programs that
  3109. exercise all of the register allocation algorithm, such as forcing
  3110. variables to be spilled to the stack.
  3111. \end{exercise}
  3112. \section{Print x86 and Conventions for Registers}
  3113. \label{sec:print-x86-reg-alloc}
  3114. Recall that the \code{print-x86} pass generates the prelude and
  3115. conclusion instructions for the \code{main} function.
  3116. %
  3117. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3118. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3119. reason for this is that our \code{main} function must adhere to the
  3120. x86 calling conventions that we described in
  3121. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3122. allocator assigned variables to other callee-saved registers
  3123. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3124. saved to the stack in the prelude and restored in the conclusion. The
  3125. simplest approach is to save and restore all of the callee-saved
  3126. registers. The more efficient approach is to keep track of which
  3127. callee-saved registers were used and only save and restore
  3128. them. Either way, make sure to take this use of stack space into
  3129. account when you are calculating the size of the frame and adjusting
  3130. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3131. frame needs to be a multiple of 16 bytes!
  3132. \section{Challenge: Move Biasing}
  3133. \label{sec:move-biasing}
  3134. This section describes an optional enhancement to register allocation
  3135. for those students who are looking for an extra challenge or who have
  3136. a deeper interest in register allocation.
  3137. We return to the running example, but we remove the supposition that
  3138. we only have one register to use. So we have the following mapping of
  3139. color numbers to registers.
  3140. \[
  3141. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3142. \]
  3143. Using the same assignment of variables to color numbers that was
  3144. produced by the register allocator described in the last section, we
  3145. get the following program.
  3146. \begin{minipage}{0.3\textwidth}
  3147. \begin{lstlisting}
  3148. movq $1, v
  3149. movq $42, w
  3150. movq v, x
  3151. addq $7, x
  3152. movq x, y
  3153. movq x, z
  3154. addq w, z
  3155. movq y, t
  3156. negq t
  3157. movq z, %rax
  3158. addq t, %rax
  3159. jmp conclusion
  3160. \end{lstlisting}
  3161. \end{minipage}
  3162. $\Rightarrow\qquad$
  3163. \begin{minipage}{0.45\textwidth}
  3164. \begin{lstlisting}
  3165. movq $1, %rcx
  3166. movq $42, $rbx
  3167. movq %rcx, %rcx
  3168. addq $7, %rcx
  3169. movq %rcx, %rdx
  3170. movq %rcx, %rcx
  3171. addq %rbx, %rcx
  3172. movq %rdx, %rbx
  3173. negq %rbx
  3174. movq %rcx, %rax
  3175. addq %rbx, %rax
  3176. jmp conclusion
  3177. \end{lstlisting}
  3178. \end{minipage}
  3179. In the above output code there are two \key{movq} instructions that
  3180. can be removed because their source and target are the same. However,
  3181. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3182. register, we could instead remove three \key{movq} instructions. We
  3183. can accomplish this by taking into account which variables appear in
  3184. \key{movq} instructions with which other variables.
  3185. We say that two variables $p$ and $q$ are \emph{move related} if they
  3186. participate together in a \key{movq} instruction, that is, \key{movq}
  3187. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  3188. allocator chooses a color for a variable, it should prefer a color
  3189. that has already been used for a move-related variable (assuming that
  3190. they do not interfere). Of course, this preference should not override
  3191. the preference for registers over stack locations. This preference
  3192. should be used as a tie breaker when choosing between registers or
  3193. when choosing between stack locations.
  3194. We recommend representing the move relationships in a graph, similar
  3195. to how we represented interference. The following is the \emph{move
  3196. graph} for our running example.
  3197. \[
  3198. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3199. \node (t) at (0,2) {$t$};
  3200. \node (z) at (3,2) {$z$};
  3201. \node (x) at (6,2) {$x$};
  3202. \node (y) at (3,0) {$y$};
  3203. \node (w) at (6,0) {$w$};
  3204. \node (v) at (9,0) {$v$};
  3205. \draw (v) to (x);
  3206. \draw (x) to (y);
  3207. \draw (x) to (z);
  3208. \draw (y) to (t);
  3209. \end{tikzpicture}
  3210. \]
  3211. Now we replay the graph coloring, pausing to see the coloring of
  3212. $y$. Recall the following configuration. The most saturated vertices
  3213. were $w$ and $y$.
  3214. \[
  3215. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3216. \node (t1) at (0,2) {$t:0,\{1\}$};
  3217. \node (z) at (3,2) {$z:1,\{0\}$};
  3218. \node (x) at (6,2) {$x:-,\{\}$};
  3219. \node (y) at (3,0) {$y:-,\{1\}$};
  3220. \node (w) at (6,0) {$w:-,\{1\}$};
  3221. \node (v) at (9,0) {$v:-,\{\}$};
  3222. \draw (t1) to (z);
  3223. \draw (z) to (y);
  3224. \draw (z) to (w);
  3225. \draw (x) to (w);
  3226. \draw (y) to (w);
  3227. \draw (v) to (w);
  3228. \end{tikzpicture}
  3229. \]
  3230. %
  3231. Last time we chose to color $w$ with $0$. But this time we note that
  3232. $w$ is not move related to any vertex, and $y$ is move related to $t$.
  3233. So we choose to color $y$ the same color, $0$.
  3234. \[
  3235. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3236. \node (t1) at (0,2) {$t:0,\{1\}$};
  3237. \node (z) at (3,2) {$z:1,\{0\}$};
  3238. \node (x) at (6,2) {$x:-,\{\}$};
  3239. \node (y) at (3,0) {$y:0,\{1\}$};
  3240. \node (w) at (6,0) {$w:-,\{0,1\}$};
  3241. \node (v) at (9,0) {$v:-,\{\}$};
  3242. \draw (t1) to (z);
  3243. \draw (z) to (y);
  3244. \draw (z) to (w);
  3245. \draw (x) to (w);
  3246. \draw (y) to (w);
  3247. \draw (v) to (w);
  3248. \end{tikzpicture}
  3249. \]
  3250. Now $w$ is the most saturated, so we color it $2$.
  3251. \[
  3252. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3253. \node (t1) at (0,2) {$t:0,\{1\}$};
  3254. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3255. \node (x) at (6,2) {$x:-,\{2\}$};
  3256. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3257. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3258. \node (v) at (9,0) {$v:-,\{2\}$};
  3259. \draw (t1) to (z);
  3260. \draw (z) to (y);
  3261. \draw (z) to (w);
  3262. \draw (x) to (w);
  3263. \draw (y) to (w);
  3264. \draw (v) to (w);
  3265. \end{tikzpicture}
  3266. \]
  3267. At this point, vertices $x$ and $v$ are most saturated,
  3268. but $x$ is move related to $y$ and $z$, so we color $x$ to $0$
  3269. to match $y$. Finally, we color $v$ to $0$.
  3270. \[
  3271. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3272. \node (t) at (0,2) {$t:0,\{1\}$};
  3273. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3274. \node (x) at (6,2) {$x:0,\{2\}$};
  3275. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3276. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3277. \node (v) at (9,0) {$v:0,\{2\}$};
  3278. \draw (t) to (z);
  3279. \draw (z) to (y);
  3280. \draw (z) to (w);
  3281. \draw (x) to (w);
  3282. \draw (y) to (w);
  3283. \draw (v) to (w);
  3284. \end{tikzpicture}
  3285. \]
  3286. So we have the following assignment of variables to registers.
  3287. \begin{gather*}
  3288. \{ v \mapsto \key{\%rbx}, \,
  3289. w \mapsto \key{\%rdx}, \,
  3290. x \mapsto \key{\%rbx}, \\
  3291. y \mapsto \key{\%rbx}, \,
  3292. z\mapsto \key{\%rcx},
  3293. t\mapsto \key{\%rbx} \}
  3294. \end{gather*}
  3295. We apply this register assignment to the running example, on the left,
  3296. to obtain the code on right.
  3297. \begin{minipage}{0.3\textwidth}
  3298. \begin{lstlisting}
  3299. movq $1, v
  3300. movq $42, w
  3301. movq v, x
  3302. addq $7, x
  3303. movq x, y
  3304. movq x, z
  3305. addq w, z
  3306. movq y, t
  3307. negq t
  3308. movq z, %rax
  3309. addq t, %rax
  3310. jmp conclusion
  3311. \end{lstlisting}
  3312. \end{minipage}
  3313. $\Rightarrow\qquad$
  3314. \begin{minipage}{0.45\textwidth}
  3315. \begin{lstlisting}
  3316. movq $1, %rbx
  3317. movq $42, %rdx
  3318. movq %rbx, %rbx
  3319. addq $7, %rbx
  3320. movq %rbx, %rbx
  3321. movq %rbx, %rcx
  3322. addq %rdx, %rcx
  3323. movq %rbx, %rbx
  3324. negq %rbx
  3325. movq %rcx, %rax
  3326. addq %rbx, %rax
  3327. jmp conclusion
  3328. \end{lstlisting}
  3329. \end{minipage}
  3330. The \code{patch-instructions} then removes the three trivial moves
  3331. from \key{rbx} to \key{rbx} to obtain the following result.
  3332. \begin{minipage}{0.45\textwidth}
  3333. \begin{lstlisting}
  3334. movq $1, %rbx
  3335. movq $42, %rdx
  3336. addq $7, %rbx
  3337. movq %rbx, %rcx
  3338. addq %rdx, %rcx
  3339. negq %rbx
  3340. movq %rcx, %rax
  3341. addq %rbx, %rax
  3342. jmp conclusion
  3343. \end{lstlisting}
  3344. \end{minipage}
  3345. \begin{exercise}\normalfont
  3346. Change your implementation of \code{allocate-registers} to take move
  3347. biasing into account. Make sure that your compiler still passes all of
  3348. the previous tests. Create two new tests that include at least one
  3349. opportunity for move biasing and visually inspect the output x86
  3350. programs to make sure that your move biasing is working properly.
  3351. \end{exercise}
  3352. \margincomment{\footnotesize To do: another neat challenge would be to do
  3353. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3354. \section{Output of the Running Example}
  3355. \label{sec:reg-alloc-output}
  3356. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3357. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3358. and move biasing. To demonstrate both the use of registers and the
  3359. stack, we have limited the register allocator to use just two
  3360. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3361. \code{main} function, we push \code{rbx} onto the stack because it is
  3362. a callee-saved register and it was assigned to variable by the
  3363. register allocator. We substract \code{8} from the \code{rsp} at the
  3364. end of the prelude to reserve space for the one spilled variable.
  3365. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3366. Moving on the the \code{start} block, we see how the registers were
  3367. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3368. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3369. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3370. that the prelude saved the callee-save register \code{rbx} onto the
  3371. stack. The spilled variables must be placed lower on the stack than
  3372. the saved callee-save registers, so in this case \code{w} is placed at
  3373. \code{-16(\%rbp)}.
  3374. In the \code{conclusion}, we undo the work that was done in the
  3375. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3376. spilled variables), then we pop the old values of \code{rbx} and
  3377. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3378. return control to the operating system.
  3379. \begin{figure}[tbp]
  3380. % s0_28.rkt
  3381. % (use-minimal-set-of-registers! #t)
  3382. % and only rbx rcx
  3383. % tmp 0 rbx
  3384. % z 1 rcx
  3385. % y 0 rbx
  3386. % w 2 16(%rbp)
  3387. % v 0 rbx
  3388. % x 0 rbx
  3389. \begin{lstlisting}
  3390. start:
  3391. movq $1, %rbx
  3392. movq $42, -16(%rbp)
  3393. addq $7, %rbx
  3394. movq %rbx, %rcx
  3395. addq -16(%rbp), %rcx
  3396. negq %rbx
  3397. movq %rcx, %rax
  3398. addq %rbx, %rax
  3399. jmp conclusion
  3400. .globl main
  3401. main:
  3402. pushq %rbp
  3403. movq %rsp, %rbp
  3404. pushq %rbx
  3405. subq $8, %rsp
  3406. jmp start
  3407. conclusion:
  3408. addq $8, %rsp
  3409. popq %rbx
  3410. popq %rbp
  3411. retq
  3412. \end{lstlisting}
  3413. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3414. \label{fig:running-example-x86}
  3415. \end{figure}
  3416. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3417. \chapter{Booleans and Control Flow}
  3418. \label{ch:bool-types}
  3419. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3420. integers. In this chapter we add a second kind of value, the Booleans,
  3421. to create the $R_2$ language. The Boolean values \emph{true} and
  3422. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3423. Racket. The $R_2$ language includes several operations that involve
  3424. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3425. conditional \key{if} expression. With the addition of \key{if}
  3426. expressions, programs can have non-trivial control flow which which
  3427. significantly impacts the \code{explicate-control} and the liveness
  3428. analysis for register allocation. Also, because we now have two kinds
  3429. of values, we need to handle programs that apply an operation to the
  3430. wrong kind of value, such as \code{(not 1)}.
  3431. There are two language design options for such situations. One option
  3432. is to signal an error and the other is to provide a wider
  3433. interpretation of the operation. The Racket language uses a mixture of
  3434. these two options, depending on the operation and the kind of
  3435. value. For example, the result of \code{(not 1)} in Racket is
  3436. \code{\#f} because Racket treats non-zero integers as if they were
  3437. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3438. error in Racket stating that \code{car} expects a pair.
  3439. The Typed Racket language makes similar design choices as Racket,
  3440. except much of the error detection happens at compile time instead of
  3441. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3442. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3443. reports a compile-time error because Typed Racket expects the type of
  3444. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3445. For the $R_2$ language we choose to be more like Typed Racket in that
  3446. we shall perform type checking during compilation. In
  3447. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3448. is, how to compile a dynamically typed language like Racket. The
  3449. $R_2$ language is a subset of Typed Racket but by no means includes
  3450. all of Typed Racket. For many operations we take a narrower
  3451. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3452. This chapter is organized as follows. We begin by defining the syntax
  3453. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3454. then introduce the idea of type checking and build a type checker for
  3455. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3456. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3457. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3458. how our compiler passes need to change to accommodate Booleans and
  3459. conditional control flow.
  3460. \section{The $R_2$ Language}
  3461. \label{sec:r2-lang}
  3462. The concrete syntax of the $R_2$ language is defined in
  3463. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3464. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3465. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3466. and the conditional \code{if} expression. Also, we expand the
  3467. operators to include
  3468. \begin{enumerate}
  3469. \item subtraction on integers,
  3470. \item the logical operators \key{and}, \key{or} and \key{not},
  3471. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3472. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3473. comparing integers.
  3474. \end{enumerate}
  3475. \begin{figure}[tp]
  3476. \centering
  3477. \fbox{
  3478. \begin{minipage}{0.96\textwidth}
  3479. \[
  3480. \begin{array}{lcl}
  3481. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3482. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3483. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3484. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3485. &\mid& \itm{bool}
  3486. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3487. \mid (\key{not}\;\Exp) \\
  3488. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3489. R_2 &::=& \Exp
  3490. \end{array}
  3491. \]
  3492. \end{minipage}
  3493. }
  3494. \caption{The concrete syntax of $R_2$, extending $R_1$
  3495. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3496. \label{fig:r2-concrete-syntax}
  3497. \end{figure}
  3498. \begin{figure}[tp]
  3499. \centering
  3500. \fbox{
  3501. \begin{minipage}{0.96\textwidth}
  3502. \[
  3503. \begin{array}{lcl}
  3504. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3505. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3506. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3507. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3508. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3509. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3510. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3511. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3512. &\mid& \BINOP{\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3513. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3514. \end{array}
  3515. \]
  3516. \end{minipage}
  3517. }
  3518. \caption{The abstract syntax of $R_2$.}
  3519. \label{fig:r2-syntax}
  3520. \end{figure}
  3521. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3522. the parts that are the same as the interpreter for $R_1$
  3523. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3524. evaluate to the corresponding Boolean values. The conditional
  3525. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3526. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3527. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3528. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3529. you might expect, but note that the \code{and} operation is
  3530. short-circuiting. That is, given the expression
  3531. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3532. $e_1$ evaluates to \code{\#f}.
  3533. With the addition of the comparison operations, there are quite a few
  3534. primitive operations and the interpreter code for them could become
  3535. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3536. out the different parts of the code for primitive operations into the
  3537. \code{interp-op} function and the similar parts of the code into the
  3538. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3539. do not use \code{interp-op} for the \code{and} operation because of
  3540. the short-circuiting behavior in the order of evaluation of its
  3541. arguments.
  3542. \begin{figure}[tbp]
  3543. \begin{lstlisting}
  3544. (define (interp-op op)
  3545. (match op
  3546. ...
  3547. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3548. ['eq? (lambda (v1 v2)
  3549. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3550. (and (boolean? v1) (boolean? v2)))
  3551. (eq? v1 v2)]))]
  3552. ['< (lambda (v1 v2)
  3553. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3554. ['<= (lambda (v1 v2)
  3555. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3556. ['> (lambda (v1 v2)
  3557. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3558. ['>= (lambda (v1 v2)
  3559. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3560. [else (error 'interp-op "unknown operator")]))
  3561. (define (interp-exp env)
  3562. (lambda (e)
  3563. (define recur (interp-exp env))
  3564. (match e
  3565. ...
  3566. [(Bool b) b]
  3567. [(If cnd thn els)
  3568. (define b (recur cnd))
  3569. (match b
  3570. [#t (recur thn)]
  3571. [#f (recur els)])]
  3572. [(Prim 'and (list e1 e2))
  3573. (define v1 (recur e1))
  3574. (match v1
  3575. [#t (match (recur e2) [#t #t] [#f #f])]
  3576. [#f #f])]
  3577. [(Prim op args)
  3578. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3579. )))
  3580. (define (interp-R2 p)
  3581. (match p
  3582. [(Program info e)
  3583. ((interp-exp '()) e)]
  3584. ))
  3585. \end{lstlisting}
  3586. \caption{Interpreter for the $R_2$ language.}
  3587. \label{fig:interp-R2}
  3588. \end{figure}
  3589. \section{Type Checking $R_2$ Programs}
  3590. \label{sec:type-check-r2}
  3591. It is helpful to think about type checking in two complementary
  3592. ways. A type checker predicts the type of value that will be produced
  3593. by each expression in the program. For $R_2$, we have just two types,
  3594. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3595. \begin{lstlisting}
  3596. (+ 10 (- (+ 12 20)))
  3597. \end{lstlisting}
  3598. produces an \key{Integer} while
  3599. \begin{lstlisting}
  3600. (and (not #f) #t)
  3601. \end{lstlisting}
  3602. produces a \key{Boolean}.
  3603. Another way to think about type checking is that it enforces a set of
  3604. rules about which operators can be applied to which kinds of
  3605. values. For example, our type checker for $R_2$ will signal an error
  3606. for the below expression because, as we have seen above, the
  3607. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3608. checker enforces the rule that the argument of \code{not} must be a
  3609. \key{Boolean}.
  3610. \begin{lstlisting}
  3611. (not (+ 10 (- (+ 12 20))))
  3612. \end{lstlisting}
  3613. The type checker for $R_2$ is a structurally recursive function over
  3614. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3615. the \code{type-check-exp} function. Given an input expression
  3616. \code{e}, the type checker either returns a type (\key{Integer} or
  3617. \key{Boolean}) or it signals an error. The type of an integer literal
  3618. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3619. To handle variables, the type checker uses an environment that maps
  3620. variables to types. Consider the clause for \key{let}. We type check
  3621. the initializing expression to obtain its type \key{T} and then
  3622. associate type \code{T} with the variable \code{x} in the
  3623. environment. When the type checker encounters a use of variable
  3624. \code{x} in the body of the \key{let}, it can find its type in the
  3625. environment.
  3626. \begin{figure}[tbp]
  3627. \begin{lstlisting}
  3628. (define (type-check-exp env)
  3629. (lambda (e)
  3630. (match e
  3631. [(Var x) (dict-ref env x)]
  3632. [(Int n) 'Integer]
  3633. [(Bool b) 'Boolean]
  3634. [(Let x e body)
  3635. (define Te ((type-check-exp env) e))
  3636. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3637. Tb]
  3638. ...
  3639. [else
  3640. (error "type-check-exp couldn't match" e)])))
  3641. (define (type-check env)
  3642. (lambda (e)
  3643. (match e
  3644. [(Program info body)
  3645. (define Tb ((type-check-exp '()) body))
  3646. (unless (equal? Tb 'Integer)
  3647. (error "result of the program must be an integer, not " Tb))
  3648. (Program info body)]
  3649. )))
  3650. \end{lstlisting}
  3651. \caption{Skeleton of a type checker for the $R_2$ language.}
  3652. \label{fig:type-check-R2}
  3653. \end{figure}
  3654. \begin{exercise}\normalfont
  3655. Complete the implementation of \code{type-check}. Test your type
  3656. checker using \code{interp-tests} and \code{compiler-tests} by passing
  3657. the \code{type-check} function as the second argument. Create 10 new
  3658. example programs in $R_2$ that you choose based on how thoroughly they
  3659. test you type checking function. Half of the example programs should
  3660. have a type error to make sure that your type checker properly rejects
  3661. them. For those programs, to signal that a type error is expected,
  3662. create an empty file with the same base name but with file extension
  3663. \code{.tyerr}. For example, if the test \code{r2\_14.rkt} is expected
  3664. to error, then create an empty file named \code{r2\_14.tyerr}. The
  3665. other half of the example programs should not have type errors. Note
  3666. that if your type checker does not signal an error for a program, then
  3667. interpreting that program should not encounter an error. If it does,
  3668. there is something wrong with your type checker.
  3669. \end{exercise}
  3670. \section{Shrink the $R_2$ Language}
  3671. \label{sec:shrink-r2}
  3672. The $R_2$ language includes several operators that are easily
  3673. expressible in terms of other operators. For example, subtraction is
  3674. expressible in terms of addition and negation.
  3675. \[
  3676. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3677. \]
  3678. Several of the comparison operations are expressible in terms of
  3679. less-than and logical negation.
  3680. \[
  3681. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3682. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3683. \]
  3684. The \key{let} is needed in the above translation to ensure that
  3685. expression $e_1$ is evaluated before $e_2$.
  3686. By performing these translations near the front-end of the compiler,
  3687. the later passes of the compiler do not need to deal with these
  3688. constructs, making those passes shorter. On the other hand, sometimes
  3689. these translations make it more difficult to generate the most
  3690. efficient code with respect to the number of instructions. However,
  3691. these differences typically do not affect the number of accesses to
  3692. memory, which is the primary factor that determines execution time on
  3693. modern computer architectures.
  3694. \begin{exercise}\normalfont
  3695. Implement the pass \code{shrink} that removes subtraction,
  3696. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3697. by translating them to other constructs in $R_2$. Create tests to
  3698. make sure that the behavior of all of these constructs stays the
  3699. same after translation.
  3700. \end{exercise}
  3701. \section{The x86$_1$ Language}
  3702. \label{sec:x86-1}
  3703. To implement the new logical operations, the comparison operations,
  3704. and the \key{if} expression, we need to delve further into the x86
  3705. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3706. the concrete and abstract syntax for a larger subset of x86 that
  3707. includes instructions for logical operations, comparisons, and
  3708. conditional jumps.
  3709. One small challenge is that x86 does not provide an instruction that
  3710. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3711. However, the \code{xorq} instruction can be used to encode \code{not}.
  3712. The \key{xorq} instruction takes two arguments, performs a pairwise
  3713. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3714. and writes the results into its second argument. Recall the truth
  3715. table for exclusive-or:
  3716. \begin{center}
  3717. \begin{tabular}{l|cc}
  3718. & 0 & 1 \\ \hline
  3719. 0 & 0 & 1 \\
  3720. 1 & 1 & 0
  3721. \end{tabular}
  3722. \end{center}
  3723. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3724. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3725. for the bit $1$, the result is the opposite of the second bit. Thus,
  3726. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3727. the first argument:
  3728. \[
  3729. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3730. \qquad\Rightarrow\qquad
  3731. \begin{array}{l}
  3732. \key{movq}~ \Arg\key{,} \Var\\
  3733. \key{xorq}~ \key{\$1,} \Var
  3734. \end{array}
  3735. \]
  3736. \begin{figure}[tp]
  3737. \fbox{
  3738. \begin{minipage}{0.96\textwidth}
  3739. \[
  3740. \begin{array}{lcl}
  3741. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3742. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3743. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3744. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3745. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3746. \key{subq} \; \Arg\key{,} \Arg \mid
  3747. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3748. && \gray{ \key{callq} \; \itm{label} \mid
  3749. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3750. && \gray{ \itm{label}\key{:}\; \Instr }
  3751. \mid \key{xorq}~\Arg\key{,}~\Arg
  3752. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3753. && \key{set}cc~\Arg
  3754. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3755. \mid \key{j}cc~\itm{label}
  3756. \\
  3757. x86_1 &::= & \gray{ \key{.globl main} }\\
  3758. & & \gray{ \key{main:} \; \Instr\ldots }
  3759. \end{array}
  3760. \]
  3761. \end{minipage}
  3762. }
  3763. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3764. \label{fig:x86-1-concrete}
  3765. \end{figure}
  3766. \begin{figure}[tp]
  3767. \fbox{
  3768. \begin{minipage}{0.96\textwidth}
  3769. \small
  3770. \[
  3771. \begin{array}{lcl}
  3772. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3773. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3774. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3775. \mid \BYTEREG{\itm{bytereg}} \\
  3776. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3777. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3778. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3779. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3780. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3781. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3782. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3783. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3784. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3785. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3786. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3787. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3788. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3789. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3790. \end{array}
  3791. \]
  3792. \end{minipage}
  3793. }
  3794. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3795. \label{fig:x86-1}
  3796. \end{figure}
  3797. Next we consider the x86 instructions that are relevant for compiling
  3798. the comparison operations. The \key{cmpq} instruction compares its two
  3799. arguments to determine whether one argument is less than, equal, or
  3800. greater than the other argument. The \key{cmpq} instruction is unusual
  3801. regarding the order of its arguments and where the result is
  3802. placed. The argument order is backwards: if you want to test whether
  3803. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3804. \key{cmpq} is placed in the special EFLAGS register. This register
  3805. cannot be accessed directly but it can be queried by a number of
  3806. instructions, including the \key{set} instruction. The \key{set}
  3807. instruction puts a \key{1} or \key{0} into its destination depending
  3808. on whether the comparison came out according to the condition code
  3809. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3810. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3811. The \key{set} instruction has an annoying quirk in that its
  3812. destination argument must be single byte register, such as \code{al}
  3813. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  3814. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  3815. then be used to move from a single byte register to a normal 64-bit
  3816. register.
  3817. The x86 instruction for conditional jump are relevant to the
  3818. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3819. updates the program counter to point to the instruction after the
  3820. indicated label depending on whether the result in the EFLAGS register
  3821. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3822. instruction falls through to the next instruction. The abstract
  3823. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3824. that it separates the instruction name from the condition code. For
  3825. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3826. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3827. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3828. instruction to set the EFLAGS register.
  3829. \section{The $C_1$ Intermediate Language}
  3830. \label{sec:c1}
  3831. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3832. we need to grow that intermediate language to handle the new features
  3833. in $R_2$: Booleans and conditional expressions.
  3834. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3835. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3836. particular, we add logical and comparison operators to the $\Exp$
  3837. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3838. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3839. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3840. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3841. sequence of statements may now end with a \code{goto} or a conditional
  3842. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3843. depending on the outcome of the comparison. In
  3844. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3845. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3846. and \key{goto}'s.
  3847. \begin{figure}[tbp]
  3848. \fbox{
  3849. \begin{minipage}{0.96\textwidth}
  3850. \small
  3851. \[
  3852. \begin{array}{lcl}
  3853. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3854. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3855. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3856. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3857. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3858. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3859. \mid \key{goto}~\itm{label}\key{;}\\
  3860. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3861. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  3862. \end{array}
  3863. \]
  3864. \end{minipage}
  3865. }
  3866. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3867. \label{fig:c1-concrete-syntax}
  3868. \end{figure}
  3869. \begin{figure}[tp]
  3870. \fbox{
  3871. \begin{minipage}{0.96\textwidth}
  3872. \small
  3873. \[
  3874. \begin{array}{lcl}
  3875. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3876. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3877. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3878. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3879. &\mid& \UNIOP{\key{'not}}{\Atm}
  3880. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3881. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3882. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3883. \mid \GOTO{\itm{label}} \\
  3884. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3885. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  3886. \end{array}
  3887. \]
  3888. \end{minipage}
  3889. }
  3890. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  3891. (Figure~\ref{fig:c0-syntax}).}
  3892. \label{fig:c1-syntax}
  3893. \end{figure}
  3894. \clearpage
  3895. \section{Remove Complex Operands}
  3896. \label{sec:remove-complex-opera-R2}
  3897. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  3898. \code{rco-atom} functions according to the definition of the output
  3899. language for this pass, $R_2^{\dagger}$, the administrative normal
  3900. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  3901. \code{Bool} form is an atomic expressions but \code{If} is not. All
  3902. three sub-expressions of an \code{If} are allowed to be complex
  3903. expressions in the output of \code{remove-complex-opera*}, but the
  3904. operands of \code{not} and the comparisons must be atoms. Regarding
  3905. the \code{If} form, it is particularly important to \textbf{not}
  3906. replace its condition with a temporary variable because that would
  3907. interfere with the generation of high-quality output in the
  3908. \code{explicate-control} pass.
  3909. \begin{figure}[tp]
  3910. \centering
  3911. \fbox{
  3912. \begin{minipage}{0.96\textwidth}
  3913. \[
  3914. \begin{array}{rcl}
  3915. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  3916. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  3917. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3918. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  3919. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  3920. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3921. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3922. \end{array}
  3923. \]
  3924. \end{minipage}
  3925. }
  3926. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  3927. \label{fig:r2-anf-syntax}
  3928. \end{figure}
  3929. \section{Explicate Control}
  3930. \label{sec:explicate-control-r2}
  3931. Recall that the purpose of \code{explicate-control} is to make the
  3932. order of evaluation explicit in the syntax of the program. With the
  3933. addition of \key{if} in $R_2$ this get more interesting.
  3934. As a motivating example, consider the following program that has an
  3935. \key{if} expression nested in the predicate of another \key{if}.
  3936. % s1_41.rkt
  3937. \begin{center}
  3938. \begin{minipage}{0.96\textwidth}
  3939. \begin{lstlisting}
  3940. (let ([x (read)])
  3941. (let ([y (read)])
  3942. (if (if (< x 1) (eq? x 0) (eq? x 2))
  3943. (+ y 2)
  3944. (+ y 10))))
  3945. \end{lstlisting}
  3946. \end{minipage}
  3947. \end{center}
  3948. %
  3949. The naive way to compile \key{if} and the comparison would be to
  3950. handle each of them in isolation, regardless of their context. Each
  3951. comparison would be translated into a \key{cmpq} instruction followed
  3952. by a couple instructions to move the result from the EFLAGS register
  3953. into a general purpose register or stack location. Each \key{if} would
  3954. be translated into the combination of a \key{cmpq} and a conditional
  3955. jump. The generated code for the inner \key{if} in the above example
  3956. would be as follows.
  3957. \begin{center}
  3958. \begin{minipage}{0.96\textwidth}
  3959. \begin{lstlisting}
  3960. ...
  3961. cmpq $1, x ;; (< x 1)
  3962. setl %al
  3963. movzbq %al, tmp
  3964. cmpq $1, tmp ;; (if (< x 1) ...)
  3965. je then_branch_1
  3966. jmp else_branch_1
  3967. ...
  3968. \end{lstlisting}
  3969. \end{minipage}
  3970. \end{center}
  3971. However, if we take context into account we can do better and reduce
  3972. the use of \key{cmpq} and EFLAG-accessing instructions.
  3973. One idea is to try and reorganize the code at the level of $R_2$,
  3974. pushing the outer \key{if} inside the inner one. This would yield the
  3975. following code.
  3976. \begin{center}
  3977. \begin{minipage}{0.96\textwidth}
  3978. \begin{lstlisting}
  3979. (let ([x (read)])
  3980. (let ([y (read)])
  3981. (if (< x 1)
  3982. (if (eq? x 0)
  3983. (+ y 2)
  3984. (+ y 10))
  3985. (if (eq? x 2)
  3986. (+ y 2)
  3987. (+ y 10)))))
  3988. \end{lstlisting}
  3989. \end{minipage}
  3990. \end{center}
  3991. Unfortunately, this approach duplicates the two branches, and a
  3992. compiler must never duplicate code!
  3993. We need a way to perform the above transformation, but without
  3994. duplicating code. The solution is straightforward if we think at the
  3995. level of x86 assembly: we can label the code for each of the branches
  3996. and insert jumps in all the places that need to execute the
  3997. branches. Put another way, we need to move away from abstract syntax
  3998. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3999. use a standard program representation called a \emph{control flow
  4000. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  4001. vertex is a labeled sequence of code, called a \emph{basic block}, and
  4002. each edge represents a jump to another block. The \key{Program}
  4003. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4004. as an alist mapping labels to basic blocks. Each basic block is
  4005. represented by the $\Tail$ non-terminal.
  4006. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4007. \code{remove-complex-opera*} pass and then the
  4008. \code{explicate-control} pass on the example program. We walk through
  4009. the output program and then discuss the algorithm.
  4010. %
  4011. Following the order of evaluation in the output of
  4012. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4013. and then the less-than-comparison to \code{1} in the predicate of the
  4014. inner \key{if}. In the output of \code{explicate-control}, in the
  4015. block labeled \code{start}, this becomes two assignment statements
  4016. followed by a conditional \key{goto} to label \code{block96} or
  4017. \code{block97}. The blocks associated with those labels contain the
  4018. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4019. respectively. Regarding the block labeled with \code{block96}, we
  4020. start with the comparison to \code{0} and then have a conditional
  4021. goto, either to label \code{block92} or label \code{block93}, which
  4022. indirectly take us to labels \code{block90} and \code{block91}, the
  4023. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4024. y 10)}. The story for the block labeled \code{block97} is similar.
  4025. \begin{figure}[tbp]
  4026. \begin{tabular}{lll}
  4027. \begin{minipage}{0.4\textwidth}
  4028. % s1_41.rkt
  4029. \begin{lstlisting}
  4030. (let ([x (read)])
  4031. (let ([y (read)])
  4032. (if (if (< x 1)
  4033. (eq? x 0)
  4034. (eq? x 2))
  4035. (+ y 2)
  4036. (+ y 10))))
  4037. \end{lstlisting}
  4038. \hspace{40pt}$\Downarrow$
  4039. \begin{lstlisting}
  4040. (let ([x (read)])
  4041. (let ([y (read)])
  4042. (if (if (< x 1)
  4043. (eq? x 0)
  4044. (eq? x 2))
  4045. (+ y 2)
  4046. (+ y 10))))
  4047. \end{lstlisting}
  4048. \end{minipage}
  4049. &
  4050. $\Rightarrow$
  4051. &
  4052. \begin{minipage}{0.55\textwidth}
  4053. \begin{lstlisting}
  4054. start:
  4055. x = (read);
  4056. y = (read);
  4057. if (< x 1)
  4058. goto block96;
  4059. else
  4060. goto block97;
  4061. block96:
  4062. if (eq? x 0)
  4063. goto block92;
  4064. else
  4065. goto block93;
  4066. block97:
  4067. if (eq? x 2)
  4068. goto block94;
  4069. else
  4070. goto block95;
  4071. block92:
  4072. goto block90;
  4073. block93:
  4074. goto block91;
  4075. block94:
  4076. goto block90;
  4077. block95:
  4078. goto block91;
  4079. block90:
  4080. return (+ y 2);
  4081. block91:
  4082. return (+ y 10);
  4083. \end{lstlisting}
  4084. \end{minipage}
  4085. \end{tabular}
  4086. \caption{Example translation from $R_2$ to $C_1$
  4087. via the \code{explicate-control}.}
  4088. \label{fig:explicate-control-s1-38}
  4089. \end{figure}
  4090. The nice thing about the output of \code{explicate-control} is that
  4091. there are no unnecessary comparisons and every comparison is part of a
  4092. conditional jump. The down-side of this output is that it includes
  4093. trivial blocks, such as the blocks labeled \code{block92} through
  4094. \code{block95}, that only jump to another block. We discuss a solution
  4095. to this problem in Section~\ref{sec:opt-jumps}.
  4096. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4097. \code{explicate-control} for $R_1$ using two mutually recursive
  4098. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4099. former function translates expressions in tail position whereas the
  4100. later function translates expressions on the right-hand-side of a
  4101. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4102. new kind of context to deal with: the predicate position of the
  4103. \key{if}. We need another function, \code{explicate-pred}, that takes
  4104. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4105. the then-branch and else-branch. The output of \code{explicate-pred}
  4106. is a block and a list of formerly \key{let}-bound variables.
  4107. Note that the three explicate functions need to construct a
  4108. control-flow graph, which we recommend they do via updates to a global
  4109. variable.
  4110. In the following paragraphs we consider the specific additions to the
  4111. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4112. of cases for the \code{explicate-pred} function.
  4113. The \code{explicate-tail} function needs an additional case for
  4114. \key{if}. The branches of the \key{if} inherit the current context, so
  4115. they are in tail position. Let $B_1$ be the result of
  4116. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4117. is a $\Tail$ AST node. Let $B_2$ be the result of apply
  4118. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4119. the $\Tail$ that results fromapplying \code{explicate-pred} to the
  4120. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4121. \key{if} as a whole translates to block $B_3$.
  4122. \[
  4123. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4124. \]
  4125. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4126. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4127. should not be confused with the labels for the blocks that appear in
  4128. the generated code. We initially construct unlabeled blocks; we only
  4129. attach labels to blocks when we add them to the control-flow graph, as
  4130. we shall see in the next case.
  4131. Next consider the case for \key{if} in the \code{explicate-assign}
  4132. function. The context of the \key{if} is an assignment to some
  4133. variable $x$ and then the control continues to some block $B_1$. The
  4134. code that we generate for both the ``then'' and ``else'' branches
  4135. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4136. add it to the control flow graph with a fresh label $\ell_1$. The
  4137. branches of the \key{if} inherit the current context, so that are in
  4138. assignment positions. Let $B_2$ be the result of applying
  4139. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4140. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4141. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4142. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4143. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4144. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4145. $B_4$.
  4146. \[
  4147. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4148. \]
  4149. The function \code{explicate-pred} will need a case for every
  4150. expression that can have type \code{Boolean}. We detail a few cases
  4151. here and leave the rest for the reader. The input to this function is
  4152. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4153. the enclosing \key{if}. Suppose the expression is the Boolean
  4154. \code{\#t}. Then we can perform a kind of partial evaluation and
  4155. translate it to the ``then'' branch $B_1$. Likewise, we translate
  4156. \code{\#f} to the ``else`` branch $B_2$.
  4157. \[
  4158. \key{\#t} \quad\Rightarrow\quad B_1,
  4159. \qquad\qquad\qquad
  4160. \key{\#f} \quad\Rightarrow\quad B_2
  4161. \]
  4162. Next, suppose the expression is a less-than comparison. We translate
  4163. it to a conditional \code{goto}. We need labels for the two branches
  4164. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4165. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4166. less-than comparison is as follows.
  4167. \[
  4168. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4169. \begin{array}{l}
  4170. \key{if}~(\key{<}~e_1~e_2) \\
  4171. \qquad\key{goto}~\ell_1\key{;}\\
  4172. \key{else}\\
  4173. \qquad\key{goto}~\ell_2\key{;}
  4174. \end{array}
  4175. \]
  4176. The case for \key{if} in \code{explicate-pred} is particularly
  4177. illuminating as it deals with the challenges that we discussed above
  4178. regarding the example of the nested \key{if} expressions. Again, we
  4179. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4180. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4181. branches of the current \key{if} inherit their context from the
  4182. current one, that is, predicate context. So we apply
  4183. \code{explicate-pred} to the ``then'' branch with the two blocks
  4184. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4185. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4186. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4187. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4188. \[
  4189. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4190. \quad\Rightarrow\quad
  4191. B_5
  4192. \]
  4193. \begin{exercise}\normalfont
  4194. Implement the pass \code{explicate-control} by adding the cases for
  4195. \key{if} to the functions for tail and assignment contexts, and
  4196. implement \code{explicate-pred} for predicate contexts. Create test
  4197. cases that exercise all of the new cases in the code for this pass.
  4198. \end{exercise}
  4199. \section{Select Instructions}
  4200. \label{sec:select-r2}
  4201. Recall that the \code{select-instructions} pass lowers from our
  4202. $C$-like intermediate representation to the pseudo-x86 language, which
  4203. is suitable for conducting register allocation. The pass is
  4204. implemented using three auxiliary functions, one for each of the
  4205. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4206. For $\Atm$, we have new cases for the Booleans. We take the usual
  4207. approach of encoding them as integers, with true as 1 and false as 0.
  4208. \[
  4209. \key{\#t} \Rightarrow \key{1}
  4210. \qquad
  4211. \key{\#f} \Rightarrow \key{0}
  4212. \]
  4213. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4214. be implemented in terms of \code{xorq} as we discussed at the
  4215. beginning of this section. Given an assignment
  4216. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4217. if the left-hand side $\itm{var}$ is
  4218. the same as $\Atm$, then just the \code{xorq} suffices.
  4219. \[
  4220. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4221. \quad\Rightarrow\quad
  4222. \key{xorq}~\key{\$}1\key{,}~\Var
  4223. \]
  4224. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4225. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4226. x86. Then we have
  4227. \[
  4228. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4229. \quad\Rightarrow\quad
  4230. \begin{array}{l}
  4231. \key{movq}~\Arg\key{,}~\Var\\
  4232. \key{xorq}~\key{\$}1\key{,}~\Var
  4233. \end{array}
  4234. \]
  4235. Next consider the cases for \code{eq?} and less-than comparison.
  4236. Translating these operations to x86 is slightly involved due to the
  4237. unusual nature of the \key{cmpq} instruction discussed above. We
  4238. recommend translating an assignment from \code{eq?} into the following
  4239. sequence of three instructions. \\
  4240. \begin{tabular}{lll}
  4241. \begin{minipage}{0.4\textwidth}
  4242. \begin{lstlisting}
  4243. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4244. \end{lstlisting}
  4245. \end{minipage}
  4246. &
  4247. $\Rightarrow$
  4248. &
  4249. \begin{minipage}{0.4\textwidth}
  4250. \begin{lstlisting}
  4251. cmpq |$\Arg_2$|, |$\Arg_1$|
  4252. sete %al
  4253. movzbq %al, |$\Var$|
  4254. \end{lstlisting}
  4255. \end{minipage}
  4256. \end{tabular} \\
  4257. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4258. and conditional \key{goto}. Both are straightforward to handle. A
  4259. \key{goto} becomes a jump instruction.
  4260. \[
  4261. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4262. \]
  4263. A conditional \key{goto} becomes a compare instruction followed
  4264. by a conditional jump (for ``then'') and the fall-through is
  4265. to a regular jump (for ``else'').\\
  4266. \begin{tabular}{lll}
  4267. \begin{minipage}{0.4\textwidth}
  4268. \begin{lstlisting}
  4269. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4270. goto |$\ell_1$|;
  4271. else
  4272. goto |$\ell_2$|;
  4273. \end{lstlisting}
  4274. \end{minipage}
  4275. &
  4276. $\Rightarrow$
  4277. &
  4278. \begin{minipage}{0.4\textwidth}
  4279. \begin{lstlisting}
  4280. cmpq |$\Arg_2$|, |$\Arg_1$|
  4281. je |$\ell_1$|
  4282. jmp |$\ell_2$|
  4283. \end{lstlisting}
  4284. \end{minipage}
  4285. \end{tabular} \\
  4286. \begin{exercise}\normalfont
  4287. Expand your \code{select-instructions} pass to handle the new features
  4288. of the $R_2$ language. Test the pass on all the examples you have
  4289. created and make sure that you have some test programs that use the
  4290. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4291. the output using the \code{interp-x86} interpreter
  4292. (Appendix~\ref{appendix:interp}).
  4293. \end{exercise}
  4294. \section{Register Allocation}
  4295. \label{sec:register-allocation-r2}
  4296. The changes required for $R_2$ affect liveness analysis, building the
  4297. interference graph, and assigning homes, but the graph coloring
  4298. algorithm itself does not change.
  4299. \subsection{Liveness Analysis}
  4300. \label{sec:liveness-analysis-r2}
  4301. Recall that for $R_1$ we implemented liveness analysis for a single
  4302. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4303. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4304. produces many basic blocks arranged in a control-flow graph. The first
  4305. question we need to consider is: what order should we process the
  4306. basic blocks? Recall that to perform liveness analysis, we need to
  4307. know the live-after set. If a basic block has no successor blocks
  4308. (i.e. no out-edges in the control flow graph), then it has an empty
  4309. live-after set and we can immediately apply liveness analysis to
  4310. it. If a basic block has some successors, then we need to complete
  4311. liveness analysis on those blocks first. Furthermore, we know that
  4312. the control flow graph does not contain any cycles because $R_2$ does
  4313. not include loops
  4314. %
  4315. \footnote{If we were to add loops to the language, then the CFG could
  4316. contain cycles and we would instead need to use the classic worklist
  4317. algorithm for computing the fixed point of the liveness
  4318. analysis~\citep{Aho:1986qf}.}.
  4319. %
  4320. Returning to the question of what order should we process the basic
  4321. blocks, the answer is reverse topological order. We recommend using
  4322. the \code{tsort} (topological sort) and \code{transpose} functions of
  4323. the Racket \code{graph} package to obtain this ordering.
  4324. The next question is how to compute the live-after set of a block
  4325. given the live-before sets of all its successor blocks. (There can be
  4326. more than one because of conditional jumps.) During compilation we do
  4327. not know which way a conditional jump will go, so we do not know which
  4328. of the successor's live-before set to use. The solution to this
  4329. challenge is based on the observation that there is no harm to the
  4330. correctness of the compiler if we classify more variables as live than
  4331. the ones that are truly live during a particular execution of the
  4332. block. Thus, we can take the union of the live-before sets from all
  4333. the successors to be the live-after set for the block. Once we have
  4334. computed the live-after set, we can proceed to perform liveness
  4335. analysis on the block just as we did in
  4336. Section~\ref{sec:liveness-analysis-r1}.
  4337. The helper functions for computing the variables in an instruction's
  4338. argument and for computing the variables read-from ($R$) or written-to
  4339. ($W$) by an instruction need to be updated to handle the new kinds of
  4340. arguments and instructions in x86$_1$.
  4341. \subsection{Build Interference}
  4342. \label{sec:build-interference-r2}
  4343. Many of the new instructions in x86$_1$ can be handled in the same way
  4344. as the instructions in x86$_0$. Thus, if your code was already quite
  4345. general, it will not need to be changed to handle the new
  4346. instructions. If you code is not general enough, I recommend that you
  4347. change your code to be more general. For example, you can factor out
  4348. the computing of the the read and write sets for each kind of
  4349. instruction into two auxiliary functions.
  4350. Note that the \key{movzbq} instruction requires some special care,
  4351. just like the \key{movq} instruction. See rule number 3 in
  4352. Section~\ref{sec:build-interference}.
  4353. %% \subsection{Assign Homes}
  4354. %% \label{sec:assign-homes-r2}
  4355. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4356. %% to be updated to handle the \key{if} statement, simply by recursively
  4357. %% processing the child nodes. Hopefully your code already handles the
  4358. %% other new instructions, but if not, you can generalize your code.
  4359. \begin{exercise}\normalfont
  4360. Update the \code{register-allocation} pass so that it works for $R_2$
  4361. and test your compiler using your previously created programs on the
  4362. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4363. \end{exercise}
  4364. \section{Patch Instructions}
  4365. The second argument of the \key{cmpq} instruction must not be an
  4366. immediate value (such as an integer). So if you are comparing two
  4367. immediates, we recommend inserting a \key{movq} instruction to put the
  4368. second argument in \key{rax}.
  4369. %
  4370. The second argument of the \key{movzbq} must be a register.
  4371. %
  4372. There are no special restrictions on the x86 instructions \key{JmpIf}
  4373. and \key{Jmp}.
  4374. \begin{exercise}\normalfont
  4375. Update \code{patch-instructions} to handle the new x86 instructions.
  4376. Test your compiler using your previously created programs on the
  4377. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4378. \end{exercise}
  4379. \section{An Example Translation}
  4380. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4381. $R_2$ translated to x86, showing the results of
  4382. \code{explicate-control}, \code{select-instructions}, and the final
  4383. x86 assembly code.
  4384. \begin{figure}[tbp]
  4385. \begin{tabular}{lll}
  4386. \begin{minipage}{0.5\textwidth}
  4387. % s1_20.rkt
  4388. \begin{lstlisting}
  4389. (if (eq? (read) 1) 42 0)
  4390. \end{lstlisting}
  4391. $\Downarrow$
  4392. \begin{lstlisting}
  4393. start:
  4394. tmp7951 = (read);
  4395. if (eq? tmp7951 1) then
  4396. goto block7952;
  4397. else
  4398. goto block7953;
  4399. block7952:
  4400. return 42;
  4401. block7953:
  4402. return 0;
  4403. \end{lstlisting}
  4404. $\Downarrow$
  4405. \begin{lstlisting}
  4406. start:
  4407. callq read_int
  4408. movq %rax, tmp7951
  4409. cmpq $1, tmp7951
  4410. je block7952
  4411. jmp block7953
  4412. block7953:
  4413. movq $0, %rax
  4414. jmp conclusion
  4415. block7952:
  4416. movq $42, %rax
  4417. jmp conclusion
  4418. \end{lstlisting}
  4419. \end{minipage}
  4420. &
  4421. $\Rightarrow\qquad$
  4422. \begin{minipage}{0.4\textwidth}
  4423. \begin{lstlisting}
  4424. start:
  4425. callq read_int
  4426. movq %rax, %rcx
  4427. cmpq $1, %rcx
  4428. je block7952
  4429. jmp block7953
  4430. block7953:
  4431. movq $0, %rax
  4432. jmp conclusion
  4433. block7952:
  4434. movq $42, %rax
  4435. jmp conclusion
  4436. .globl main
  4437. main:
  4438. pushq %rbp
  4439. movq %rsp, %rbp
  4440. pushq %r13
  4441. pushq %r12
  4442. pushq %rbx
  4443. pushq %r14
  4444. subq $0, %rsp
  4445. jmp start
  4446. conclusion:
  4447. addq $0, %rsp
  4448. popq %r14
  4449. popq %rbx
  4450. popq %r12
  4451. popq %r13
  4452. popq %rbp
  4453. retq
  4454. \end{lstlisting}
  4455. \end{minipage}
  4456. \end{tabular}
  4457. \caption{Example compilation of an \key{if} expression to x86.}
  4458. \label{fig:if-example-x86}
  4459. \end{figure}
  4460. \begin{figure}[p]
  4461. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4462. \node (R2) at (0,2) {\large $R_2$};
  4463. \node (R2-2) at (3,2) {\large $R_2$};
  4464. \node (R2-3) at (6,2) {\large $R_2$};
  4465. \node (R2-4) at (9,2) {\large $R_2$};
  4466. \node (R2-5) at (9,0) {\large $R_2$};
  4467. \node (C1-1) at (3,-2) {\large $C_1$};
  4468. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4469. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4470. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4471. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4472. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4473. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4474. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4475. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4476. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4477. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4478. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4479. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4480. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4481. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4482. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4483. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4484. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4485. \end{tikzpicture}
  4486. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4487. \label{fig:R2-passes}
  4488. \end{figure}
  4489. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4490. compilation of $R_2$.
  4491. \section{Challenge: Optimize and Remove Jumps}
  4492. \label{sec:opt-jumps}
  4493. Recall that in the example output of \code{explicate-control} in
  4494. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4495. \code{block60} are trivial blocks, they do nothing but jump to another
  4496. block. The first goal of this challenge assignment is to remove those
  4497. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4498. \code{explicate-control} on the left and shows the result of bypassing
  4499. the trivial blocks on the right. Let us focus on \code{block61}. The
  4500. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4501. \code{block55}. The optimized code on the right of
  4502. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4503. \code{then} branch jumping directly to \code{block55}. The story is
  4504. similar for the \code{else} branch, as well as for the two branches in
  4505. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4506. have been optimized in this way, there are no longer any jumps to
  4507. blocks \code{block57} through \code{block60}, so they can be removed.
  4508. \begin{figure}[tbp]
  4509. \begin{tabular}{lll}
  4510. \begin{minipage}{0.4\textwidth}
  4511. \begin{lstlisting}
  4512. block62:
  4513. tmp54 = (read);
  4514. if (eq? tmp54 2) then
  4515. goto block59;
  4516. else
  4517. goto block60;
  4518. block61:
  4519. tmp53 = (read);
  4520. if (eq? tmp53 0) then
  4521. goto block57;
  4522. else
  4523. goto block58;
  4524. block60:
  4525. goto block56;
  4526. block59:
  4527. goto block55;
  4528. block58:
  4529. goto block56;
  4530. block57:
  4531. goto block55;
  4532. block56:
  4533. return (+ 700 77);
  4534. block55:
  4535. return (+ 10 32);
  4536. start:
  4537. tmp52 = (read);
  4538. if (eq? tmp52 1) then
  4539. goto block61;
  4540. else
  4541. goto block62;
  4542. \end{lstlisting}
  4543. \end{minipage}
  4544. &
  4545. $\Rightarrow$
  4546. &
  4547. \begin{minipage}{0.55\textwidth}
  4548. \begin{lstlisting}
  4549. block62:
  4550. tmp54 = (read);
  4551. if (eq? tmp54 2) then
  4552. goto block55;
  4553. else
  4554. goto block56;
  4555. block61:
  4556. tmp53 = (read);
  4557. if (eq? tmp53 0) then
  4558. goto block55;
  4559. else
  4560. goto block56;
  4561. block56:
  4562. return (+ 700 77);
  4563. block55:
  4564. return (+ 10 32);
  4565. start:
  4566. tmp52 = (read);
  4567. if (eq? tmp52 1) then
  4568. goto block61;
  4569. else
  4570. goto block62;
  4571. \end{lstlisting}
  4572. \end{minipage}
  4573. \end{tabular}
  4574. \caption{Optimize jumps by removing trivial blocks.}
  4575. \label{fig:optimize-jumps}
  4576. \end{figure}
  4577. The name of this pass is \code{optimize-jumps}. We recommend
  4578. implementing this pass in two phases. The first phrase builds a hash
  4579. table that maps labels to possibly improved labels. The second phase
  4580. changes the target of each \code{goto} to use the improved label. If
  4581. the label is for a trivial block, then the hash table should map the
  4582. label to the first non-trivial block that can be reached from this
  4583. label by jumping through trivial blocks. If the label is for a
  4584. non-trivial block, then the hash table should map the label to itself;
  4585. we do not want to change jumps to non-trivial blocks.
  4586. The first phase can be accomplished by constructing an empty hash
  4587. table, call it \code{short-cut}, and then iterating over the control
  4588. flow graph. Each time you encouter a block that is just a \code{goto},
  4589. then update the hash table, mapping the block's source to the target
  4590. of the \code{goto}. Also, the hash table may already have mapped some
  4591. labels to the block's source, to you must iterate through the hash
  4592. table and update all of those so that they instead map to the target
  4593. of the \code{goto}.
  4594. For the second phase, we recommend iterating through the $\Tail$ of
  4595. each block in the program, updating the target of every \code{goto}
  4596. according to the mapping in \code{short-cut}.
  4597. \begin{exercise}\normalfont
  4598. Implement the \code{optimize-jumps} pass as a transformation from
  4599. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4600. Check that \code{optimize-jumps} removes trivial blocks in a few
  4601. example programs. Then check that your compiler still passes all of
  4602. your tests.
  4603. \end{exercise}
  4604. There is another opportunity for optimizing jumps that is apparent in
  4605. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4606. end with a jump to \code{block7953} and there are no other jumps to
  4607. \code{block7953} in the rest of the program. In this situation we can
  4608. avoid the runtime overhead of this jump by merging \code{block7953}
  4609. into the preceeding block, in this case the \code{start} block.
  4610. Figure~\ref{fig:remove-jumps} shows the output of
  4611. \code{select-instructions} on the left and the result of this
  4612. optimization on the right.
  4613. \begin{figure}[tbp]
  4614. \begin{tabular}{lll}
  4615. \begin{minipage}{0.5\textwidth}
  4616. % s1_20.rkt
  4617. \begin{lstlisting}
  4618. start:
  4619. callq read_int
  4620. movq %rax, tmp7951
  4621. cmpq $1, tmp7951
  4622. je block7952
  4623. jmp block7953
  4624. block7953:
  4625. movq $0, %rax
  4626. jmp conclusion
  4627. block7952:
  4628. movq $42, %rax
  4629. jmp conclusion
  4630. \end{lstlisting}
  4631. \end{minipage}
  4632. &
  4633. $\Rightarrow\qquad$
  4634. \begin{minipage}{0.4\textwidth}
  4635. \begin{lstlisting}
  4636. start:
  4637. callq read_int
  4638. movq %rax, tmp7951
  4639. cmpq $1, tmp7951
  4640. je block7952
  4641. movq $0, %rax
  4642. jmp conclusion
  4643. block7952:
  4644. movq $42, %rax
  4645. jmp conclusion
  4646. \end{lstlisting}
  4647. \end{minipage}
  4648. \end{tabular}
  4649. \caption{Merging basic blocks by removing unnecessary jumps.}
  4650. \label{fig:remove-jumps}
  4651. \end{figure}
  4652. \begin{exercise}\normalfont
  4653. Implement a pass named \code{remove-jumps} that merges basic blocks
  4654. into their preceeding basic block, when there is only one preceeding
  4655. block. The pass should translate from psuedo $x86_1$ to pseudo
  4656. $x86_1$ and it should come immediately after
  4657. \code{select-instructions}. Check that \code{remove-jumps}
  4658. accomplishes the goal of merging basic blocks on several test
  4659. programs and check that your compiler passes all of your tests.
  4660. \end{exercise}
  4661. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4662. \chapter{Tuples and Garbage Collection}
  4663. \label{ch:tuples}
  4664. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4665. add simple structures. \\ --Jeremy}
  4666. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4667. things to discuss in this chapter. \\ --Jeremy}
  4668. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4669. all the IR grammars are spelled out! \\ --Jeremy}
  4670. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4671. but keep type annotations on vector creation and local variables, function
  4672. parameters, etc. \\ --Jeremy}
  4673. \margincomment{\scriptsize Be more explicit about how to deal with
  4674. the root stack. \\ --Jeremy}
  4675. In this chapter we study the implementation of mutable tuples (called
  4676. ``vectors'' in Racket). This language feature is the first to use the
  4677. computer's \emph{heap} because the lifetime of a Racket tuple is
  4678. indefinite, that is, a tuple lives forever from the programmer's
  4679. viewpoint. Of course, from an implementer's viewpoint, it is important
  4680. to reclaim the space associated with a tuple when it is no longer
  4681. needed, which is why we also study \emph{garbage collection}
  4682. techniques in this chapter.
  4683. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4684. interpreter and type checker. The $R_3$ language extends the $R_2$
  4685. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4686. \code{void} value. The reason for including the later is that the
  4687. \code{vector-set!} operation returns a value of type
  4688. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4689. called the \code{Unit} type in the programming languages
  4690. literature. Racket's \code{Void} type is inhabited by a single value
  4691. \code{void} which corresponds to \code{unit} or \code{()} in the
  4692. literature~\citep{Pierce:2002hj}.}.
  4693. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4694. copying live objects back and forth between two halves of the
  4695. heap. The garbage collector requires coordination with the compiler so
  4696. that it can see all of the \emph{root} pointers, that is, pointers in
  4697. registers or on the procedure call stack.
  4698. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4699. discuss all the necessary changes and additions to the compiler
  4700. passes, including a new compiler pass named \code{expose-allocation}.
  4701. \section{The $R_3$ Language}
  4702. \label{sec:r3}
  4703. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4704. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4705. $R_3$ language includes three new forms: \code{vector} for creating a
  4706. tuple, \code{vector-ref} for reading an element of a tuple, and
  4707. \code{vector-set!} for writing to an element of a tuple. The program
  4708. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4709. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4710. the 3-tuple, demonstrating that tuples are first-class values. The
  4711. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4712. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4713. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4714. 1-tuple. So the result of the program is \code{42}.
  4715. \begin{figure}[tbp]
  4716. \centering
  4717. \fbox{
  4718. \begin{minipage}{0.96\textwidth}
  4719. \[
  4720. \begin{array}{lcl}
  4721. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4722. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4723. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4724. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4725. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4726. \mid (\key{and}\;\Exp\;\Exp)
  4727. \mid (\key{or}\;\Exp\;\Exp)
  4728. \mid (\key{not}\;\Exp) } \\
  4729. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4730. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4731. &\mid& (\key{vector}\;\Exp\ldots)
  4732. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4733. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4734. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4735. R_3 &::=& \Exp
  4736. \end{array}
  4737. \]
  4738. \end{minipage}
  4739. }
  4740. \caption{The concrete syntax of $R_3$, extending $R_2$
  4741. (Figure~\ref{fig:r2-concrete-syntax}).}
  4742. \label{fig:r3-concrete-syntax}
  4743. \end{figure}
  4744. \begin{figure}[tbp]
  4745. \begin{lstlisting}
  4746. (let ([t (vector 40 #t (vector 2))])
  4747. (if (vector-ref t 1)
  4748. (+ (vector-ref t 0)
  4749. (vector-ref (vector-ref t 2) 0))
  4750. 44))
  4751. \end{lstlisting}
  4752. \caption{Example program that creates tuples and reads from them.}
  4753. \label{fig:vector-eg}
  4754. \end{figure}
  4755. \begin{figure}[tp]
  4756. \centering
  4757. \fbox{
  4758. \begin{minipage}{0.96\textwidth}
  4759. \[
  4760. \begin{array}{lcl}
  4761. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4762. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4763. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4764. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4765. &\mid& \gray{ \BOOL{\itm{bool}}
  4766. \mid \AND{\Exp}{\Exp} }\\
  4767. &\mid& \gray{ \OR{\Exp}{\Exp}
  4768. \mid \NOT{\Exp} } \\
  4769. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  4770. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4771. &\mid& \VECTOR{\Exp} \\
  4772. &\mid& \VECREF{\Exp}{\Int}\\
  4773. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4774. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  4775. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4776. \end{array}
  4777. \]
  4778. \end{minipage}
  4779. }
  4780. \caption{The abstract syntax of $R_3$.}
  4781. \label{fig:r3-syntax}
  4782. \end{figure}
  4783. Tuples are our first encounter with heap-allocated data, which raises
  4784. several interesting issues. First, variable binding performs a
  4785. shallow-copy when dealing with tuples, which means that different
  4786. variables can refer to the same tuple, that is, different variables
  4787. can be \emph{aliases} for the same entity. Consider the following
  4788. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4789. Thus, the mutation through \code{t2} is visible when referencing the
  4790. tuple from \code{t1}, so the result of this program is \code{42}.
  4791. \begin{center}
  4792. \begin{minipage}{0.96\textwidth}
  4793. \begin{lstlisting}
  4794. (let ([t1 (vector 3 7)])
  4795. (let ([t2 t1])
  4796. (let ([_ (vector-set! t2 0 42)])
  4797. (vector-ref t1 0))))
  4798. \end{lstlisting}
  4799. \end{minipage}
  4800. \end{center}
  4801. The next issue concerns the lifetime of tuples. Of course, they are
  4802. created by the \code{vector} form, but when does their lifetime end?
  4803. Notice that $R_3$ does not include an operation for deleting
  4804. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  4805. of static scoping. For example, the following program returns
  4806. \code{42} even though the variable \code{w} goes out of scope prior to
  4807. the \code{vector-ref} that reads from the vector it was bound to.
  4808. \begin{center}
  4809. \begin{minipage}{0.96\textwidth}
  4810. \begin{lstlisting}
  4811. (let ([v (vector (vector 44))])
  4812. (let ([x (let ([w (vector 42)])
  4813. (let ([_ (vector-set! v 0 w)])
  4814. 0))])
  4815. (+ x (vector-ref (vector-ref v 0) 0))))
  4816. \end{lstlisting}
  4817. \end{minipage}
  4818. \end{center}
  4819. From the perspective of programmer-observable behavior, tuples live
  4820. forever. Of course, if they really lived forever, then many programs
  4821. would run out of memory.\footnote{The $R_3$ language does not have
  4822. looping or recursive functions, so it is nigh impossible to write a
  4823. program in $R_3$ that will run out of memory. However, we add
  4824. recursive functions in the next Chapter!} A Racket implementation
  4825. must therefore perform automatic garbage collection.
  4826. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4827. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4828. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4829. operations in Racket. One subtle point is that the \code{vector-set!}
  4830. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4831. can be passed around just like other values inside an $R_3$ program
  4832. and a \code{\#<void>} value can be compared for equality with another
  4833. \code{\#<void>} value. However, there are no other operations specific
  4834. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  4835. the \code{void?} predicate that returns \code{\#t} when applied to
  4836. \code{\#<void>} and \code{\#f} otherwise.
  4837. \begin{figure}[tbp]
  4838. \begin{lstlisting}
  4839. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4840. (define (interp-op op)
  4841. (match op
  4842. ...
  4843. ['vector vector]
  4844. ['vector-ref vector-ref]
  4845. ['vector-set! vector-set!]
  4846. [else (error 'interp-op "unknown operator")]))
  4847. (define (interp-exp env)
  4848. (lambda (e)
  4849. (define recur (interp-exp env))
  4850. (match e
  4851. ...
  4852. )))
  4853. (define (interp-R3 p)
  4854. (match p
  4855. [(Program '() e)
  4856. ((interp-exp '()) e)]
  4857. ))
  4858. \end{lstlisting}
  4859. \caption{Interpreter for the $R_3$ language.}
  4860. \label{fig:interp-R3}
  4861. \end{figure}
  4862. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4863. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4864. need to know which variables contain pointers into the heap, that is,
  4865. which variables contain vectors. Also, when allocating a vector, we
  4866. need to know which elements of the vector are pointers. We can obtain
  4867. this information during type checking. The type checker in
  4868. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4869. expression, it also wraps every sub-expression $e$ with the form
  4870. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4871. Subsequently, in the \code{uncover-locals} pass
  4872. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4873. propagated to all variables (including the temporaries generated by
  4874. \code{remove-complex-opera*}).
  4875. \begin{figure}[hb]
  4876. \begin{lstlisting}
  4877. (define (type-check-exp env)
  4878. (lambda (e)
  4879. (define recur (type-check-exp env))
  4880. (match e
  4881. ...
  4882. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4883. [(Prim 'vector es)
  4884. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  4885. (let ([t `(Vector ,@t*)])
  4886. (values (HasType (Prim 'vector e*) t) t))]
  4887. [(Prim 'vector-ref (list e (Int i)))
  4888. (define-values (e^ t) (recur e))
  4889. (match t
  4890. [`(Vector ,ts ...)
  4891. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4892. (error 'type-check-exp "invalid index ~a" i))
  4893. (let ([t (list-ref ts i)])
  4894. (values
  4895. (HasType (Prim 'vector-ref
  4896. (list e^ (HasType (Int i) 'Integer)))
  4897. t)
  4898. t))]
  4899. [else (error "expected a vector in vector-ref, not" t)])]
  4900. [(Prim 'eq? (list e1 e2))
  4901. (define-values (e1^ T1) (recur e1))
  4902. (define-values (e2^ T2) (recur e2))
  4903. (unless (equal? T1 T2)
  4904. (error "arguments of eq? must have the same type, but are not"
  4905. (list T1 T2)))
  4906. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4907. ...
  4908. )))
  4909. \end{lstlisting}
  4910. \caption{Type checker for the $R_3$ language.}
  4911. \label{fig:typecheck-R3}
  4912. \end{figure}
  4913. \section{Garbage Collection}
  4914. \label{sec:GC}
  4915. Here we study a relatively simple algorithm for garbage collection
  4916. that is the basis of state-of-the-art garbage
  4917. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4918. particular, we describe a two-space copying
  4919. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4920. perform the
  4921. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4922. coarse-grained depiction of what happens in a two-space collector,
  4923. showing two time steps, prior to garbage collection (on the top) and
  4924. after garbage collection (on the bottom). In a two-space collector,
  4925. the heap is divided into two parts named the FromSpace and the
  4926. ToSpace. Initially, all allocations go to the FromSpace until there is
  4927. not enough room for the next allocation request. At that point, the
  4928. garbage collector goes to work to make more room.
  4929. The garbage collector must be careful not to reclaim tuples that will
  4930. be used by the program in the future. Of course, it is impossible in
  4931. general to predict what a program will do, but we can over approximate
  4932. the will-be-used tuples by preserving all tuples that could be
  4933. accessed by \emph{any} program given the current computer state. A
  4934. program could access any tuple whose address is in a register or on
  4935. the procedure call stack. These addresses are called the \emph{root
  4936. set}. In addition, a program could access any tuple that is
  4937. transitively reachable from the root set. Thus, it is safe for the
  4938. garbage collector to reclaim the tuples that are not reachable in this
  4939. way.
  4940. So the goal of the garbage collector is twofold:
  4941. \begin{enumerate}
  4942. \item preserve all tuple that are reachable from the root set via a
  4943. path of pointers, that is, the \emph{live} tuples, and
  4944. \item reclaim the memory of everything else, that is, the
  4945. \emph{garbage}.
  4946. \end{enumerate}
  4947. A copying collector accomplishes this by copying all of the live
  4948. objects from the FromSpace into the ToSpace and then performs a slight
  4949. of hand, treating the ToSpace as the new FromSpace and the old
  4950. FromSpace as the new ToSpace. In the example of
  4951. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4952. root set, one in a register and two on the stack. All of the live
  4953. objects have been copied to the ToSpace (the right-hand side of
  4954. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4955. pointer relationships. For example, the pointer in the register still
  4956. points to a 2-tuple whose first element is a 3-tuple and whose second
  4957. element is a 2-tuple. There are four tuples that are not reachable
  4958. from the root set and therefore do not get copied into the ToSpace.
  4959. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  4960. created by a well-typed program in $R_3$ because it contains a
  4961. cycle. However, creating cycles will be possible once we get to $R_6$.
  4962. We design the garbage collector to deal with cycles to begin with so
  4963. we will not need to revisit this issue.
  4964. \begin{figure}[tbp]
  4965. \centering
  4966. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4967. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4968. \caption{A copying collector in action.}
  4969. \label{fig:copying-collector}
  4970. \end{figure}
  4971. There are many alternatives to copying collectors (and their bigger
  4972. siblings, the generational collectors) when its comes to garbage
  4973. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  4974. reference counting~\citep{Collins:1960aa}. The strengths of copying
  4975. collectors are that allocation is fast (just a comparison and pointer
  4976. increment), there is no fragmentation, cyclic garbage is collected,
  4977. and the time complexity of collection only depends on the amount of
  4978. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  4979. main disadvantages of a two-space copying collector is that it uses a
  4980. lot of space and takes a long time to perform the copy, though these
  4981. problems are ameliorated in generational collectors. Racket and
  4982. Scheme programs tend to allocate many small objects and generate a lot
  4983. of garbage, so copying and generational collectors are a good fit.
  4984. Garbage collection is an active research topic, especially concurrent
  4985. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  4986. developing new techniques and revisiting old
  4987. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  4988. meet every year at the International Symposium on Memory Management to
  4989. present these findings.
  4990. \subsection{Graph Copying via Cheney's Algorithm}
  4991. \label{sec:cheney}
  4992. Let us take a closer look at the copying of the live objects. The
  4993. allocated objects and pointers can be viewed as a graph and we need to
  4994. copy the part of the graph that is reachable from the root set. To
  4995. make sure we copy all of the reachable vertices in the graph, we need
  4996. an exhaustive graph traversal algorithm, such as depth-first search or
  4997. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  4998. such algorithms take into account the possibility of cycles by marking
  4999. which vertices have already been visited, so as to ensure termination
  5000. of the algorithm. These search algorithms also use a data structure
  5001. such as a stack or queue as a to-do list to keep track of the vertices
  5002. that need to be visited. We shall use breadth-first search and a trick
  5003. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5004. and copying tuples into the ToSpace.
  5005. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5006. copy progresses. The queue is represented by a chunk of contiguous
  5007. memory at the beginning of the ToSpace, using two pointers to track
  5008. the front and the back of the queue. The algorithm starts by copying
  5009. all tuples that are immediately reachable from the root set into the
  5010. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5011. old tuple to indicate that it has been visited. We discuss how this
  5012. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5013. pointers inside the copied tuples in the queue still point back to the
  5014. FromSpace. Once the initial queue has been created, the algorithm
  5015. enters a loop in which it repeatedly processes the tuple at the front
  5016. of the queue and pops it off the queue. To process a tuple, the
  5017. algorithm copies all the tuple that are directly reachable from it to
  5018. the ToSpace, placing them at the back of the queue. The algorithm then
  5019. updates the pointers in the popped tuple so they point to the newly
  5020. copied tuples.
  5021. \begin{figure}[tbp]
  5022. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5023. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5024. \label{fig:cheney}
  5025. \end{figure}
  5026. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5027. tuple whose second element is $42$ to the back of the queue. The other
  5028. pointer goes to a tuple that has already been copied, so we do not
  5029. need to copy it again, but we do need to update the pointer to the new
  5030. location. This can be accomplished by storing a \emph{forwarding}
  5031. pointer to the new location in the old tuple, back when we initially
  5032. copied the tuple into the ToSpace. This completes one step of the
  5033. algorithm. The algorithm continues in this way until the front of the
  5034. queue is empty, that is, until the front catches up with the back.
  5035. \subsection{Data Representation}
  5036. \label{sec:data-rep-gc}
  5037. The garbage collector places some requirements on the data
  5038. representations used by our compiler. First, the garbage collector
  5039. needs to distinguish between pointers and other kinds of data. There
  5040. are several ways to accomplish this.
  5041. \begin{enumerate}
  5042. \item Attached a tag to each object that identifies what type of
  5043. object it is~\citep{McCarthy:1960dz}.
  5044. \item Store different types of objects in different
  5045. regions~\citep{Steele:1977ab}.
  5046. \item Use type information from the program to either generate
  5047. type-specific code for collecting or to generate tables that can
  5048. guide the
  5049. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5050. \end{enumerate}
  5051. Dynamically typed languages, such as Lisp, need to tag objects
  5052. anyways, so option 1 is a natural choice for those languages.
  5053. However, $R_3$ is a statically typed language, so it would be
  5054. unfortunate to require tags on every object, especially small and
  5055. pervasive objects like integers and Booleans. Option 3 is the
  5056. best-performing choice for statically typed languages, but comes with
  5057. a relatively high implementation complexity. To keep this chapter
  5058. within a 2-week time budget, we recommend a combination of options 1
  5059. and 2, using separate strategies for the stack and the heap.
  5060. Regarding the stack, we recommend using a separate stack for pointers,
  5061. which we call a \emph{root stack} (a.k.a. ``shadow
  5062. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5063. is, when a local variable needs to be spilled and is of type
  5064. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5065. stack instead of the normal procedure call stack. Furthermore, we
  5066. always spill vector-typed variables if they are live during a call to
  5067. the collector, thereby ensuring that no pointers are in registers
  5068. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5069. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5070. the data layout using a root stack. The root stack contains the two
  5071. pointers from the regular stack and also the pointer in the second
  5072. register.
  5073. \begin{figure}[tbp]
  5074. \centering \includegraphics[width=0.65\textwidth]{figs/root-stack}
  5075. \caption{Maintaining a root stack to facilitate garbage collection.}
  5076. \label{fig:shadow-stack}
  5077. \end{figure}
  5078. The problem of distinguishing between pointers and other kinds of data
  5079. also arises inside of each tuple on the heap. We solve this problem by
  5080. attaching a tag, an extra 64-bits, to each
  5081. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5082. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5083. that we have drawn the bits in a big-endian way, from right-to-left,
  5084. with bit location 0 (the least significant bit) on the far right,
  5085. which corresponds to the direction of the x86 shifting instructions
  5086. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5087. is dedicated to specifying which elements of the tuple are pointers,
  5088. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5089. indicates there is a pointer and a 0 bit indicates some other kind of
  5090. data. The pointer mask starts at bit location 7. We have limited
  5091. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5092. the pointer mask. The tag also contains two other pieces of
  5093. information. The length of the tuple (number of elements) is stored in
  5094. bits location 1 through 6. Finally, the bit at location 0 indicates
  5095. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5096. value 1, then this tuple has not yet been copied. If the bit has
  5097. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5098. of a pointer are always zero anyways because our tuples are 8-byte
  5099. aligned.)
  5100. \begin{figure}[tbp]
  5101. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5102. \caption{Representation of tuples in the heap.}
  5103. \label{fig:tuple-rep}
  5104. \end{figure}
  5105. \subsection{Implementation of the Garbage Collector}
  5106. \label{sec:organize-gz}
  5107. An implementation of the copying collector is provided in the
  5108. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5109. interface to the garbage collector that is used by the compiler. The
  5110. \code{initialize} function creates the FromSpace, ToSpace, and root
  5111. stack and should be called in the prelude of the \code{main}
  5112. function. The \code{initialize} function puts the address of the
  5113. beginning of the FromSpace into the global variable
  5114. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5115. the address that is 1-past the last element of the FromSpace. (We use
  5116. half-open intervals to represent chunks of
  5117. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5118. points to the first element of the root stack.
  5119. As long as there is room left in the FromSpace, your generated code
  5120. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5121. %
  5122. The amount of room left in FromSpace is the difference between the
  5123. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5124. function should be called when there is not enough room left in the
  5125. FromSpace for the next allocation. The \code{collect} function takes
  5126. a pointer to the current top of the root stack (one past the last item
  5127. that was pushed) and the number of bytes that need to be
  5128. allocated. The \code{collect} function performs the copying collection
  5129. and leaves the heap in a state such that the next allocation will
  5130. succeed.
  5131. \begin{figure}[tbp]
  5132. \begin{lstlisting}
  5133. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5134. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5135. int64_t* free_ptr;
  5136. int64_t* fromspace_begin;
  5137. int64_t* fromspace_end;
  5138. int64_t** rootstack_begin;
  5139. \end{lstlisting}
  5140. \caption{The compiler's interface to the garbage collector.}
  5141. \label{fig:gc-header}
  5142. \end{figure}
  5143. %% \begin{exercise}
  5144. %% In the file \code{runtime.c} you will find the implementation of
  5145. %% \code{initialize} and a partial implementation of \code{collect}.
  5146. %% The \code{collect} function calls another function, \code{cheney},
  5147. %% to perform the actual copy, and that function is left to the reader
  5148. %% to implement. The following is the prototype for \code{cheney}.
  5149. %% \begin{lstlisting}
  5150. %% static void cheney(int64_t** rootstack_ptr);
  5151. %% \end{lstlisting}
  5152. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5153. %% rootstack (which is an array of pointers). The \code{cheney} function
  5154. %% also communicates with \code{collect} through the global
  5155. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5156. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5157. %% the ToSpace:
  5158. %% \begin{lstlisting}
  5159. %% static int64_t* tospace_begin;
  5160. %% static int64_t* tospace_end;
  5161. %% \end{lstlisting}
  5162. %% The job of the \code{cheney} function is to copy all the live
  5163. %% objects (reachable from the root stack) into the ToSpace, update
  5164. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5165. %% update the root stack so that it points to the objects in the
  5166. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5167. %% and ToSpace.
  5168. %% \end{exercise}
  5169. %% \section{Compiler Passes}
  5170. %% \label{sec:code-generation-gc}
  5171. The introduction of garbage collection has a non-trivial impact on our
  5172. compiler passes. We introduce two new compiler passes named
  5173. \code{expose-allocation} and \code{uncover-locals}. We make
  5174. significant changes to \code{select-instructions},
  5175. \code{build-interference}, \code{allocate-registers}, and
  5176. \code{print-x86} and make minor changes in severl more passes. The
  5177. following program will serve as our running example. It creates two
  5178. tuples, one nested inside the other. Both tuples have length one. The
  5179. program accesses the element in the inner tuple tuple via two vector
  5180. references.
  5181. % tests/s2_17.rkt
  5182. \begin{lstlisting}
  5183. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5184. \end{lstlisting}
  5185. \section{Shrink}
  5186. \label{sec:shrink-R3}
  5187. Recall that the \code{shrink} pass translates the primitives operators
  5188. into a smaller set of primitives. Because this pass comes after type
  5189. checking, but before the passes that require the type information in
  5190. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5191. to wrap \code{HasType} around each AST node that it generates.
  5192. \section{Expose Allocation}
  5193. \label{sec:expose-allocation}
  5194. The pass \code{expose-allocation} lowers the \code{vector} creation
  5195. form into a conditional call to the collector followed by the
  5196. allocation. We choose to place the \code{expose-allocation} pass
  5197. before \code{remove-complex-opera*} because the code generated by
  5198. \code{expose-allocation} contains complex operands. We also place
  5199. \code{expose-allocation} before \code{explicate-control} because
  5200. \code{expose-allocation} introduces new variables using \code{let},
  5201. but \code{let} is gone after \code{explicate-control}.
  5202. The output of \code{expose-allocation} is a language $R'_3$ that
  5203. extends $R_3$ with the three new forms that we use in the translation
  5204. of the \code{vector} form.
  5205. \[
  5206. \begin{array}{lcl}
  5207. \Exp &::=& \cdots
  5208. \mid (\key{collect} \,\itm{int})
  5209. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5210. \mid (\key{global-value} \,\itm{name})
  5211. \end{array}
  5212. \]
  5213. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5214. $n$ bytes. It will become a call to the \code{collect} function in
  5215. \code{runtime.c} in \code{select-instructions}. The
  5216. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements. The
  5217. $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5218. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5219. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5220. a global variable, such as \code{free\_ptr}.
  5221. In the following, we show the transformation for the \code{vector}
  5222. form into 1) a sequence of let-bindings for the initializing
  5223. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5224. \code{allocate}, and 4) the initialization of the vector. In the
  5225. following, \itm{len} refers to the length of the vector and
  5226. \itm{bytes} is how many total bytes need to be allocated for the
  5227. vector, which is 8 for the tag plus \itm{len} times 8.
  5228. \begin{lstlisting}
  5229. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5230. |$\Longrightarrow$|
  5231. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5232. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5233. (global-value fromspace_end))
  5234. (void)
  5235. (collect |\itm{bytes}|))])
  5236. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5237. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5238. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5239. |$v$|) ... )))) ...)
  5240. \end{lstlisting}
  5241. In the above, we suppressed all of the \code{has-type} forms in the
  5242. output for the sake of readability. The placement of the initializing
  5243. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5244. sequence of \code{vector-set!} is important, as those expressions may
  5245. trigger garbage collection and we cannot have an allocated but
  5246. uninitialized tuple on the heap during a collection.
  5247. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5248. \code{expose-allocation} pass on our running example.
  5249. \begin{figure}[tbp]
  5250. % tests/s2_17.rkt
  5251. \begin{lstlisting}
  5252. (vector-ref
  5253. (vector-ref
  5254. (let ([vecinit7976
  5255. (let ([vecinit7972 42])
  5256. (let ([collectret7974
  5257. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5258. (void)
  5259. (collect 16)
  5260. )])
  5261. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5262. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5263. alloc7971)
  5264. )
  5265. )
  5266. )
  5267. ])
  5268. (let ([collectret7978
  5269. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5270. (void)
  5271. (collect 16)
  5272. )])
  5273. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5274. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5275. alloc7975)
  5276. )
  5277. )
  5278. )
  5279. 0)
  5280. 0)
  5281. \end{lstlisting}
  5282. \caption{Output of the \code{expose-allocation} pass, minus
  5283. all of the \code{has-type} forms.}
  5284. \label{fig:expose-alloc-output}
  5285. \end{figure}
  5286. \section{Remove Complex Operands}
  5287. \label{sec:remove-complex-opera-R3}
  5288. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5289. should all be treated as complex operands. A new case for
  5290. \code{HasType} is needed and the case for \code{Prim} needs to be
  5291. handled carefully to prevent the \code{Prim} node from being separated
  5292. from its enclosing \code{HasType}.
  5293. \section{Explicate Control and the $C_2$ language}
  5294. \label{sec:explicate-control-r3}
  5295. \begin{figure}[tbp]
  5296. \fbox{
  5297. \begin{minipage}{0.96\textwidth}
  5298. \small
  5299. \[
  5300. \begin{array}{lcl}
  5301. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5302. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5303. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5304. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5305. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5306. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5307. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5308. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5309. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5310. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5311. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5312. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5313. \end{array}
  5314. \]
  5315. \end{minipage}
  5316. }
  5317. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5318. \label{fig:c2-concrete-syntax}
  5319. \end{figure}
  5320. \begin{figure}[tp]
  5321. \fbox{
  5322. \begin{minipage}{0.96\textwidth}
  5323. \small
  5324. \[
  5325. \begin{array}{lcl}
  5326. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5327. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5328. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5329. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5330. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5331. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5332. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  5333. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  5334. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5335. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5336. \mid (\key{Collect} \,\itm{int}) \\
  5337. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5338. \mid \GOTO{\itm{label}} } \\
  5339. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5340. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5341. \end{array}
  5342. \]
  5343. \end{minipage}
  5344. }
  5345. \caption{The abstract syntax of $C_2$, an extention of $C_1$
  5346. (Figure~\ref{fig:c1-syntax}).}
  5347. \label{fig:c2-syntax}
  5348. \end{figure}
  5349. The output of \code{explicate-control} is a program in the
  5350. intermediate language $C_2$, whose concrete syntax is defined in
  5351. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5352. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5353. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5354. \key{global-value} expressions and the \code{collect} statement. The
  5355. \code{explicate-control} pass can treat these new forms much like the
  5356. other forms.
  5357. \section{Uncover Locals}
  5358. \label{sec:uncover-locals-r3}
  5359. Recall that the \code{explicate-control} function collects all of the
  5360. local variables so that it can store them in the $\itm{info}$ field of
  5361. the \code{Program} structure. Also recall that we need to know the
  5362. types of all the local variables for purposes of identifying the root
  5363. set for the garbage collector. Thus, we create a pass named
  5364. \code{uncover-locals} to collect not just the variables but the
  5365. variables and their types in the form of an alist. Thanks to the
  5366. \code{HasType} nodes, the types are readily available at every
  5367. assignment to a variable. We recommend storing the resulting alist in
  5368. the $\itm{info}$ field of the program, associated with the
  5369. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5370. of the \code{uncover-locals} pass on the running example.
  5371. \begin{figure}[tbp]
  5372. % tests/s2_17.rkt
  5373. \begin{lstlisting}
  5374. locals:
  5375. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5376. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5377. collectret7974 : 'Void, initret7977 : 'Void,
  5378. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5379. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5380. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5381. vecinit7972 : 'Integer, initret7973 : 'Void,
  5382. block91:
  5383. (collect 16)
  5384. goto block89;
  5385. block90:
  5386. collectret7974 = (void);
  5387. goto block89;
  5388. block89:
  5389. alloc7971 = (allocate 1 (Vector Integer));
  5390. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5391. vecinit7976 = alloc7971;
  5392. tmp7982 = (global-value free_ptr);
  5393. tmp7983 = (+ tmp7982 16);
  5394. tmp7984 = (global-value fromspace_end);
  5395. if (< tmp7983 tmp7984) then
  5396. goto block87;
  5397. else
  5398. goto block88;
  5399. block88:
  5400. (collect 16)
  5401. goto block86;
  5402. block87:
  5403. collectret7978 = (void);
  5404. goto block86;
  5405. block86:
  5406. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5407. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5408. tmp7985 = (vector-ref alloc7975 0);
  5409. return (vector-ref tmp7985 0);
  5410. start:
  5411. vecinit7972 = 42;
  5412. tmp7979 = (global-value free_ptr);
  5413. tmp7980 = (+ tmp7979 16);
  5414. tmp7981 = (global-value fromspace_end);
  5415. if (< tmp7980 tmp7981) then
  5416. goto block90;
  5417. else
  5418. goto block91;
  5419. \end{lstlisting}
  5420. \caption{Output of \code{uncover-locals} for the running example.}
  5421. \label{fig:uncover-locals-r3}
  5422. \end{figure}
  5423. \clearpage
  5424. \section{Select Instructions and the x86$_2$ Language}
  5425. \label{sec:select-instructions-gc}
  5426. %% void (rep as zero)
  5427. %% allocate
  5428. %% collect (callq collect)
  5429. %% vector-ref
  5430. %% vector-set!
  5431. %% global (postpone)
  5432. In this pass we generate x86 code for most of the new operations that
  5433. were needed to compile tuples, including \code{Allocate},
  5434. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5435. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5436. the later has a different concrete syntax (see
  5437. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5438. The \code{vector-ref} and \code{vector-set!} forms translate into
  5439. \code{movq} instructions. (The plus one in the offset is to get past
  5440. the tag at the beginning of the tuple representation.)
  5441. \begin{lstlisting}
  5442. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5443. |$\Longrightarrow$|
  5444. movq |$\itm{vec}'$|, %r11
  5445. movq |$-8(n+1)$|(%r11), |$\itm{lhs}$|
  5446. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5447. |$\Longrightarrow$|
  5448. movq |$\itm{vec}'$|, %r11
  5449. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5450. movq $0, |$\itm{lhs}$|
  5451. \end{lstlisting}
  5452. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by translating
  5453. $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5454. register \code{r11} ensures that offset expression
  5455. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5456. removing \code{r11} from consideration by the register allocating.
  5457. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5458. \code{rax}. Then the generated code for \code{vector-set!} would be
  5459. \begin{lstlisting}
  5460. movq |$\itm{vec}'$|, %rax
  5461. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5462. movq $0, |$\itm{lhs}$|
  5463. \end{lstlisting}
  5464. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5465. \code{patch-instructions} would insert a move through \code{rax}
  5466. as follows.
  5467. \begin{lstlisting}
  5468. movq |$\itm{vec}'$|, %rax
  5469. movq |$\itm{arg}'$|, %rax
  5470. movq %rax, |$8(n+1)$|(%rax)
  5471. movq $0, |$\itm{lhs}$|
  5472. \end{lstlisting}
  5473. But the above sequence of instructions does not work because we're
  5474. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5475. $\itm{arg}'$) at the same time!
  5476. We compile the \code{allocate} form to operations on the
  5477. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5478. is the next free address in the FromSpace, so we move it into the
  5479. \itm{lhs} and then move it forward by enough space for the tuple being
  5480. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5481. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5482. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5483. how the tag is organized. We recommend using the Racket operations
  5484. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5485. during compilation. The type annotation in the \code{vector} form is
  5486. used to determine the pointer mask region of the tag.
  5487. \begin{lstlisting}
  5488. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5489. |$\Longrightarrow$|
  5490. movq free_ptr(%rip), |$\itm{lhs}'$|
  5491. addq $|$8(\itm{len}+1)$|, free_ptr(%rip)
  5492. movq |$\itm{lhs}'$|, %r11
  5493. movq $|$\itm{tag}$|, 0(%r11)
  5494. \end{lstlisting}
  5495. The \code{collect} form is compiled to a call to the \code{collect}
  5496. function in the runtime. The arguments to \code{collect} are 1) the
  5497. top of the root stack and 2) the number of bytes that need to be
  5498. allocated. We shall use another dedicated register, \code{r15}, to
  5499. store the pointer to the top of the root stack. So \code{r15} is not
  5500. available for use by the register allocator.
  5501. \begin{lstlisting}
  5502. (collect |$\itm{bytes}$|)
  5503. |$\Longrightarrow$|
  5504. movq %r15, %rdi
  5505. movq $|\itm{bytes}|, %rsi
  5506. callq collect
  5507. \end{lstlisting}
  5508. \begin{figure}[tp]
  5509. \fbox{
  5510. \begin{minipage}{0.96\textwidth}
  5511. \[
  5512. \begin{array}{lcl}
  5513. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5514. x86_1 &::= & \gray{ \key{.globl main} }\\
  5515. & & \gray{ \key{main:} \; \Instr\ldots }
  5516. \end{array}
  5517. \]
  5518. \end{minipage}
  5519. }
  5520. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5521. \label{fig:x86-2-concrete}
  5522. \end{figure}
  5523. \begin{figure}[tp]
  5524. \fbox{
  5525. \begin{minipage}{0.96\textwidth}
  5526. \small
  5527. \[
  5528. \begin{array}{lcl}
  5529. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5530. \mid \BYTEREG{\Reg}} \\
  5531. &\mid& (\key{Global}~\Var) \\
  5532. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5533. \end{array}
  5534. \]
  5535. \end{minipage}
  5536. }
  5537. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5538. \label{fig:x86-2}
  5539. \end{figure}
  5540. The concrete and abstract syntax of the $x86_2$ language is defined in
  5541. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5542. x86$_1$ just in the addition of the form for global variables.
  5543. %
  5544. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5545. \code{select-instructions} pass on the running example.
  5546. \begin{figure}[tbp]
  5547. \centering
  5548. % tests/s2_17.rkt
  5549. \begin{minipage}[t]{0.5\textwidth}
  5550. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5551. block35:
  5552. movq free_ptr(%rip), alloc9024
  5553. addq $16, free_ptr(%rip)
  5554. movq alloc9024, %r11
  5555. movq $131, 0(%r11)
  5556. movq alloc9024, %r11
  5557. movq vecinit9025, 8(%r11)
  5558. movq $0, initret9026
  5559. movq alloc9024, %r11
  5560. movq 8(%r11), tmp9034
  5561. movq tmp9034, %r11
  5562. movq 8(%r11), %rax
  5563. jmp conclusion
  5564. block36:
  5565. movq $0, collectret9027
  5566. jmp block35
  5567. block38:
  5568. movq free_ptr(%rip), alloc9020
  5569. addq $16, free_ptr(%rip)
  5570. movq alloc9020, %r11
  5571. movq $3, 0(%r11)
  5572. movq alloc9020, %r11
  5573. movq vecinit9021, 8(%r11)
  5574. movq $0, initret9022
  5575. movq alloc9020, vecinit9025
  5576. movq free_ptr(%rip), tmp9031
  5577. movq tmp9031, tmp9032
  5578. addq $16, tmp9032
  5579. movq fromspace_end(%rip), tmp9033
  5580. cmpq tmp9033, tmp9032
  5581. jl block36
  5582. jmp block37
  5583. block37:
  5584. movq %r15, %rdi
  5585. movq $16, %rsi
  5586. callq 'collect
  5587. jmp block35
  5588. block39:
  5589. movq $0, collectret9023
  5590. jmp block38
  5591. \end{lstlisting}
  5592. \end{minipage}
  5593. \begin{minipage}[t]{0.45\textwidth}
  5594. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5595. start:
  5596. movq $42, vecinit9021
  5597. movq free_ptr(%rip), tmp9028
  5598. movq tmp9028, tmp9029
  5599. addq $16, tmp9029
  5600. movq fromspace_end(%rip), tmp9030
  5601. cmpq tmp9030, tmp9029
  5602. jl block39
  5603. jmp block40
  5604. block40:
  5605. movq %r15, %rdi
  5606. movq $16, %rsi
  5607. callq 'collect
  5608. jmp block38
  5609. \end{lstlisting}
  5610. \end{minipage}
  5611. \caption{Output of the \code{select-instructions} pass.}
  5612. \label{fig:select-instr-output-gc}
  5613. \end{figure}
  5614. \clearpage
  5615. \section{Register Allocation}
  5616. \label{sec:reg-alloc-gc}
  5617. As discussed earlier in this chapter, the garbage collector needs to
  5618. access all the pointers in the root set, that is, all variables that
  5619. are vectors. It will be the responsibility of the register allocator
  5620. to make sure that:
  5621. \begin{enumerate}
  5622. \item the root stack is used for spilling vector-typed variables, and
  5623. \item if a vector-typed variable is live during a call to the
  5624. collector, it must be spilled to ensure it is visible to the
  5625. collector.
  5626. \end{enumerate}
  5627. The later responsibility can be handled during construction of the
  5628. inference graph, by adding interference edges between the call-live
  5629. vector-typed variables and all the callee-saved registers. (They
  5630. already interfere with the caller-saved registers.) The type
  5631. information for variables is in the \code{program} form, so we
  5632. recommend adding another parameter to the \code{build-interference}
  5633. function to communicate this alist.
  5634. The spilling of vector-typed variables to the root stack can be
  5635. handled after graph coloring, when choosing how to assign the colors
  5636. (integers) to registers and stack locations. The \code{program} output
  5637. of this pass changes to also record the number of spills to the root
  5638. stack.
  5639. % build-interference
  5640. %
  5641. % callq
  5642. % extra parameter for var->type assoc. list
  5643. % update 'program' and 'if'
  5644. % allocate-registers
  5645. % allocate spilled vectors to the rootstack
  5646. % don't change color-graph
  5647. \section{Print x86}
  5648. \label{sec:print-x86-gc}
  5649. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5650. \code{print-x86} pass on the running example. In the prelude and
  5651. conclusion of the \code{main} function, we treat the root stack very
  5652. much like the regular stack in that we move the root stack pointer
  5653. (\code{r15}) to make room for the spills to the root stack, except
  5654. that the root stack grows up instead of down. For the running
  5655. example, there was just one spill so we increment \code{r15} by 8
  5656. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5657. One issue that deserves special care is that there may be a call to
  5658. \code{collect} prior to the initializing assignments for all the
  5659. variables in the root stack. We do not want the garbage collector to
  5660. accidentally think that some uninitialized variable is a pointer that
  5661. needs to be followed. Thus, we zero-out all locations on the root
  5662. stack in the prelude of \code{main}. In
  5663. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5664. %
  5665. \lstinline{movq $0, (%r15)}
  5666. %
  5667. accomplishes this task. The garbage collector tests each root to see
  5668. if it is null prior to dereferencing it.
  5669. \begin{figure}[htbp]
  5670. \begin{minipage}[t]{0.5\textwidth}
  5671. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5672. block35:
  5673. movq free_ptr(%rip), %rcx
  5674. addq $16, free_ptr(%rip)
  5675. movq %rcx, %r11
  5676. movq $131, 0(%r11)
  5677. movq %rcx, %r11
  5678. movq -8(%r15), %rax
  5679. movq %rax, 8(%r11)
  5680. movq $0, %rdx
  5681. movq %rcx, %r11
  5682. movq 8(%r11), %rcx
  5683. movq %rcx, %r11
  5684. movq 8(%r11), %rax
  5685. jmp conclusion
  5686. block36:
  5687. movq $0, %rcx
  5688. jmp block35
  5689. block38:
  5690. movq free_ptr(%rip), %rcx
  5691. addq $16, free_ptr(%rip)
  5692. movq %rcx, %r11
  5693. movq $3, 0(%r11)
  5694. movq %rcx, %r11
  5695. movq %rbx, 8(%r11)
  5696. movq $0, %rdx
  5697. movq %rcx, -8(%r15)
  5698. movq free_ptr(%rip), %rcx
  5699. addq $16, %rcx
  5700. movq fromspace_end(%rip), %rdx
  5701. cmpq %rdx, %rcx
  5702. jl block36
  5703. movq %r15, %rdi
  5704. movq $16, %rsi
  5705. callq collect
  5706. jmp block35
  5707. block39:
  5708. movq $0, %rcx
  5709. jmp block38
  5710. \end{lstlisting}
  5711. \end{minipage}
  5712. \begin{minipage}[t]{0.45\textwidth}
  5713. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5714. start:
  5715. movq $42, %rbx
  5716. movq free_ptr(%rip), %rdx
  5717. addq $16, %rdx
  5718. movq fromspace_end(%rip), %rcx
  5719. cmpq %rcx, %rdx
  5720. jl block39
  5721. movq %r15, %rdi
  5722. movq $16, %rsi
  5723. callq collect
  5724. jmp block38
  5725. .globl main
  5726. main:
  5727. pushq %rbp
  5728. movq %rsp, %rbp
  5729. pushq %r13
  5730. pushq %r12
  5731. pushq %rbx
  5732. pushq %r14
  5733. subq $0, %rsp
  5734. movq $16384, %rdi
  5735. movq $16, %rsi
  5736. callq initialize
  5737. movq rootstack_begin(%rip), %r15
  5738. movq $0, (%r15)
  5739. addq $8, %r15
  5740. jmp start
  5741. conclusion:
  5742. subq $8, %r15
  5743. addq $0, %rsp
  5744. popq %r14
  5745. popq %rbx
  5746. popq %r12
  5747. popq %r13
  5748. popq %rbp
  5749. retq
  5750. \end{lstlisting}
  5751. \end{minipage}
  5752. \caption{Output of the \code{print-x86} pass.}
  5753. \label{fig:print-x86-output-gc}
  5754. \end{figure}
  5755. \begin{figure}[p]
  5756. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5757. \node (R3) at (0,2) {\large $R_3$};
  5758. \node (R3-2) at (3,2) {\large $R_3$};
  5759. \node (R3-3) at (6,2) {\large $R_3$};
  5760. \node (R3-4) at (9,2) {\large $R_3$};
  5761. \node (R3-5) at (9,0) {\large $R'_3$};
  5762. \node (R3-6) at (6,0) {\large $R'_3$};
  5763. \node (C2-4) at (3,-2) {\large $C_2$};
  5764. \node (C2-3) at (0,-2) {\large $C_2$};
  5765. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5766. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5767. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5768. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5769. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5770. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5771. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5772. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5773. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5774. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5775. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5776. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5777. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5778. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5779. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5780. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5781. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5782. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5783. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5784. \end{tikzpicture}
  5785. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5786. \label{fig:R3-passes}
  5787. \end{figure}
  5788. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5789. for the compilation of $R_3$.
  5790. \section{Challenge: Simple Structures}
  5791. \label{sec:simple-structures}
  5792. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  5793. $R^s_3$, which extends $R^3$ with support for simple structures.
  5794. Recall that a \code{struct} in Typed Racket is a user-defined data
  5795. type that contains named fields and that is heap allocated, similar to
  5796. a vector. The following is an example of a structure definition, in
  5797. this case the definition of a \code{point} type.
  5798. \begin{lstlisting}
  5799. (struct point ([x : Integer] [y : Integer]) #:mutable)
  5800. \end{lstlisting}
  5801. \begin{figure}[tbp]
  5802. \centering
  5803. \fbox{
  5804. \begin{minipage}{0.96\textwidth}
  5805. \[
  5806. \begin{array}{lcl}
  5807. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5808. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void}\\
  5809. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5810. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  5811. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  5812. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5813. \mid (\key{and}\;\Exp\;\Exp)
  5814. \mid (\key{or}\;\Exp\;\Exp)
  5815. \mid (\key{not}\;\Exp) } \\
  5816. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5817. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  5818. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  5819. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  5820. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  5821. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  5822. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  5823. R_3 &::=& \Def \ldots \; \Exp
  5824. \end{array}
  5825. \]
  5826. \end{minipage}
  5827. }
  5828. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  5829. (Figure~\ref{fig:r3-concrete-syntax}).}
  5830. \label{fig:r3s-concrete-syntax}
  5831. \end{figure}
  5832. An instance of a structure is created using function call syntax, with
  5833. the name of the structure in the function position:
  5834. \begin{lstlisting}
  5835. (point 7 12)
  5836. \end{lstlisting}
  5837. Function-call syntax is also used to read the value in a field of a
  5838. structure. The function name is formed by the structure name, a dash,
  5839. and the field name. The following example uses \code{point-x} and
  5840. \code{point-y} to access the \code{x} and \code{y} fields of two point
  5841. instances.
  5842. \begin{center}
  5843. \begin{lstlisting}
  5844. (let ([pt1 (point 7 12)])
  5845. (let ([pt2 (point 4 3)])
  5846. (+ (- (point-x pt1) (point-x pt2))
  5847. (- (point-y pt1) (point-y pt2)))))
  5848. \end{lstlisting}
  5849. \end{center}
  5850. Similarly, to write to a field of a structure, use its set function,
  5851. whose name starts with \code{set-}, followed by the structure name,
  5852. then a dash, then the field name, and conclused with an exclamation
  5853. mark. The folowing example uses \code{set-point-x!} to change the
  5854. \code{x} field from \code{7} to \code{42}.
  5855. \begin{center}
  5856. \begin{lstlisting}
  5857. (let ([pt (point 7 12)])
  5858. (let ([_ (set-point-x! pt 42)])
  5859. (point-x pt)))
  5860. \end{lstlisting}
  5861. \end{center}
  5862. \begin{exercise}\normalfont
  5863. Extend your compiler with support for simple structures, compiling
  5864. $R^s_3$ to x86 assembly code. Create five new test cases that use
  5865. structures and test your compiler.
  5866. \end{exercise}
  5867. \section{Challenge: Generational Collection}
  5868. The copying collector described in Section~\ref{sec:GC} can incur
  5869. significant runtime overhead because the call to \code{collect} takes
  5870. time proportional to all of the live data. One way to reduce this
  5871. overhead is to reduce how much data is inspected in each call to
  5872. \code{collect}. In particular, researchers have observed that recently
  5873. allocated data is more likely to become garbage then data that has
  5874. survived one or more previous calls to \code{collect}. This insight
  5875. motivated the creation of \emph{generational garbage collectors} that
  5876. 1) segragates data according to its age into two or more generations,
  5877. 2) allocates less space for younger generations, so collecting them is
  5878. faster, and more space for the older generations, and 3) performs
  5879. collection on the younger generations more frequently then for older
  5880. generations~\citep{Wilson:1992fk}.
  5881. For this challenge assignment, the goal is to adapt the copying
  5882. collector implemented in \code{runtime.c} to use two generations, one
  5883. for young data and one for old data. Each generation consists of a
  5884. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  5885. \code{collect} function to use the two generations.
  5886. \begin{enumerate}
  5887. \item Copy the young generation's FromSpace to its ToSpace then switch
  5888. the role of the ToSpace and FromSpace
  5889. \item If there is enough space for the requested number of bytes in
  5890. the young FromSpace, then return from \code{collect}.
  5891. \item If there is not enough space in the young FromSpace for the
  5892. requested bytes, then move the data from the young generation to the
  5893. old one with the following steps:
  5894. \begin{enumerate}
  5895. \item If there is enough room in the old FromSpace, copy the young
  5896. FromSpace to the old FromSpace and then return.
  5897. \item If there is not enough room in the old FromSpace, then collect
  5898. the old generation by copying the old FromSpace to the old ToSpace
  5899. and swap the roles of the old FromSpace and ToSpace.
  5900. \item If there is enough room now, copy the young FromSpace to the
  5901. old FromSpace and return. Otherwise, allocate a larger FromSpace
  5902. and ToSpace for the old generation. Copy the young FromSpace and
  5903. the old FromSpace into the larger FromSpace for the old
  5904. generation and then return.
  5905. \end{enumerate}
  5906. \end{enumerate}
  5907. We recommend that you generalize the \code{cheney} function so that it
  5908. can be used for all the copies mentioned above: between the young
  5909. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  5910. between the young FromSpace and old FromSpace. This can be
  5911. accomplished by adding parameters to \code{cheney} that replace its
  5912. use of the global variables \code{fromspace\_begin},
  5913. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  5914. Note that the collection of the young generation does not traverse the
  5915. old generation. This introduces a potential problem: there may be
  5916. young data that is only reachable through pointers in the old
  5917. generation. If these pointers are not taken into account, the
  5918. collector could throw away young data that is live! One solution,
  5919. called \emph{pointer recording}, is to maintain a set of all the
  5920. pointers from the old generation into the new generation and consider
  5921. this set as part of the root set. To maintain this set, the compiler
  5922. must insert extra instructions around every \code{vector-set!}. If the
  5923. vector being modified is in the old generation, and if the value being
  5924. written is a pointer into the new generation, than that pointer must
  5925. be added to the set. Also, if the value being overwritten was a
  5926. pointer into the new generation, then that pointer should be removed
  5927. from the set.
  5928. \begin{exercise}\normalfont
  5929. Adapt the \code{collect} function in \code{runtime.c} to implement
  5930. generational garbage collection, as outlined in this section.
  5931. Update the code generation for \code{vector-set!} to implement
  5932. pointer recording. Make sure that your new compiler and runtime
  5933. passes your test suite.
  5934. \end{exercise}
  5935. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5936. \chapter{Functions}
  5937. \label{ch:functions}
  5938. This chapter studies the compilation of functions similar to those
  5939. found in the C language. This corresponds to a subset of Typed Racket
  5940. in which only top-level function definitions are allowed. This kind of
  5941. function is an important stepping stone to implementing
  5942. lexically-scoped functions, that is, \key{lambda} abstractions, which
  5943. is the topic of Chapter~\ref{ch:lambdas}.
  5944. \section{The $R_4$ Language}
  5945. The concrete and abstract syntax for function definitions and function
  5946. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  5947. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  5948. $R_4$ begin with zero or more function definitions. The function
  5949. names from these definitions are in-scope for the entire program,
  5950. including all other function definitions (so the ordering of function
  5951. definitions does not matter). The concrete syntax for function
  5952. application is $(\Exp \; \Exp \ldots)$ where the first expression must
  5953. evaluate to a function and the rest are the arguments.
  5954. The abstract syntax for function application is
  5955. $\APPLY{\Exp}{\Exp\ldots}$.
  5956. %% The syntax for function application does not include an explicit
  5957. %% keyword, which is error prone when using \code{match}. To alleviate
  5958. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  5959. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  5960. Functions are first-class in the sense that a function pointer is data
  5961. and can be stored in memory or passed as a parameter to another
  5962. function. Thus, we introduce a function type, written
  5963. \begin{lstlisting}
  5964. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5965. \end{lstlisting}
  5966. for a function whose $n$ parameters have the types $\Type_1$ through
  5967. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5968. these functions (with respect to Racket functions) is that they are
  5969. not lexically scoped. That is, the only external entities that can be
  5970. referenced from inside a function body are other globally-defined
  5971. functions. The syntax of $R_4$ prevents functions from being nested
  5972. inside each other.
  5973. \begin{figure}[tp]
  5974. \centering
  5975. \fbox{
  5976. \begin{minipage}{0.96\textwidth}
  5977. \small
  5978. \[
  5979. \begin{array}{lcl}
  5980. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5981. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  5982. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5983. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5984. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5985. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5986. \mid (\key{and}\;\Exp\;\Exp)
  5987. \mid (\key{or}\;\Exp\;\Exp)
  5988. \mid (\key{not}\;\Exp)} \\
  5989. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5990. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  5991. (\key{vector-ref}\;\Exp\;\Int)} \\
  5992. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  5993. \mid (\key{has-type}~\Exp~\Type)} \\
  5994. &\mid& (\Exp \; \Exp \ldots) \\
  5995. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp) \\
  5996. R_4 &::=& \Def \ldots \; \Exp
  5997. \end{array}
  5998. \]
  5999. \end{minipage}
  6000. }
  6001. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6002. \label{fig:r4-concrete-syntax}
  6003. \end{figure}
  6004. \begin{figure}[tp]
  6005. \centering
  6006. \fbox{
  6007. \begin{minipage}{0.96\textwidth}
  6008. \small
  6009. \[
  6010. \begin{array}{lcl}
  6011. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6012. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6013. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6014. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6015. &\mid& \gray{ \BOOL{\itm{bool}}
  6016. \mid \AND{\Exp}{\Exp} }\\
  6017. &\mid& \gray{ \OR{\Exp}{\Exp}
  6018. \mid \NOT{\Exp} } \\
  6019. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6020. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6021. &\mid& \gray{ \VECTOR{\Exp} } \\
  6022. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  6023. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  6024. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6025. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6026. \Def &::=& \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp}\\
  6027. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp}
  6028. \end{array}
  6029. \]
  6030. \end{minipage}
  6031. }
  6032. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6033. \label{fig:r4-syntax}
  6034. \end{figure}
  6035. The program in Figure~\ref{fig:r4-function-example} is a
  6036. representative example of defining and using functions in $R_4$. We
  6037. define a function \code{map-vec} that applies some other function
  6038. \code{f} to both elements of a vector and returns a new
  6039. vector containing the results. We also define a function \code{add1}.
  6040. The program applies
  6041. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6042. \code{(vector 1 42)}, from which we return the \code{42}.
  6043. \begin{figure}[tbp]
  6044. \begin{lstlisting}
  6045. (define (map-vec [f : (Integer -> Integer)]
  6046. [v : (Vector Integer Integer)])
  6047. : (Vector Integer Integer)
  6048. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6049. (define (add1 [x : Integer]) : Integer
  6050. (+ x 1))
  6051. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6052. \end{lstlisting}
  6053. \caption{Example of using functions in $R_4$.}
  6054. \label{fig:r4-function-example}
  6055. \end{figure}
  6056. The definitional interpreter for $R_4$ is in
  6057. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6058. responsible for setting up the mutual recursion between the top-level
  6059. function definitions. We use the classic back-patching approach that
  6060. uses mutable variables and makes two passes over the function
  6061. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6062. top-level environment using a mutable cons cell for each function
  6063. definition. Note that the \code{lambda} value for each function is
  6064. incomplete; it does not yet include the environment. Once the
  6065. top-level environment is constructed, we then iterate over it and
  6066. update the \code{lambda} values to use the top-level environment.
  6067. \begin{figure}[tp]
  6068. \begin{lstlisting}
  6069. (define (interp-exp env)
  6070. (lambda (e)
  6071. (define recur (interp-exp env))
  6072. (match e
  6073. ...
  6074. [(Apply fun args)
  6075. (define fun-val (recur fun))
  6076. (define arg-vals (for/list ([e args]) (recur e)))
  6077. (match fun-val
  6078. [`(lambda (,xs ...) ,body ,fun-env)
  6079. (define new-env (append (map cons xs arg-vals) fun-env))
  6080. ((interp-exp new-env) body)])]
  6081. ...
  6082. )))
  6083. (define (interp-def d)
  6084. (match d
  6085. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6086. (mcons f `(lambda ,xs ,body ()))]
  6087. ))
  6088. (define (interp-R4 p)
  6089. (match p
  6090. [(ProgramDefsExp info ds body)
  6091. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6092. (for/list ([b top-level])
  6093. (set-mcdr! b (match (mcdr b)
  6094. [`(lambda ,xs ,body ())
  6095. `(lambda ,xs ,body ,top-level)])))
  6096. ((interp-exp top-level) body))]
  6097. ))
  6098. \end{lstlisting}
  6099. \caption{Interpreter for the $R_4$ language.}
  6100. \label{fig:interp-R4}
  6101. \end{figure}
  6102. \section{Functions in x86}
  6103. \label{sec:fun-x86}
  6104. \margincomment{\tiny Make sure callee-saved registers are discussed
  6105. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6106. \margincomment{\tiny Talk about the return address on the
  6107. stack and what callq and retq does.\\ --Jeremy }
  6108. The x86 architecture provides a few features to support the
  6109. implementation of functions. We have already seen that x86 provides
  6110. labels so that one can refer to the location of an instruction, as is
  6111. needed for jump instructions. Labels can also be used to mark the
  6112. beginning of the instructions for a function. Going further, we can
  6113. obtain the address of a label by using the \key{leaq} instruction and
  6114. \key{rip}-relative addressing. For example, the following puts the
  6115. address of the \code{add1} label into the \code{rbx} register.
  6116. \begin{lstlisting}
  6117. leaq add1(%rip), %rbx
  6118. \end{lstlisting}
  6119. The instruction pointer register \key{rip} (aka. the program counter
  6120. or PC) always points to the next instruction to be executed. When
  6121. combined with an label, as in \code{add1(\%rip)}, the linker computes
  6122. the distance $d$ between the address of \code{add1} and where the
  6123. \code{rip} would be at that moment and then changes \code{add1(\%rip)}
  6124. to \code{$d$(\%rip)}, which at runtime will compute the address of
  6125. \code{add1}.
  6126. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6127. jump to a function whose location is given by a label. To support
  6128. function calls in this chapter we instead will be jumping to a
  6129. function whose location is given by an address in a register, that is,
  6130. we need to make an \emph{indirect function call}. The x86 syntax for
  6131. this is a \code{callq} instruction but with an asterisk before the
  6132. register name.
  6133. \begin{lstlisting}
  6134. callq *%rbx
  6135. \end{lstlisting}
  6136. \subsection{Calling Conventions}
  6137. The \code{callq} instruction provides partial support for implementing
  6138. functions: it pushes the return address on the stack and it jumps to
  6139. the target. However, \code{callq} does not handle
  6140. \begin{enumerate}
  6141. \item parameter passing,
  6142. \item saving and restoring frames on the procedure call stack, or
  6143. \item determining how registers are shared by different functions.
  6144. \end{enumerate}
  6145. These issues require coordination between the caller and the callee,
  6146. which is often assembly code written by different programmers or
  6147. generated by different compilers. As a result, people have developed
  6148. \emph{conventions} that govern how functions calls are performed.
  6149. Here we use conventions that are compatible with those of the
  6150. \code{gcc} compiler~\citep{Matz:2013aa}.
  6151. Regarding (1) parameter passing, the convention is to use the
  6152. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  6153. \code{rcx}, \code{r8}, and \code{r9}, in that order, to pass arguments
  6154. to a function. If there are more than six arguments, then the
  6155. convention is to use space on the frame of the caller for the rest of
  6156. the arguments. However, to ease the implementation of efficient tail
  6157. calls (Section~\ref{sec:tail-call}), we arrange to never need more
  6158. than six arguments.
  6159. %
  6160. The register \code{rax} is for the return value of the function.
  6161. Regarding (2) frames and the procedure call stack, recall from
  6162. Section~\ref{sec:x86} that the stack grows down, with each function
  6163. call using a chunk of space called a frame. The caller sets the stack
  6164. pointer, register \code{rsp}, to the last data item in its frame. The
  6165. callee must not change anything in the caller's frame, that is,
  6166. anything that is at or above the stack pointer. The callee is free to
  6167. use locations that are below the stack pointer.
  6168. Regarding (3) the sharing of registers between different functions,
  6169. recall from Section~\ref{sec:calling-conventions} that the registers
  6170. are divided into two groups, the caller-saved registers and the
  6171. callee-saved registers. The caller should assume that all the
  6172. caller-saved registers get overwritten with arbitrary values by the
  6173. callee. That is why we recommend in
  6174. Section~\ref{sec:calling-conventions} that variables that are live
  6175. during a function call should not be assigned to caller-saved
  6176. registers.
  6177. On the flip side, if the callee wants to use a callee-saved register,
  6178. the callee must save the contents of those registers on their stack
  6179. frame and then put them back prior to returning to the caller. That
  6180. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6181. the register allocator assigns a variable to a callee-saved register,
  6182. then the prelude of the \code{main} function must save that register
  6183. to the stack and the conclusion of \code{main} must restore it. This
  6184. recommendation now generalizes to all functions.
  6185. Also recall that the base pointer, register \code{rbp}, is used as a
  6186. point-of-reference within a frame, so that each local variable can be
  6187. accessed at a fixed offset from the base pointer
  6188. (Section~\ref{sec:x86}).
  6189. %
  6190. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6191. and callee frames.
  6192. \begin{figure}[tbp]
  6193. \centering
  6194. \begin{tabular}{r|r|l|l} \hline
  6195. Caller View & Callee View & Contents & Frame \\ \hline
  6196. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6197. 0(\key{\%rbp}) & & old \key{rbp} \\
  6198. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6199. \ldots & & \ldots \\
  6200. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6201. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6202. \ldots & & \ldots \\
  6203. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6204. %% & & \\
  6205. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6206. %% & \ldots & \ldots \\
  6207. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6208. \hline
  6209. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6210. & 0(\key{\%rbp}) & old \key{rbp} \\
  6211. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6212. & \ldots & \ldots \\
  6213. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6214. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6215. & \ldots & \ldots \\
  6216. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6217. \end{tabular}
  6218. \caption{Memory layout of caller and callee frames.}
  6219. \label{fig:call-frames}
  6220. \end{figure}
  6221. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6222. %% local variables and for storing the values of callee-saved registers
  6223. %% (we shall refer to all of these collectively as ``locals''), and that
  6224. %% at the beginning of a function we move the stack pointer \code{rsp}
  6225. %% down to make room for them.
  6226. %% We recommend storing the local variables
  6227. %% first and then the callee-saved registers, so that the local variables
  6228. %% can be accessed using \code{rbp} the same as before the addition of
  6229. %% functions.
  6230. %% To make additional room for passing arguments, we shall
  6231. %% move the stack pointer even further down. We count how many stack
  6232. %% arguments are needed for each function call that occurs inside the
  6233. %% body of the function and find their maximum. Adding this number to the
  6234. %% number of locals gives us how much the \code{rsp} should be moved at
  6235. %% the beginning of the function. In preparation for a function call, we
  6236. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6237. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6238. %% so on.
  6239. %% Upon calling the function, the stack arguments are retrieved by the
  6240. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6241. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6242. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6243. %% the layout of the caller and callee frames. Notice how important it is
  6244. %% that we correctly compute the maximum number of arguments needed for
  6245. %% function calls; if that number is too small then the arguments and
  6246. %% local variables will smash into each other!
  6247. \subsection{Efficient Tail Calls}
  6248. \label{sec:tail-call}
  6249. In general, the amount of stack space used by a program is determined
  6250. by the longest chain of nested function calls. That is, if function
  6251. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6252. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6253. $n$ can grow quite large in the case of recursive or mutually
  6254. recursive functions. However, in some cases we can arrange to use only
  6255. constant space, i.e. $O(1)$, instead of $O(n)$.
  6256. If a function call is the last action in a function body, then that
  6257. call is said to be a \emph{tail call}. In such situations, the frame
  6258. of the caller is no longer needed, so we can pop the caller's frame
  6259. before making the tail call. With this approach, a recursive function
  6260. that only makes tail calls will only use $O(1)$ stack space.
  6261. Functional languages like Racket typically rely heavily on recursive
  6262. functions, so they typically guarantee that all tail calls will be
  6263. optimized in this way.
  6264. However, some care is needed with regards to argument passing in tail
  6265. calls. As mentioned above, for arguments beyond the sixth, the
  6266. convention is to use space in the caller's frame for passing
  6267. arguments. But for a tail call we pop the caller's frame and can no
  6268. longer use it. Another alternative is to use space in the callee's
  6269. frame for passing arguments. However, this option is also problematic
  6270. because the caller and callee's frame overlap in memory. As we begin
  6271. to copy the arguments from their sources in the caller's frame, the
  6272. target locations in the callee's frame might overlap with the sources
  6273. for later arguments! We solve this problem by not using the stack for
  6274. passing more than six arguments but instead using the heap, as we
  6275. describe in the Section~\ref{sec:limit-functions-r4}.
  6276. As mentioned above, for a tail call we pop the caller's frame prior to
  6277. making the tail call. The instructions for popping a frame are the
  6278. instructions that we usually place in the conclusion of a
  6279. function. Thus, we also need to place such code immediately before
  6280. each tail call. These instructions include restoring the callee-saved
  6281. registers, so it is good that the argument passing registers are all
  6282. caller-saved registers.
  6283. One last note regarding which instruction to use to make the tail
  6284. call. When the callee is finished, it should not return to the current
  6285. function, but it should return to the function that called the current
  6286. one. Thus, the return address that is already on the stack is the
  6287. right one, and we should not use \key{callq} to make the tail call, as
  6288. that would unnecessarily overwrite the return address. Instead we can
  6289. simply use the \key{jmp} instruction. Like the indirect function call,
  6290. we write an indirect jump with a register prefixed with an asterisk.
  6291. We recommend using \code{rax} to hold the jump target because the
  6292. preceding conclusion overwrites just about everything else.
  6293. \begin{lstlisting}
  6294. jmp *%rax
  6295. \end{lstlisting}
  6296. \section{Shrink $R_4$}
  6297. \label{sec:shrink-r4}
  6298. The \code{shrink} pass performs a minor modifications to ease the
  6299. later passes. This pass introduces an explicit \code{main} function
  6300. and changes the top \code{ProgramDefsExp} form to
  6301. \code{ProgramDefs} as follows.
  6302. \begin{lstlisting}
  6303. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6304. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6305. \end{lstlisting}
  6306. where $\itm{mainDef}$ is
  6307. \begin{lstlisting}
  6308. (Def main () Integer () |$\Exp'$|)
  6309. \end{lstlisting}
  6310. \section{Reveal Functions and the $F_1$ language}
  6311. \label{sec:reveal-functions-r4}
  6312. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6313. respect: it conflates the use of function names and local
  6314. variables. This is a problem because we need to compile the use of a
  6315. function name differently than the use of a local variable; we need to
  6316. use \code{leaq} to convert the function name (a label in x86) to an
  6317. address in a register. Thus, it is a good idea to create a new pass
  6318. that changes function references from just a symbol $f$ to
  6319. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6320. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6321. \begin{figure}[tp]
  6322. \centering
  6323. \fbox{
  6324. \begin{minipage}{0.96\textwidth}
  6325. \[
  6326. \begin{array}{lcl}
  6327. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6328. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6329. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6330. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6331. &\mid& \gray{ \BOOL{\itm{bool}}
  6332. \mid \AND{\Exp}{\Exp} }\\
  6333. &\mid& \gray{ \OR{\Exp}{\Exp}
  6334. \mid \NOT{\Exp} } \\
  6335. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6336. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6337. &\mid& \gray{ \VECTOR{\Exp} } \\
  6338. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  6339. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  6340. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6341. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6342. &\mid& \FUNREF{\Var}\\
  6343. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6344. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6345. \end{array}
  6346. \]
  6347. \end{minipage}
  6348. }
  6349. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6350. (Figure~\ref{fig:r4-syntax}).}
  6351. \label{fig:f1-syntax}
  6352. \end{figure}
  6353. %% Distinguishing between calls in tail position and non-tail position
  6354. %% requires the pass to have some notion of context. We recommend using
  6355. %% two mutually recursive functions, one for processing expressions in
  6356. %% tail position and another for the rest.
  6357. Placing this pass after \code{uniquify} will make sure that there are
  6358. no local variables and functions that share the same name. On the
  6359. other hand, \code{reveal-functions} needs to come before the
  6360. \code{explicate-control} pass because that pass helps us compile
  6361. \code{FunRef} forms into assignment statements.
  6362. \section{Limit Functions}
  6363. \label{sec:limit-functions-r4}
  6364. Recall that we wish to limit the number of function parameters to six
  6365. so that we do not need to use the stack for argument passing, which
  6366. makes it easier to implement efficient tail calls. However, because
  6367. the input language $R_4$ supports arbitrary numbers of function
  6368. arguments, we have some work to do!
  6369. This pass transforms functions and function calls that involve more
  6370. than six arguments to pass the first five arguments as usual, but it
  6371. packs the rest of the arguments into a vector and passes it as the
  6372. sixth argument. So for any function call with $n$ arguments more than
  6373. six, the \code{limit-functions} pass transforms it in the following
  6374. way.
  6375. \begin{tabular}{lll}
  6376. \begin{minipage}{0.2\textwidth}
  6377. \begin{lstlisting}
  6378. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6379. \end{lstlisting}
  6380. \end{minipage}
  6381. &
  6382. $\Rightarrow$
  6383. &
  6384. \begin{minipage}{0.4\textwidth}
  6385. \begin{lstlisting}
  6386. (|$e_0$| |$e_1$| |$\ldots$| |$e_5$| (vector |$e_6$| |$\ldots$| |$e_n$|))
  6387. \end{lstlisting}
  6388. \end{minipage}
  6389. \end{tabular}
  6390. \margincomment{UNDER CONSTRUCTION --Jeremy}
  6391. In the body of the function, all occurrences of the $i$th argument in
  6392. which $i>5$ must be replaced with a \code{vector-ref}.
  6393. \section{Remove Complex Operators and Operands}
  6394. \label{sec:rco-r4}
  6395. The primary decisions to make for this pass is whether to classify
  6396. \code{fun-ref} and \code{app} as either simple or complex
  6397. expressions. Recall that a simple expression will eventually end up as
  6398. just an ``immediate'' argument of an x86 instruction. Function
  6399. application will be translated to a sequence of instructions, so
  6400. \code{app} must be classified as complex expression. Regarding
  6401. \code{fun-ref}, as discussed above, the function label needs to
  6402. be converted to an address using the \code{leaq} instruction. Thus,
  6403. even though \code{fun-ref} seems rather simple, it needs to be
  6404. classified as a complex expression so that we generate an assignment
  6405. statement with a left-hand side that can serve as the target of the
  6406. \code{leaq}.
  6407. \section{Explicate Control and the $C_3$ language}
  6408. \label{sec:explicate-control-r4}
  6409. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  6410. \key{explicate-control}. The three mutually recursive functions for
  6411. this pass, for assignment, tail, and predicate contexts, must all be
  6412. updated with cases for \code{fun-ref} and \code{app}. In
  6413. assignment and predicate contexts, \code{app} becomes \code{call},
  6414. whereas in tail position \code{app} becomes \code{tailcall}. We
  6415. recommend defining a new function for processing function definitions.
  6416. This code is similar to the case for \code{program} in $R_3$. The
  6417. top-level \code{explicate-control} function that handles the
  6418. \code{program} form of $R_4$ can then apply this new function to all
  6419. the function definitions.
  6420. \begin{figure}[tp]
  6421. \fbox{
  6422. \begin{minipage}{0.96\textwidth}
  6423. \[
  6424. \begin{array}{lcl}
  6425. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6426. \\
  6427. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6428. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  6429. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  6430. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6431. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  6432. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6433. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg\ldots) \\
  6434. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6435. \mid (\key{collect} \,\itm{int}) }\\
  6436. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6437. &\mid& \gray{(\key{goto}\,\itm{label})
  6438. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6439. &\mid& (\key{tailcall} \,\Arg\,\Arg\ldots) \\
  6440. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6441. C_3 & ::= & (\key{program}\;\itm{info}\;\Def\ldots)
  6442. \end{array}
  6443. \]
  6444. \end{minipage}
  6445. }
  6446. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  6447. \label{fig:c3-syntax}
  6448. \end{figure}
  6449. \section{Uncover Locals}
  6450. \label{sec:uncover-locals-r4}
  6451. The function for processing $\Tail$ should be updated with a case for
  6452. \code{tailcall}. We also recommend creating a new function for
  6453. processing function definitions. Each function definition in $C_3$ has
  6454. its own set of local variables, so the code for function definitions
  6455. should be similar to the case for the \code{program} form in $C_2$.
  6456. \section{Select Instructions and the x86$_3$ Language}
  6457. \label{sec:select-r4}
  6458. The output of select instructions is a program in the x86$_3$
  6459. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6460. \begin{figure}[tp]
  6461. \fbox{
  6462. \begin{minipage}{0.96\textwidth}
  6463. \[
  6464. \begin{array}{lcl}
  6465. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6466. \mid (\key{deref}\,\Reg\,\Int) } \\
  6467. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6468. \mid (\key{global}\; \itm{name}) } \\
  6469. &\mid& (\key{fun-ref}\; \itm{label})\\
  6470. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6471. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6472. (\key{subq} \; \Arg\; \Arg) \mid
  6473. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6474. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6475. (\key{pushq}\;\Arg) \mid
  6476. (\key{popq}\;\Arg) \mid
  6477. (\key{retq}) } \\
  6478. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6479. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6480. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6481. \mid (\key{jmp} \; \itm{label})
  6482. \mid (\key{j}\itm{cc} \; \itm{label})
  6483. \mid (\key{label} \; \itm{label}) } \\
  6484. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6485. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  6486. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6487. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6488. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6489. \end{array}
  6490. \]
  6491. \end{minipage}
  6492. }
  6493. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6494. \label{fig:x86-3}
  6495. \end{figure}
  6496. An assignment of \code{FunRef} becomes a \code{leaq} instruction
  6497. as follows: \\
  6498. \begin{tabular}{lll}
  6499. \begin{minipage}{0.45\textwidth}
  6500. \begin{lstlisting}
  6501. (Assign |$\itm{lhs}$| (FunRef |$f$|))
  6502. \end{lstlisting}
  6503. \end{minipage}
  6504. &
  6505. $\Rightarrow$
  6506. &
  6507. \begin{minipage}{0.4\textwidth}
  6508. \begin{lstlisting}
  6509. (Instr 'leaq (list (FunRef |$f$|) |$\itm{lhs}'$|))
  6510. \end{lstlisting}
  6511. \end{minipage}
  6512. \end{tabular} \\
  6513. Regarding function definitions, we need to remove their parameters and
  6514. instead perform parameter passing in terms of the conventions
  6515. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  6516. in the argument passing registers, and inside the function we should
  6517. generate a \code{movq} instruction for each parameter, to move the
  6518. argument value from the appropriate register to a new local variable
  6519. with the same name as the old parameter.
  6520. Next, consider the compilation of function calls, which have the
  6521. following form upon input to \code{select-instructions}.
  6522. \begin{lstlisting}
  6523. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  6524. \end{lstlisting}
  6525. In the mirror image of handling the parameters of function
  6526. definitions, the arguments \itm{args} need to be moved to the argument
  6527. passing registers.
  6528. %
  6529. Once the instructions for parameter passing have been generated, the
  6530. function call itself can be performed with an indirect function call,
  6531. for which I recommend creating the new instruction
  6532. \code{indirect-callq}. Of course, the return value from the function
  6533. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  6534. \begin{lstlisting}
  6535. (indirect-callq |\itm{fun}|)
  6536. (movq (reg rax) |\itm{lhs}|)
  6537. \end{lstlisting}
  6538. Regarding tail calls, the parameter passing is the same as non-tail
  6539. calls: generate instructions to move the arguments into to the
  6540. argument passing registers. After that we need to pop the frame from
  6541. the procedure call stack. However, we do not yet know how big the
  6542. frame is; that gets determined during register allocation. So instead
  6543. of generating those instructions here, we invent a new instruction
  6544. that means ``pop the frame and then do an indirect jump'', which we
  6545. name \code{tail-jmp}.
  6546. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6547. using the label \code{start} for the initial block of a program, and
  6548. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6549. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  6550. can be compiled to an assignment to \code{rax} followed by a jump to
  6551. \code{conclusion}. With the addition of function definitions, we will
  6552. have a starting block and conclusion for each function, but their
  6553. labels need to be unique. We recommend prepending the function's name
  6554. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6555. labels. (Alternatively, one could \code{gensym} labels for the start
  6556. and conclusion and store them in the $\itm{info}$ field of the
  6557. function definition.)
  6558. \section{Uncover Live}
  6559. %% The rest of the passes need only minor modifications to handle the new
  6560. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6561. %% \code{leaq}.
  6562. Inside \code{uncover-live}, when computing the $W$ set (written
  6563. variables) for an \code{indirect-callq} instruction, we recommend
  6564. including all the caller-saved registers, which will have the affect
  6565. of making sure that no caller-saved register actually needs to be
  6566. saved.
  6567. \section{Build Interference Graph}
  6568. With the addition of function definitions, we compute an interference
  6569. graph for each function (not just one for the whole program).
  6570. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6571. spill vector-typed variables that are live during a call to the
  6572. \code{collect}. With the addition of functions to our language, we
  6573. need to revisit this issue. Many functions will perform allocation and
  6574. therefore have calls to the collector inside of them. Thus, we should
  6575. not only spill a vector-typed variable when it is live during a call
  6576. to \code{collect}, but we should spill the variable if it is live
  6577. during any function call. Thus, in the \code{build-interference} pass,
  6578. we recommend adding interference edges between call-live vector-typed
  6579. variables and the callee-saved registers (in addition to the usual
  6580. addition of edges between call-live variables and the caller-saved
  6581. registers).
  6582. \section{Patch Instructions}
  6583. In \code{patch-instructions}, you should deal with the x86
  6584. idiosyncrasy that the destination argument of \code{leaq} must be a
  6585. register. Additionally, you should ensure that the argument of
  6586. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  6587. code generation more convenient, because we will be trampling many
  6588. registers before the tail call (as explained below).
  6589. \section{Print x86}
  6590. For the \code{print-x86} pass, we recommend the following translations:
  6591. \begin{lstlisting}
  6592. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6593. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6594. \end{lstlisting}
  6595. Handling \code{tail-jmp} requires a bit more care. A straightforward
  6596. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  6597. is what we will want to do, but before the jump we need to pop the
  6598. current frame. So we need to restore the state of the registers to the
  6599. point they were at when the current function was called. This
  6600. sequence of instructions is the same as the code for the conclusion of
  6601. a function.
  6602. Note that your \code{print-x86} pass needs to add the code for saving
  6603. and restoring callee-saved registers, if you have not already
  6604. implemented that. This is necessary when generating code for function
  6605. definitions.
  6606. \section{An Example Translation}
  6607. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6608. function in $R_4$ to x86. The figure also includes the results of the
  6609. \code{explicate-control} and \code{select-instructions} passes. We
  6610. have omitted the \code{has-type} AST nodes for readability. Can you
  6611. see any ways to improve the translation?
  6612. \begin{figure}[tbp]
  6613. \begin{tabular}{ll}
  6614. \begin{minipage}{0.45\textwidth}
  6615. % s3_2.rkt
  6616. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6617. (program
  6618. (define (add [x : Integer]
  6619. [y : Integer])
  6620. : Integer (+ x y))
  6621. (add 40 2))
  6622. \end{lstlisting}
  6623. $\Downarrow$
  6624. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6625. (program ()
  6626. (define (add86 [x87 : Integer]
  6627. [y88 : Integer]) : Integer ()
  6628. ((add86start . (return (+ x87 y88)))))
  6629. (define (main) : Integer ()
  6630. ((mainstart .
  6631. (seq (assign tmp89 (fun-ref add86))
  6632. (tailcall tmp89 40 2))))))
  6633. \end{lstlisting}
  6634. \end{minipage}
  6635. &
  6636. $\Rightarrow$
  6637. \begin{minipage}{0.5\textwidth}
  6638. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6639. (program ()
  6640. (define (add86)
  6641. ((locals (x87 . Integer) (y88 . Integer))
  6642. (num-params . 2))
  6643. ((add86start .
  6644. (block ()
  6645. (movq (reg rcx) (var x87))
  6646. (movq (reg rdx) (var y88))
  6647. (movq (var x87) (reg rax))
  6648. (addq (var y88) (reg rax))
  6649. (jmp add86conclusion)))))
  6650. (define (main)
  6651. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6652. (num-params . 0))
  6653. ((mainstart .
  6654. (block ()
  6655. (leaq (fun-ref add86) (var tmp89))
  6656. (movq (int 40) (reg rcx))
  6657. (movq (int 2) (reg rdx))
  6658. (tail-jmp (var tmp89))))))
  6659. \end{lstlisting}
  6660. $\Downarrow$
  6661. \end{minipage}
  6662. \end{tabular}
  6663. \begin{tabular}{lll}
  6664. \begin{minipage}{0.3\textwidth}
  6665. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6666. _add90start:
  6667. movq %rcx, %rsi
  6668. movq %rdx, %rcx
  6669. movq %rsi, %rax
  6670. addq %rcx, %rax
  6671. jmp _add90conclusion
  6672. .globl _add90
  6673. .align 16
  6674. _add90:
  6675. pushq %rbp
  6676. movq %rsp, %rbp
  6677. pushq %r12
  6678. pushq %rbx
  6679. pushq %r13
  6680. pushq %r14
  6681. subq $0, %rsp
  6682. jmp _add90start
  6683. _add90conclusion:
  6684. addq $0, %rsp
  6685. popq %r14
  6686. popq %r13
  6687. popq %rbx
  6688. popq %r12
  6689. subq $0, %r15
  6690. popq %rbp
  6691. retq
  6692. \end{lstlisting}
  6693. \end{minipage}
  6694. &
  6695. \begin{minipage}{0.3\textwidth}
  6696. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6697. _mainstart:
  6698. leaq _add90(%rip), %rsi
  6699. movq $40, %rcx
  6700. movq $2, %rdx
  6701. movq %rsi, %rax
  6702. addq $0, %rsp
  6703. popq %r14
  6704. popq %r13
  6705. popq %rbx
  6706. popq %r12
  6707. subq $0, %r15
  6708. popq %rbp
  6709. jmp *%rax
  6710. .globl _main
  6711. .align 16
  6712. _main:
  6713. pushq %rbp
  6714. movq %rsp, %rbp
  6715. pushq %r12
  6716. pushq %rbx
  6717. pushq %r13
  6718. pushq %r14
  6719. subq $0, %rsp
  6720. movq $16384, %rdi
  6721. movq $16, %rsi
  6722. callq _initialize
  6723. movq _rootstack_begin(%rip), %r15
  6724. jmp _mainstart
  6725. \end{lstlisting}
  6726. \end{minipage}
  6727. &
  6728. \begin{minipage}{0.3\textwidth}
  6729. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6730. _mainconclusion:
  6731. addq $0, %rsp
  6732. popq %r14
  6733. popq %r13
  6734. popq %rbx
  6735. popq %r12
  6736. subq $0, %r15
  6737. popq %rbp
  6738. retq
  6739. \end{lstlisting}
  6740. \end{minipage}
  6741. \end{tabular}
  6742. \caption{Example compilation of a simple function to x86.}
  6743. \label{fig:add-fun}
  6744. \end{figure}
  6745. \begin{exercise}\normalfont
  6746. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6747. Create 5 new programs that use functions, including examples that pass
  6748. functions and return functions from other functions and including
  6749. recursive functions. Test your compiler on these new programs and all
  6750. of your previously created test programs.
  6751. \end{exercise}
  6752. \begin{figure}[p]
  6753. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6754. \node (R4) at (0,2) {\large $R_4$};
  6755. \node (R4-2) at (3,2) {\large $R_4$};
  6756. \node (R4-3) at (6,2) {\large $R_4$};
  6757. \node (F1-1) at (12,0) {\large $F_1$};
  6758. \node (F1-2) at (9,0) {\large $F_1$};
  6759. \node (F1-3) at (6,0) {\large $F_1$};
  6760. \node (F1-4) at (3,0) {\large $F_1$};
  6761. \node (C3-1) at (6,-2) {\large $C_3$};
  6762. \node (C3-2) at (3,-2) {\large $C_3$};
  6763. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6764. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6765. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  6766. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6767. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6768. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6769. \path[->,bend left=15] (R4) edge [above] node
  6770. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6771. \path[->,bend left=15] (R4-2) edge [above] node
  6772. {\ttfamily\footnotesize uniquify} (R4-3);
  6773. \path[->,bend left=15] (R4-3) edge [right] node
  6774. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6775. \path[->,bend left=15] (F1-1) edge [below] node
  6776. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6777. \path[->,bend right=15] (F1-2) edge [above] node
  6778. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6779. \path[->,bend right=15] (F1-3) edge [above] node
  6780. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6781. \path[->,bend left=15] (F1-4) edge [right] node
  6782. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6783. \path[->,bend left=15] (C3-1) edge [below] node
  6784. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6785. \path[->,bend right=15] (C3-2) edge [left] node
  6786. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6787. \path[->,bend left=15] (x86-2) edge [left] node
  6788. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6789. \path[->,bend right=15] (x86-2-1) edge [below] node
  6790. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6791. \path[->,bend right=15] (x86-2-2) edge [left] node
  6792. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6793. \path[->,bend left=15] (x86-3) edge [above] node
  6794. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6795. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6796. \end{tikzpicture}
  6797. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6798. \label{fig:R4-passes}
  6799. \end{figure}
  6800. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6801. the compilation of $R_4$.
  6802. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6803. \chapter{Lexically Scoped Functions}
  6804. \label{ch:lambdas}
  6805. This chapter studies lexically scoped functions as they appear in
  6806. functional languages such as Racket. By lexical scoping we mean that a
  6807. function's body may refer to variables whose binding site is outside
  6808. of the function, in an enclosing scope.
  6809. %
  6810. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6811. anonymous function defined using the \key{lambda} form. The body of
  6812. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6813. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6814. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6815. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6816. returned from the function \code{f}. Below the definition of \code{f},
  6817. we have two calls to \code{f} with different arguments for \code{x},
  6818. first \code{5} then \code{3}. The functions returned from \code{f} are
  6819. bound to variables \code{g} and \code{h}. Even though these two
  6820. functions were created by the same \code{lambda}, they are really
  6821. different functions because they use different values for
  6822. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6823. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6824. the result of this program is \code{42}.
  6825. \begin{figure}[btp]
  6826. % s4_6.rkt
  6827. \begin{lstlisting}
  6828. (define (f [x : Integer]) : (Integer -> Integer)
  6829. (let ([y 4])
  6830. (lambda: ([z : Integer]) : Integer
  6831. (+ x (+ y z)))))
  6832. (let ([g (f 5)])
  6833. (let ([h (f 3)])
  6834. (+ (g 11) (h 15))))
  6835. \end{lstlisting}
  6836. \caption{Example of a lexically scoped function.}
  6837. \label{fig:lexical-scoping}
  6838. \end{figure}
  6839. \section{The $R_5$ Language}
  6840. The syntax for this language with anonymous functions and lexical
  6841. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6842. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6843. for function application. In this chapter we shall describe how to
  6844. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6845. into a combination of functions (as in $R_4$) and tuples (as in
  6846. $R_3$).
  6847. \begin{figure}[tp]
  6848. \centering
  6849. \fbox{
  6850. \begin{minipage}{0.96\textwidth}
  6851. \[
  6852. \begin{array}{lcl}
  6853. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6854. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  6855. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  6856. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6857. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6858. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6859. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6860. \mid (\key{and}\;\Exp\;\Exp)
  6861. \mid (\key{or}\;\Exp\;\Exp)
  6862. \mid (\key{not}\;\Exp) } \\
  6863. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6864. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6865. (\key{vector-ref}\;\Exp\;\Int)} \\
  6866. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6867. &\mid& \gray{(\Exp \; \Exp\ldots)} \\
  6868. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp) \\
  6869. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  6870. R_5 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  6871. \end{array}
  6872. \]
  6873. \end{minipage}
  6874. }
  6875. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6876. with \key{lambda}.}
  6877. \label{fig:r5-syntax}
  6878. \end{figure}
  6879. To compile lexically-scoped functions to top-level function
  6880. definitions, the compiler will need to provide special treatment to
  6881. variable occurrences such as \code{x} and \code{y} in the body of the
  6882. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6883. of $R_4$ may not refer to variables defined outside the function. To
  6884. identify such variable occurrences, we review the standard notion of
  6885. free variable.
  6886. \begin{definition}
  6887. A variable is \emph{free with respect to an expression} $e$ if the
  6888. variable occurs inside $e$ but does not have an enclosing binding in
  6889. $e$.
  6890. \end{definition}
  6891. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6892. free with respect to the expression \code{(+ x (+ y z))}. On the
  6893. other hand, only \code{x} and \code{y} are free with respect to the
  6894. following expression because \code{z} is bound by the \code{lambda}.
  6895. \begin{lstlisting}
  6896. (lambda: ([z : Integer]) : Integer
  6897. (+ x (+ y z)))
  6898. \end{lstlisting}
  6899. Once we have identified the free variables of a \code{lambda}, we need
  6900. to arrange for some way to transport, at runtime, the values of those
  6901. variables from the point where the \code{lambda} was created to the
  6902. point where the \code{lambda} is applied. Referring again to
  6903. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6904. needs to be used in the application of \code{g} to \code{11}, but the
  6905. binding of \code{x} to \code{3} needs to be used in the application of
  6906. \code{h} to \code{15}. An efficient solution to the problem, due to
  6907. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6908. free variables together with the function pointer for the lambda's
  6909. code, an arrangement called a \emph{flat closure} (which we shorten to
  6910. just ``closure'') . Fortunately, we have all the ingredients to make
  6911. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6912. Chapter~\ref{ch:functions} gave us function pointers. The function
  6913. pointer shall reside at index $0$ and the values for free variables
  6914. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6915. the two closures created by the two calls to \code{f} in
  6916. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6917. the same \key{lambda}, they share the same function pointer but differ
  6918. in the values for the free variable \code{x}.
  6919. \begin{figure}[tbp]
  6920. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6921. \caption{Example closure representation for the \key{lambda}'s
  6922. in Figure~\ref{fig:lexical-scoping}.}
  6923. \label{fig:closures}
  6924. \end{figure}
  6925. \section{Interpreting $R_5$}
  6926. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6927. $R_5$. The clause for \key{lambda} saves the current environment
  6928. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6929. the environment from the \key{lambda}, the \code{lam-env}, when
  6930. interpreting the body of the \key{lambda}. The \code{lam-env}
  6931. environment is extended with the mapping of parameters to argument
  6932. values.
  6933. \begin{figure}[tbp]
  6934. \begin{lstlisting}
  6935. (define (interp-exp env)
  6936. (lambda (e)
  6937. (define recur (interp-exp env))
  6938. (match e
  6939. ...
  6940. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6941. `(lambda ,xs ,body ,env)]
  6942. [`(app ,fun ,args ...)
  6943. (define fun-val ((interp-exp env) fun))
  6944. (define arg-vals (map (interp-exp env) args))
  6945. (match fun-val
  6946. [`(lambda (,xs ...) ,body ,lam-env)
  6947. (define new-env (append (map cons xs arg-vals) lam-env))
  6948. ((interp-exp new-env) body)]
  6949. [else (error "interp-exp, expected function, not" fun-val)])]
  6950. [else (error 'interp-exp "unrecognized expression")]
  6951. )))
  6952. \end{lstlisting}
  6953. \caption{Interpreter for $R_5$.}
  6954. \label{fig:interp-R5}
  6955. \end{figure}
  6956. \section{Type Checking $R_5$}
  6957. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6958. \key{lambda} form. The body of the \key{lambda} is checked in an
  6959. environment that includes the current environment (because it is
  6960. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6961. require the body's type to match the declared return type.
  6962. \begin{figure}[tbp]
  6963. \begin{lstlisting}
  6964. (define (typecheck-R5 env)
  6965. (lambda (e)
  6966. (match e
  6967. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6968. (define new-env (append (map cons xs Ts) env))
  6969. (define bodyT ((typecheck-R5 new-env) body))
  6970. (cond [(equal? rT bodyT)
  6971. `(,@Ts -> ,rT)]
  6972. [else
  6973. (error "mismatch in return type" bodyT rT)])]
  6974. ...
  6975. )))
  6976. \end{lstlisting}
  6977. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6978. \label{fig:typecheck-R5}
  6979. \end{figure}
  6980. \section{Closure Conversion}
  6981. The compiling of lexically-scoped functions into top-level function
  6982. definitions is accomplished in the pass \code{convert-to-closures}
  6983. that comes after \code{reveal-functions} and before
  6984. \code{limit-functions}.
  6985. As usual, we shall implement the pass as a recursive function over the
  6986. AST. All of the action is in the clauses for \key{lambda} and
  6987. \key{app}. We transform a \key{lambda} expression into an expression
  6988. that creates a closure, that is, creates a vector whose first element
  6989. is a function pointer and the rest of the elements are the free
  6990. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6991. generated to identify the function.
  6992. \begin{tabular}{lll}
  6993. \begin{minipage}{0.4\textwidth}
  6994. \begin{lstlisting}
  6995. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6996. \end{lstlisting}
  6997. \end{minipage}
  6998. &
  6999. $\Rightarrow$
  7000. &
  7001. \begin{minipage}{0.4\textwidth}
  7002. \begin{lstlisting}
  7003. (vector |\itm{name}| |\itm{fvs}| ...)
  7004. \end{lstlisting}
  7005. \end{minipage}
  7006. \end{tabular} \\
  7007. %
  7008. In addition to transforming each \key{lambda} into a \key{vector}, we
  7009. must create a top-level function definition for each \key{lambda}, as
  7010. shown below.\\
  7011. \begin{minipage}{0.8\textwidth}
  7012. \begin{lstlisting}
  7013. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7014. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7015. ...
  7016. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7017. |\itm{body'}|)...))
  7018. \end{lstlisting}
  7019. \end{minipage}\\
  7020. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7021. parameters are the normal parameters of the \key{lambda}. The types
  7022. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7023. underscore is a dummy type because it is rather difficult to give a
  7024. type to the function in the closure's type, and it does not matter.
  7025. The sequence of \key{let} forms bind the free variables to their
  7026. values obtained from the closure.
  7027. We transform function application into code that retrieves the
  7028. function pointer from the closure and then calls the function, passing
  7029. in the closure as the first argument. We bind $e'$ to a temporary
  7030. variable to avoid code duplication.
  7031. \begin{tabular}{lll}
  7032. \begin{minipage}{0.3\textwidth}
  7033. \begin{lstlisting}
  7034. (app |$e$| |\itm{es}| ...)
  7035. \end{lstlisting}
  7036. \end{minipage}
  7037. &
  7038. $\Rightarrow$
  7039. &
  7040. \begin{minipage}{0.5\textwidth}
  7041. \begin{lstlisting}
  7042. (let ([|\itm{tmp}| |$e'$|])
  7043. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7044. \end{lstlisting}
  7045. \end{minipage}
  7046. \end{tabular} \\
  7047. There is also the question of what to do with top-level function
  7048. definitions. To maintain a uniform translation of function
  7049. application, we turn function references into closures.
  7050. \begin{tabular}{lll}
  7051. \begin{minipage}{0.3\textwidth}
  7052. \begin{lstlisting}
  7053. (fun-ref |$f$|)
  7054. \end{lstlisting}
  7055. \end{minipage}
  7056. &
  7057. $\Rightarrow$
  7058. &
  7059. \begin{minipage}{0.5\textwidth}
  7060. \begin{lstlisting}
  7061. (vector (fun-ref |$f$|))
  7062. \end{lstlisting}
  7063. \end{minipage}
  7064. \end{tabular} \\
  7065. %
  7066. The top-level function definitions need to be updated as well to take
  7067. an extra closure parameter.
  7068. \section{An Example Translation}
  7069. \label{sec:example-lambda}
  7070. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  7071. conversion for the example program demonstrating lexical scoping that
  7072. we discussed at the beginning of this chapter.
  7073. \begin{figure}[h]
  7074. \begin{minipage}{0.8\textwidth}
  7075. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7076. (program
  7077. (define (f [x : Integer]) : (Integer -> Integer)
  7078. (let ([y 4])
  7079. (lambda: ([z : Integer]) : Integer
  7080. (+ x (+ y z)))))
  7081. (let ([g (f 5)])
  7082. (let ([h (f 3)])
  7083. (+ (g 11) (h 15)))))
  7084. \end{lstlisting}
  7085. $\Downarrow$
  7086. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7087. (program (type Integer)
  7088. (define (f (x : Integer)) : (Integer -> Integer)
  7089. (let ((y 4))
  7090. (lambda: ((z : Integer)) : Integer
  7091. (+ x (+ y z)))))
  7092. (let ((g (app (fun-ref f) 5)))
  7093. (let ((h (app (fun-ref f) 3)))
  7094. (+ (app g 11) (app h 15)))))
  7095. \end{lstlisting}
  7096. $\Downarrow$
  7097. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7098. (program (type Integer)
  7099. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  7100. (let ((y 4))
  7101. (vector (fun-ref lam.1) x y)))
  7102. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  7103. (let ((x (vector-ref clos.2 1)))
  7104. (let ((y (vector-ref clos.2 2)))
  7105. (+ x (+ y z)))))
  7106. (let ((g (let ((t.1 (vector (fun-ref f))))
  7107. (app (vector-ref t.1 0) t.1 5))))
  7108. (let ((h (let ((t.2 (vector (fun-ref f))))
  7109. (app (vector-ref t.2 0) t.2 3))))
  7110. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  7111. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  7112. \end{lstlisting}
  7113. \end{minipage}
  7114. \caption{Example of closure conversion.}
  7115. \label{fig:lexical-functions-example}
  7116. \end{figure}
  7117. \begin{figure}[p]
  7118. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7119. \node (R4) at (0,2) {\large $R_4$};
  7120. \node (R4-2) at (3,2) {\large $R_4$};
  7121. \node (R4-3) at (6,2) {\large $R_4$};
  7122. \node (F1-1) at (12,0) {\large $F_1$};
  7123. \node (F1-2) at (9,0) {\large $F_1$};
  7124. \node (F1-3) at (6,0) {\large $F_1$};
  7125. \node (F1-4) at (3,0) {\large $F_1$};
  7126. \node (F1-5) at (0,0) {\large $F_1$};
  7127. \node (C3-1) at (6,-2) {\large $C_3$};
  7128. \node (C3-2) at (3,-2) {\large $C_3$};
  7129. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7130. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7131. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7132. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7133. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7134. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7135. \path[->,bend left=15] (R4) edge [above] node
  7136. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7137. \path[->,bend left=15] (R4-2) edge [above] node
  7138. {\ttfamily\footnotesize uniquify} (R4-3);
  7139. \path[->] (R4-3) edge [right] node
  7140. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7141. \path[->,bend left=15] (F1-1) edge [below] node
  7142. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7143. \path[->,bend right=15] (F1-2) edge [above] node
  7144. {\ttfamily\footnotesize limit-functions} (F1-3);
  7145. \path[->,bend right=15] (F1-3) edge [above] node
  7146. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7147. \path[->,bend right=15] (F1-4) edge [above] node
  7148. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7149. \path[->] (F1-5) edge [left] node
  7150. {\ttfamily\footnotesize explicate-control} (C3-1);
  7151. \path[->,bend left=15] (C3-1) edge [below] node
  7152. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7153. \path[->,bend right=15] (C3-2) edge [left] node
  7154. {\ttfamily\footnotesize select-instr.} (x86-2);
  7155. \path[->,bend left=15] (x86-2) edge [left] node
  7156. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7157. \path[->,bend right=15] (x86-2-1) edge [below] node
  7158. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7159. \path[->,bend right=15] (x86-2-2) edge [left] node
  7160. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7161. \path[->,bend left=15] (x86-3) edge [above] node
  7162. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7163. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7164. \end{tikzpicture}
  7165. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7166. functions.}
  7167. \label{fig:R5-passes}
  7168. \end{figure}
  7169. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7170. for the compilation of $R_5$.
  7171. \begin{exercise}\normalfont
  7172. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7173. Create 5 new programs that use \key{lambda} functions and make use of
  7174. lexical scoping. Test your compiler on these new programs and all of
  7175. your previously created test programs.
  7176. \end{exercise}
  7177. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7178. \chapter{Dynamic Typing}
  7179. \label{ch:type-dynamic}
  7180. In this chapter we discuss the compilation of a dynamically typed
  7181. language, named $R_7$, that is a subset of the Racket
  7182. language. (Recall that in the previous chapters we have studied
  7183. subsets of the \emph{Typed} Racket language.) In dynamically typed
  7184. languages, an expression may produce values of differing
  7185. type. Consider the following example with a conditional expression
  7186. that may return a Boolean or an integer depending on the input to the
  7187. program.
  7188. \begin{lstlisting}
  7189. (not (if (eq? (read) 1) #f 0))
  7190. \end{lstlisting}
  7191. Languages that allow expressions to produce different kinds of values
  7192. are called \emph{polymorphic}. There are many kinds of polymorphism,
  7193. such as subtype polymorphism and parametric
  7194. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  7195. talking about here does not have a special name, but it is the usual
  7196. kind that arises in dynamically typed languages.
  7197. Another characteristic of dynamically typed languages is that
  7198. primitive operations, such as \code{not}, are often defined to operate
  7199. on many different types of values. In fact, in Racket, the \code{not}
  7200. operator produces a result for any kind of value: given \code{\#f} it
  7201. returns \code{\#t} and given anything else it returns \code{\#f}.
  7202. Furthermore, even when primitive operations restrict their inputs to
  7203. values of a certain type, this restriction is enforced at runtime
  7204. instead of during compilation. For example, the following vector
  7205. reference results in a run-time contract violation.
  7206. \begin{lstlisting}
  7207. (vector-ref (vector 42) #t)
  7208. \end{lstlisting}
  7209. \begin{figure}[tp]
  7210. \centering
  7211. \fbox{
  7212. \begin{minipage}{0.97\textwidth}
  7213. \[
  7214. \begin{array}{rcl}
  7215. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7216. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7217. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  7218. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  7219. &\mid& \key{\#t} \mid \key{\#f}
  7220. \mid (\key{and}\;\Exp\;\Exp)
  7221. \mid (\key{or}\;\Exp\;\Exp)
  7222. \mid (\key{not}\;\Exp) \\
  7223. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  7224. &\mid& (\key{vector}\;\Exp\ldots) \mid
  7225. (\key{vector-ref}\;\Exp\;\Exp) \\
  7226. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  7227. &\mid& (\Exp \; \Exp\ldots) \mid (\key{lambda}\; (\Var\ldots) \; \Exp) \\
  7228. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7229. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7230. \Def &::=& (\key{define}\; (\Var \; \Var\ldots) \; \Exp) \\
  7231. R_7 &::=& (\key{program} \; \Def\ldots\; \Exp)
  7232. \end{array}
  7233. \]
  7234. \end{minipage}
  7235. }
  7236. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7237. \label{fig:r7-syntax}
  7238. \end{figure}
  7239. The syntax of $R_7$, our subset of Racket, is defined in
  7240. Figure~\ref{fig:r7-syntax}.
  7241. %
  7242. The definitional interpreter for $R_7$ is given in
  7243. Figure~\ref{fig:interp-R7}.
  7244. \begin{figure}[tbp]
  7245. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7246. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  7247. (define (valid-op? op) (member op '(+ - and or not)))
  7248. (define (interp-r7 env)
  7249. (lambda (ast)
  7250. (define recur (interp-r7 env))
  7251. (match ast
  7252. [(? symbol?) (lookup ast env)]
  7253. [(? integer?) `(inject ,ast Integer)]
  7254. [#t `(inject #t Boolean)]
  7255. [#f `(inject #f Boolean)]
  7256. [`(read) `(inject ,(read-fixnum) Integer)]
  7257. [`(lambda (,xs ...) ,body)
  7258. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  7259. [`(define (,f ,xs ...) ,body)
  7260. (mcons f `(lambda ,xs ,body))]
  7261. [`(program ,ds ... ,body)
  7262. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  7263. (for/list ([b top-level])
  7264. (set-mcdr! b (match (mcdr b)
  7265. [`(lambda ,xs ,body)
  7266. `(inject (lambda ,xs ,body ,top-level)
  7267. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  7268. ((interp-r7 top-level) body))]
  7269. [`(vector ,(app recur elts) ...)
  7270. (define tys (map get-tagged-type elts))
  7271. `(inject ,(apply vector elts) (Vector ,@tys))]
  7272. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  7273. (match v1
  7274. [`(inject ,vec ,ty)
  7275. (vector-set! vec n v2)
  7276. `(inject (void) Void)])]
  7277. [`(vector-ref ,(app recur v) ,n)
  7278. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  7279. [`(let ([,x ,(app recur v)]) ,body)
  7280. ((interp-r7 (cons (cons x v) env)) body)]
  7281. [`(,op ,es ...) #:when (valid-op? op)
  7282. (interp-r7-op op (for/list ([e es]) (recur e)))]
  7283. [`(eq? ,(app recur l) ,(app recur r))
  7284. `(inject ,(equal? l r) Boolean)]
  7285. [`(if ,(app recur q) ,t ,f)
  7286. (match q
  7287. [`(inject #f Boolean) (recur f)]
  7288. [else (recur t)])]
  7289. [`(,(app recur f-val) ,(app recur vs) ...)
  7290. (match f-val
  7291. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  7292. (define new-env (append (map cons xs vs) lam-env))
  7293. ((interp-r7 new-env) body)]
  7294. [else (error "interp-r7, expected function, not" f-val)])])))
  7295. \end{lstlisting}
  7296. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  7297. \label{fig:interp-R7}
  7298. \end{figure}
  7299. Let us consider how we might compile $R_7$ to x86, thinking about the
  7300. first example above. Our bit-level representation of the Boolean
  7301. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7302. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7303. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7304. general, cannot be determined at compile time, but depends on the
  7305. runtime type of its input, as in the example above that depends on the
  7306. result of \code{(read)}.
  7307. The way around this problem is to include information about a value's
  7308. runtime type in the value itself, so that this information can be
  7309. inspected by operators such as \code{not}. In particular, we shall
  7310. steal the 3 right-most bits from our 64-bit values to encode the
  7311. runtime type. We shall use $001$ to identify integers, $100$ for
  7312. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7313. void value. We shall refer to these 3 bits as the \emph{tag} and we
  7314. define the following auxiliary function.
  7315. \begin{align*}
  7316. \itm{tagof}(\key{Integer}) &= 001 \\
  7317. \itm{tagof}(\key{Boolean}) &= 100 \\
  7318. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7319. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7320. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7321. \itm{tagof}(\key{Void}) &= 101
  7322. \end{align*}
  7323. (We shall say more about the new \key{Vectorof} type shortly.)
  7324. This stealing of 3 bits comes at some
  7325. price: our integers are reduced to ranging from $-2^{60}$ to
  7326. $2^{60}$. The stealing does not adversely affect vectors and
  7327. procedures because those values are addresses, and our addresses are
  7328. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7329. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7330. bits with the tag and we can simply zero-out the tag to recover the
  7331. original address.
  7332. In some sense, these tagged values are a new kind of value. Indeed,
  7333. we can extend our \emph{typed} language with tagged values by adding a
  7334. new type to classify them, called \key{Any}, and with operations for
  7335. creating and using tagged values, yielding the $R_6$ language that we
  7336. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7337. fundamental support for polymorphism and runtime types that we need to
  7338. support dynamic typing.
  7339. There is an interesting interaction between tagged values and garbage
  7340. collection. A variable of type \code{Any} might refer to a vector and
  7341. therefore it might be a root that needs to be inspected and copied
  7342. during garbage collection. Thus, we need to treat variables of type
  7343. \code{Any} in a similar way to variables of type \code{Vector} for
  7344. purposes of register allocation, which we discuss in
  7345. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7346. variable of type \code{Any} is spilled, it must be spilled to the root
  7347. stack. But this means that the garbage collector needs to be able to
  7348. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7349. value that points to a tuple, and (3) a tagged value that is not a
  7350. tuple. We enable this differentiation by choosing not to use the tag
  7351. $000$. Instead, that bit pattern is reserved for identifying plain old
  7352. pointers to tuples. On the other hand, if one of the first three bits
  7353. is set, then we have a tagged value, and inspecting the tag can
  7354. differentiation between vectors ($010$) and the other kinds of values.
  7355. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  7356. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7357. extend our compiler to handle the new features of $R_6$
  7358. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7359. \ref{sec:register-allocation-r6}).
  7360. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7361. \label{sec:r6-lang}
  7362. \begin{figure}[tp]
  7363. \centering
  7364. \fbox{
  7365. \begin{minipage}{0.97\textwidth}
  7366. \[
  7367. \begin{array}{lcl}
  7368. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7369. \mid (\key{Vector}\;\Type\ldots) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7370. &\mid& \gray{(\Type\ldots \; \key{->}\; \Type)} \mid \key{Any} \\
  7371. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}\ldots) \\
  7372. &\mid& (\key{Any}\ldots \; \key{->}\; \key{Any})\\
  7373. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7374. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7375. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7376. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7377. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7378. \mid (\key{and}\;\Exp\;\Exp)
  7379. \mid (\key{or}\;\Exp\;\Exp)
  7380. \mid (\key{not}\;\Exp)} \\
  7381. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7382. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7383. (\key{vector-ref}\;\Exp\;\Int)} \\
  7384. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7385. &\mid& \gray{(\Exp \; \Exp\ldots)
  7386. \mid (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7387. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7388. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7389. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7390. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7391. R_6 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7392. \end{array}
  7393. \]
  7394. \end{minipage}
  7395. }
  7396. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7397. with \key{Any}.}
  7398. \label{fig:r6-syntax}
  7399. \end{figure}
  7400. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7401. $(\key{inject}\; e\; T)$ form converts the value produced by
  7402. expression $e$ of type $T$ into a tagged value. The
  7403. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7404. expression $e$ into a value of type $T$ or else halts the program if
  7405. the type tag is equivalent to $T$. We treat
  7406. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7407. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7408. Note that in both \key{inject} and
  7409. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7410. which simplifies the implementation and corresponds with what is
  7411. needed for compiling untyped Racket. The type predicates,
  7412. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7413. if the tag corresponds to the predicate, and return \key{\#t}
  7414. otherwise.
  7415. %
  7416. Selections from the type checker for $R_6$ are shown in
  7417. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7418. Figure~\ref{fig:interp-R6}.
  7419. \begin{figure}[btp]
  7420. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7421. (define (flat-ty? ty) ...)
  7422. (define (typecheck-R6 env)
  7423. (lambda (e)
  7424. (define recur (typecheck-R6 env))
  7425. (match e
  7426. [`(inject ,e ,ty)
  7427. (unless (flat-ty? ty)
  7428. (error "may only inject a value of flat type, not ~a" ty))
  7429. (define-values (new-e e-ty) (recur e))
  7430. (cond
  7431. [(equal? e-ty ty)
  7432. (values `(inject ,new-e ,ty) 'Any)]
  7433. [else
  7434. (error "inject expected ~a to have type ~a" e ty)])]
  7435. [`(project ,e ,ty)
  7436. (unless (flat-ty? ty)
  7437. (error "may only project to a flat type, not ~a" ty))
  7438. (define-values (new-e e-ty) (recur e))
  7439. (cond
  7440. [(equal? e-ty 'Any)
  7441. (values `(project ,new-e ,ty) ty)]
  7442. [else
  7443. (error "project expected ~a to have type Any" e)])]
  7444. [`(vector-ref ,e ,i)
  7445. (define-values (new-e e-ty) (recur e))
  7446. (match e-ty
  7447. [`(Vector ,ts ...) ...]
  7448. [`(Vectorof ,ty)
  7449. (unless (exact-nonnegative-integer? i)
  7450. (error 'type-check "invalid index ~a" i))
  7451. (values `(vector-ref ,new-e ,i) ty)]
  7452. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7453. ...
  7454. )))
  7455. \end{lstlisting}
  7456. \caption{Type checker for parts of the $R_6$ language.}
  7457. \label{fig:typecheck-R6}
  7458. \end{figure}
  7459. % to do: add rules for vector-ref, etc. for Vectorof
  7460. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7461. \begin{figure}[btp]
  7462. \begin{lstlisting}
  7463. (define primitives (set 'boolean? ...))
  7464. (define (interp-op op)
  7465. (match op
  7466. ['boolean? (lambda (v)
  7467. (match v
  7468. [`(tagged ,v1 Boolean) #t]
  7469. [else #f]))]
  7470. ...))
  7471. ;; Equivalence of flat types
  7472. (define (tyeq? t1 t2)
  7473. (match `(,t1 ,t2)
  7474. [`((Vectorof Any) (Vector ,t2s ...))
  7475. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7476. [`((Vector ,t1s ...) (Vectorof Any))
  7477. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7478. [else (equal? t1 t2)]))
  7479. (define (interp-R6 env)
  7480. (lambda (ast)
  7481. (match ast
  7482. [`(inject ,e ,t)
  7483. `(tagged ,((interp-R6 env) e) ,t)]
  7484. [`(project ,e ,t2)
  7485. (define v ((interp-R6 env) e))
  7486. (match v
  7487. [`(tagged ,v1 ,t1)
  7488. (cond [(tyeq? t1 t2)
  7489. v1]
  7490. [else
  7491. (error "in project, type mismatch" t1 t2)])]
  7492. [else
  7493. (error "in project, expected tagged value" v)])]
  7494. ...)))
  7495. \end{lstlisting}
  7496. \caption{Interpreter for $R_6$.}
  7497. \label{fig:interp-R6}
  7498. \end{figure}
  7499. %\clearpage
  7500. \section{Shrinking $R_6$}
  7501. \label{sec:shrink-r6}
  7502. In the \code{shrink} pass we recommend compiling \code{project} into
  7503. an explicit \code{if} expression that uses three new operations:
  7504. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7505. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7506. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7507. value from a tagged value. Finally, the \code{exit} operation ends the
  7508. execution of the program by invoking the operating system's
  7509. \code{exit} function. So the translation for \code{project} is as
  7510. follows. (We have omitted the \code{has-type} AST nodes to make this
  7511. output more readable.)
  7512. \begin{tabular}{lll}
  7513. \begin{minipage}{0.3\textwidth}
  7514. \begin{lstlisting}
  7515. (project |$e$| |$\Type$|)
  7516. \end{lstlisting}
  7517. \end{minipage}
  7518. &
  7519. $\Rightarrow$
  7520. &
  7521. \begin{minipage}{0.5\textwidth}
  7522. \begin{lstlisting}
  7523. (let ([|$\itm{tmp}$| |$e'$|])
  7524. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7525. (value-of-any |$\itm{tmp}$|)
  7526. (exit)))
  7527. \end{lstlisting}
  7528. \end{minipage}
  7529. \end{tabular} \\
  7530. Similarly, we recommend translating the type predicates
  7531. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7532. \section{Instruction Selection for $R_6$}
  7533. \label{sec:select-r6}
  7534. \paragraph{Inject}
  7535. We recommend compiling an \key{inject} as follows if the type is
  7536. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7537. destination to the left by the number of bits specified its source
  7538. argument (in this case $3$, the length of the tag) and it preserves
  7539. the sign of the integer. We use the \key{orq} instruction to combine
  7540. the tag and the value to form the tagged value. \\
  7541. \begin{tabular}{lll}
  7542. \begin{minipage}{0.4\textwidth}
  7543. \begin{lstlisting}
  7544. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7545. \end{lstlisting}
  7546. \end{minipage}
  7547. &
  7548. $\Rightarrow$
  7549. &
  7550. \begin{minipage}{0.5\textwidth}
  7551. \begin{lstlisting}
  7552. (movq |$e'$| |\itm{lhs}'|)
  7553. (salq (int 3) |\itm{lhs}'|)
  7554. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7555. \end{lstlisting}
  7556. \end{minipage}
  7557. \end{tabular} \\
  7558. The instruction selection for vectors and procedures is different
  7559. because their is no need to shift them to the left. The rightmost 3
  7560. bits are already zeros as described above. So we just combine the
  7561. value and the tag using \key{orq}. \\
  7562. \begin{tabular}{lll}
  7563. \begin{minipage}{0.4\textwidth}
  7564. \begin{lstlisting}
  7565. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7566. \end{lstlisting}
  7567. \end{minipage}
  7568. &
  7569. $\Rightarrow$
  7570. &
  7571. \begin{minipage}{0.5\textwidth}
  7572. \begin{lstlisting}
  7573. (movq |$e'$| |\itm{lhs}'|)
  7574. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7575. \end{lstlisting}
  7576. \end{minipage}
  7577. \end{tabular}
  7578. \paragraph{Tag of Any}
  7579. Recall that the \code{tag-of-any} operation extracts the type tag from
  7580. a value of type \code{Any}. The type tag is the bottom three bits, so
  7581. we obtain the tag by taking the bitwise-and of the value with $111$
  7582. ($7$ in decimal).
  7583. \begin{tabular}{lll}
  7584. \begin{minipage}{0.4\textwidth}
  7585. \begin{lstlisting}
  7586. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7587. \end{lstlisting}
  7588. \end{minipage}
  7589. &
  7590. $\Rightarrow$
  7591. &
  7592. \begin{minipage}{0.5\textwidth}
  7593. \begin{lstlisting}
  7594. (movq |$e'$| |\itm{lhs}'|)
  7595. (andq (int 7) |\itm{lhs}'|)
  7596. \end{lstlisting}
  7597. \end{minipage}
  7598. \end{tabular}
  7599. \paragraph{Value of Any}
  7600. Like \key{inject}, the instructions for \key{value-of-any} are
  7601. different depending on whether the type $T$ is a pointer (vector or
  7602. procedure) or not (Integer or Boolean). The following shows the
  7603. instruction selection for Integer and Boolean. We produce an untagged
  7604. value by shifting it to the right by 3 bits.
  7605. %
  7606. \\
  7607. \begin{tabular}{lll}
  7608. \begin{minipage}{0.4\textwidth}
  7609. \begin{lstlisting}
  7610. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7611. \end{lstlisting}
  7612. \end{minipage}
  7613. &
  7614. $\Rightarrow$
  7615. &
  7616. \begin{minipage}{0.5\textwidth}
  7617. \begin{lstlisting}
  7618. (movq |$e'$| |\itm{lhs}'|)
  7619. (sarq (int 3) |\itm{lhs}'|)
  7620. \end{lstlisting}
  7621. \end{minipage}
  7622. \end{tabular} \\
  7623. %
  7624. In the case for vectors and procedures, there is no need to
  7625. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7626. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7627. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7628. \code{movq} into the destination $\itm{lhs}$. We then generate
  7629. \code{andq} with the tagged value to get the desired result. \\
  7630. %
  7631. \begin{tabular}{lll}
  7632. \begin{minipage}{0.4\textwidth}
  7633. \begin{lstlisting}
  7634. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7635. \end{lstlisting}
  7636. \end{minipage}
  7637. &
  7638. $\Rightarrow$
  7639. &
  7640. \begin{minipage}{0.5\textwidth}
  7641. \begin{lstlisting}
  7642. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7643. (andq |$e'$| |\itm{lhs}'|)
  7644. \end{lstlisting}
  7645. \end{minipage}
  7646. \end{tabular}
  7647. %% \paragraph{Type Predicates} We leave it to the reader to
  7648. %% devise a sequence of instructions to implement the type predicates
  7649. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7650. \section{Register Allocation for $R_6$}
  7651. \label{sec:register-allocation-r6}
  7652. As mentioned above, a variable of type \code{Any} might refer to a
  7653. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7654. of type \code{Any} in the same way that it treats variables of type
  7655. \code{Vector} for purposes of garbage collection. In particular,
  7656. \begin{itemize}
  7657. \item If a variable of type \code{Any} is live during a function call,
  7658. then it must be spilled. One way to accomplish this is to augment
  7659. the pass \code{build-interference} to mark all variables that are
  7660. live after a \code{callq} as interfering with all the registers.
  7661. \item If a variable of type \code{Any} is spilled, it must be spilled
  7662. to the root stack instead of the normal procedure call stack.
  7663. \end{itemize}
  7664. \begin{exercise}\normalfont
  7665. Expand your compiler to handle $R_6$ as discussed in the last few
  7666. sections. Create 5 new programs that use the \code{Any} type and the
  7667. new operations (\code{inject}, \code{project}, \code{boolean?},
  7668. etc.). Test your compiler on these new programs and all of your
  7669. previously created test programs.
  7670. \end{exercise}
  7671. \section{Compiling $R_7$ to $R_6$}
  7672. \label{sec:compile-r7}
  7673. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7674. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7675. given a subexpression $e$ of $R_7$, the pass will produce an
  7676. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7677. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7678. the Boolean \code{\#t}, which must be injected to produce an
  7679. expression of type \key{Any}.
  7680. %
  7681. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7682. addition, is representative of compilation for many operations: the
  7683. arguments have type \key{Any} and must be projected to \key{Integer}
  7684. before the addition can be performed.
  7685. The compilation of \key{lambda} (third row of
  7686. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7687. produce type annotations: we simply use \key{Any}.
  7688. %
  7689. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7690. has to account for some differences in behavior between $R_7$ and
  7691. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7692. kind of values can be used in various places. For example, the
  7693. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7694. the arguments need not be of the same type (but in that case, the
  7695. result will be \code{\#f}).
  7696. \begin{figure}[btp]
  7697. \centering
  7698. \begin{tabular}{|lll|} \hline
  7699. \begin{minipage}{0.25\textwidth}
  7700. \begin{lstlisting}
  7701. #t
  7702. \end{lstlisting}
  7703. \end{minipage}
  7704. &
  7705. $\Rightarrow$
  7706. &
  7707. \begin{minipage}{0.6\textwidth}
  7708. \begin{lstlisting}
  7709. (inject #t Boolean)
  7710. \end{lstlisting}
  7711. \end{minipage}
  7712. \\[2ex]\hline
  7713. \begin{minipage}{0.25\textwidth}
  7714. \begin{lstlisting}
  7715. (+ |$e_1$| |$e_2$|)
  7716. \end{lstlisting}
  7717. \end{minipage}
  7718. &
  7719. $\Rightarrow$
  7720. &
  7721. \begin{minipage}{0.6\textwidth}
  7722. \begin{lstlisting}
  7723. (inject
  7724. (+ (project |$e'_1$| Integer)
  7725. (project |$e'_2$| Integer))
  7726. Integer)
  7727. \end{lstlisting}
  7728. \end{minipage}
  7729. \\[2ex]\hline
  7730. \begin{minipage}{0.25\textwidth}
  7731. \begin{lstlisting}
  7732. (lambda (|$x_1 \ldots$|) |$e$|)
  7733. \end{lstlisting}
  7734. \end{minipage}
  7735. &
  7736. $\Rightarrow$
  7737. &
  7738. \begin{minipage}{0.6\textwidth}
  7739. \begin{lstlisting}
  7740. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7741. (Any|$\ldots$|Any -> Any))
  7742. \end{lstlisting}
  7743. \end{minipage}
  7744. \\[2ex]\hline
  7745. \begin{minipage}{0.25\textwidth}
  7746. \begin{lstlisting}
  7747. (app |$e_0$| |$e_1 \ldots e_n$|)
  7748. \end{lstlisting}
  7749. \end{minipage}
  7750. &
  7751. $\Rightarrow$
  7752. &
  7753. \begin{minipage}{0.6\textwidth}
  7754. \begin{lstlisting}
  7755. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7756. |$e'_1 \ldots e'_n$|)
  7757. \end{lstlisting}
  7758. \end{minipage}
  7759. \\[2ex]\hline
  7760. \begin{minipage}{0.25\textwidth}
  7761. \begin{lstlisting}
  7762. (vector-ref |$e_1$| |$e_2$|)
  7763. \end{lstlisting}
  7764. \end{minipage}
  7765. &
  7766. $\Rightarrow$
  7767. &
  7768. \begin{minipage}{0.6\textwidth}
  7769. \begin{lstlisting}
  7770. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7771. (let ([tmp2 (project |$e'_2$| Integer)])
  7772. (vector-ref tmp1 tmp2)))
  7773. \end{lstlisting}
  7774. \end{minipage}
  7775. \\[2ex]\hline
  7776. \begin{minipage}{0.25\textwidth}
  7777. \begin{lstlisting}
  7778. (if |$e_1$| |$e_2$| |$e_3$|)
  7779. \end{lstlisting}
  7780. \end{minipage}
  7781. &
  7782. $\Rightarrow$
  7783. &
  7784. \begin{minipage}{0.6\textwidth}
  7785. \begin{lstlisting}
  7786. (if (eq? |$e'_1$| (inject #f Boolean))
  7787. |$e'_3$|
  7788. |$e'_2$|)
  7789. \end{lstlisting}
  7790. \end{minipage}
  7791. \\[2ex]\hline
  7792. \begin{minipage}{0.25\textwidth}
  7793. \begin{lstlisting}
  7794. (eq? |$e_1$| |$e_2$|)
  7795. \end{lstlisting}
  7796. \end{minipage}
  7797. &
  7798. $\Rightarrow$
  7799. &
  7800. \begin{minipage}{0.6\textwidth}
  7801. \begin{lstlisting}
  7802. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7803. \end{lstlisting}
  7804. \end{minipage}
  7805. \\[2ex]\hline
  7806. \end{tabular}
  7807. \caption{Compiling $R_7$ to $R_6$.}
  7808. \label{fig:compile-r7-r6}
  7809. \end{figure}
  7810. \begin{exercise}\normalfont
  7811. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7812. Create tests for $R_7$ by adapting all of your previous test programs
  7813. by removing type annotations. Add 5 more tests programs that
  7814. specifically rely on the language being dynamically typed. That is,
  7815. they should not be legal programs in a statically typed language, but
  7816. nevertheless, they should be valid $R_7$ programs that run to
  7817. completion without error.
  7818. \end{exercise}
  7819. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7820. \chapter{Gradual Typing}
  7821. \label{ch:gradual-typing}
  7822. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7823. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7824. \chapter{Parametric Polymorphism}
  7825. \label{ch:parametric-polymorphism}
  7826. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7827. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7828. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7829. \chapter{High-level Optimization}
  7830. \label{ch:high-level-optimization}
  7831. This chapter will present a procedure inlining pass based on the
  7832. algorithm of \citet{Waddell:1997fk}.
  7833. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7834. \chapter{Appendix}
  7835. \section{Interpreters}
  7836. \label{appendix:interp}
  7837. We provide interpreters for each of the source languages $R_0$, $R_1$,
  7838. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  7839. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  7840. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  7841. the rest of the intermediate languages, including pseudo-x86 and x86
  7842. are in the \key{interp.rkt} file.
  7843. \section{Utility Functions}
  7844. \label{appendix:utilities}
  7845. The utility functions described here are in the \key{utilities.rkt}
  7846. file.
  7847. \paragraph{\code{interp-tests}}
  7848. The \key{interp-tests} function runs the compiler passes and the
  7849. interpreters on each of the specified tests to check whether each pass
  7850. is correct. The \key{interp-tests} function has the following
  7851. parameters:
  7852. \begin{description}
  7853. \item[name (a string)] a name to identify the compiler,
  7854. \item[typechecker] a function of exactly one argument that either
  7855. raises an error using the \code{error} function when it encounters a
  7856. type error, or returns \code{\#f} when it encounters a type
  7857. error. If there is no type error, the type checker returns the
  7858. program.
  7859. \item[passes] a list with one entry per pass. An entry is a list with
  7860. three things: a string giving the name of the pass, the function
  7861. that implements the pass (a translator from AST to AST), and a
  7862. function that implements the interpreter (a function from AST to
  7863. result value) for the language of the output of the pass.
  7864. \item[source-interp] an interpreter for the source language. The
  7865. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  7866. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  7867. \item[tests] a list of test numbers that specifies which tests to
  7868. run. (see below)
  7869. \end{description}
  7870. %
  7871. The \key{interp-tests} function assumes that the subdirectory
  7872. \key{tests} has a collection of Racket programs whose names all start
  7873. with the family name, followed by an underscore and then the test
  7874. number, ending with the file extension \key{.rkt}. Also, for each test
  7875. program that calls \code{read} one or more times, there is a file with
  7876. the same name except that the file extension is \key{.in} that
  7877. provides the input for the Racket program. If the test program is
  7878. expected to fail type checking, then there should be an empty file of
  7879. the same name but with extension \key{.tyerr}.
  7880. \paragraph{\code{compiler-tests}}
  7881. runs the compiler passes to generate x86 (a \key{.s} file) and then
  7882. runs the GNU C compiler (gcc) to generate machine code. It runs the
  7883. machine code and checks that the output is $42$. The parameters to the
  7884. \code{compiler-tests} function are similar to those of the
  7885. \code{interp-tests} function, and consist of
  7886. \begin{itemize}
  7887. \item a compiler name (a string),
  7888. \item a type checker,
  7889. \item description of the passes,
  7890. \item name of a test-family, and
  7891. \item a list of test numbers.
  7892. \end{itemize}
  7893. \paragraph{\code{compile-file}}
  7894. takes a description of the compiler passes (see the comment for
  7895. \key{interp-tests}) and returns a function that, given a program file
  7896. name (a string ending in \key{.rkt}), applies all of the passes and
  7897. writes the output to a file whose name is the same as the program file
  7898. name but with \key{.rkt} replaced with \key{.s}.
  7899. \paragraph{\code{read-program}}
  7900. takes a file path and parses that file (it must be a Racket program)
  7901. into an abstract syntax tree.
  7902. \paragraph{\code{parse-program}}
  7903. takes an S-expression representation of an abstract syntax tree and converts it into
  7904. the struct-based representation.
  7905. \paragraph{\code{assert}}
  7906. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  7907. and displays the message \key{msg} if the Boolean \key{bool} is false.
  7908. \paragraph{\code{lookup}}
  7909. % remove discussion of lookup? -Jeremy
  7910. takes a key and an alist, and returns the first value that is
  7911. associated with the given key, if there is one. If not, an error is
  7912. triggered. The alist may contain both immutable pairs (built with
  7913. \key{cons}) and mutable pairs (built with \key{mcons}).
  7914. %The \key{map2} function ...
  7915. \section{x86 Instruction Set Quick-Reference}
  7916. \label{sec:x86-quick-reference}
  7917. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7918. do. We write $A \to B$ to mean that the value of $A$ is written into
  7919. location $B$. Address offsets are given in bytes. The instruction
  7920. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  7921. registers (such as \code{\%rax}), or memory references (such as
  7922. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  7923. reference per instruction. Other operands must be immediates or
  7924. registers.
  7925. \begin{table}[tbp]
  7926. \centering
  7927. \begin{tabular}{l|l}
  7928. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7929. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7930. \texttt{negq} $A$ & $- A \to A$ \\
  7931. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7932. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7933. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  7934. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7935. \texttt{retq} & Pops the return address and jumps to it \\
  7936. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7937. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7938. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  7939. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  7940. be an immediate) \\
  7941. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7942. matches the condition code of the instruction, otherwise go to the
  7943. next instructions. The condition codes are \key{e} for ``equal'',
  7944. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7945. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7946. \texttt{jl} $L$ & \\
  7947. \texttt{jle} $L$ & \\
  7948. \texttt{jg} $L$ & \\
  7949. \texttt{jge} $L$ & \\
  7950. \texttt{jmp} $L$ & Jump to label $L$ \\
  7951. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7952. \texttt{movzbq} $A$, $B$ &
  7953. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7954. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7955. and the extra bytes of $B$ are set to zero.} \\
  7956. & \\
  7957. & \\
  7958. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7959. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7960. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7961. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7962. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7963. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7964. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7965. description of the condition codes. $A$ must be a single byte register
  7966. (e.g., \texttt{al} or \texttt{cl}).} \\
  7967. \texttt{setl} $A$ & \\
  7968. \texttt{setle} $A$ & \\
  7969. \texttt{setg} $A$ & \\
  7970. \texttt{setge} $A$ &
  7971. \end{tabular}
  7972. \vspace{5pt}
  7973. \caption{Quick-reference for the x86 instructions used in this book.}
  7974. \label{tab:x86-instr}
  7975. \end{table}
  7976. \bibliographystyle{plainnat}
  7977. \bibliography{all}
  7978. \end{document}
  7979. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7980. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7981. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7982. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7983. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7984. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7985. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7986. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7987. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7988. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7989. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7990. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7991. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7992. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7993. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7994. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7995. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7996. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7997. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7998. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7999. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8000. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8001. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8002. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8003. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8004. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8005. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8006. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8007. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8008. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8009. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8010. % LocalWords: struct symtab