book.tex 337 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  76. deletekeywords={read},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~}
  80. }
  81. \newtheorem{theorem}{Theorem}
  82. \newtheorem{lemma}[theorem]{Lemma}
  83. \newtheorem{corollary}[theorem]{Corollary}
  84. \newtheorem{proposition}[theorem]{Proposition}
  85. \newtheorem{constraint}[theorem]{Constraint}
  86. \newtheorem{definition}[theorem]{Definition}
  87. \newtheorem{exercise}[theorem]{Exercise}
  88. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  89. % 'dedication' environment: To add a dedication paragraph at the start of book %
  90. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  91. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  92. \newenvironment{dedication}
  93. {
  94. \cleardoublepage
  95. \thispagestyle{empty}
  96. \vspace*{\stretch{1}}
  97. \hfill\begin{minipage}[t]{0.66\textwidth}
  98. \raggedright
  99. }
  100. {
  101. \end{minipage}
  102. \vspace*{\stretch{3}}
  103. \clearpage
  104. }
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. % Chapter quote at the start of chapter %
  107. % Source: http://tex.stackexchange.com/a/53380 %
  108. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  109. \makeatletter
  110. \renewcommand{\@chapapp}{}% Not necessary...
  111. \newenvironment{chapquote}[2][2em]
  112. {\setlength{\@tempdima}{#1}%
  113. \def\chapquote@author{#2}%
  114. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  115. \itshape}
  116. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  117. \makeatother
  118. \input{defs}
  119. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  120. \title{\Huge \textbf{Essentials of Compilation} \\
  121. \huge An Incremental Approach}
  122. \author{\textsc{Jeremy G. Siek} \\
  123. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  124. Indiana University \\
  125. \\
  126. with contributions from: \\
  127. Carl Factora \\
  128. Andre Kuhlenschmidt \\
  129. Ryan R. Newton \\
  130. Ryan Scott \\
  131. Cameron Swords \\
  132. Michael M. Vitousek \\
  133. Michael Vollmer
  134. }
  135. \begin{document}
  136. \frontmatter
  137. \maketitle
  138. \begin{dedication}
  139. This book is dedicated to the programming language wonks at Indiana
  140. University.
  141. \end{dedication}
  142. \tableofcontents
  143. \listoffigures
  144. %\listoftables
  145. \mainmatter
  146. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  147. \chapter*{Preface}
  148. The tradition of compiler writing at Indiana University goes back to
  149. research and courses about programming languages by Daniel Friedman in
  150. the 1970's and 1980's. Dan conducted research on lazy
  151. evaluation~\citep{Friedman:1976aa} in the context of
  152. Lisp~\citep{McCarthy:1960dz} and then studied
  153. continuations~\citep{Felleisen:kx} and
  154. macros~\citep{Kohlbecker:1986dk} in the context of the
  155. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  156. of those courses, Kent Dybvig, went on to build Chez
  157. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  158. compiler for Scheme. After completing his Ph.D. at the University of
  159. North Carolina, Kent returned to teach at Indiana University.
  160. Throughout the 1990's and 2000's, Kent continued development of Chez
  161. Scheme and taught the compiler course.
  162. The compiler course evolved to incorporate novel pedagogical ideas
  163. while also including elements of effective real-world compilers. One
  164. of Dan's ideas was to split the compiler into many small ``passes'' so
  165. that the code for each pass would be easy to understood in isolation.
  166. (In contrast, most compilers of the time were organized into only a
  167. few monolithic passes for reasons of compile-time efficiency.) Kent,
  168. with later help from his students Dipanwita Sarkar and Andrew Keep,
  169. developed infrastructure to support this approach and evolved the
  170. course, first to use micro-sized passes and then into even smaller
  171. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  172. student in this compiler course in the early 2000's, as part of his
  173. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  174. the course immensely!
  175. During that time, another student named Abdulaziz Ghuloum observed
  176. that the front-to-back organization of the course made it difficult
  177. for students to understand the rationale for the compiler
  178. design. Abdulaziz proposed an incremental approach in which the
  179. students build the compiler in stages; they start by implementing a
  180. complete compiler for a very small subset of the input language and in
  181. each subsequent stage they add a language feature and add or modify
  182. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  183. the students see how the language features motivate aspects of the
  184. compiler design.
  185. After graduating from Indiana University in 2005, Jeremy went on to
  186. teach at the University of Colorado. He adapted the nano pass and
  187. incremental approaches to compiling a subset of the Python
  188. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  189. on the surface but there is a large overlap in the compiler techniques
  190. required for the two languages. Thus, Jeremy was able to teach much of
  191. the same content from the Indiana compiler course. He very much
  192. enjoyed teaching the course organized in this way, and even better,
  193. many of the students learned a lot and got excited about compilers.
  194. Jeremy returned to teach at Indiana University in 2013. In his
  195. absence the compiler course had switched from the front-to-back
  196. organization to a back-to-front organization. Seeing how well the
  197. incremental approach worked at Colorado, he started porting and
  198. adapting the structure of the Colorado course back into the land of
  199. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  200. the course is now about compiling a subset of Racket (and Typed
  201. Racket) to the x86 assembly language. The compiler is implemented in
  202. Racket 7.1~\citep{plt-tr}.
  203. This is the textbook for the incremental version of the compiler
  204. course at Indiana University (Spring 2016 - present) and it is the
  205. first open textbook for an Indiana compiler course. With this book we
  206. hope to make the Indiana compiler course available to people that have
  207. not had the chance to study in Bloomington in person. Many of the
  208. compiler design decisions in this book are drawn from the assignment
  209. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  210. are the most important topics from \cite{Dybvig:2010aa} but we have
  211. omitted topics that we think are less interesting conceptually and we
  212. have made simplifications to reduce complexity. In this way, this
  213. book leans more towards pedagogy than towards the efficiency of the
  214. generated code. Also, the book differs in places where we saw the
  215. opportunity to make the topics more fun, such as in relating register
  216. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  217. \section*{Prerequisites}
  218. The material in this book is challenging but rewarding. It is meant to
  219. prepare students for a lifelong career in programming languages.
  220. The book uses the Racket language both for the implementation of the
  221. compiler and for the language that is compiled, so a student should be
  222. proficient with Racket (or Scheme) prior to reading this book. There
  223. are many excellent resources for learning Scheme and
  224. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  225. is helpful but not necessary for the student to have prior exposure to
  226. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  227. obtain from a computer systems
  228. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  229. parts of x86-64 assembly language that are needed.
  230. %\section*{Structure of book}
  231. % You might want to add short description about each chapter in this book.
  232. %\section*{About the companion website}
  233. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  234. %\begin{itemize}
  235. % \item A link to (freely downlodable) latest version of this document.
  236. % \item Link to download LaTeX source for this document.
  237. % \item Miscellaneous material (e.g. suggested readings etc).
  238. %\end{itemize}
  239. \section*{Acknowledgments}
  240. Many people have contributed to the ideas, techniques, organization,
  241. and teaching of the materials in this book. We especially thank the
  242. following people.
  243. \begin{itemize}
  244. \item Bor-Yuh Evan Chang
  245. \item Kent Dybvig
  246. \item Daniel P. Friedman
  247. \item Ronald Garcia
  248. \item Abdulaziz Ghuloum
  249. \item Jay McCarthy
  250. \item Dipanwita Sarkar
  251. \item Andrew Keep
  252. \item Oscar Waddell
  253. \item Michael Wollowski
  254. \end{itemize}
  255. \mbox{}\\
  256. \noindent Jeremy G. Siek \\
  257. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  258. %\noindent Spring 2016
  259. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  260. \chapter{Preliminaries}
  261. \label{ch:trees-recur}
  262. In this chapter we review the basic tools that are needed to implement
  263. a compiler. Programs are typically input by a programmer as text,
  264. i.e., a sequence of characters. The program-as-text representation is
  265. called \emph{concrete syntax}. We use concrete syntax to concisely
  266. write down and talk about programs. Inside the compiler, we use
  267. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  268. that efficiently supports the operations that the compiler needs to
  269. perform.
  270. \index{concrete syntax}
  271. \index{abstract syntax}
  272. \index{abstract syntax tree}
  273. \index{AST}
  274. \index{program}
  275. \index{parse}
  276. %
  277. The translation from concrete syntax to abstract syntax is a process
  278. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  279. and implementation of parsing in this book. A parser is provided in
  280. the supporting materials for translating from concrete syntax to
  281. abstract syntax for the languages used in this book.
  282. ASTs can be represented in many different ways inside the compiler,
  283. depending on the programming language used to write the compiler.
  284. %
  285. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  286. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  287. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  288. and pattern matching to inspect individual nodes in an AST
  289. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  290. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  291. chapter provides an brief introduction to these ideas.
  292. \index{struct}
  293. \section{Abstract Syntax Trees and Racket Structures}
  294. \label{sec:ast}
  295. Compilers use abstract syntax trees to represent programs because
  296. compilers often need to ask questions like: for a given part of a
  297. program, what kind of language feature is it? What are the sub-parts
  298. of this part of the program? Consider the program on the left and its
  299. AST on the right. This program is an addition and it has two
  300. sub-parts, a read operation and a negation. The negation has another
  301. sub-part, the integer constant \code{8}. By using a tree to represent
  302. the program, we can easily follow the links to go from one part of a
  303. program to its sub-parts.
  304. \begin{center}
  305. \begin{minipage}{0.4\textwidth}
  306. \begin{lstlisting}
  307. (+ (read) (- 8))
  308. \end{lstlisting}
  309. \end{minipage}
  310. \begin{minipage}{0.4\textwidth}
  311. \begin{equation}
  312. \begin{tikzpicture}
  313. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  314. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  315. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  316. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  317. \draw[->] (plus) to (read);
  318. \draw[->] (plus) to (minus);
  319. \draw[->] (minus) to (8);
  320. \end{tikzpicture}
  321. \label{eq:arith-prog}
  322. \end{equation}
  323. \end{minipage}
  324. \end{center}
  325. We use the standard terminology for trees to describe ASTs: each
  326. circle above is called a \emph{node}. The arrows connect a node to its
  327. \emph{children} (which are also nodes). The top-most node is the
  328. \emph{root}. Every node except for the root has a \emph{parent} (the
  329. node it is the child of). If a node has no children, it is a
  330. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  331. \index{node}
  332. \index{children}
  333. \index{root}
  334. \index{parent}
  335. \index{leaf}
  336. \index{internal node}
  337. %% Recall that an \emph{symbolic expression} (S-expression) is either
  338. %% \begin{enumerate}
  339. %% \item an atom, or
  340. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  341. %% where $e_1$ and $e_2$ are each an S-expression.
  342. %% \end{enumerate}
  343. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  344. %% null value \code{'()}, etc. We can create an S-expression in Racket
  345. %% simply by writing a backquote (called a quasi-quote in Racket)
  346. %% followed by the textual representation of the S-expression. It is
  347. %% quite common to use S-expressions to represent a list, such as $a, b
  348. %% ,c$ in the following way:
  349. %% \begin{lstlisting}
  350. %% `(a . (b . (c . ())))
  351. %% \end{lstlisting}
  352. %% Each element of the list is in the first slot of a pair, and the
  353. %% second slot is either the rest of the list or the null value, to mark
  354. %% the end of the list. Such lists are so common that Racket provides
  355. %% special notation for them that removes the need for the periods
  356. %% and so many parenthesis:
  357. %% \begin{lstlisting}
  358. %% `(a b c)
  359. %% \end{lstlisting}
  360. %% The following expression creates an S-expression that represents AST
  361. %% \eqref{eq:arith-prog}.
  362. %% \begin{lstlisting}
  363. %% `(+ (read) (- 8))
  364. %% \end{lstlisting}
  365. %% When using S-expressions to represent ASTs, the convention is to
  366. %% represent each AST node as a list and to put the operation symbol at
  367. %% the front of the list. The rest of the list contains the children. So
  368. %% in the above case, the root AST node has operation \code{`+} and its
  369. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  370. %% diagram \eqref{eq:arith-prog}.
  371. %% To build larger S-expressions one often needs to splice together
  372. %% several smaller S-expressions. Racket provides the comma operator to
  373. %% splice an S-expression into a larger one. For example, instead of
  374. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  375. %% we could have first created an S-expression for AST
  376. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  377. %% S-expression.
  378. %% \begin{lstlisting}
  379. %% (define ast1.4 `(- 8))
  380. %% (define ast1.1 `(+ (read) ,ast1.4))
  381. %% \end{lstlisting}
  382. %% In general, the Racket expression that follows the comma (splice)
  383. %% can be any expression that produces an S-expression.
  384. We define a Racket \code{struct} for each kind of node. For this
  385. chapter we require just two kinds of nodes: one for integer constants
  386. and one for primitive operations. The following is the \code{struct}
  387. definition for integer constants.
  388. \begin{lstlisting}
  389. (struct Int (value))
  390. \end{lstlisting}
  391. An integer node includes just one thing: the integer value.
  392. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  393. \begin{lstlisting}
  394. (define eight (Int 8))
  395. \end{lstlisting}
  396. We say that the value created by \code{(Int 8)} is an
  397. \emph{instance} of the \code{Int} structure.
  398. The following is the \code{struct} definition for primitives operations.
  399. \begin{lstlisting}
  400. (struct Prim (op arg*))
  401. \end{lstlisting}
  402. A primitive operation node includes an operator symbol \code{op}
  403. and a list of children \code{arg*}. For example, to create
  404. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  405. \begin{lstlisting}
  406. (define neg-eight (Prim '- (list eight)))
  407. \end{lstlisting}
  408. Primitive operations may have zero or more children. The \code{read}
  409. operator has zero children:
  410. \begin{lstlisting}
  411. (define rd (Prim 'read '()))
  412. \end{lstlisting}
  413. whereas the addition operator has two children:
  414. \begin{lstlisting}
  415. (define ast1.1 (Prim '+ (list rd neg-eight)))
  416. \end{lstlisting}
  417. We have made a design choice regarding the \code{Prim} structure.
  418. Instead of using one structure for many different operations
  419. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  420. structure for each operation, as follows.
  421. \begin{lstlisting}
  422. (struct Read ())
  423. (struct Add (left right))
  424. (struct Neg (value))
  425. \end{lstlisting}
  426. The reason we choose to use just one structure is that in many parts
  427. of the compiler the code for the different primitive operators is the
  428. same, so we might as well just write that code once, which is enabled
  429. by using a single structure.
  430. When compiling a program such as \eqref{eq:arith-prog}, we need to
  431. know that the operation associated with the root node is addition and
  432. we need to be able to access its two children. Racket provides pattern
  433. matching over structures to support these kinds of queries, as we
  434. shall see in Section~\ref{sec:pattern-matching}.
  435. In this book, we often write down the concrete syntax of a program
  436. even when we really have in mind the AST because the concrete syntax
  437. is more concise. We recommend that, in your mind, you always think of
  438. programs as abstract syntax trees.
  439. \section{Grammars}
  440. \label{sec:grammar}
  441. \index{integer}
  442. \index{literal}
  443. \index{constant}
  444. A programming language can be thought of as a \emph{set} of programs.
  445. The set is typically infinite (one can always create larger and larger
  446. programs), so one cannot simply describe a language by listing all of
  447. the programs in the language. Instead we write down a set of rules, a
  448. \emph{grammar}, for building programs. Grammars are often used to
  449. define the concrete syntax of a language, but they can also be used to
  450. describe the abstract syntax. We shall write our rules in a variant of
  451. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  452. \index{Backus-Naur Form}\index{BNF}
  453. As an example, we describe a small language, named $R_0$, that consists of
  454. integers and arithmetic operations.
  455. \index{grammar}
  456. The first grammar rule for the abstract syntax of $R_0$ says that an
  457. instance of the \code{Int} structure is an expression:
  458. \begin{equation}
  459. \Exp ::= \INT{\Int} \label{eq:arith-int}
  460. \end{equation}
  461. %
  462. Each rule has a left-hand-side and a right-hand-side. The way to read
  463. a rule is that if you have all the program parts on the
  464. right-hand-side, then you can create an AST node and categorize it
  465. according to the left-hand-side.
  466. %
  467. A name such as $\Exp$ that is
  468. defined by the grammar rules is a \emph{non-terminal}.
  469. \index{non-terminal}
  470. %
  471. The name $\Int$ is a also a non-terminal, but instead of defining it
  472. with a grammar rule, we define it with the following explanation. We
  473. make the simplifying design decision that all of the languages in this
  474. book only handle machine-representable integers. On most modern
  475. machines this corresponds to integers represented with 64-bits, i.e.,
  476. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  477. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  478. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  479. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  480. that the sequence of decimals represent an integer in range $-2^{62}$
  481. to $2^{62}-1$.
  482. The second grammar rule is the \texttt{read} operation that receives
  483. an input integer from the user of the program.
  484. \begin{equation}
  485. \Exp ::= \READ{} \label{eq:arith-read}
  486. \end{equation}
  487. The third rule says that, given an $\Exp$ node, you can build another
  488. $\Exp$ node by negating it.
  489. \begin{equation}
  490. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  491. \end{equation}
  492. Symbols in typewriter font such as \key{-} and \key{read} are
  493. \emph{terminal} symbols and must literally appear in the program for
  494. the rule to be applicable.
  495. \index{terminal}
  496. We can apply the rules to build ASTs in the $R_0$
  497. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  498. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  499. an $\Exp$.
  500. \begin{center}
  501. \begin{minipage}{0.4\textwidth}
  502. \begin{lstlisting}
  503. (Prim '- (list (Int 8)))
  504. \end{lstlisting}
  505. \end{minipage}
  506. \begin{minipage}{0.25\textwidth}
  507. \begin{equation}
  508. \begin{tikzpicture}
  509. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  510. \node[draw, circle] (8) at (0, -1.2) {$8$};
  511. \draw[->] (minus) to (8);
  512. \end{tikzpicture}
  513. \label{eq:arith-neg8}
  514. \end{equation}
  515. \end{minipage}
  516. \end{center}
  517. The next grammar rule defines addition expressions:
  518. \begin{equation}
  519. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  520. \end{equation}
  521. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  522. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  523. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  524. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  525. to show that
  526. \begin{lstlisting}
  527. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  528. \end{lstlisting}
  529. is an $\Exp$ in the $R_0$ language.
  530. If you have an AST for which the above rules do not apply, then the
  531. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  532. is not in $R_0$ because there are no rules for \code{+} with only one
  533. argument, nor for \key{-} with two arguments. Whenever we define a
  534. language with a grammar, the language only includes those programs
  535. that are justified by the rules.
  536. The last grammar rule for $R_0$ states that there is a \code{Program}
  537. node to mark the top of the whole program:
  538. \[
  539. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  540. \]
  541. The \code{Program} structure is defined as follows
  542. \begin{lstlisting}
  543. (struct Program (info body))
  544. \end{lstlisting}
  545. where \code{body} is an expression. In later chapters, the \code{info}
  546. part will be used to store auxiliary information but for now it is
  547. just the empty list.
  548. It is common to have many grammar rules with the same left-hand side
  549. but different right-hand sides, such as the rules for $\Exp$ in the
  550. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  551. combine several right-hand-sides into a single rule.
  552. We collect all of the grammar rules for the abstract syntax of $R_0$
  553. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  554. defined in Figure~\ref{fig:r0-concrete-syntax}.
  555. The \code{read-program} function provided in \code{utilities.rkt} of
  556. the support materials reads a program in from a file (the sequence of
  557. characters in the concrete syntax of Racket) and parses it into an
  558. abstract syntax tree. See the description of \code{read-program} in
  559. Appendix~\ref{appendix:utilities} for more details.
  560. \begin{figure}[tp]
  561. \fbox{
  562. \begin{minipage}{0.96\textwidth}
  563. \[
  564. \begin{array}{rcl}
  565. \begin{array}{rcl}
  566. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  567. R_0 &::=& \Exp
  568. \end{array}
  569. \end{array}
  570. \]
  571. \end{minipage}
  572. }
  573. \caption{The concrete syntax of $R_0$.}
  574. \label{fig:r0-concrete-syntax}
  575. \end{figure}
  576. \begin{figure}[tp]
  577. \fbox{
  578. \begin{minipage}{0.96\textwidth}
  579. \[
  580. \begin{array}{rcl}
  581. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  582. &\mid& \ADD{\Exp}{\Exp} \\
  583. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  584. \end{array}
  585. \]
  586. \end{minipage}
  587. }
  588. \caption{The abstract syntax of $R_0$.}
  589. \label{fig:r0-syntax}
  590. \end{figure}
  591. \section{Pattern Matching}
  592. \label{sec:pattern-matching}
  593. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  594. the parts of an AST node. Racket provides the \texttt{match} form to
  595. access the parts of a structure. Consider the following example and
  596. the output on the right. \index{match} \index{pattern matching}
  597. \begin{center}
  598. \begin{minipage}{0.5\textwidth}
  599. \begin{lstlisting}
  600. (match ast1.1
  601. [(Prim op (list child1 child2))
  602. (print op)])
  603. \end{lstlisting}
  604. \end{minipage}
  605. \vrule
  606. \begin{minipage}{0.25\textwidth}
  607. \begin{lstlisting}
  608. '+
  609. \end{lstlisting}
  610. \end{minipage}
  611. \end{center}
  612. In the above example, the \texttt{match} form takes the AST
  613. \eqref{eq:arith-prog} and binds its parts to the three pattern
  614. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  615. general, a match clause consists of a \emph{pattern} and a
  616. \emph{body}.
  617. \index{pattern}
  618. Patterns are recursively defined to be either a pattern
  619. variable, a structure name followed by a pattern for each of the
  620. structure's arguments, or an S-expression (symbols, lists, etc.).
  621. (See Chapter 12 of The Racket
  622. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  623. and Chapter 9 of The Racket
  624. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  625. for a complete description of \code{match}.)
  626. %
  627. The body of a match clause may contain arbitrary Racket code. The
  628. pattern variables can be used in the scope of the body.
  629. A \code{match} form may contain several clauses, as in the following
  630. function \code{leaf?} that recognizes when an $R_0$ node is
  631. a leaf. The \code{match} proceeds through the clauses in order,
  632. checking whether the pattern can match the input AST. The
  633. body of the first clause that matches is executed. The output of
  634. \code{leaf?} for several ASTs is shown on the right.
  635. \begin{center}
  636. \begin{minipage}{0.6\textwidth}
  637. \begin{lstlisting}
  638. (define (leaf? arith)
  639. (match arith
  640. [(Int n) #t]
  641. [(Prim 'read '()) #t]
  642. [(Prim '- (list c1)) #f]
  643. [(Prim '+ (list c1 c2)) #f]))
  644. (leaf? (Prim 'read '()))
  645. (leaf? (Prim '- (list (Int 8))))
  646. (leaf? (Int 8))
  647. \end{lstlisting}
  648. \end{minipage}
  649. \vrule
  650. \begin{minipage}{0.25\textwidth}
  651. \begin{lstlisting}
  652. #t
  653. #f
  654. #t
  655. \end{lstlisting}
  656. \end{minipage}
  657. \end{center}
  658. When writing a \code{match}, we refer to the grammar definition to
  659. identify which non-terminal we are expecting to match against, then we
  660. make sure that 1) we have one clause for each alternative of that
  661. non-terminal and 2) that the pattern in each clause corresponds to the
  662. corresponding right-hand side of a grammar rule. For the \code{match}
  663. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  664. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  665. alternatives, so the \code{match} has 4 clauses. The pattern in each
  666. clause corresponds to the right-hand side of a grammar rule. For
  667. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  668. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  669. patterns, replace non-terminals such as $\Exp$ with pattern variables
  670. of your choice (e.g. \code{c1} and \code{c2}).
  671. \section{Recursion}
  672. \label{sec:recursion}
  673. \index{recursive function}
  674. Programs are inherently recursive. For example, an $R_0$ expression is
  675. often made of smaller expressions. Thus, the natural way to process an
  676. entire program is with a recursive function. As a first example of
  677. such a recursive function, we define \texttt{exp?} below, which takes
  678. an arbitrary value and determines whether or not it is an $R_0$
  679. expression.
  680. %
  681. When a recursive function is defined using a sequence of match clauses
  682. that correspond to a grammar, and the body of each clause makes a
  683. recursive call on each child node, then we say the function is defined
  684. by \emph{structural recursion}\footnote{This principle of structuring
  685. code according to the data definition is advocated in the book
  686. \emph{How to Design Programs}
  687. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  688. define a second function, named \code{R0?}, that determines whether a
  689. value is an $R_0$ program. In general we can expect to write one
  690. recursive function to handle each non-terminal in a grammar.
  691. \index{structural recursion}
  692. %
  693. \begin{center}
  694. \begin{minipage}{0.7\textwidth}
  695. \begin{lstlisting}
  696. (define (exp? ast)
  697. (match ast
  698. [(Int n) #t]
  699. [(Prim 'read '()) #t]
  700. [(Prim '- (list e)) (exp? e)]
  701. [(Prim '+ (list e1 e2))
  702. (and (exp? e1) (exp? e2))]
  703. [else #f]))
  704. (define (R0? ast)
  705. (match ast
  706. [(Program '() e) (exp? e)]
  707. [else #f]))
  708. (R0? (Program '() ast1.1)
  709. (R0? (Program '()
  710. (Prim '- (list (Prim 'read '())
  711. (Prim '+ (list (Num 8)))))))
  712. \end{lstlisting}
  713. \end{minipage}
  714. \vrule
  715. \begin{minipage}{0.25\textwidth}
  716. \begin{lstlisting}
  717. #t
  718. #f
  719. \end{lstlisting}
  720. \end{minipage}
  721. \end{center}
  722. You may be tempted to merge the two functions into one, like this:
  723. \begin{center}
  724. \begin{minipage}{0.5\textwidth}
  725. \begin{lstlisting}
  726. (define (R0? ast)
  727. (match ast
  728. [(Int n) #t]
  729. [(Prim 'read '()) #t]
  730. [(Prim '- (list e)) (R0? e)]
  731. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  732. [(Program '() e) (R0? e)]
  733. [else #f]))
  734. \end{lstlisting}
  735. \end{minipage}
  736. \end{center}
  737. %
  738. Sometimes such a trick will save a few lines of code, especially when
  739. it comes to the \code{Program} wrapper. Yet this style is generally
  740. \emph{not} recommended because it can get you into trouble.
  741. %
  742. For example, the above function is subtly wrong:
  743. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  744. will return true, when it should return false.
  745. %% NOTE FIXME - must check for consistency on this issue throughout.
  746. \section{Interpreters}
  747. \label{sec:interp-R0}
  748. \index{interpreter}
  749. The meaning, or semantics, of a program is typically defined in the
  750. specification of the language. For example, the Scheme language is
  751. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  752. defined in its reference manual~\citep{plt-tr}. In this book we use an
  753. interpreter to define the meaning of each language that we consider,
  754. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  755. interpreter that is designated (by some people) as the definition of a
  756. language is called a \emph{definitional interpreter}.
  757. \index{definitional interpreter}
  758. We warm up by creating a definitional interpreter for the $R_0$ language, which
  759. serves as a second example of structural recursion. The
  760. \texttt{interp-R0} function is defined in
  761. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  762. input program followed by a call to the \lstinline{interp-exp} helper
  763. function, which in turn has one match clause per grammar rule for
  764. $R_0$ expressions.
  765. \begin{figure}[tp]
  766. \begin{lstlisting}
  767. (define (interp-exp e)
  768. (match e
  769. [(Int n) n]
  770. [(Prim 'read '())
  771. (define r (read))
  772. (cond [(fixnum? r) r]
  773. [else (error 'interp-R0 "expected an integer" r)])]
  774. [(Prim '- (list e))
  775. (define v (interp-exp e))
  776. (fx- 0 v)]
  777. [(Prim '+ (list e1 e2))
  778. (define v1 (interp-exp e1))
  779. (define v2 (interp-exp e2))
  780. (fx+ v1 v2)]
  781. ))
  782. (define (interp-R0 p)
  783. (match p
  784. [(Program '() e) (interp-exp e)]
  785. ))
  786. \end{lstlisting}
  787. \caption{Interpreter for the $R_0$ language.}
  788. \label{fig:interp-R0}
  789. \end{figure}
  790. Let us consider the result of interpreting a few $R_0$ programs. The
  791. following program adds two integers.
  792. \begin{lstlisting}
  793. (+ 10 32)
  794. \end{lstlisting}
  795. The result is \key{42}. We wrote the above program in concrete syntax,
  796. whereas the parsed abstract syntax is:
  797. \begin{lstlisting}
  798. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  799. \end{lstlisting}
  800. The next example demonstrates that expressions may be nested within
  801. each other, in this case nesting several additions and negations.
  802. \begin{lstlisting}
  803. (+ 10 (- (+ 12 20)))
  804. \end{lstlisting}
  805. What is the result of the above program?
  806. As mentioned previously, the $R_0$ language does not support
  807. arbitrarily-large integers, but only $63$-bit integers, so we
  808. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  809. in Racket.
  810. Suppose
  811. \[
  812. n = 999999999999999999
  813. \]
  814. which indeed fits in $63$-bits. What happens when we run the
  815. following program in our interpreter?
  816. \begin{lstlisting}
  817. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  818. \end{lstlisting}
  819. It produces an error:
  820. \begin{lstlisting}
  821. fx+: result is not a fixnum
  822. \end{lstlisting}
  823. We establish the convention that if running the definitional
  824. interpreter on a program produces an error, then the meaning of that
  825. program is \emph{unspecified}. That means a compiler for the language
  826. is under no obligations regarding that program; it may or may not
  827. produce an executable, and if it does, that executable can do
  828. anything. This convention applies to the languages defined in this
  829. book, as a way to simplify the student's task of implementing them,
  830. but this convention is not applicable to all programming languages.
  831. \index{unspecified behavior}
  832. Moving on to the last feature of the $R_0$ language, the \key{read}
  833. operation prompts the user of the program for an integer. Recall that
  834. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  835. \code{8}. So if we run
  836. \begin{lstlisting}
  837. (interp-R0 (Program '() ast1.1))
  838. \end{lstlisting}
  839. and if the input is \code{50}, then we get the answer to life, the
  840. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  841. Guide to the Galaxy} by Douglas Adams.}
  842. We include the \key{read} operation in $R_0$ so a clever student
  843. cannot implement a compiler for $R_0$ that simply runs the interpreter
  844. during compilation to obtain the output and then generates the trivial
  845. code to produce the output. (Yes, a clever student did this in the
  846. first instance of this course.)
  847. The job of a compiler is to translate a program in one language into a
  848. program in another language so that the output program behaves the
  849. same way as the input program does according to its definitional
  850. interpreter. This idea is depicted in the following diagram. Suppose
  851. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  852. interpreter for each language. Suppose that the compiler translates
  853. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  854. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  855. respective interpreters with input $i$ should yield the same output
  856. $o$.
  857. \begin{equation} \label{eq:compile-correct}
  858. \begin{tikzpicture}[baseline=(current bounding box.center)]
  859. \node (p1) at (0, 0) {$P_1$};
  860. \node (p2) at (3, 0) {$P_2$};
  861. \node (o) at (3, -2.5) {$o$};
  862. \path[->] (p1) edge [above] node {compile} (p2);
  863. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  864. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  865. \end{tikzpicture}
  866. \end{equation}
  867. In the next section we see our first example of a compiler.
  868. \section{Example Compiler: a Partial Evaluator}
  869. \label{sec:partial-evaluation}
  870. In this section we consider a compiler that translates $R_0$ programs
  871. into $R_0$ programs that may be more efficient, that is, this compiler
  872. is an optimizer. This optimizer eagerly computes the parts of the
  873. program that do not depend on any inputs, a process known as
  874. \emph{partial evaluation}~\cite{Jones:1993uq}.
  875. \index{partial evaluation}
  876. For example, given the following program
  877. \begin{lstlisting}
  878. (+ (read) (- (+ 5 3)))
  879. \end{lstlisting}
  880. our compiler will translate it into the program
  881. \begin{lstlisting}
  882. (+ (read) -8)
  883. \end{lstlisting}
  884. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  885. evaluator for the $R_0$ language. The output of the partial evaluator
  886. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  887. recursion over $\Exp$ is captured in the \code{pe-exp} function
  888. whereas the code for partially evaluating the negation and addition
  889. operations is factored into two separate helper functions:
  890. \code{pe-neg} and \code{pe-add}. The input to these helper
  891. functions is the output of partially evaluating the children.
  892. \begin{figure}[tp]
  893. \begin{lstlisting}
  894. (define (pe-neg r)
  895. (match r
  896. [(Int n) (Int (fx- 0 n))]
  897. [else (Prim '- (list r))]))
  898. (define (pe-add r1 r2)
  899. (match* (r1 r2)
  900. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  901. [(_ _) (Prim '+ (list r1 r2))]))
  902. (define (pe-exp e)
  903. (match e
  904. [(Int n) (Int n)]
  905. [(Prim 'read '()) (Prim 'read '())]
  906. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  907. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  908. ))
  909. (define (pe-R0 p)
  910. (match p
  911. [(Program '() e) (Program '() (pe-exp e))]
  912. ))
  913. \end{lstlisting}
  914. \caption{A partial evaluator for $R_0$ expressions.}
  915. \label{fig:pe-arith}
  916. \end{figure}
  917. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  918. arguments are integers and if they are, perform the appropriate
  919. arithmetic. Otherwise, they create an AST node for the operation
  920. (either negation or addition).
  921. To gain some confidence that the partial evaluator is correct, we can
  922. test whether it produces programs that get the same result as the
  923. input programs. That is, we can test whether it satisfies Diagram
  924. \eqref{eq:compile-correct}. The following code runs the partial
  925. evaluator on several examples and tests the output program. The
  926. \texttt{parse-program} and \texttt{assert} functions are defined in
  927. Appendix~\ref{appendix:utilities}.\\
  928. \begin{minipage}{1.0\textwidth}
  929. \begin{lstlisting}
  930. (define (test-pe p)
  931. (assert "testing pe-R0"
  932. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  933. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  934. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  935. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  936. \end{lstlisting}
  937. \end{minipage}
  938. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  939. \chapter{Integers and Variables}
  940. \label{ch:int-exp}
  941. This chapter is about compiling the subset of Racket that includes
  942. integer arithmetic and local variable binding, which we name $R_1$, to
  943. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  944. to x86-64 simply as x86. The chapter begins with a description of the
  945. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  946. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  947. discuss only what is needed for compiling $R_1$. We introduce more of
  948. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  949. reflect on their differences and come up with a plan to break down the
  950. translation from $R_1$ to x86 into a handful of steps
  951. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  952. chapter give detailed hints regarding each step
  953. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  954. to give enough hints that the well-prepared reader, together with a
  955. few friends, can implement a compiler from $R_1$ to x86 in a couple
  956. weeks while at the same time leaving room for some fun and creativity.
  957. To give the reader a feeling for the scale of this first compiler, the
  958. instructor solution for the $R_1$ compiler is less than 500 lines of
  959. code.
  960. \section{The $R_1$ Language}
  961. \label{sec:s0}
  962. \index{variable}
  963. The $R_1$ language extends the $R_0$ language with variable
  964. definitions. The concrete syntax of the $R_1$ language is defined by
  965. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  966. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  967. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  968. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  969. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  970. \key{Program} struct to mark the top of the program.
  971. %% The $\itm{info}$
  972. %% field of the \key{Program} structure contains an \emph{association
  973. %% list} (a list of key-value pairs) that is used to communicate
  974. %% auxiliary data from one compiler pass the next.
  975. Despite the simplicity of the $R_1$ language, it is rich enough to
  976. exhibit several compilation techniques.
  977. \begin{figure}[tp]
  978. \centering
  979. \fbox{
  980. \begin{minipage}{0.96\textwidth}
  981. \[
  982. \begin{array}{rcl}
  983. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  984. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  985. R_1 &::=& \Exp
  986. \end{array}
  987. \]
  988. \end{minipage}
  989. }
  990. \caption{The concrete syntax of $R_1$.}
  991. \label{fig:r1-concrete-syntax}
  992. \end{figure}
  993. \begin{figure}[tp]
  994. \centering
  995. \fbox{
  996. \begin{minipage}{0.96\textwidth}
  997. \[
  998. \begin{array}{rcl}
  999. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1000. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1001. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1002. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1003. \end{array}
  1004. \]
  1005. \end{minipage}
  1006. }
  1007. \caption{The abstract syntax of $R_1$.}
  1008. \label{fig:r1-syntax}
  1009. \end{figure}
  1010. Let us dive further into the syntax and semantics of the $R_1$
  1011. language. The \key{Let} feature defines a variable for use within its
  1012. body and initializes the variable with the value of an expression.
  1013. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1014. The concrete syntax for \key{Let} is
  1015. \begin{lstlisting}
  1016. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1017. \end{lstlisting}
  1018. For example, the following program initializes \code{x} to $32$ and then
  1019. evaluates the body \code{(+ 10 x)}, producing $42$.
  1020. \begin{lstlisting}
  1021. (let ([x (+ 12 20)]) (+ 10 x))
  1022. \end{lstlisting}
  1023. When there are multiple \key{let}'s for the same variable, the closest
  1024. enclosing \key{let} is used. That is, variable definitions overshadow
  1025. prior definitions. Consider the following program with two \key{let}'s
  1026. that define variables named \code{x}. Can you figure out the result?
  1027. \begin{lstlisting}
  1028. (let ([x 32]) (+ (let ([x 10]) x) x))
  1029. \end{lstlisting}
  1030. For the purposes of depicting which variable uses correspond to which
  1031. definitions, the following shows the \code{x}'s annotated with
  1032. subscripts to distinguish them. Double check that your answer for the
  1033. above is the same as your answer for this annotated version of the
  1034. program.
  1035. \begin{lstlisting}
  1036. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1037. \end{lstlisting}
  1038. The initializing expression is always evaluated before the body of the
  1039. \key{let}, so in the following, the \key{read} for \code{x} is
  1040. performed before the \key{read} for \code{y}. Given the input
  1041. $52$ then $10$, the following produces $42$ (not $-42$).
  1042. \begin{lstlisting}
  1043. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1044. \end{lstlisting}
  1045. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1046. \small
  1047. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1048. An \emph{association list} (alist) is a list of key-value pairs.
  1049. For example, we can map people to their ages with an alist.
  1050. \index{alist}\index{association list}
  1051. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1052. (define ages
  1053. '((jane . 25) (sam . 24) (kate . 45)))
  1054. \end{lstlisting}
  1055. The \emph{dictionary} interface is for mapping keys to values.
  1056. Every alist implements this interface. \index{dictionary} The package
  1057. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1058. provides many functions for working with dictionaries. Here
  1059. are a few of them:
  1060. \begin{description}
  1061. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1062. returns the value associated with the given $\itm{key}$.
  1063. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1064. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1065. but otherwise is the same as $\itm{dict}$.
  1066. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1067. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1068. of keys and values in $\itm{dict}$. For example, the following
  1069. creates a new alist in which the ages are incremented.
  1070. \end{description}
  1071. \vspace{-10pt}
  1072. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1073. (for/list ([(k v) (in-dict ages)])
  1074. (cons k (add1 v)))
  1075. \end{lstlisting}
  1076. \end{tcolorbox}
  1077. \end{wrapfigure}
  1078. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1079. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1080. \key{match} clauses for variables and for \key{let}. For \key{let},
  1081. we need a way to communicate the value of a variable to all the uses
  1082. of a variable. To accomplish this, we maintain a mapping from
  1083. variables to values. Throughout the compiler we often need to map
  1084. variables to information about them. We refer to these mappings as
  1085. \emph{environments}\index{environment}
  1086. \footnote{Another common term for environment in the compiler
  1087. literature is \emph{symbol table}\index{symbol table}.}.
  1088. For simplicity, we use an
  1089. association list (alist) to represent the environment. The sidebar to
  1090. the right gives a brief introduction to alists and the
  1091. \code{racket/dict} package. The \code{interp-R1} function takes the
  1092. current environment, \code{env}, as an extra parameter. When the
  1093. interpreter encounters a variable, it finds the corresponding value
  1094. using the \code{dict-ref} function. When the interpreter encounters a
  1095. \key{Let}, it evaluates the initializing expression, extends the
  1096. environment with the result value bound to the variable, using
  1097. \code{dict-set}, then evaluates the body of the \key{Let}.
  1098. \begin{figure}[tp]
  1099. \begin{lstlisting}
  1100. (define (interp-exp env)
  1101. (lambda (e)
  1102. (match e
  1103. [(Int n) n]
  1104. [(Prim 'read '())
  1105. (define r (read))
  1106. (cond [(fixnum? r) r]
  1107. [else (error 'interp-R1 "expected an integer" r)])]
  1108. [(Prim '- (list e))
  1109. (define v ((interp-exp env) e))
  1110. (fx- 0 v)]
  1111. [(Prim '+ (list e1 e2))
  1112. (define v1 ((interp-exp env) e1))
  1113. (define v2 ((interp-exp env) e2))
  1114. (fx+ v1 v2)]
  1115. [(Var x) (dict-ref env x)]
  1116. [(Let x e body)
  1117. (define new-env (dict-set env x ((interp-exp env) e)))
  1118. ((interp-exp new-env) body)]
  1119. )))
  1120. (define (interp-R1 p)
  1121. (match p
  1122. [(Program '() e) ((interp-exp '()) e)]
  1123. ))
  1124. \end{lstlisting}
  1125. \caption{Interpreter for the $R_1$ language.}
  1126. \label{fig:interp-R1}
  1127. \end{figure}
  1128. The goal for this chapter is to implement a compiler that translates
  1129. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1130. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1131. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1132. is, they both output the same integer $n$. We depict this correctness
  1133. criteria in the following diagram.
  1134. \[
  1135. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1136. \node (p1) at (0, 0) {$P_1$};
  1137. \node (p2) at (4, 0) {$P_2$};
  1138. \node (o) at (4, -2) {$n$};
  1139. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1140. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1141. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1142. \end{tikzpicture}
  1143. \]
  1144. In the next section we introduce enough of the x86 assembly
  1145. language to compile $R_1$.
  1146. \section{The x86$_0$ Assembly Language}
  1147. \label{sec:x86}
  1148. \index{x86}
  1149. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1150. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1151. %
  1152. An x86 program begins with a \code{main} label followed by a sequence
  1153. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1154. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1155. instructions.\index{instruction}
  1156. %
  1157. An x86 program is stored in the computer's memory and the computer has
  1158. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1159. that points to the address of the next
  1160. instruction to be executed. For most instructions, once the
  1161. instruction is executed, the program counter is incremented to point
  1162. to the immediately following instruction in memory. Most x86
  1163. instructions take two operands, where each operand is either an
  1164. integer constant (called \emph{immediate value}\index{immediate value}),
  1165. a \emph{register}\index{register}, or a memory location.
  1166. A register is a special kind of variable. Each
  1167. one holds a 64-bit value; there are 16 registers in the computer and
  1168. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1169. as a mapping of 64-bit addresses to 64-bit values%
  1170. \footnote{This simple story suffices for describing how sequential
  1171. programs access memory but is not sufficient for multi-threaded
  1172. programs. However, multi-threaded execution is beyond the scope of
  1173. this book.}.
  1174. %
  1175. We use the AT\&T syntax expected by the GNU assembler, which comes
  1176. with the \key{gcc} compiler that we use for compiling assembly code to
  1177. machine code.
  1178. %
  1179. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1180. the x86 instructions used in this book.
  1181. % to do: finish treatment of imulq
  1182. % it's needed for vector's in R6/R7
  1183. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1184. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1185. && \key{r8} \mid \key{r9} \mid \key{r10}
  1186. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1187. \mid \key{r14} \mid \key{r15}}
  1188. \begin{figure}[tp]
  1189. \fbox{
  1190. \begin{minipage}{0.96\textwidth}
  1191. \[
  1192. \begin{array}{lcl}
  1193. \Reg &::=& \allregisters{} \\
  1194. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1195. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1196. \key{subq} \; \Arg\key{,} \Arg \mid
  1197. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1198. && \key{callq} \; \mathit{label} \mid
  1199. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1200. && \itm{label}\key{:}\; \Instr \\
  1201. x86_0 &::= & \key{.globl main}\\
  1202. & & \key{main:} \; \Instr\ldots
  1203. \end{array}
  1204. \]
  1205. \end{minipage}
  1206. }
  1207. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1208. \label{fig:x86-0-concrete}
  1209. \end{figure}
  1210. An immediate value is written using the notation \key{\$}$n$ where $n$
  1211. is an integer.
  1212. %
  1213. A register is written with a \key{\%} followed by the register name,
  1214. such as \key{\%rax}.
  1215. %
  1216. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1217. which obtains the address stored in register $r$ and then adds $n$
  1218. bytes to the address. The resulting address is used to either load or
  1219. store to memory depending on whether it occurs as a source or
  1220. destination argument of an instruction.
  1221. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1222. source $s$ and destination $d$, applies the arithmetic operation, then
  1223. writes the result back to the destination $d$.
  1224. %
  1225. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1226. stores the result in $d$.
  1227. %
  1228. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1229. specified by the label and $\key{retq}$ returns from a procedure to
  1230. its caller. We discuss procedure calls in more detail later in this
  1231. chapter and in Chapter~\ref{ch:functions}. The
  1232. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1233. the address of the instruction after the specified label.
  1234. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1235. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1236. \key{main} procedure is externally visible, which is necessary so
  1237. that the operating system can call it. The label \key{main:}
  1238. indicates the beginning of the \key{main} procedure which is where
  1239. the operating system starts executing this program. The instruction
  1240. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1241. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1242. $10$ in \key{rax} and puts the result, $42$, back into
  1243. \key{rax}.
  1244. %
  1245. The last instruction, \key{retq}, finishes the \key{main} function by
  1246. returning the integer in \key{rax} to the operating system. The
  1247. operating system interprets this integer as the program's exit
  1248. code. By convention, an exit code of 0 indicates that a program
  1249. completed successfully, and all other exit codes indicate various
  1250. errors. Nevertheless, we return the result of the program as the exit
  1251. code.
  1252. %\begin{wrapfigure}{r}{2.25in}
  1253. \begin{figure}[tbp]
  1254. \begin{lstlisting}
  1255. .globl main
  1256. main:
  1257. movq $10, %rax
  1258. addq $32, %rax
  1259. retq
  1260. \end{lstlisting}
  1261. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1262. \label{fig:p0-x86}
  1263. %\end{wrapfigure}
  1264. \end{figure}
  1265. Unfortunately, x86 varies in a couple ways depending on what operating
  1266. system it is assembled in. The code examples shown here are correct on
  1267. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1268. labels like \key{main} must be prefixed with an underscore, as in
  1269. \key{\_main}.
  1270. We exhibit the use of memory for storing intermediate results in the
  1271. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1272. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1273. memory called the \emph{procedure call stack} (or \emph{stack} for
  1274. short). \index{stack}\index{procedure call stack} The stack consists
  1275. of a separate \emph{frame}\index{frame} for each procedure call. The
  1276. memory layout for an individual frame is shown in
  1277. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1278. \emph{stack pointer}\index{stack pointer} and points to the item at
  1279. the top of the stack. The stack grows downward in memory, so we
  1280. increase the size of the stack by subtracting from the stack pointer.
  1281. In the context of a procedure call, the \emph{return
  1282. address}\index{return address} is the next instruction after the
  1283. call instruction on the caller side. During a function call, the
  1284. return address is pushed onto the stack. The register \key{rbp} is
  1285. the \emph{base pointer}\index{base pointer} and is used to access
  1286. variables associated with the current procedure call. The base
  1287. pointer of the caller is pushed onto the stack after the return
  1288. address. We number the variables from $1$ to $n$. Variable $1$ is
  1289. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1290. $-16\key{(\%rbp)}$, etc.
  1291. \begin{figure}[tbp]
  1292. \begin{lstlisting}
  1293. start:
  1294. movq $10, -8(%rbp)
  1295. negq -8(%rbp)
  1296. movq -8(%rbp), %rax
  1297. addq $52, %rax
  1298. jmp conclusion
  1299. .globl main
  1300. main:
  1301. pushq %rbp
  1302. movq %rsp, %rbp
  1303. subq $16, %rsp
  1304. jmp start
  1305. conclusion:
  1306. addq $16, %rsp
  1307. popq %rbp
  1308. retq
  1309. \end{lstlisting}
  1310. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1311. \label{fig:p1-x86}
  1312. \end{figure}
  1313. \begin{figure}[tbp]
  1314. \centering
  1315. \begin{tabular}{|r|l|} \hline
  1316. Position & Contents \\ \hline
  1317. 8(\key{\%rbp}) & return address \\
  1318. 0(\key{\%rbp}) & old \key{rbp} \\
  1319. -8(\key{\%rbp}) & variable $1$ \\
  1320. -16(\key{\%rbp}) & variable $2$ \\
  1321. \ldots & \ldots \\
  1322. 0(\key{\%rsp}) & variable $n$\\ \hline
  1323. \end{tabular}
  1324. \caption{Memory layout of a frame.}
  1325. \label{fig:frame}
  1326. \end{figure}
  1327. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1328. control is transfered from the operating system to the \code{main}
  1329. function. The operating system issues a \code{callq main} instruction
  1330. which pushes its return address on the stack and then jumps to
  1331. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1332. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1333. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1334. alignment (because the \code{callq} pushed the return address). The
  1335. first three instructions are the typical \emph{prelude}\index{prelude}
  1336. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1337. pointer for the caller onto the stack and subtracts $8$ from the stack
  1338. pointer. At this point the stack pointer is back to being 16-byte
  1339. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1340. base pointer so that it points the location of the old base
  1341. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1342. pointer down to make enough room for storing variables. This program
  1343. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1344. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1345. we are ready to make calls to other functions. The last instruction of
  1346. the prelude is \code{jmp start}, which transfers control to the
  1347. instructions that were generated from the Racket expression \code{(+
  1348. 10 32)}.
  1349. The four instructions under the label \code{start} carry out the work
  1350. of computing \code{(+ 52 (- 10)))}. The first instruction
  1351. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1352. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1353. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1354. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1355. \code{rax}, at which point \code{rax} contains $42$.
  1356. The three instructions under the label \code{conclusion} are the
  1357. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1358. two instructions are necessary to get the state of the machine back to
  1359. where it was at the beginning of the procedure. The instruction
  1360. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1361. old base pointer. The amount added here needs to match the amount that
  1362. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1363. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1364. pointer. The last instruction, \key{retq}, jumps back to the
  1365. procedure that called this one and adds 8 to the stack pointer, which
  1366. returns the stack pointer to where it was prior to the procedure call.
  1367. The compiler needs a convenient representation for manipulating x86
  1368. programs, so we define an abstract syntax for x86 in
  1369. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1370. a subscript $0$ because later we introduce extended versions of this
  1371. assembly language. The main difference compared to the concrete syntax
  1372. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1373. labeled instructions to appear anywhere, but instead organizes
  1374. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1375. and associates a label with every block, which is why the \key{CFG} struct
  1376. (for control-flow graph) includes an alist mapping labels to
  1377. blocks. The reason for this organization becomes apparent in
  1378. Chapter~\ref{ch:bool-types} when we introduce conditional
  1379. branching. The \code{Block} structure includes an $\itm{info}$ field
  1380. that is not needed for this chapter, but will become useful in
  1381. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1382. field should just contain an empty list.
  1383. \begin{figure}[tp]
  1384. \fbox{
  1385. \begin{minipage}{0.96\textwidth}
  1386. \small
  1387. \[
  1388. \begin{array}{lcl}
  1389. \Reg &::=& \allregisters{} \\
  1390. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1391. \mid \DEREF{\Reg}{\Int} \\
  1392. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1393. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1394. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1395. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1396. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1397. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1398. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1399. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1400. \end{array}
  1401. \]
  1402. \end{minipage}
  1403. }
  1404. \caption{The abstract syntax of x86$_0$ assembly.}
  1405. \label{fig:x86-0-ast}
  1406. \end{figure}
  1407. \section{Planning the trip to x86 via the $C_0$ language}
  1408. \label{sec:plan-s0-x86}
  1409. To compile one language to another it helps to focus on the
  1410. differences between the two languages because the compiler will need
  1411. to bridge those differences. What are the differences between $R_1$
  1412. and x86 assembly? Here are some of the most important ones:
  1413. \begin{enumerate}
  1414. \item[(a)] x86 arithmetic instructions typically have two arguments
  1415. and update the second argument in place. In contrast, $R_1$
  1416. arithmetic operations take two arguments and produce a new value.
  1417. An x86 instruction may have at most one memory-accessing argument.
  1418. Furthermore, some instructions place special restrictions on their
  1419. arguments.
  1420. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1421. whereas x86 instructions restrict their arguments to be integers
  1422. constants, registers, and memory locations.
  1423. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1424. sequence of instructions and jumps to labeled positions, whereas in
  1425. $R_1$ the order of evaluation is a left-to-right depth-first
  1426. traversal of the abstract syntax tree.
  1427. \item[(d)] An $R_1$ program can have any number of variables whereas
  1428. x86 has 16 registers and the procedure calls stack.
  1429. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1430. same name. The registers and memory locations of x86 all have unique
  1431. names or addresses.
  1432. \end{enumerate}
  1433. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1434. the problem into several steps, dealing with the above differences one
  1435. at a time. Each of these steps is called a \emph{pass} of the
  1436. compiler.\index{pass}\index{compiler pass}
  1437. %
  1438. This terminology comes from each step traverses (i.e. passes over) the
  1439. AST of the program.
  1440. %
  1441. We begin by sketching how we might implement each pass, and give them
  1442. names. We then figure out an ordering of the passes and the
  1443. input/output language for each pass. The very first pass has $R_1$ as
  1444. its input language and the last pass has x86 as its output
  1445. language. In between we can choose whichever language is most
  1446. convenient for expressing the output of each pass, whether that be
  1447. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1448. Finally, to implement each pass we write one recursive function per
  1449. non-terminal in the grammar of the input language of the pass.
  1450. \index{intermediate language}
  1451. \begin{description}
  1452. \item[Pass \key{select-instructions}] To handle the difference between
  1453. $R_1$ operations and x86 instructions we convert each $R_1$
  1454. operation to a short sequence of instructions that accomplishes the
  1455. same task.
  1456. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1457. subexpression (i.e. operator and operand, and hence the name
  1458. \key{opera*}) is an \emph{atomic} expression (a variable or
  1459. integer), we introduce temporary variables to hold the results
  1460. of subexpressions.\index{atomic expression}
  1461. \item[Pass \key{explicate-control}] To make the execution order of the
  1462. program explicit, we convert from the abstract syntax tree
  1463. representation into a control-flow graph in which each node
  1464. contains a sequence of statements and the edges between nodes say
  1465. where to go at the end of the sequence.
  1466. \item[Pass \key{assign-homes}] To handle the difference between the
  1467. variables in $R_1$ versus the registers and stack locations in x86,
  1468. we map each variable to a register or stack location.
  1469. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1470. by renaming every variable to a unique name, so that shadowing no
  1471. longer occurs.
  1472. \end{description}
  1473. The next question is: in what order should we apply these passes? This
  1474. question can be challenging because it is difficult to know ahead of
  1475. time which orders will be better (easier to implement, produce more
  1476. efficient code, etc.) so oftentimes trial-and-error is
  1477. involved. Nevertheless, we can try to plan ahead and make educated
  1478. choices regarding the ordering.
  1479. Let us consider the ordering of \key{uniquify} and
  1480. \key{remove-complex-opera*}. The assignment of subexpressions to
  1481. temporary variables involves introducing new variables and moving
  1482. subexpressions, which might change the shadowing of variables and
  1483. inadvertently change the behavior of the program. But if we apply
  1484. \key{uniquify} first, this will not be an issue. Of course, this means
  1485. that in \key{remove-complex-opera*}, we need to ensure that the
  1486. temporary variables that it creates are unique.
  1487. What should be the ordering of \key{explicate-control} with respect to
  1488. \key{uniquify}? The \key{uniquify} pass should come first because
  1489. \key{explicate-control} changes all the \key{let}-bound variables to
  1490. become local variables whose scope is the entire program, which would
  1491. confuse variables with the same name.
  1492. %
  1493. Likewise, we place \key{explicate-control} after
  1494. \key{remove-complex-opera*} because \key{explicate-control} removes
  1495. the \key{let} form, but it is convenient to use \key{let} in the
  1496. output of \key{remove-complex-opera*}.
  1497. %
  1498. Regarding \key{assign-homes}, it is helpful to place
  1499. \key{explicate-control} first because \key{explicate-control} changes
  1500. \key{let}-bound variables into program-scope variables. This means
  1501. that the \key{assign-homes} pass can read off the variables from the
  1502. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1503. entire program in search of \key{let}-bound variables.
  1504. Last, we need to decide on the ordering of \key{select-instructions}
  1505. and \key{assign-homes}. These two passes are intertwined, creating a
  1506. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1507. have already determined which instructions will be used, because x86
  1508. instructions have restrictions about which of their arguments can be
  1509. registers versus stack locations. One might want to give preferential
  1510. treatment to variables that occur in register-argument positions. On
  1511. the other hand, it may turn out to be impossible to make sure that all
  1512. such variables are assigned to registers, and then one must redo the
  1513. selection of instructions. Some compilers handle this problem by
  1514. iteratively repeating these two passes until a good solution is found.
  1515. We shall use a simpler approach in which \key{select-instructions}
  1516. comes first, followed by the \key{assign-homes}, then a third
  1517. pass named \key{patch-instructions} that uses a reserved register to
  1518. patch-up outstanding problems regarding instructions with too many
  1519. memory accesses. The disadvantage of this approach is some programs
  1520. may not execute as efficiently as they would if we used the iterative
  1521. approach and used all of the registers for variables.
  1522. \begin{figure}[tbp]
  1523. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1524. \node (R1) at (0,2) {\large $R_1$};
  1525. \node (R1-2) at (3,2) {\large $R_1$};
  1526. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1527. %\node (C0-1) at (6,0) {\large $C_0$};
  1528. \node (C0-2) at (3,0) {\large $C_0$};
  1529. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1530. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1531. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1532. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1533. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1534. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1535. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1536. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1537. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1538. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1539. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1540. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1541. \end{tikzpicture}
  1542. \caption{Overview of the passes for compiling $R_1$. }
  1543. \label{fig:R1-passes}
  1544. \end{figure}
  1545. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1546. passes in the form of a graph. Each pass is an edge and the
  1547. input/output language of each pass is a node in the graph. The output
  1548. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1549. are still in the $R_1$ language, but the output of the pass
  1550. \key{explicate-control} is in a different language $C_0$ that is
  1551. designed to make the order of evaluation explicit in its syntax, which
  1552. we introduce in the next section. The \key{select-instruction} pass
  1553. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1554. \key{patch-instructions} passes input and output variants of x86
  1555. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1556. \key{print-x86}, which converts from the abstract syntax of
  1557. $\text{x86}_0$ to the concrete syntax of x86.
  1558. In the next sections we discuss the $C_0$ language and the
  1559. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1560. remainder of this chapter gives hints regarding the implementation of
  1561. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1562. \subsection{The $C_0$ Intermediate Language}
  1563. The output of \key{explicate-control} is similar to the $C$
  1564. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1565. categories for expressions and statements, so we name it $C_0$. The
  1566. concrete syntax for $C_0$ is defined in
  1567. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1568. is defined in Figure~\ref{fig:c0-syntax}.
  1569. %
  1570. The $C_0$ language supports the same operators as $R_1$ but the
  1571. arguments of operators are restricted to atomic expressions (variables
  1572. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1573. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1574. executed in sequence using the \key{Seq} form. A sequence of
  1575. statements always ends with \key{Return}, a guarantee that is baked
  1576. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1577. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1578. which refers to an expression that is the last one to execute within a
  1579. function. (A expression in tail position may contain subexpressions,
  1580. and those may or may not be in tail position depending on the kind of
  1581. expression.)
  1582. A $C_0$ program consists of a control-flow graph (represented as an
  1583. alist mapping labels to tails). This is more general than
  1584. necessary for the present chapter, as we do not yet need to introduce
  1585. \key{goto} for jumping to labels, but it saves us from having to
  1586. change the syntax of the program construct in
  1587. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1588. \key{start}, and the whole program is its tail.
  1589. %
  1590. The $\itm{info}$ field of the \key{Program} form, after the
  1591. \key{explicate-control} pass, contains a mapping from the symbol
  1592. \key{locals} to a list of variables, that is, a list of all the
  1593. variables used in the program. At the start of the program, these
  1594. variables are uninitialized; they become initialized on their first
  1595. assignment.
  1596. \begin{figure}[tbp]
  1597. \fbox{
  1598. \begin{minipage}{0.96\textwidth}
  1599. \[
  1600. \begin{array}{lcl}
  1601. \Atm &::=& \Int \mid \Var \\
  1602. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1603. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1604. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1605. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1606. \end{array}
  1607. \]
  1608. \end{minipage}
  1609. }
  1610. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1611. \label{fig:c0-concrete-syntax}
  1612. \end{figure}
  1613. \begin{figure}[tbp]
  1614. \fbox{
  1615. \begin{minipage}{0.96\textwidth}
  1616. \[
  1617. \begin{array}{lcl}
  1618. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1619. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1620. &\mid& \ADD{\Atm}{\Atm}\\
  1621. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1622. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1623. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1624. \end{array}
  1625. \]
  1626. \end{minipage}
  1627. }
  1628. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1629. \label{fig:c0-syntax}
  1630. \end{figure}
  1631. %% The \key{select-instructions} pass is optimistic in the sense that it
  1632. %% treats variables as if they were all mapped to registers. The
  1633. %% \key{select-instructions} pass generates a program that consists of
  1634. %% x86 instructions but that still uses variables, so it is an
  1635. %% intermediate language that is technically different than x86, which
  1636. %% explains the asterisks in the diagram above.
  1637. %% In this Chapter we shall take the easy road to implementing
  1638. %% \key{assign-homes} and simply map all variables to stack locations.
  1639. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1640. %% smarter approach in which we make a best-effort to map variables to
  1641. %% registers, resorting to the stack only when necessary.
  1642. %% Once variables have been assigned to their homes, we can finalize the
  1643. %% instruction selection by dealing with an idiosyncrasy of x86
  1644. %% assembly. Many x86 instructions have two arguments but only one of the
  1645. %% arguments may be a memory reference (and the stack is a part of
  1646. %% memory). Because some variables may get mapped to stack locations,
  1647. %% some of our generated instructions may violate this restriction. The
  1648. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1649. %% replacing every violating instruction with a short sequence of
  1650. %% instructions that use the \key{rax} register. Once we have implemented
  1651. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1652. %% need to patch instructions will be relatively rare.
  1653. \subsection{The dialects of x86}
  1654. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1655. the pass \key{select-instructions}. It extends x86$_0$ with an
  1656. unbounded number of program-scope variables and has looser rules
  1657. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1658. output of \key{print-x86}, is the concrete syntax for x86.
  1659. \section{Uniquify Variables}
  1660. \label{sec:uniquify-s0}
  1661. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1662. programs in which every \key{let} uses a unique variable name. For
  1663. example, the \code{uniquify} pass should translate the program on the
  1664. left into the program on the right. \\
  1665. \begin{tabular}{lll}
  1666. \begin{minipage}{0.4\textwidth}
  1667. \begin{lstlisting}
  1668. (let ([x 32])
  1669. (+ (let ([x 10]) x) x))
  1670. \end{lstlisting}
  1671. \end{minipage}
  1672. &
  1673. $\Rightarrow$
  1674. &
  1675. \begin{minipage}{0.4\textwidth}
  1676. \begin{lstlisting}
  1677. (let ([x.1 32])
  1678. (+ (let ([x.2 10]) x.2) x.1))
  1679. \end{lstlisting}
  1680. \end{minipage}
  1681. \end{tabular} \\
  1682. %
  1683. The following is another example translation, this time of a program
  1684. with a \key{let} nested inside the initializing expression of another
  1685. \key{let}.\\
  1686. \begin{tabular}{lll}
  1687. \begin{minipage}{0.4\textwidth}
  1688. \begin{lstlisting}
  1689. (let ([x (let ([x 4])
  1690. (+ x 1))])
  1691. (+ x 2))
  1692. \end{lstlisting}
  1693. \end{minipage}
  1694. &
  1695. $\Rightarrow$
  1696. &
  1697. \begin{minipage}{0.4\textwidth}
  1698. \begin{lstlisting}
  1699. (let ([x.2 (let ([x.1 4])
  1700. (+ x.1 1))])
  1701. (+ x.2 2))
  1702. \end{lstlisting}
  1703. \end{minipage}
  1704. \end{tabular}
  1705. We recommend implementing \code{uniquify} by creating a function named
  1706. \code{uniquify-exp} that is structurally recursive function and mostly
  1707. just copies the input program. However, when encountering a \key{let},
  1708. it should generate a unique name for the variable (the Racket function
  1709. \code{gensym} is handy for this) and associate the old name with the
  1710. new unique name in an alist. The \code{uniquify-exp}
  1711. function will need to access this alist when it gets to a
  1712. variable reference, so we add another parameter to \code{uniquify-exp}
  1713. for the alist.
  1714. The skeleton of the \code{uniquify-exp} function is shown in
  1715. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1716. convenient to partially apply it to a symbol table and then apply it
  1717. to different expressions, as in the last clause for primitive
  1718. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1719. form is useful for applying a function to each element of a list to produce
  1720. a new list.
  1721. \index{for/list}
  1722. \begin{exercise}
  1723. \normalfont % I don't like the italics for exercises. -Jeremy
  1724. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1725. implement the clauses for variables and for the \key{let} form.
  1726. \end{exercise}
  1727. \begin{figure}[tbp]
  1728. \begin{lstlisting}
  1729. (define (uniquify-exp symtab)
  1730. (lambda (e)
  1731. (match e
  1732. [(Var x) ___]
  1733. [(Int n) (Int n)]
  1734. [(Let x e body) ___]
  1735. [(Prim op es)
  1736. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1737. )))
  1738. (define (uniquify p)
  1739. (match p
  1740. [(Program '() e)
  1741. (Program '() ((uniquify-exp '()) e))]
  1742. )))
  1743. \end{lstlisting}
  1744. \caption{Skeleton for the \key{uniquify} pass.}
  1745. \label{fig:uniquify-s0}
  1746. \end{figure}
  1747. \begin{exercise}
  1748. \normalfont % I don't like the italics for exercises. -Jeremy
  1749. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1750. and checking whether the output programs produce the same result as
  1751. the input programs. The $R_1$ programs should be designed to test the
  1752. most interesting parts of the \key{uniquify} pass, that is, the
  1753. programs should include \key{let} forms, variables, and variables
  1754. that overshadow each other. The five programs should be in a
  1755. subdirectory named \key{tests} and they should have the same file name
  1756. except for a different integer at the end of the name, followed by the
  1757. ending \key{.rkt}. Use the \key{interp-tests} function
  1758. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1759. your \key{uniquify} pass on the example programs. See the
  1760. \key{run-tests.rkt} script in the student support code for an example
  1761. of how to use \key{interp-tests}.
  1762. \end{exercise}
  1763. \section{Remove Complex Operands}
  1764. \label{sec:remove-complex-opera-R1}
  1765. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1766. $R_1$ programs in which the arguments of operations are atomic
  1767. expressions. Put another way, this pass removes complex
  1768. operands\index{complex operand}, such as the expression \code{(- 10)}
  1769. in the program below. This is accomplished by introducing a new
  1770. \key{let}-bound variable, binding the complex operand to the new
  1771. variable, and then using the new variable in place of the complex
  1772. operand, as shown in the output of \code{remove-complex-opera*} on the
  1773. right.\\
  1774. \begin{tabular}{lll}
  1775. \begin{minipage}{0.4\textwidth}
  1776. % s0_19.rkt
  1777. \begin{lstlisting}
  1778. (+ 52 (- 10))
  1779. \end{lstlisting}
  1780. \end{minipage}
  1781. &
  1782. $\Rightarrow$
  1783. &
  1784. \begin{minipage}{0.4\textwidth}
  1785. \begin{lstlisting}
  1786. (let ([tmp.1 (- 10)])
  1787. (+ 52 tmp.1))
  1788. \end{lstlisting}
  1789. \end{minipage}
  1790. \end{tabular}
  1791. \begin{figure}[tp]
  1792. \centering
  1793. \fbox{
  1794. \begin{minipage}{0.96\textwidth}
  1795. \[
  1796. \begin{array}{rcl}
  1797. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1798. \Exp &::=& \Atm \mid \READ{} \\
  1799. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1800. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1801. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1802. \end{array}
  1803. \]
  1804. \end{minipage}
  1805. }
  1806. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1807. \label{fig:r1-anf-syntax}
  1808. \end{figure}
  1809. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1810. this pass, language $R_1^{\dagger}$. The main difference is that
  1811. operator arguments are required to be atomic expressions. In the
  1812. literature this is called \emph{administrative normal form}, or ANF
  1813. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1814. \index{administrative normal form}
  1815. \index{ANF}
  1816. We recommend implementing this pass with two mutually recursive
  1817. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1818. \code{rco-atom} to subexpressions that are required to be atomic and
  1819. to apply \code{rco-exp} to subexpressions that can be atomic or
  1820. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1821. $R_1$ expression as input. The \code{rco-exp} function returns an
  1822. expression. The \code{rco-atom} function returns two things: an
  1823. atomic expression and alist mapping temporary variables to complex
  1824. subexpressions. You can return multiple things from a function using
  1825. Racket's \key{values} form and you can receive multiple things from a
  1826. function call using the \key{define-values} form. If you are not
  1827. familiar with these features, review the Racket documentation. Also,
  1828. 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}}
  1829. form is useful for applying a function to each
  1830. element of a list, in the case where the function returns multiple
  1831. values.
  1832. \index{for/lists}
  1833. The following shows the output of \code{rco-atom} on the expression
  1834. \code{(- 10)} (using concrete syntax to be concise).
  1835. \begin{tabular}{lll}
  1836. \begin{minipage}{0.4\textwidth}
  1837. \begin{lstlisting}
  1838. (- 10)
  1839. \end{lstlisting}
  1840. \end{minipage}
  1841. &
  1842. $\Rightarrow$
  1843. &
  1844. \begin{minipage}{0.4\textwidth}
  1845. \begin{lstlisting}
  1846. tmp.1
  1847. ((tmp.1 . (- 10)))
  1848. \end{lstlisting}
  1849. \end{minipage}
  1850. \end{tabular}
  1851. Take special care of programs such as the next one that \key{let}-bind
  1852. variables with integers or other variables. You should leave them
  1853. unchanged, as shown in to the program on the right \\
  1854. \begin{tabular}{lll}
  1855. \begin{minipage}{0.4\textwidth}
  1856. % s0_20.rkt
  1857. \begin{lstlisting}
  1858. (let ([a 42])
  1859. (let ([b a])
  1860. b))
  1861. \end{lstlisting}
  1862. \end{minipage}
  1863. &
  1864. $\Rightarrow$
  1865. &
  1866. \begin{minipage}{0.4\textwidth}
  1867. \begin{lstlisting}
  1868. (let ([a 42])
  1869. (let ([b a])
  1870. b))
  1871. \end{lstlisting}
  1872. \end{minipage}
  1873. \end{tabular} \\
  1874. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1875. produce the following output.\\
  1876. \begin{minipage}{0.4\textwidth}
  1877. \begin{lstlisting}
  1878. (let ([tmp.1 42])
  1879. (let ([a tmp.1])
  1880. (let ([tmp.2 a])
  1881. (let ([b tmp.2])
  1882. b))))
  1883. \end{lstlisting}
  1884. \end{minipage}
  1885. \begin{exercise}
  1886. \normalfont Implement the \code{remove-complex-opera*} pass.
  1887. Test the new pass on all of the example programs that you created to test the
  1888. \key{uniquify} pass and create three new example programs that are
  1889. designed to exercise the interesting code in the
  1890. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1891. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1892. your passes on the example programs.
  1893. \end{exercise}
  1894. \section{Explicate Control}
  1895. \label{sec:explicate-control-r1}
  1896. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1897. programs that make the order of execution explicit in their
  1898. syntax. For now this amounts to flattening \key{let} constructs into a
  1899. sequence of assignment statements. For example, consider the following
  1900. $R_1$ program.\\
  1901. % s0_11.rkt
  1902. \begin{minipage}{0.96\textwidth}
  1903. \begin{lstlisting}
  1904. (let ([y (let ([x 20])
  1905. (+ x (let ([x 22]) x)))])
  1906. y)
  1907. \end{lstlisting}
  1908. \end{minipage}\\
  1909. %
  1910. The output of the previous pass and of \code{explicate-control} is
  1911. shown below. Recall that the right-hand-side of a \key{let} executes
  1912. before its body, so the order of evaluation for this program is to
  1913. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1914. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1915. output of \code{explicate-control} makes this ordering explicit.\\
  1916. \begin{tabular}{lll}
  1917. \begin{minipage}{0.4\textwidth}
  1918. \begin{lstlisting}
  1919. (let ([y (let ([x.1 20])
  1920. (let ([x.2 22])
  1921. (+ x.1 x.2)))])
  1922. y)
  1923. \end{lstlisting}
  1924. \end{minipage}
  1925. &
  1926. $\Rightarrow$
  1927. &
  1928. \begin{minipage}{0.4\textwidth}
  1929. \begin{lstlisting}
  1930. locals: y x.1 x.2
  1931. start:
  1932. x.1 = 20;
  1933. x.2 = 22;
  1934. y = (+ x.1 x.2);
  1935. return y;
  1936. \end{lstlisting}
  1937. \end{minipage}
  1938. \end{tabular}
  1939. We recommend implementing \code{explicate-control} using two mutually
  1940. recursive functions: \code{explicate-tail} and
  1941. \code{explicate-assign}. The first function should be applied to
  1942. expressions in tail position whereas the second should be applied to
  1943. expressions that occur on the right-hand-side of a \key{let}.
  1944. %
  1945. The \code{explicate-tail} function takes an $R_1$ expression as input
  1946. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1947. list of formerly \key{let}-bound variables.
  1948. %
  1949. The \code{explicate-assign} function takes an $R_1$ expression, the
  1950. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1951. should come after the assignment (e.g., the code generated for the
  1952. body of the \key{let}). It returns a $\Tail$ and a list of
  1953. variables. The \code{explicate-assign} function is in
  1954. accumulator-passing style in that its third parameter is some $C_0$
  1955. code which it then adds to and returns. The reader might be tempted to
  1956. instead organize \code{explicate-assign} in a more direct fashion,
  1957. without the third parameter and perhaps using \code{append} to combine
  1958. statements. We warn against that alternative because the
  1959. accumulator-passing style is key to how we generate high-quality code
  1960. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1961. The top-level \code{explicate-control} function should invoke
  1962. \code{explicate-tail} on the body of the \key{program} and then
  1963. associate the \code{locals} symbol with the resulting list of
  1964. variables in the $\itm{info}$ field, as in the above example.
  1965. \section{Select Instructions}
  1966. \label{sec:select-r1}
  1967. \index{instruction selection}
  1968. In the \code{select-instructions} pass we begin the work of
  1969. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1970. this pass is a variant of x86 that still uses variables, so we add an
  1971. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1972. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1973. \code{select-instructions} in terms of three auxiliary functions, one
  1974. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1975. The cases for $\Atm$ are straightforward, variables stay
  1976. the same and integer constants are changed to immediates:
  1977. $\INT{n}$ changes to $\IMM{n}$.
  1978. Next we consider the cases for $\Stmt$, starting with arithmetic
  1979. operations. For example, in $C_0$ an addition operation can take the
  1980. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1981. need to use the \key{addq} instruction which does an in-place
  1982. update. So we must first move \code{10} to \code{x}. \\
  1983. \begin{tabular}{lll}
  1984. \begin{minipage}{0.4\textwidth}
  1985. \begin{lstlisting}
  1986. x = (+ 10 32);
  1987. \end{lstlisting}
  1988. \end{minipage}
  1989. &
  1990. $\Rightarrow$
  1991. &
  1992. \begin{minipage}{0.4\textwidth}
  1993. \begin{lstlisting}
  1994. movq $10, x
  1995. addq $32, x
  1996. \end{lstlisting}
  1997. \end{minipage}
  1998. \end{tabular} \\
  1999. %
  2000. There are cases that require special care to avoid generating
  2001. needlessly complicated code. If one of the arguments of the addition
  2002. is the same as the left-hand side of the assignment, then there is no
  2003. need for the extra move instruction. For example, the following
  2004. assignment statement can be translated into a single \key{addq}
  2005. instruction.\\
  2006. \begin{tabular}{lll}
  2007. \begin{minipage}{0.4\textwidth}
  2008. \begin{lstlisting}
  2009. x = (+ 10 x);
  2010. \end{lstlisting}
  2011. \end{minipage}
  2012. &
  2013. $\Rightarrow$
  2014. &
  2015. \begin{minipage}{0.4\textwidth}
  2016. \begin{lstlisting}
  2017. addq $10, x
  2018. \end{lstlisting}
  2019. \end{minipage}
  2020. \end{tabular} \\
  2021. The \key{read} operation does not have a direct counterpart in x86
  2022. assembly, so we have instead implemented this functionality in the C
  2023. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2024. in the file \code{runtime.c}. In general, we refer to all of the
  2025. functionality in this file as the \emph{runtime system}\index{runtime system},
  2026. or simply the \emph{runtime} for short. When compiling your generated x86
  2027. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2028. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2029. the executable. For our purposes of code generation, all you need to
  2030. do is translate an assignment of \key{read} into some variable
  2031. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2032. function followed by a move from \code{rax} to the left-hand side.
  2033. The move from \code{rax} is needed because the return value from
  2034. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2035. \begin{tabular}{lll}
  2036. \begin{minipage}{0.3\textwidth}
  2037. \begin{lstlisting}
  2038. |$\itm{var}$| = (read);
  2039. \end{lstlisting}
  2040. \end{minipage}
  2041. &
  2042. $\Rightarrow$
  2043. &
  2044. \begin{minipage}{0.3\textwidth}
  2045. \begin{lstlisting}
  2046. callq read_int
  2047. movq %rax, |$\itm{var}$|
  2048. \end{lstlisting}
  2049. \end{minipage}
  2050. \end{tabular} \\
  2051. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2052. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2053. assignment to the \key{rax} register followed by a jump to the
  2054. conclusion of the program (so the conclusion needs to be labeled).
  2055. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2056. recursively and append the resulting instructions.
  2057. \begin{exercise}
  2058. \normalfont
  2059. Implement the \key{select-instructions} pass and test it on all of the
  2060. example programs that you created for the previous passes and create
  2061. three new example programs that are designed to exercise all of the
  2062. interesting code in this pass. Use the \key{interp-tests} function
  2063. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2064. your passes on the example programs.
  2065. \end{exercise}
  2066. \section{Assign Homes}
  2067. \label{sec:assign-r1}
  2068. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2069. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2070. Thus, the \key{assign-homes} pass is responsible for placing all of
  2071. the program variables in registers or on the stack. For runtime
  2072. efficiency, it is better to place variables in registers, but as there
  2073. are only 16 registers, some programs must necessarily resort to
  2074. placing some variables on the stack. In this chapter we focus on the
  2075. mechanics of placing variables on the stack. We study an algorithm for
  2076. placing variables in registers in
  2077. Chapter~\ref{ch:register-allocation-r1}.
  2078. Consider again the following $R_1$ program.
  2079. % s0_20.rkt
  2080. \begin{lstlisting}
  2081. (let ([a 42])
  2082. (let ([b a])
  2083. b))
  2084. \end{lstlisting}
  2085. For reference, we repeat the output of \code{select-instructions} on
  2086. the left and show the output of \code{assign-homes} on the right.
  2087. Recall that \key{explicate-control} associated the list of
  2088. variables with the \code{locals} symbol in the program's $\itm{info}$
  2089. field, so \code{assign-homes} has convenient access to the them. In
  2090. this example, we assign variable \code{a} to stack location
  2091. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2092. \begin{tabular}{l}
  2093. \begin{minipage}{0.4\textwidth}
  2094. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2095. locals: a b
  2096. start:
  2097. movq $42, a
  2098. movq a, b
  2099. movq b, %rax
  2100. jmp conclusion
  2101. \end{lstlisting}
  2102. \end{minipage}
  2103. {$\Rightarrow$}
  2104. \begin{minipage}{0.4\textwidth}
  2105. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2106. stack-space: 16
  2107. start:
  2108. movq $42, -8(%rbp)
  2109. movq -8(%rbp), -16(%rbp)
  2110. movq -16(%rbp), %rax
  2111. jmp conclusion
  2112. \end{lstlisting}
  2113. \end{minipage}
  2114. \end{tabular} \\
  2115. In the process of assigning variables to stack locations, it is
  2116. convenient to compute and store the size of the frame (in bytes) in
  2117. the $\itm{info}$ field of the \key{Program} node, with the key
  2118. \code{stack-space}, which will be needed later to generate the
  2119. procedure conclusion. The x86-64 standard requires the frame size to
  2120. be a multiple of 16 bytes.
  2121. \index{frame}
  2122. \begin{exercise}
  2123. \normalfont Implement the \key{assign-homes} pass and test it on all
  2124. of the example programs that you created for the previous passes pass.
  2125. We recommend that \key{assign-homes} take an extra parameter that is a
  2126. mapping of variable names to homes (stack locations for now). Use the
  2127. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2128. \key{utilities.rkt} to test your passes on the example programs.
  2129. \end{exercise}
  2130. \section{Patch Instructions}
  2131. \label{sec:patch-s0}
  2132. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2133. programs to $\text{x86}_0$ programs by making sure that each
  2134. instruction adheres to the restrictions of the x86 assembly language.
  2135. In particular, at most one argument of an instruction may be a memory
  2136. reference.
  2137. We return to the following running example.
  2138. % s0_20.rkt
  2139. \begin{lstlisting}
  2140. (let ([a 42])
  2141. (let ([b a])
  2142. b))
  2143. \end{lstlisting}
  2144. After the \key{assign-homes} pass, the above program has been translated to
  2145. the following. \\
  2146. \begin{minipage}{0.5\textwidth}
  2147. \begin{lstlisting}
  2148. stack-space: 16
  2149. start:
  2150. movq $42, -8(%rbp)
  2151. movq -8(%rbp), -16(%rbp)
  2152. movq -16(%rbp), %rax
  2153. jmp conclusion
  2154. \end{lstlisting}
  2155. \end{minipage}\\
  2156. The second \key{movq} instruction is problematic because both
  2157. arguments are stack locations. We suggest fixing this problem by
  2158. moving from the source location to the register \key{rax} and then
  2159. from \key{rax} to the destination location, as follows.
  2160. \begin{lstlisting}
  2161. movq -8(%rbp), %rax
  2162. movq %rax, -16(%rbp)
  2163. \end{lstlisting}
  2164. \begin{exercise}
  2165. \normalfont
  2166. Implement the \key{patch-instructions} pass and test it on all of the
  2167. example programs that you created for the previous passes and create
  2168. three new example programs that are designed to exercise all of the
  2169. interesting code in this pass. Use the \key{interp-tests} function
  2170. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2171. your passes on the example programs.
  2172. \end{exercise}
  2173. \section{Print x86}
  2174. \label{sec:print-x86}
  2175. The last step of the compiler from $R_1$ to x86 is to convert the
  2176. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2177. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2178. \key{format} and \key{string-append} functions are useful in this
  2179. regard. The main work that this step needs to perform is to create the
  2180. \key{main} function and the standard instructions for its prelude and
  2181. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2182. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2183. variables, so we suggest computing it in the \key{assign-homes} pass
  2184. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2185. of the \key{program} node.
  2186. %% Your compiled code should print the result of the program's execution
  2187. %% by using the \code{print\_int} function provided in
  2188. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2189. %% far, this final result should be stored in the \key{rax} register.
  2190. %% We'll talk more about how to perform function calls with arguments in
  2191. %% general later on, but for now, place the following after the compiled
  2192. %% code for the $R_1$ program but before the conclusion:
  2193. %% \begin{lstlisting}
  2194. %% movq %rax, %rdi
  2195. %% callq print_int
  2196. %% \end{lstlisting}
  2197. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2198. %% stores the first argument to be passed into \key{print\_int}.
  2199. If you want your program to run on Mac OS X, your code needs to
  2200. determine whether or not it is running on a Mac, and prefix
  2201. underscores to labels like \key{main}. You can determine the platform
  2202. with the Racket call \code{(system-type 'os)}, which returns
  2203. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2204. %% In addition to
  2205. %% placing underscores on \key{main}, you need to put them in front of
  2206. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2207. %% \_print\_int}).
  2208. \begin{exercise}
  2209. \normalfont Implement the \key{print-x86} pass and test it on all of
  2210. the example programs that you created for the previous passes. Use the
  2211. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2212. \key{utilities.rkt} to test your complete compiler on the example
  2213. programs. See the \key{run-tests.rkt} script in the student support
  2214. code for an example of how to use \key{compiler-tests}. Also, remember
  2215. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2216. \key{gcc}.
  2217. \end{exercise}
  2218. \section{Challenge: Partial Evaluator for $R_1$}
  2219. \label{sec:pe-R1}
  2220. \index{partial evaluation}
  2221. This section describes optional challenge exercises that involve
  2222. adapting and improving the partial evaluator for $R_0$ that was
  2223. introduced in Section~\ref{sec:partial-evaluation}.
  2224. \begin{exercise}\label{ex:pe-R1}
  2225. \normalfont
  2226. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2227. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2228. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2229. and variables to the $R_0$ language, so you will need to add cases for
  2230. them in the \code{pe-exp} function. Also, note that the \key{program}
  2231. form changes slightly to include an $\itm{info}$ field. Once
  2232. complete, add the partial evaluation pass to the front of your
  2233. compiler and make sure that your compiler still passes all of the
  2234. tests.
  2235. \end{exercise}
  2236. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2237. \begin{exercise}
  2238. \normalfont
  2239. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2240. \code{pe-add} auxiliary functions with functions that know more about
  2241. arithmetic. For example, your partial evaluator should translate
  2242. \begin{lstlisting}
  2243. (+ 1 (+ (read) 1))
  2244. \end{lstlisting}
  2245. into
  2246. \begin{lstlisting}
  2247. (+ 2 (read))
  2248. \end{lstlisting}
  2249. To accomplish this, the \code{pe-exp} function should produce output
  2250. in the form of the $\itm{residual}$ non-terminal of the following
  2251. grammar.
  2252. \[
  2253. \begin{array}{lcl}
  2254. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2255. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2256. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2257. \end{array}
  2258. \]
  2259. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2260. that their inputs are $\itm{residual}$ expressions and they should
  2261. return $\itm{residual}$ expressions. Once the improvements are
  2262. complete, make sure that your compiler still passes all of the tests.
  2263. After all, fast code is useless if it produces incorrect results!
  2264. \end{exercise}
  2265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2266. \chapter{Register Allocation}
  2267. \label{ch:register-allocation-r1}
  2268. \index{register allocation}
  2269. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2270. make our life easier. However, we can improve the performance of the
  2271. generated code if we instead place some variables into registers. The
  2272. CPU can access a register in a single cycle, whereas accessing the
  2273. stack takes many cycles if the relevant data is in cache or many more
  2274. to access main memory if the data is not in cache.
  2275. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2276. serves as a running example. We show the source program and also the
  2277. output of instruction selection. At that point the program is almost
  2278. x86 assembly but not quite; it still contains variables instead of
  2279. stack locations or registers.
  2280. \begin{figure}
  2281. \begin{minipage}{0.45\textwidth}
  2282. Example $R_1$ program:
  2283. % s0_28.rkt
  2284. \begin{lstlisting}
  2285. (let ([v 1])
  2286. (let ([w 42])
  2287. (let ([x (+ v 7)])
  2288. (let ([y x])
  2289. (let ([z (+ x w)])
  2290. (+ z (- y)))))))
  2291. \end{lstlisting}
  2292. \end{minipage}
  2293. \begin{minipage}{0.45\textwidth}
  2294. After instruction selection:
  2295. \begin{lstlisting}
  2296. locals: (v w x y z t)
  2297. start:
  2298. movq $1, v
  2299. movq $42, w
  2300. movq v, x
  2301. addq $7, x
  2302. movq x, y
  2303. movq x, z
  2304. addq w, z
  2305. movq y, t
  2306. negq t
  2307. movq z, %rax
  2308. addq t, %rax
  2309. jmp conclusion
  2310. \end{lstlisting}
  2311. \end{minipage}
  2312. \caption{An example program for register allocation.}
  2313. \label{fig:reg-eg}
  2314. \end{figure}
  2315. The goal of register allocation is to fit as many variables into
  2316. registers as possible. A program sometimes has more variables than
  2317. registers, so we cannot map each variable to a different
  2318. register. Fortunately, it is common for different variables to be
  2319. needed during different periods of time during program execution, and
  2320. in such cases several variables can be mapped to the same register.
  2321. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2322. After the variable \code{x} is moved to \code{z} it is no longer
  2323. needed. Variable \code{y}, on the other hand, is used only after this
  2324. point, so \code{x} and \code{y} could share the same register. The
  2325. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2326. where a variable is needed. Once we have that information, we compute
  2327. which variables are needed at the same time, i.e., which ones
  2328. \emph{interfere} with each other, and represent this relation as an
  2329. undirected graph whose vertices are variables and edges indicate when
  2330. two variables interfere (Section~\ref{sec:build-interference}). We
  2331. then model register allocation as a graph coloring problem, which we
  2332. discuss in Section~\ref{sec:graph-coloring}.
  2333. In the event that we run out of registers despite these efforts, we
  2334. place the remaining variables on the stack, similar to what we did in
  2335. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2336. for assigning a variable to a stack location. The process of spilling
  2337. variables is handled as part of the graph coloring process described
  2338. in \ref{sec:graph-coloring}.
  2339. We make the simplifying assumption that each variable is assigned to
  2340. one location (a register or stack address). A more sophisticated
  2341. approach is to assign a variable to one or more locations in different
  2342. regions of the program. For example, if a variable is used many times
  2343. in short sequence and then only used again after many other
  2344. instructions, it could be more efficient to assign the variable to a
  2345. register during the intial sequence and then move it to the stack for
  2346. the rest of its lifetime. We refer the interested reader to
  2347. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2348. about this approach.
  2349. % discuss prioritizing variables based on how much they are used.
  2350. \section{Registers and Calling Conventions}
  2351. \label{sec:calling-conventions}
  2352. \index{calling conventions}
  2353. As we perform register allocation, we need to be aware of the
  2354. conventions that govern the way in which registers interact with
  2355. function calls, such as calls to the \code{read\_int} function in our
  2356. generated code and even the call that the operating system makes to
  2357. execute our \code{main} function. The convention for x86 is that the
  2358. caller is responsible for freeing up some registers, the
  2359. \emph{caller-saved registers}, prior to the function call, and the
  2360. callee is responsible for preserving the values in some other
  2361. registers, the \emph{callee-saved registers}.
  2362. \index{caller-saved registers}
  2363. \index{callee-saved registers}
  2364. The caller-saved registers are
  2365. \begin{lstlisting}
  2366. rax rcx rdx rsi rdi r8 r9 r10 r11
  2367. \end{lstlisting}
  2368. while the callee-saved registers are
  2369. \begin{lstlisting}
  2370. rsp rbp rbx r12 r13 r14 r15
  2371. \end{lstlisting}
  2372. We can think about this caller/callee convention from two points of
  2373. view, the caller view and the callee view:
  2374. \begin{itemize}
  2375. \item The caller should assume that all the caller-saved registers get
  2376. overwritten with arbitrary values by the callee. On the other hand,
  2377. the caller can safely assume that all the callee-saved registers
  2378. contain the same values after the call that they did before the
  2379. call.
  2380. \item The callee can freely use any of the caller-saved registers.
  2381. However, if the callee wants to use a callee-saved register, the
  2382. callee must arrange to put the original value back in the register
  2383. prior to returning to the caller, which is usually accomplished by
  2384. saving the value to the stack in the prelude of the function and
  2385. restoring the value in the conclusion of the function.
  2386. \end{itemize}
  2387. The next question is how these calling conventions impact register
  2388. allocation. Consider the $R_1$ program in
  2389. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2390. example from the caller point of view and then from the callee point
  2391. of view.
  2392. The program makes two calls to the \code{read} function. Also, the
  2393. variable \code{x} is in-use during the second call to \code{read}, so
  2394. we need to make sure that the value in \code{x} does not get
  2395. accidentally wiped out by the call to \code{read}. One obvious
  2396. approach is to save all the values in caller-saved registers to the
  2397. stack prior to each function call, and restore them after each
  2398. call. That way, if the register allocator chooses to assign \code{x}
  2399. to a caller-saved register, its value will be preserved accross the
  2400. call to \code{read}. However, the disadvantage of this approach is
  2401. that saving and restoring to the stack is relatively slow. If \code{x}
  2402. is not used many times, it may be better to assign \code{x} to a stack
  2403. location in the first place. Or better yet, if we can arrange for
  2404. \code{x} to be placed in a callee-saved register, then it won't need
  2405. to be saved and restored during function calls.
  2406. The approach that we recommend is to treat variables differently
  2407. depending on whether they are in-use during a function call. If a
  2408. variable is in-use during a function call, then we never assign it to
  2409. a caller-saved register: we either assign it to a callee-saved
  2410. register or we spill it to the stack. If a variable is not in-use
  2411. during any function call, then we try the following alternatives in
  2412. order 1) look for an available caller-saved register (to leave room
  2413. for other variables in the callee-saved register), 2) look for a
  2414. callee-saved register, and 3) spill the variable to the stack.
  2415. It is straightforward to implement this approach in a graph coloring
  2416. register allocator. First, we know which variables are in-use during
  2417. every function call because we compute that information for every
  2418. instruciton (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2419. build the interference graph (Section~\ref{sec:build-interference}),
  2420. we can place an edge between each of these variables and the
  2421. caller-saved registers in the interference graph. This will prevent
  2422. the graph coloring algorithm from assigning those variables to
  2423. caller-saved registers.
  2424. Returning to the example in
  2425. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2426. generated x86 code on the right-hand side, focusing on the
  2427. \code{start} block. Notice that variable \code{x} is assigned to
  2428. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2429. place during the second call to \code{read\_int}. Next, notice that
  2430. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2431. because there are no function calls in the remainder of the block.
  2432. Next we analyze the example from the callee point of view, focusing on
  2433. the prelude and conclusion of the \code{main} function. As usual the
  2434. prelude begins with saving the \code{rbp} register to the stack and
  2435. setting the \code{rbp} to the current stack pointer. We now know why
  2436. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2437. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2438. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2439. variable (\code{x}). There are several more callee-saved register that
  2440. are not saved in the prelude because they were not assigned to
  2441. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2442. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2443. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2444. from the stack with a \code{popq} instruction.
  2445. \index{prelude}\index{conclusion}
  2446. \begin{figure}[tp]
  2447. \begin{minipage}{0.45\textwidth}
  2448. Example $R_1$ program:
  2449. %s0_14.rkt
  2450. \begin{lstlisting}
  2451. (let ([x (read)])
  2452. (let ([y (read)])
  2453. (+ (+ x y) 42)))
  2454. \end{lstlisting}
  2455. \end{minipage}
  2456. \begin{minipage}{0.45\textwidth}
  2457. Generated x86 assembly:
  2458. \begin{lstlisting}
  2459. start:
  2460. callq read_int
  2461. movq %rax, %rbx
  2462. callq read_int
  2463. movq %rax, %rcx
  2464. addq %rcx, %rbx
  2465. movq %rbx, %rax
  2466. addq $42, %rax
  2467. jmp _conclusion
  2468. .globl main
  2469. main:
  2470. pushq %rbp
  2471. movq %rsp, %rbp
  2472. pushq %rbx
  2473. subq $8, %rsp
  2474. jmp start
  2475. conclusion:
  2476. addq $8, %rsp
  2477. popq %rbx
  2478. popq %rbp
  2479. retq
  2480. \end{lstlisting}
  2481. \end{minipage}
  2482. \caption{An example with function calls.}
  2483. \label{fig:example-calling-conventions}
  2484. \end{figure}
  2485. \section{Liveness Analysis}
  2486. \label{sec:liveness-analysis-r1}
  2487. \index{liveness analysis}
  2488. A variable is \emph{live} if the variable is used at some later point
  2489. in the program and there is not an intervening assignment to the
  2490. variable.
  2491. %
  2492. To understand the latter condition, consider the following code
  2493. fragment in which there are two writes to \code{b}. Are \code{a} and
  2494. \code{b} both live at the same time?
  2495. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2496. movq $5, a
  2497. movq $30, b
  2498. movq a, c
  2499. movq $10, b
  2500. addq b, c
  2501. \end{lstlisting}
  2502. The answer is no because the integer \code{30} written to \code{b} on
  2503. line 2 is never used. The variable \code{b} is read on line 5 and
  2504. there is an intervening write to \code{b} on line 4, so the read on
  2505. line 5 receives the value written on line 4, not line 2.
  2506. \begin{wrapfigure}[20]{l}[1.0in]{0.6\textwidth}
  2507. \small
  2508. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2509. A \emph{set} is an unordered collection of elements without duplicates.
  2510. \index{set}
  2511. \begin{description}
  2512. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2513. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2514. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2515. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2516. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2517. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2518. \end{description}
  2519. \end{tcolorbox}
  2520. \end{wrapfigure}
  2521. The live variables can be computed by traversing the instruction
  2522. sequence back to front (i.e., backwards in execution order). Let
  2523. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2524. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2525. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2526. variables before instruction $I_k$. The live variables after an
  2527. instruction are always the same as the live variables before the next
  2528. instruction.
  2529. \index{live-after}
  2530. \index{live-before}
  2531. \begin{equation} \label{eq:live-after-before-next}
  2532. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2533. \end{equation}
  2534. To start things off, there are no live variables after the last
  2535. instruction, so
  2536. \begin{equation}\label{eq:live-last-empty}
  2537. L_{\mathsf{after}}(n) = \emptyset
  2538. \end{equation}
  2539. We then apply the following rule repeatedly, traversing the
  2540. instruction sequence back to front.
  2541. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2542. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2543. \end{equation}
  2544. where $W(k)$ are the variables written to by instruction $I_k$ and
  2545. $R(k)$ are the variables read by instruction $I_k$.
  2546. Let us walk through the above example, applying these formulas
  2547. starting with the instruction on line 5. We collect the answers in the
  2548. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2549. instruction is $\emptyset$ because it is the last instruction
  2550. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2551. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2552. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2553. is
  2554. \[
  2555. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2556. \]
  2557. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2558. the live-before set from line 5 to be the live-after set for this
  2559. instruction (formula~\ref{eq:live-after-before-next}).
  2560. \[
  2561. L_{\mathsf{after}}(4) = \{ b, c \}
  2562. \]
  2563. This move instruction writes to $b$ and does not read from any
  2564. variables, so we have the following live-before set
  2565. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2566. \[
  2567. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2568. \]
  2569. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2570. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2571. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2572. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2573. variable that is not live and does not read from a variable.
  2574. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2575. because it writes to variable $a$.
  2576. \begin{center}
  2577. \begin{minipage}{0.45\textwidth}
  2578. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2579. movq $5, a
  2580. movq $30, b
  2581. movq a, c
  2582. movq $10, b
  2583. addq b, c
  2584. \end{lstlisting}
  2585. \end{minipage}
  2586. \vrule\hspace{10pt}
  2587. \begin{minipage}{0.45\textwidth}
  2588. \begin{align*}
  2589. L_{\mathsf{before}}(1)= \emptyset,
  2590. L_{\mathsf{after}}(1)= \{a\}\\
  2591. L_{\mathsf{before}}(2)= \{a\},
  2592. L_{\mathsf{after}}(2)= \{a\}\\
  2593. L_{\mathsf{before}}(3)= \{a\},
  2594. L_{\mathsf{after}}(2)= \{c\}\\
  2595. L_{\mathsf{before}}(4)= \{c\},
  2596. L_{\mathsf{after}}(4)= \{b,c\}\\
  2597. L_{\mathsf{before}}(5)= \{b,c\},
  2598. L_{\mathsf{after}}(5)= \emptyset
  2599. \end{align*}
  2600. \end{minipage}
  2601. \end{center}
  2602. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2603. for the running example program, with the live-before and live-after
  2604. sets shown between each instruction to make the figure easy to read.
  2605. \begin{figure}[tp]
  2606. \hspace{20pt}
  2607. \begin{minipage}{0.45\textwidth}
  2608. \begin{lstlisting}
  2609. |$\{\}$|
  2610. movq $1, v
  2611. |$\{v\}$|
  2612. movq $42, w
  2613. |$\{v,w\}$|
  2614. movq v, x
  2615. |$\{w,x\}$|
  2616. addq $7, x
  2617. |$\{w,x\}$|
  2618. movq x, y
  2619. |$\{w,x,y\}$|
  2620. movq x, z
  2621. |$\{w,y,z\}$|
  2622. addq w, z
  2623. |$\{y,z\}$|
  2624. movq y, t
  2625. |$\{t,z\}$|
  2626. negq t
  2627. |$\{t,z\}$|
  2628. movq z, %rax
  2629. |$\{t\}$|
  2630. addq t, %rax
  2631. |$\{\}$|
  2632. jmp conclusion
  2633. |$\{\}$|
  2634. \end{lstlisting}
  2635. \end{minipage}
  2636. \caption{The running example annotated with live-after sets.}
  2637. \label{fig:live-eg}
  2638. \end{figure}
  2639. \begin{exercise}\normalfont
  2640. Implement the compiler pass named \code{uncover-live} that computes
  2641. the live-after sets. We recommend storing the live-after sets (a list
  2642. of a set of variables) in the $\itm{info}$ field of the \key{Block}
  2643. structure. We recommend using the
  2644. \href{https://docs.racket-lang.org/reference/sets.html}{\code{racket/set}}
  2645. package for representing sets of variables.
  2646. %
  2647. We recommend organizing your code to use a helper function that takes
  2648. a list of instructions and an initial live-after set (typically empty)
  2649. and returns the list of live-after sets.
  2650. %
  2651. We recommend creating helper functions to 1) compute the set of
  2652. variables that appear in an argument (of an instruction), 2) compute
  2653. the variables read by an instruction which corresponds to the $R$
  2654. function discussed above, and 3) the variables written by an
  2655. instruction which corresponds to $W$.
  2656. \end{exercise}
  2657. \section{Building the Interference Graph}
  2658. \label{sec:build-interference}
  2659. Based on the liveness analysis, we know where each variable is needed.
  2660. However, during register allocation, we need to answer questions of
  2661. the specific form: are variables $u$ and $v$ live at the same time?
  2662. (And therefore cannot be assigned to the same register.) To make this
  2663. question easier to answer, we create an explicit data structure, an
  2664. \emph{interference graph}\index{interference graph}. An interference
  2665. graph is an undirected graph that has an edge between two variables if
  2666. they are live at the same time, that is, if they interfere with each
  2667. other.
  2668. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2669. \small
  2670. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2671. A \emph{graph} is a collection of vertices and edges where each
  2672. edge connects two vertices. A graph is \emph{directed} if each
  2673. edge points from a source to a target. Otherwise the graph is
  2674. \emph{undirected}.
  2675. \index{graph}\index{directed graph}\index{undirected graph}
  2676. \begin{description}
  2677. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2678. directed graph from a list of edges. Each edge is a list
  2679. containing the source and target vertex.
  2680. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2681. undirected graph from a list of edges. Each edge is represented by
  2682. a list containing two vertices.
  2683. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2684. inserts a vertex into the graph.
  2685. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2686. inserts an edge between the two vertices into the graph.
  2687. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2688. returns a sequence of all the neighbors of the given vertex.
  2689. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2690. returns a sequence of all the vertices in the graph.
  2691. \end{description}
  2692. \end{tcolorbox}
  2693. \end{wrapfigure}
  2694. The most obvious way to compute the interference graph is to look at
  2695. the set of live variables between each statement in the program and
  2696. add an edge to the graph for every pair of variables in the same set.
  2697. This approach is less than ideal for two reasons. First, it can be
  2698. expensive because it takes $O(n^2)$ time to look at every pair in a
  2699. set of $n$ live variables. Second, there is a special case in which
  2700. two variables that are live at the same time do not actually interfere
  2701. with each other: when they both contain the same value because we have
  2702. assigned one to the other.
  2703. A better way to compute the interference graph is to focus on the
  2704. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2705. instruction to overwrite something in a live variable. So for each
  2706. instruction, we create an edge between the variable being written to
  2707. and all the \emph{other} live variables. (One should not create self
  2708. edges.) For a \key{callq} instruction, think of all caller-saved
  2709. registers as being written to, so an edge must be added between every
  2710. live variable and every caller-saved register. For \key{movq}, we deal
  2711. with the above-mentioned special case by not adding an edge between a
  2712. live variable $v$ and destination $d$ if $v$ matches the source of the
  2713. move. So we have the following three rules.
  2714. \begin{enumerate}
  2715. \item If instruction $I_k$ is an arithmetic instruction such as
  2716. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2717. L_{\mathsf{after}}(k)$ unless $v = d$.
  2718. \item If instruction $I_k$ is of the form \key{callq}
  2719. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2720. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2721. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2722. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2723. d$ or $v = s$.
  2724. \end{enumerate}
  2725. Working from the top to bottom of Figure~\ref{fig:live-eg}, apply the
  2726. above rules to each instruction. We highlight a few of the
  2727. instructions and then refer the reader to
  2728. Figure~\ref{fig:interference-results} all the interference results.
  2729. The first instruction is \lstinline{movq $1, v}, so rule 3 applies,
  2730. and the live-after set is $\{v\}$. We do not add any interference
  2731. edges because the one live variable $v$ is also the destination of
  2732. this instruction.
  2733. %
  2734. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2735. again, and the live-after set is $\{v,w\}$. So the target $w$ of
  2736. \key{movq} interferes with $v$.
  2737. %
  2738. Next we skip forward to the instruction \lstinline{movq x, y}.
  2739. \begin{figure}[tbp]
  2740. \begin{quote}
  2741. \begin{tabular}{ll}
  2742. \lstinline{movq $1, v}& no interference by rule 3,\\
  2743. \lstinline{movq $42, w}& $w$ interferes with $v$ by rule 3,\\
  2744. \lstinline{movq v, x}& $x$ interferes with $w$ by rule 3,\\
  2745. \lstinline{addq $7, x}& $x$ interferes with $w$ by rule 1,\\
  2746. \lstinline{movq x, y}& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2747. \lstinline{movq x, z}& $z$ interferes with $w$ and $y$ by rule 3,\\
  2748. \lstinline{addq w, z}& $z$ interferes with $y$ by rule 1, \\
  2749. \lstinline{movq y, t}& $t$ interferes with $z$ by rule 3, \\
  2750. \lstinline{negq t}& $t$ interferes with $z$ by rule 1, \\
  2751. \lstinline{movq z, %rax} & no interference (ignore rax), \\
  2752. \lstinline{addq t, %rax} & no interference (ignore rax). \\
  2753. \lstinline{jmp conclusion}& no interference.
  2754. \end{tabular}
  2755. \end{quote}
  2756. \caption{Interference results for the running example.}
  2757. \label{fig:interference-results}
  2758. \end{figure}
  2759. The resulting interference graph is shown in
  2760. Figure~\ref{fig:interfere}.
  2761. \begin{figure}[tbp]
  2762. \large
  2763. \[
  2764. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2765. \node (t1) at (0,2) {$t$};
  2766. \node (z) at (3,2) {$z$};
  2767. \node (x) at (6,2) {$x$};
  2768. \node (y) at (3,0) {$y$};
  2769. \node (w) at (6,0) {$w$};
  2770. \node (v) at (9,0) {$v$};
  2771. \draw (t1) to (z);
  2772. \draw (z) to (y);
  2773. \draw (z) to (w);
  2774. \draw (x) to (w);
  2775. \draw (y) to (w);
  2776. \draw (v) to (w);
  2777. \end{tikzpicture}
  2778. \]
  2779. \caption{The interference graph of the example program.}
  2780. \label{fig:interfere}
  2781. \end{figure}
  2782. %% Our next concern is to choose a data structure for representing the
  2783. %% interference graph. There are many choices for how to represent a
  2784. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2785. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2786. %% data structure is to study the algorithm that uses the data structure,
  2787. %% determine what operations need to be performed, and then choose the
  2788. %% data structure that provide the most efficient implementations of
  2789. %% those operations. Often times the choice of data structure can have an
  2790. %% effect on the time complexity of the algorithm, as it does here. If
  2791. %% you skim the next section, you will see that the register allocation
  2792. %% algorithm needs to ask the graph for all of its vertices and, given a
  2793. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2794. %% correct choice of graph representation is that of an adjacency
  2795. %% list. There are helper functions in \code{utilities.rkt} for
  2796. %% representing graphs using the adjacency list representation:
  2797. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2798. %% (Appendix~\ref{appendix:utilities}).
  2799. %% %
  2800. %% \margincomment{\footnotesize To do: change to use the
  2801. %% Racket graph library. \\ --Jeremy}
  2802. %% %
  2803. %% In particular, those functions use a hash table to map each vertex to
  2804. %% the set of adjacent vertices, and the sets are represented using
  2805. %% Racket's \key{set}, which is also a hash table.
  2806. \begin{exercise}\normalfont
  2807. Implement the compiler pass named \code{build-interference} according
  2808. to the algorithm suggested above. We recommend using the \code{graph}
  2809. package to create and inspect the interference graph. The output
  2810. graph of this pass should be stored in the $\itm{info}$ field of the
  2811. program, under the key \code{conflicts}.
  2812. \end{exercise}
  2813. \section{Graph Coloring via Sudoku}
  2814. \label{sec:graph-coloring}
  2815. \index{graph coloring}
  2816. \index{Sudoku}
  2817. \index{color}
  2818. We come to the main event, mapping variables to registers (or to stack
  2819. locations in the event that we run out of registers). We need to make
  2820. sure that two variables do not get mapped to the same register if the
  2821. two variables interfere with each other. Thinking about the
  2822. interference graph, this means that adjacent vertices must be mapped
  2823. to different registers. If we think of registers as colors, the
  2824. register allocation problem becomes the widely-studied graph coloring
  2825. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2826. The reader may be more familiar with the graph coloring problem than he
  2827. or she realizes; the popular game of Sudoku is an instance of the
  2828. graph coloring problem. The following describes how to build a graph
  2829. out of an initial Sudoku board.
  2830. \begin{itemize}
  2831. \item There is one vertex in the graph for each Sudoku square.
  2832. \item There is an edge between two vertices if the corresponding squares
  2833. are in the same row, in the same column, or if the squares are in
  2834. the same $3\times 3$ region.
  2835. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2836. \item Based on the initial assignment of numbers to squares in the
  2837. Sudoku board, assign the corresponding colors to the corresponding
  2838. vertices in the graph.
  2839. \end{itemize}
  2840. If you can color the remaining vertices in the graph with the nine
  2841. colors, then you have also solved the corresponding game of Sudoku.
  2842. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2843. the corresponding graph with colored vertices. We map the Sudoku
  2844. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2845. sampling of the vertices (the colored ones) because showing edges for
  2846. all of the vertices would make the graph unreadable.
  2847. \begin{figure}[tbp]
  2848. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2849. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2850. \caption{A Sudoku game board and the corresponding colored graph.}
  2851. \label{fig:sudoku-graph}
  2852. \end{figure}
  2853. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2854. strategies to come up with an algorithm for allocating registers. For
  2855. example, one of the basic techniques for Sudoku is called Pencil
  2856. Marks. The idea is to use a process of elimination to determine what
  2857. numbers no longer make sense for a square and write down those
  2858. numbers in the square (writing very small). For example, if the number
  2859. $1$ is assigned to a square, then by process of elimination, you can
  2860. write the pencil mark $1$ in all the squares in the same row, column,
  2861. and region. Many Sudoku computer games provide automatic support for
  2862. Pencil Marks.
  2863. %
  2864. The Pencil Marks technique corresponds to the notion of
  2865. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2866. The saturation of a
  2867. vertex, in Sudoku terms, is the set of numbers that are no longer
  2868. available. In graph terminology, we have the following definition:
  2869. \begin{equation*}
  2870. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2871. \text{ and } \mathrm{color}(v) = c \}
  2872. \end{equation*}
  2873. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2874. edge with $u$.
  2875. Using the Pencil Marks technique leads to a simple strategy for
  2876. filling in numbers: if there is a square with only one possible number
  2877. left, then choose that number! But what if there are no squares with
  2878. only one possibility left? One brute-force approach is to try them
  2879. all: choose the first and if it ultimately leads to a solution,
  2880. great. If not, backtrack and choose the next possibility. One good
  2881. thing about Pencil Marks is that it reduces the degree of branching in
  2882. the search tree. Nevertheless, backtracking can be horribly time
  2883. consuming. One way to reduce the amount of backtracking is to use the
  2884. most-constrained-first heuristic. That is, when choosing a square,
  2885. always choose one with the fewest possibilities left (the vertex with
  2886. the highest saturation). The idea is that choosing highly constrained
  2887. squares earlier rather than later is better because later on there may
  2888. not be any possibilities left for those squares.
  2889. However, register allocation is easier than Sudoku because the
  2890. register allocator can map variables to stack locations when the
  2891. registers run out. Thus, it makes sense to drop backtracking in favor
  2892. of greedy search, that is, make the best choice at the time and keep
  2893. going. We still wish to minimize the number of colors needed, so
  2894. keeping the most-constrained-first heuristic is a good idea.
  2895. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2896. algorithm for register allocation based on saturation and the
  2897. most-constrained-first heuristic. It is roughly equivalent to the
  2898. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2899. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2900. Sudoku, the algorithm represents colors with integers. The first $k$
  2901. colors corresponding to the $k$ registers in a given machine and the
  2902. rest of the integers corresponding to stack locations.
  2903. \begin{figure}[btp]
  2904. \centering
  2905. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2906. Algorithm: DSATUR
  2907. Input: a graph |$G$|
  2908. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2909. |$W \gets \mathit{vertices}(G)$|
  2910. while |$W \neq \emptyset$| do
  2911. pick a vertex |$u$| from |$W$| with the highest saturation,
  2912. breaking ties randomly
  2913. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2914. |$\mathrm{color}[u] \gets c$|
  2915. |$W \gets W - \{u\}$|
  2916. \end{lstlisting}
  2917. \caption{The saturation-based greedy graph coloring algorithm.}
  2918. \label{fig:satur-algo}
  2919. \end{figure}
  2920. With this algorithm in hand, let us return to the running example and
  2921. consider how to color the interference graph in
  2922. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2923. colored and they are unsaturated, so we annotate each of them with a
  2924. dash for their color and an empty set for the saturation.
  2925. \[
  2926. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2927. \node (t1) at (0,2) {$t:-,\{\}$};
  2928. \node (z) at (3,2) {$z:-,\{\}$};
  2929. \node (x) at (6,2) {$x:-,\{\}$};
  2930. \node (y) at (3,0) {$y:-,\{\}$};
  2931. \node (w) at (6,0) {$w:-,\{\}$};
  2932. \node (v) at (9,0) {$v:-,\{\}$};
  2933. \draw (t1) to (z);
  2934. \draw (z) to (y);
  2935. \draw (z) to (w);
  2936. \draw (x) to (w);
  2937. \draw (y) to (w);
  2938. \draw (v) to (w);
  2939. \end{tikzpicture}
  2940. \]
  2941. The algorithm says to select a maximally saturated vertex and color it
  2942. $0$. In this case we have a 6-way tie, so we arbitrarily pick
  2943. $t$. We then mark color $0$ as no longer available for $z$ because
  2944. it interferes with $t$.
  2945. \[
  2946. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2947. \node (t1) at (0,2) {$t:0,\{\}$};
  2948. \node (z) at (3,2) {$z:-,\{0\}$};
  2949. \node (x) at (6,2) {$x:-,\{\}$};
  2950. \node (y) at (3,0) {$y:-,\{\}$};
  2951. \node (w) at (6,0) {$w:-,\{\}$};
  2952. \node (v) at (9,0) {$v:-,\{\}$};
  2953. \draw (t1) to (z);
  2954. \draw (z) to (y);
  2955. \draw (z) to (w);
  2956. \draw (x) to (w);
  2957. \draw (y) to (w);
  2958. \draw (v) to (w);
  2959. \end{tikzpicture}
  2960. \]
  2961. Next we repeat the process, selecting another maximally saturated
  2962. vertex, which is $z$, and color it with the first available number,
  2963. which is $1$.
  2964. \[
  2965. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2966. \node (t1) at (0,2) {$t:0,\{1\}$};
  2967. \node (z) at (3,2) {$z:1,\{0\}$};
  2968. \node (x) at (6,2) {$x:-,\{\}$};
  2969. \node (y) at (3,0) {$y:-,\{1\}$};
  2970. \node (w) at (6,0) {$w:-,\{1\}$};
  2971. \node (v) at (9,0) {$v:-,\{\}$};
  2972. \draw (t1) to (z);
  2973. \draw (z) to (y);
  2974. \draw (z) to (w);
  2975. \draw (x) to (w);
  2976. \draw (y) to (w);
  2977. \draw (v) to (w);
  2978. \end{tikzpicture}
  2979. \]
  2980. The most saturated vertices are now $w$ and $y$. We color $w$ with the
  2981. first available color, which is $0$.
  2982. \[
  2983. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2984. \node (t1) at (0,2) {$t:0,\{1\}$};
  2985. \node (z) at (3,2) {$z:1,\{0\}$};
  2986. \node (x) at (6,2) {$x:-,\{0\}$};
  2987. \node (y) at (3,0) {$y:-,\{0,1\}$};
  2988. \node (w) at (6,0) {$w:0,\{1\}$};
  2989. \node (v) at (9,0) {$v:-,\{0\}$};
  2990. \draw (t1) to (z);
  2991. \draw (z) to (y);
  2992. \draw (z) to (w);
  2993. \draw (x) to (w);
  2994. \draw (y) to (w);
  2995. \draw (v) to (w);
  2996. \end{tikzpicture}
  2997. \]
  2998. Vertex $y$ is now the most highly saturated, so we color $y$ with $2$.
  2999. We cannot choose $0$ or $1$ because those numbers are in $y$'s
  3000. saturation set. Indeed, $y$ interferes with $w$ and $z$, whose colors
  3001. are $0$ and $1$ respectively.
  3002. \[
  3003. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3004. \node (t1) at (0,2) {$t:0,\{1\}$};
  3005. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3006. \node (x) at (6,2) {$x:-,\{0\}$};
  3007. \node (y) at (3,0) {$y:2,\{0,1\}$};
  3008. \node (w) at (6,0) {$w:0,\{1,2\}$};
  3009. \node (v) at (9,0) {$v:-,\{0\}$};
  3010. \draw (t1) to (z);
  3011. \draw (z) to (y);
  3012. \draw (z) to (w);
  3013. \draw (x) to (w);
  3014. \draw (y) to (w);
  3015. \draw (v) to (w);
  3016. \end{tikzpicture}
  3017. \]
  3018. Now $x$ and $v$ are the most saturated, so we color $v$ it $1$.
  3019. \[
  3020. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3021. \node (t1) at (0,2) {$t:0,\{1\}$};
  3022. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3023. \node (x) at (6,2) {$x:-,\{0\}$};
  3024. \node (y) at (3,0) {$y:2,\{0,1\}$};
  3025. \node (w) at (6,0) {$w:0,\{1,2\}$};
  3026. \node (v) at (9,0) {$v:1,\{0\}$};
  3027. \draw (t1) to (z);
  3028. \draw (z) to (y);
  3029. \draw (z) to (w);
  3030. \draw (x) to (w);
  3031. \draw (y) to (w);
  3032. \draw (v) to (w);
  3033. \end{tikzpicture}
  3034. \]
  3035. In the last step of the algorithm, we color $x$ with $1$.
  3036. \[
  3037. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3038. \node (t1) at (0,2) {$t:0,\{1,\}$};
  3039. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3040. \node (x) at (6,2) {$x:1,\{0\}$};
  3041. \node (y) at (3,0) {$y:2,\{0,1\}$};
  3042. \node (w) at (6,0) {$w:0,\{1,2\}$};
  3043. \node (v) at (9,0) {$v:1,\{0\}$};
  3044. \draw (t1) to (z);
  3045. \draw (z) to (y);
  3046. \draw (z) to (w);
  3047. \draw (x) to (w);
  3048. \draw (y) to (w);
  3049. \draw (v) to (w);
  3050. \end{tikzpicture}
  3051. \]
  3052. With the coloring complete, we finalize the assignment of variables to
  3053. registers and stack locations. Recall that if we have $k$ registers,
  3054. we map the first $k$ colors to registers and the rest to stack
  3055. locations. Suppose for the moment that we have just one register to
  3056. use for register allocation, \key{rcx}. Then the following is the
  3057. mapping of colors to registers and stack allocations.
  3058. \[
  3059. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3060. \]
  3061. Putting this mapping together with the above coloring of the
  3062. variables, we arrive at the following assignment of variables to
  3063. registers and stack locations.
  3064. \begin{gather*}
  3065. \{ v \mapsto \key{\%rcx}, \,
  3066. w \mapsto \key{\%rcx}, \,
  3067. x \mapsto \key{-8(\%rbp)}, \\
  3068. y \mapsto \key{-16(\%rbp)}, \,
  3069. z\mapsto \key{-8(\%rbp)},
  3070. t\mapsto \key{\%rcx} \}
  3071. \end{gather*}
  3072. Applying this assignment to our running example, on the left, yields
  3073. the program on the right.
  3074. % why frame size of 32? -JGS
  3075. \begin{center}
  3076. \begin{minipage}{0.3\textwidth}
  3077. \begin{lstlisting}
  3078. movq $1, v
  3079. movq $42, w
  3080. movq v, x
  3081. addq $7, x
  3082. movq x, y
  3083. movq x, z
  3084. addq w, z
  3085. movq y, t
  3086. negq t
  3087. movq z, %rax
  3088. addq t, %rax
  3089. jmp conclusion
  3090. \end{lstlisting}
  3091. \end{minipage}
  3092. $\Rightarrow\qquad$
  3093. \begin{minipage}{0.45\textwidth}
  3094. \begin{lstlisting}
  3095. movq $1, %rcx
  3096. movq $42, %rcx
  3097. movq %rcx, -8(%rbp)
  3098. addq $7, -8(%rbp)
  3099. movq -8(%rbp), -16(%rbp)
  3100. movq -8(%rbp), -8(%rbp)
  3101. addq %rcx, -8(%rbp)
  3102. movq -16(%rbp), %rcx
  3103. negq %rcx
  3104. movq -8(%rbp), %rax
  3105. addq %rcx, %rax
  3106. jmp conclusion
  3107. \end{lstlisting}
  3108. \end{minipage}
  3109. \end{center}
  3110. The resulting program is almost an x86 program. The remaining step is
  3111. the patch instructions pass. In this example, the trivial move of
  3112. \code{-8(\%rbp)} to itself is deleted and the addition of
  3113. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3114. \code{rax} as follows.
  3115. \begin{lstlisting}
  3116. movq -8(%rbp), %rax
  3117. addq %rax, -16(%rbp)
  3118. \end{lstlisting}
  3119. An overview of all of the passes involved in register allocation is
  3120. shown in Figure~\ref{fig:reg-alloc-passes}.
  3121. \begin{figure}[tbp]
  3122. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3123. \node (R1) at (0,2) {\large $R_1$};
  3124. \node (R1-2) at (3,2) {\large $R_1$};
  3125. \node (R1-3) at (6,2) {\large $R_1$};
  3126. \node (C0-1) at (3,0) {\large $C_0$};
  3127. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3128. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3129. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3130. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3131. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3132. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3133. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3134. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3135. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3136. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3137. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3138. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3139. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3140. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3141. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3142. \end{tikzpicture}
  3143. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3144. \label{fig:reg-alloc-passes}
  3145. \end{figure}
  3146. \begin{exercise}\normalfont
  3147. Implement the pass \code{allocate-registers}, which should come
  3148. after the \code{build-interference} pass. The three new passes,
  3149. \code{uncover-live}, \code{build-interference}, and
  3150. \code{allocate-registers} replace the \code{assign-homes} pass of
  3151. Section~\ref{sec:assign-r1}.
  3152. We recommend that you create a helper function named
  3153. \code{color-graph} that takes an interference graph and a list of
  3154. all the variables in the program. This function should return a
  3155. mapping of variables to their colors (represented as natural
  3156. numbers). By creating this helper function, you will be able to
  3157. reuse it in Chapter~\ref{ch:functions} when you add support for
  3158. functions. The support code includes an implementation of the
  3159. priority queue data structure in the file
  3160. \code{priority\_queue.rkt}, which might come in handy for
  3161. prioritizing highly saturated nodes inside your \code{color-graph}
  3162. function.
  3163. Once you have obtained the coloring from \code{color-graph}, you can
  3164. assign the variables to registers or stack locations and then reuse
  3165. code from the \code{assign-homes} pass from
  3166. Section~\ref{sec:assign-r1} to replace the variables with their
  3167. assigned location.
  3168. Test your updated compiler by creating new example programs that
  3169. exercise all of the register allocation algorithm, such as forcing
  3170. variables to be spilled to the stack.
  3171. \end{exercise}
  3172. \section{Print x86 and Conventions for Registers}
  3173. \label{sec:print-x86-reg-alloc}
  3174. \index{calling conventions}
  3175. \index{prelude}\index{conclusion}
  3176. Recall that the \code{print-x86} pass generates the prelude and
  3177. conclusion instructions for the \code{main} function.
  3178. %
  3179. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3180. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3181. reason for this is that our \code{main} function must adhere to the
  3182. x86 calling conventions that we described in
  3183. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3184. allocator assigned variables to other callee-saved registers
  3185. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3186. saved to the stack in the prelude and restored in the conclusion. The
  3187. simplest approach is to save and restore all of the callee-saved
  3188. registers. The more efficient approach is to keep track of which
  3189. callee-saved registers were used and only save and restore
  3190. them. Either way, make sure to take this use of stack space into
  3191. account when you are calculating the size of the frame and adjusting
  3192. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3193. frame needs to be a multiple of 16 bytes!
  3194. \section{Challenge: Move Biasing}
  3195. \label{sec:move-biasing}
  3196. \index{move biasing}
  3197. This section describes an optional enhancement to register allocation
  3198. for those students who are looking for an extra challenge or who have
  3199. a deeper interest in register allocation.
  3200. We return to the running example, but we remove the supposition that
  3201. we only have one register to use. So we have the following mapping of
  3202. color numbers to registers.
  3203. \[
  3204. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3205. \]
  3206. Using the same assignment of variables to color numbers that was
  3207. produced by the register allocator described in the last section, we
  3208. get the following program.
  3209. \begin{minipage}{0.3\textwidth}
  3210. \begin{lstlisting}
  3211. movq $1, v
  3212. movq $42, w
  3213. movq v, x
  3214. addq $7, x
  3215. movq x, y
  3216. movq x, z
  3217. addq w, z
  3218. movq y, t
  3219. negq t
  3220. movq z, %rax
  3221. addq t, %rax
  3222. jmp conclusion
  3223. \end{lstlisting}
  3224. \end{minipage}
  3225. $\Rightarrow\qquad$
  3226. \begin{minipage}{0.45\textwidth}
  3227. \begin{lstlisting}
  3228. movq $1, %rcx
  3229. movq $42, $rbx
  3230. movq %rcx, %rcx
  3231. addq $7, %rcx
  3232. movq %rcx, %rdx
  3233. movq %rcx, %rcx
  3234. addq %rbx, %rcx
  3235. movq %rdx, %rbx
  3236. negq %rbx
  3237. movq %rcx, %rax
  3238. addq %rbx, %rax
  3239. jmp conclusion
  3240. \end{lstlisting}
  3241. \end{minipage}
  3242. In the above output code there are two \key{movq} instructions that
  3243. can be removed because their source and target are the same. However,
  3244. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3245. register, we could instead remove three \key{movq} instructions. We
  3246. can accomplish this by taking into account which variables appear in
  3247. \key{movq} instructions with which other variables.
  3248. We say that two variables $p$ and $q$ are \emph{move related}\index{move related}
  3249. if they participate together in a \key{movq} instruction, that is, \key{movq}
  3250. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  3251. allocator chooses a color for a variable, it should prefer a color
  3252. that has already been used for a move-related variable (assuming that
  3253. they do not interfere). Of course, this preference should not override
  3254. the preference for registers over stack locations. This preference
  3255. should be used as a tie breaker when choosing between registers or
  3256. when choosing between stack locations.
  3257. We recommend representing the move relationships in a graph, similar
  3258. to how we represented interference. The following is the \emph{move
  3259. graph} for our running example.
  3260. \[
  3261. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3262. \node (t) at (0,2) {$t$};
  3263. \node (z) at (3,2) {$z$};
  3264. \node (x) at (6,2) {$x$};
  3265. \node (y) at (3,0) {$y$};
  3266. \node (w) at (6,0) {$w$};
  3267. \node (v) at (9,0) {$v$};
  3268. \draw (v) to (x);
  3269. \draw (x) to (y);
  3270. \draw (x) to (z);
  3271. \draw (y) to (t);
  3272. \end{tikzpicture}
  3273. \]
  3274. Now we replay the graph coloring, pausing to see the coloring of
  3275. $y$. Recall the following configuration. The most saturated vertices
  3276. were $w$ and $y$.
  3277. \[
  3278. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3279. \node (t1) at (0,2) {$t:0,\{1\}$};
  3280. \node (z) at (3,2) {$z:1,\{0\}$};
  3281. \node (x) at (6,2) {$x:-,\{\}$};
  3282. \node (y) at (3,0) {$y:-,\{1\}$};
  3283. \node (w) at (6,0) {$w:-,\{1\}$};
  3284. \node (v) at (9,0) {$v:-,\{\}$};
  3285. \draw (t1) to (z);
  3286. \draw (z) to (y);
  3287. \draw (z) to (w);
  3288. \draw (x) to (w);
  3289. \draw (y) to (w);
  3290. \draw (v) to (w);
  3291. \end{tikzpicture}
  3292. \]
  3293. %
  3294. Last time we chose to color $w$ with $0$. But this time we note that
  3295. $w$ is not move related to any vertex, and $y$ is move related to $t$.
  3296. So we choose to color $y$ the same color, $0$.
  3297. \[
  3298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3299. \node (t1) at (0,2) {$t:0,\{1\}$};
  3300. \node (z) at (3,2) {$z:1,\{0\}$};
  3301. \node (x) at (6,2) {$x:-,\{\}$};
  3302. \node (y) at (3,0) {$y:0,\{1\}$};
  3303. \node (w) at (6,0) {$w:-,\{0,1\}$};
  3304. \node (v) at (9,0) {$v:-,\{\}$};
  3305. \draw (t1) to (z);
  3306. \draw (z) to (y);
  3307. \draw (z) to (w);
  3308. \draw (x) to (w);
  3309. \draw (y) to (w);
  3310. \draw (v) to (w);
  3311. \end{tikzpicture}
  3312. \]
  3313. Now $w$ is the most saturated, so we color it $2$.
  3314. \[
  3315. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3316. \node (t1) at (0,2) {$t:0,\{1\}$};
  3317. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3318. \node (x) at (6,2) {$x:-,\{2\}$};
  3319. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3320. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3321. \node (v) at (9,0) {$v:-,\{2\}$};
  3322. \draw (t1) to (z);
  3323. \draw (z) to (y);
  3324. \draw (z) to (w);
  3325. \draw (x) to (w);
  3326. \draw (y) to (w);
  3327. \draw (v) to (w);
  3328. \end{tikzpicture}
  3329. \]
  3330. At this point, vertices $x$ and $v$ are most saturated,
  3331. but $x$ is move related to $y$ and $z$, so we color $x$ to $0$
  3332. to match $y$. Finally, we color $v$ to $0$.
  3333. \[
  3334. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3335. \node (t) at (0,2) {$t:0,\{1\}$};
  3336. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3337. \node (x) at (6,2) {$x:0,\{2\}$};
  3338. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3339. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3340. \node (v) at (9,0) {$v:0,\{2\}$};
  3341. \draw (t) to (z);
  3342. \draw (z) to (y);
  3343. \draw (z) to (w);
  3344. \draw (x) to (w);
  3345. \draw (y) to (w);
  3346. \draw (v) to (w);
  3347. \end{tikzpicture}
  3348. \]
  3349. So we have the following assignment of variables to registers.
  3350. \begin{gather*}
  3351. \{ v \mapsto \key{\%rbx}, \,
  3352. w \mapsto \key{\%rdx}, \,
  3353. x \mapsto \key{\%rbx}, \\
  3354. y \mapsto \key{\%rbx}, \,
  3355. z\mapsto \key{\%rcx},
  3356. t\mapsto \key{\%rbx} \}
  3357. \end{gather*}
  3358. We apply this register assignment to the running example, on the left,
  3359. to obtain the code on right.
  3360. \begin{minipage}{0.3\textwidth}
  3361. \begin{lstlisting}
  3362. movq $1, v
  3363. movq $42, w
  3364. movq v, x
  3365. addq $7, x
  3366. movq x, y
  3367. movq x, z
  3368. addq w, z
  3369. movq y, t
  3370. negq t
  3371. movq z, %rax
  3372. addq t, %rax
  3373. jmp conclusion
  3374. \end{lstlisting}
  3375. \end{minipage}
  3376. $\Rightarrow\qquad$
  3377. \begin{minipage}{0.45\textwidth}
  3378. \begin{lstlisting}
  3379. movq $1, %rbx
  3380. movq $42, %rdx
  3381. movq %rbx, %rbx
  3382. addq $7, %rbx
  3383. movq %rbx, %rbx
  3384. movq %rbx, %rcx
  3385. addq %rdx, %rcx
  3386. movq %rbx, %rbx
  3387. negq %rbx
  3388. movq %rcx, %rax
  3389. addq %rbx, %rax
  3390. jmp conclusion
  3391. \end{lstlisting}
  3392. \end{minipage}
  3393. The \code{patch-instructions} then removes the three trivial moves
  3394. from \key{rbx} to \key{rbx} to obtain the following result.
  3395. \begin{minipage}{0.45\textwidth}
  3396. \begin{lstlisting}
  3397. movq $1, %rbx
  3398. movq $42, %rdx
  3399. addq $7, %rbx
  3400. movq %rbx, %rcx
  3401. addq %rdx, %rcx
  3402. negq %rbx
  3403. movq %rcx, %rax
  3404. addq %rbx, %rax
  3405. jmp conclusion
  3406. \end{lstlisting}
  3407. \end{minipage}
  3408. \begin{exercise}\normalfont
  3409. Change your implementation of \code{allocate-registers} to take move
  3410. biasing into account. Make sure that your compiler still passes all of
  3411. the previous tests. Create two new tests that include at least one
  3412. opportunity for move biasing and visually inspect the output x86
  3413. programs to make sure that your move biasing is working properly.
  3414. \end{exercise}
  3415. \margincomment{\footnotesize To do: another neat challenge would be to do
  3416. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3417. \section{Output of the Running Example}
  3418. \label{sec:reg-alloc-output}
  3419. \index{prelude}\index{conclusion}
  3420. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3421. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3422. and move biasing. To demonstrate both the use of registers and the
  3423. stack, we have limited the register allocator to use just two
  3424. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3425. \code{main} function, we push \code{rbx} onto the stack because it is
  3426. a callee-saved register and it was assigned to variable by the
  3427. register allocator. We substract \code{8} from the \code{rsp} at the
  3428. end of the prelude to reserve space for the one spilled variable.
  3429. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3430. Moving on the the \code{start} block, we see how the registers were
  3431. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3432. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3433. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3434. that the prelude saved the callee-save register \code{rbx} onto the
  3435. stack. The spilled variables must be placed lower on the stack than
  3436. the saved callee-save registers, so in this case \code{w} is placed at
  3437. \code{-16(\%rbp)}.
  3438. In the \code{conclusion}, we undo the work that was done in the
  3439. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3440. spilled variables), then we pop the old values of \code{rbx} and
  3441. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3442. return control to the operating system.
  3443. \begin{figure}[tbp]
  3444. % s0_28.rkt
  3445. % (use-minimal-set-of-registers! #t)
  3446. % and only rbx rcx
  3447. % tmp 0 rbx
  3448. % z 1 rcx
  3449. % y 0 rbx
  3450. % w 2 16(%rbp)
  3451. % v 0 rbx
  3452. % x 0 rbx
  3453. \begin{lstlisting}
  3454. start:
  3455. movq $1, %rbx
  3456. movq $42, -16(%rbp)
  3457. addq $7, %rbx
  3458. movq %rbx, %rcx
  3459. addq -16(%rbp), %rcx
  3460. negq %rbx
  3461. movq %rcx, %rax
  3462. addq %rbx, %rax
  3463. jmp conclusion
  3464. .globl main
  3465. main:
  3466. pushq %rbp
  3467. movq %rsp, %rbp
  3468. pushq %rbx
  3469. subq $8, %rsp
  3470. jmp start
  3471. conclusion:
  3472. addq $8, %rsp
  3473. popq %rbx
  3474. popq %rbp
  3475. retq
  3476. \end{lstlisting}
  3477. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3478. \label{fig:running-example-x86}
  3479. \end{figure}
  3480. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3481. \chapter{Booleans and Control Flow}
  3482. \label{ch:bool-types}
  3483. \index{Boolean}
  3484. \index{control flow}
  3485. \index{conditional expression}
  3486. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3487. integers. In this chapter we add a second kind of value, the Booleans,
  3488. to create the $R_2$ language. The Boolean values \emph{true} and
  3489. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3490. Racket. The $R_2$ language includes several operations that involve
  3491. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3492. conditional \key{if} expression. With the addition of \key{if}
  3493. expressions, programs can have non-trivial control flow which which
  3494. significantly impacts the \code{explicate-control} and the liveness
  3495. analysis for register allocation. Also, because we now have two kinds
  3496. of values, we need to handle programs that apply an operation to the
  3497. wrong kind of value, such as \code{(not 1)}.
  3498. There are two language design options for such situations. One option
  3499. is to signal an error and the other is to provide a wider
  3500. interpretation of the operation. The Racket language uses a mixture of
  3501. these two options, depending on the operation and the kind of
  3502. value. For example, the result of \code{(not 1)} in Racket is
  3503. \code{\#f} because Racket treats non-zero integers as if they were
  3504. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3505. error in Racket stating that \code{car} expects a pair.
  3506. The Typed Racket language makes similar design choices as Racket,
  3507. except much of the error detection happens at compile time instead of
  3508. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3509. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3510. reports a compile-time error because Typed Racket expects the type of
  3511. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3512. For the $R_2$ language we choose to be more like Typed Racket in that
  3513. we shall perform type checking during compilation. In
  3514. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3515. is, how to compile a dynamically typed language like Racket. The
  3516. $R_2$ language is a subset of Typed Racket but by no means includes
  3517. all of Typed Racket. For many operations we take a narrower
  3518. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3519. This chapter is organized as follows. We begin by defining the syntax
  3520. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3521. then introduce the idea of type checking and build a type checker for
  3522. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3523. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3524. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3525. how our compiler passes need to change to accommodate Booleans and
  3526. conditional control flow.
  3527. \section{The $R_2$ Language}
  3528. \label{sec:r2-lang}
  3529. The concrete syntax of the $R_2$ language is defined in
  3530. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3531. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3532. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3533. and the conditional \code{if} expression. Also, we expand the
  3534. operators to include
  3535. \begin{enumerate}
  3536. \item subtraction on integers,
  3537. \item the logical operators \key{and}, \key{or} and \key{not},
  3538. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3539. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3540. comparing integers.
  3541. \end{enumerate}
  3542. \begin{figure}[tp]
  3543. \centering
  3544. \fbox{
  3545. \begin{minipage}{0.96\textwidth}
  3546. \[
  3547. \begin{array}{lcl}
  3548. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3549. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3550. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3551. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3552. &\mid& \itm{bool}
  3553. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3554. \mid (\key{not}\;\Exp) \\
  3555. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3556. R_2 &::=& \Exp
  3557. \end{array}
  3558. \]
  3559. \end{minipage}
  3560. }
  3561. \caption{The concrete syntax of $R_2$, extending $R_1$
  3562. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3563. \label{fig:r2-concrete-syntax}
  3564. \end{figure}
  3565. \begin{figure}[tp]
  3566. \centering
  3567. \fbox{
  3568. \begin{minipage}{0.96\textwidth}
  3569. \[
  3570. \begin{array}{lcl}
  3571. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3572. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3573. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3574. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3575. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3576. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3577. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3578. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3579. &\mid& \BINOP{\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3580. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3581. \end{array}
  3582. \]
  3583. \end{minipage}
  3584. }
  3585. \caption{The abstract syntax of $R_2$.}
  3586. \label{fig:r2-syntax}
  3587. \end{figure}
  3588. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3589. the parts that are the same as the interpreter for $R_1$
  3590. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3591. evaluate to the corresponding Boolean values. The conditional
  3592. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3593. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3594. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3595. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3596. you might expect, but note that the \code{and} operation is
  3597. short-circuiting. That is, given the expression
  3598. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3599. $e_1$ evaluates to \code{\#f}.
  3600. With the addition of the comparison operations, there are quite a few
  3601. primitive operations and the interpreter code for them could become
  3602. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3603. out the different parts of the code for primitive operations into the
  3604. \code{interp-op} function and the similar parts of the code into the
  3605. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3606. do not use \code{interp-op} for the \code{and} operation because of
  3607. the short-circuiting behavior in the order of evaluation of its
  3608. arguments.
  3609. \begin{figure}[tbp]
  3610. \begin{lstlisting}
  3611. (define (interp-op op)
  3612. (match op
  3613. ...
  3614. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3615. ['eq? (lambda (v1 v2)
  3616. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3617. (and (boolean? v1) (boolean? v2)))
  3618. (eq? v1 v2)]))]
  3619. ['< (lambda (v1 v2)
  3620. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3621. ['<= (lambda (v1 v2)
  3622. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3623. ['> (lambda (v1 v2)
  3624. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3625. ['>= (lambda (v1 v2)
  3626. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3627. [else (error 'interp-op "unknown operator")]))
  3628. (define (interp-exp env)
  3629. (lambda (e)
  3630. (define recur (interp-exp env))
  3631. (match e
  3632. ...
  3633. [(Bool b) b]
  3634. [(If cnd thn els)
  3635. (define b (recur cnd))
  3636. (match b
  3637. [#t (recur thn)]
  3638. [#f (recur els)])]
  3639. [(Prim 'and (list e1 e2))
  3640. (define v1 (recur e1))
  3641. (match v1
  3642. [#t (match (recur e2) [#t #t] [#f #f])]
  3643. [#f #f])]
  3644. [(Prim op args)
  3645. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3646. )))
  3647. (define (interp-R2 p)
  3648. (match p
  3649. [(Program info e)
  3650. ((interp-exp '()) e)]
  3651. ))
  3652. \end{lstlisting}
  3653. \caption{Interpreter for the $R_2$ language.}
  3654. \label{fig:interp-R2}
  3655. \end{figure}
  3656. \section{Type Checking $R_2$ Programs}
  3657. \label{sec:type-check-r2}
  3658. \index{type checking}
  3659. \index{semantic analysis}
  3660. It is helpful to think about type checking in two complementary
  3661. ways. A type checker predicts the type of value that will be produced
  3662. by each expression in the program. For $R_2$, we have just two types,
  3663. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3664. \begin{lstlisting}
  3665. (+ 10 (- (+ 12 20)))
  3666. \end{lstlisting}
  3667. produces an \key{Integer} while
  3668. \begin{lstlisting}
  3669. (and (not #f) #t)
  3670. \end{lstlisting}
  3671. produces a \key{Boolean}.
  3672. Another way to think about type checking is that it enforces a set of
  3673. rules about which operators can be applied to which kinds of
  3674. values. For example, our type checker for $R_2$ will signal an error
  3675. for the below expression because, as we have seen above, the
  3676. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3677. checker enforces the rule that the argument of \code{not} must be a
  3678. \key{Boolean}.
  3679. \begin{lstlisting}
  3680. (not (+ 10 (- (+ 12 20))))
  3681. \end{lstlisting}
  3682. The type checker for $R_2$ is a structurally recursive function over
  3683. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3684. the \code{type-check-exp} function. Given an input expression
  3685. \code{e}, the type checker either returns a type (\key{Integer} or
  3686. \key{Boolean}) or it signals an error. The type of an integer literal
  3687. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3688. To handle variables, the type checker uses an environment that maps
  3689. variables to types. Consider the clause for \key{let}. We type check
  3690. the initializing expression to obtain its type \key{T} and then
  3691. associate type \code{T} with the variable \code{x} in the
  3692. environment. When the type checker encounters a use of variable
  3693. \code{x} in the body of the \key{let}, it can find its type in the
  3694. environment.
  3695. \begin{figure}[tbp]
  3696. \begin{lstlisting}
  3697. (define (type-check-exp env)
  3698. (lambda (e)
  3699. (match e
  3700. [(Var x) (dict-ref env x)]
  3701. [(Int n) 'Integer]
  3702. [(Bool b) 'Boolean]
  3703. [(Let x e body)
  3704. (define Te ((type-check-exp env) e))
  3705. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3706. Tb]
  3707. ...
  3708. [else
  3709. (error "type-check-exp couldn't match" e)])))
  3710. (define (type-check env)
  3711. (lambda (e)
  3712. (match e
  3713. [(Program info body)
  3714. (define Tb ((type-check-exp '()) body))
  3715. (unless (equal? Tb 'Integer)
  3716. (error "result of the program must be an integer, not " Tb))
  3717. (Program info body)]
  3718. )))
  3719. \end{lstlisting}
  3720. \caption{Skeleton of a type checker for the $R_2$ language.}
  3721. \label{fig:type-check-R2}
  3722. \end{figure}
  3723. \begin{exercise}\normalfont
  3724. Complete the implementation of \code{type-check}. Test your type
  3725. checker using \code{interp-tests} and \code{compiler-tests} by passing
  3726. the \code{type-check} function as the second argument. Create 10 new
  3727. example programs in $R_2$ that you choose based on how thoroughly they
  3728. test you type checking function. Half of the example programs should
  3729. have a type error to make sure that your type checker properly rejects
  3730. them. For those programs, to signal that a type error is expected,
  3731. create an empty file with the same base name but with file extension
  3732. \code{.tyerr}. For example, if the test \code{r2\_14.rkt} is expected
  3733. to error, then create an empty file named \code{r2\_14.tyerr}. The
  3734. other half of the example programs should not have type errors. Note
  3735. that if your type checker does not signal an error for a program, then
  3736. interpreting that program should not encounter an error. If it does,
  3737. there is something wrong with your type checker.
  3738. \end{exercise}
  3739. \section{Shrink the $R_2$ Language}
  3740. \label{sec:shrink-r2}
  3741. The $R_2$ language includes several operators that are easily
  3742. expressible in terms of other operators. For example, subtraction is
  3743. expressible in terms of addition and negation.
  3744. \[
  3745. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3746. \]
  3747. Several of the comparison operations are expressible in terms of
  3748. less-than and logical negation.
  3749. \[
  3750. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3751. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3752. \]
  3753. The \key{let} is needed in the above translation to ensure that
  3754. expression $e_1$ is evaluated before $e_2$.
  3755. By performing these translations near the front-end of the compiler,
  3756. the later passes of the compiler do not need to deal with these
  3757. constructs, making those passes shorter. On the other hand, sometimes
  3758. these translations make it more difficult to generate the most
  3759. efficient code with respect to the number of instructions. However,
  3760. these differences typically do not affect the number of accesses to
  3761. memory, which is the primary factor that determines execution time on
  3762. modern computer architectures.
  3763. \begin{exercise}\normalfont
  3764. Implement the pass \code{shrink} that removes subtraction,
  3765. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3766. by translating them to other constructs in $R_2$. Create tests to
  3767. make sure that the behavior of all of these constructs stays the
  3768. same after translation.
  3769. \end{exercise}
  3770. \section{The x86$_1$ Language}
  3771. \label{sec:x86-1}
  3772. \index{x86}
  3773. To implement the new logical operations, the comparison operations,
  3774. and the \key{if} expression, we need to delve further into the x86
  3775. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3776. the concrete and abstract syntax for a larger subset of x86 that
  3777. includes instructions for logical operations, comparisons, and
  3778. conditional jumps.
  3779. One small challenge is that x86 does not provide an instruction that
  3780. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3781. However, the \code{xorq} instruction can be used to encode \code{not}.
  3782. The \key{xorq} instruction takes two arguments, performs a pairwise
  3783. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3784. and writes the results into its second argument. Recall the truth
  3785. table for exclusive-or:
  3786. \begin{center}
  3787. \begin{tabular}{l|cc}
  3788. & 0 & 1 \\ \hline
  3789. 0 & 0 & 1 \\
  3790. 1 & 1 & 0
  3791. \end{tabular}
  3792. \end{center}
  3793. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3794. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3795. for the bit $1$, the result is the opposite of the second bit. Thus,
  3796. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3797. the first argument:
  3798. \[
  3799. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3800. \qquad\Rightarrow\qquad
  3801. \begin{array}{l}
  3802. \key{movq}~ \Arg\key{,} \Var\\
  3803. \key{xorq}~ \key{\$1,} \Var
  3804. \end{array}
  3805. \]
  3806. \begin{figure}[tp]
  3807. \fbox{
  3808. \begin{minipage}{0.96\textwidth}
  3809. \[
  3810. \begin{array}{lcl}
  3811. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3812. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3813. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3814. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3815. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3816. \key{subq} \; \Arg\key{,} \Arg \mid
  3817. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3818. && \gray{ \key{callq} \; \itm{label} \mid
  3819. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3820. && \gray{ \itm{label}\key{:}\; \Instr }
  3821. \mid \key{xorq}~\Arg\key{,}~\Arg
  3822. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3823. && \key{set}cc~\Arg
  3824. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3825. \mid \key{j}cc~\itm{label}
  3826. \\
  3827. x86_1 &::= & \gray{ \key{.globl main} }\\
  3828. & & \gray{ \key{main:} \; \Instr\ldots }
  3829. \end{array}
  3830. \]
  3831. \end{minipage}
  3832. }
  3833. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3834. \label{fig:x86-1-concrete}
  3835. \end{figure}
  3836. \begin{figure}[tp]
  3837. \fbox{
  3838. \begin{minipage}{0.96\textwidth}
  3839. \small
  3840. \[
  3841. \begin{array}{lcl}
  3842. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3843. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3844. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3845. \mid \BYTEREG{\itm{bytereg}} \\
  3846. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3847. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3848. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3849. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3850. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3851. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3852. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3853. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3854. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3855. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3856. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3857. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3858. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3859. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3860. \end{array}
  3861. \]
  3862. \end{minipage}
  3863. }
  3864. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3865. \label{fig:x86-1}
  3866. \end{figure}
  3867. Next we consider the x86 instructions that are relevant for compiling
  3868. the comparison operations. The \key{cmpq} instruction compares its two
  3869. arguments to determine whether one argument is less than, equal, or
  3870. greater than the other argument. The \key{cmpq} instruction is unusual
  3871. regarding the order of its arguments and where the result is
  3872. placed. The argument order is backwards: if you want to test whether
  3873. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3874. \key{cmpq} is placed in the special EFLAGS register. This register
  3875. cannot be accessed directly but it can be queried by a number of
  3876. instructions, including the \key{set} instruction. The \key{set}
  3877. instruction puts a \key{1} or \key{0} into its destination depending
  3878. on whether the comparison came out according to the condition code
  3879. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3880. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3881. The \key{set} instruction has an annoying quirk in that its
  3882. destination argument must be single byte register, such as \code{al}
  3883. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  3884. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  3885. then be used to move from a single byte register to a normal 64-bit
  3886. register.
  3887. The x86 instruction for conditional jump are relevant to the
  3888. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3889. updates the program counter to point to the instruction after the
  3890. indicated label depending on whether the result in the EFLAGS register
  3891. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3892. instruction falls through to the next instruction. The abstract
  3893. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3894. that it separates the instruction name from the condition code. For
  3895. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3896. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3897. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3898. instruction to set the EFLAGS register.
  3899. \section{The $C_1$ Intermediate Language}
  3900. \label{sec:c1}
  3901. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3902. we need to grow that intermediate language to handle the new features
  3903. in $R_2$: Booleans and conditional expressions.
  3904. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3905. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3906. particular, we add logical and comparison operators to the $\Exp$
  3907. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3908. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3909. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3910. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3911. sequence of statements may now end with a \code{goto} or a conditional
  3912. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3913. depending on the outcome of the comparison. In
  3914. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3915. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3916. and \key{goto}'s.
  3917. \begin{figure}[tbp]
  3918. \fbox{
  3919. \begin{minipage}{0.96\textwidth}
  3920. \small
  3921. \[
  3922. \begin{array}{lcl}
  3923. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3924. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3925. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3926. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3927. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3928. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3929. \mid \key{goto}~\itm{label}\key{;}\\
  3930. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3931. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  3932. \end{array}
  3933. \]
  3934. \end{minipage}
  3935. }
  3936. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3937. \label{fig:c1-concrete-syntax}
  3938. \end{figure}
  3939. \begin{figure}[tp]
  3940. \fbox{
  3941. \begin{minipage}{0.96\textwidth}
  3942. \small
  3943. \[
  3944. \begin{array}{lcl}
  3945. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3946. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3947. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3948. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3949. &\mid& \UNIOP{\key{'not}}{\Atm}
  3950. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3951. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3952. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3953. \mid \GOTO{\itm{label}} \\
  3954. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3955. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  3956. \end{array}
  3957. \]
  3958. \end{minipage}
  3959. }
  3960. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  3961. (Figure~\ref{fig:c0-syntax}).}
  3962. \label{fig:c1-syntax}
  3963. \end{figure}
  3964. \clearpage
  3965. \section{Remove Complex Operands}
  3966. \label{sec:remove-complex-opera-R2}
  3967. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  3968. \code{rco-atom} functions according to the definition of the output
  3969. language for this pass, $R_2^{\dagger}$, the administrative normal
  3970. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  3971. \code{Bool} form is an atomic expressions but \code{If} is not. All
  3972. three sub-expressions of an \code{If} are allowed to be complex
  3973. expressions in the output of \code{remove-complex-opera*}, but the
  3974. operands of \code{not} and the comparisons must be atoms. Regarding
  3975. the \code{If} form, it is particularly important to \textbf{not}
  3976. replace its condition with a temporary variable because that would
  3977. interfere with the generation of high-quality output in the
  3978. \code{explicate-control} pass.
  3979. \begin{figure}[tp]
  3980. \centering
  3981. \fbox{
  3982. \begin{minipage}{0.96\textwidth}
  3983. \[
  3984. \begin{array}{rcl}
  3985. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  3986. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  3987. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3988. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  3989. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  3990. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3991. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3992. \end{array}
  3993. \]
  3994. \end{minipage}
  3995. }
  3996. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  3997. \label{fig:r2-anf-syntax}
  3998. \end{figure}
  3999. \section{Explicate Control}
  4000. \label{sec:explicate-control-r2}
  4001. Recall that the purpose of \code{explicate-control} is to make the
  4002. order of evaluation explicit in the syntax of the program. With the
  4003. addition of \key{if} in $R_2$ this get more interesting.
  4004. As a motivating example, consider the following program that has an
  4005. \key{if} expression nested in the predicate of another \key{if}.
  4006. % s1_41.rkt
  4007. \begin{center}
  4008. \begin{minipage}{0.96\textwidth}
  4009. \begin{lstlisting}
  4010. (let ([x (read)])
  4011. (let ([y (read)])
  4012. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4013. (+ y 2)
  4014. (+ y 10))))
  4015. \end{lstlisting}
  4016. \end{minipage}
  4017. \end{center}
  4018. %
  4019. The naive way to compile \key{if} and the comparison would be to
  4020. handle each of them in isolation, regardless of their context. Each
  4021. comparison would be translated into a \key{cmpq} instruction followed
  4022. by a couple instructions to move the result from the EFLAGS register
  4023. into a general purpose register or stack location. Each \key{if} would
  4024. be translated into the combination of a \key{cmpq} and a conditional
  4025. jump. The generated code for the inner \key{if} in the above example
  4026. would be as follows.
  4027. \begin{center}
  4028. \begin{minipage}{0.96\textwidth}
  4029. \begin{lstlisting}
  4030. ...
  4031. cmpq $1, x ;; (< x 1)
  4032. setl %al
  4033. movzbq %al, tmp
  4034. cmpq $1, tmp ;; (if (< x 1) ...)
  4035. je then_branch_1
  4036. jmp else_branch_1
  4037. ...
  4038. \end{lstlisting}
  4039. \end{minipage}
  4040. \end{center}
  4041. However, if we take context into account we can do better and reduce
  4042. the use of \key{cmpq} and EFLAG-accessing instructions.
  4043. One idea is to try and reorganize the code at the level of $R_2$,
  4044. pushing the outer \key{if} inside the inner one. This would yield the
  4045. following code.
  4046. \begin{center}
  4047. \begin{minipage}{0.96\textwidth}
  4048. \begin{lstlisting}
  4049. (let ([x (read)])
  4050. (let ([y (read)])
  4051. (if (< x 1)
  4052. (if (eq? x 0)
  4053. (+ y 2)
  4054. (+ y 10))
  4055. (if (eq? x 2)
  4056. (+ y 2)
  4057. (+ y 10)))))
  4058. \end{lstlisting}
  4059. \end{minipage}
  4060. \end{center}
  4061. Unfortunately, this approach duplicates the two branches, and a
  4062. compiler must never duplicate code!
  4063. We need a way to perform the above transformation, but without
  4064. duplicating code. The solution is straightforward if we think at the
  4065. level of x86 assembly: we can label the code for each of the branches
  4066. and insert jumps in all the places that need to execute the
  4067. branches. Put another way, we need to move away from abstract syntax
  4068. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  4069. use a standard program representation called a \emph{control flow
  4070. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4071. \index{control-flow graph}
  4072. Each vertex is a labeled sequence of code, called a \emph{basic block}, and
  4073. each edge represents a jump to another block. The \key{Program}
  4074. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4075. as an alist mapping labels to basic blocks. Each basic block is
  4076. represented by the $\Tail$ non-terminal.
  4077. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4078. \code{remove-complex-opera*} pass and then the
  4079. \code{explicate-control} pass on the example program. We walk through
  4080. the output program and then discuss the algorithm.
  4081. %
  4082. Following the order of evaluation in the output of
  4083. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4084. and then the less-than-comparison to \code{1} in the predicate of the
  4085. inner \key{if}. In the output of \code{explicate-control}, in the
  4086. block labeled \code{start}, this becomes two assignment statements
  4087. followed by a conditional \key{goto} to label \code{block96} or
  4088. \code{block97}. The blocks associated with those labels contain the
  4089. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4090. respectively. Regarding the block labeled with \code{block96}, we
  4091. start with the comparison to \code{0} and then have a conditional
  4092. goto, either to label \code{block92} or label \code{block93}, which
  4093. indirectly take us to labels \code{block90} and \code{block91}, the
  4094. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4095. y 10)}. The story for the block labeled \code{block97} is similar.
  4096. \begin{figure}[tbp]
  4097. \begin{tabular}{lll}
  4098. \begin{minipage}{0.4\textwidth}
  4099. % s1_41.rkt
  4100. \begin{lstlisting}
  4101. (let ([x (read)])
  4102. (let ([y (read)])
  4103. (if (if (< x 1)
  4104. (eq? x 0)
  4105. (eq? x 2))
  4106. (+ y 2)
  4107. (+ y 10))))
  4108. \end{lstlisting}
  4109. \hspace{40pt}$\Downarrow$
  4110. \begin{lstlisting}
  4111. (let ([x (read)])
  4112. (let ([y (read)])
  4113. (if (if (< x 1)
  4114. (eq? x 0)
  4115. (eq? x 2))
  4116. (+ y 2)
  4117. (+ y 10))))
  4118. \end{lstlisting}
  4119. \end{minipage}
  4120. &
  4121. $\Rightarrow$
  4122. &
  4123. \begin{minipage}{0.55\textwidth}
  4124. \begin{lstlisting}
  4125. start:
  4126. x = (read);
  4127. y = (read);
  4128. if (< x 1)
  4129. goto block96;
  4130. else
  4131. goto block97;
  4132. block96:
  4133. if (eq? x 0)
  4134. goto block92;
  4135. else
  4136. goto block93;
  4137. block97:
  4138. if (eq? x 2)
  4139. goto block94;
  4140. else
  4141. goto block95;
  4142. block92:
  4143. goto block90;
  4144. block93:
  4145. goto block91;
  4146. block94:
  4147. goto block90;
  4148. block95:
  4149. goto block91;
  4150. block90:
  4151. return (+ y 2);
  4152. block91:
  4153. return (+ y 10);
  4154. \end{lstlisting}
  4155. \end{minipage}
  4156. \end{tabular}
  4157. \caption{Example translation from $R_2$ to $C_1$
  4158. via the \code{explicate-control}.}
  4159. \label{fig:explicate-control-s1-38}
  4160. \end{figure}
  4161. The nice thing about the output of \code{explicate-control} is that
  4162. there are no unnecessary comparisons and every comparison is part of a
  4163. conditional jump. The down-side of this output is that it includes
  4164. trivial blocks, such as the blocks labeled \code{block92} through
  4165. \code{block95}, that only jump to another block. We discuss a solution
  4166. to this problem in Section~\ref{sec:opt-jumps}.
  4167. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4168. \code{explicate-control} for $R_1$ using two mutually recursive
  4169. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4170. former function translates expressions in tail position whereas the
  4171. later function translates expressions on the right-hand-side of a
  4172. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4173. new kind of context to deal with: the predicate position of the
  4174. \key{if}. We need another function, \code{explicate-pred}, that takes
  4175. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4176. the then-branch and else-branch. The output of \code{explicate-pred}
  4177. is a block and a list of formerly \key{let}-bound variables.
  4178. Note that the three explicate functions need to construct a
  4179. control-flow graph, which we recommend they do via updates to a global
  4180. variable.
  4181. In the following paragraphs we consider the specific additions to the
  4182. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4183. of cases for the \code{explicate-pred} function.
  4184. The \code{explicate-tail} function needs an additional case for
  4185. \key{if}. The branches of the \key{if} inherit the current context, so
  4186. they are in tail position. Let $B_1$ be the result of
  4187. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4188. is a $\Tail$ AST node. Let $B_2$ be the result of apply
  4189. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4190. the $\Tail$ that results fromapplying \code{explicate-pred} to the
  4191. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4192. \key{if} as a whole translates to block $B_3$.
  4193. \[
  4194. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4195. \]
  4196. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4197. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4198. should not be confused with the labels for the blocks that appear in
  4199. the generated code. We initially construct unlabeled blocks; we only
  4200. attach labels to blocks when we add them to the control-flow graph, as
  4201. we shall see in the next case.
  4202. Next consider the case for \key{if} in the \code{explicate-assign}
  4203. function. The context of the \key{if} is an assignment to some
  4204. variable $x$ and then the control continues to some block $B_1$. The
  4205. code that we generate for both the ``then'' and ``else'' branches
  4206. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4207. add it to the control flow graph with a fresh label $\ell_1$. The
  4208. branches of the \key{if} inherit the current context, so that are in
  4209. assignment positions. Let $B_2$ be the result of applying
  4210. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4211. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4212. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4213. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4214. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4215. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4216. $B_4$.
  4217. \[
  4218. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4219. \]
  4220. The function \code{explicate-pred} will need a case for every
  4221. expression that can have type \code{Boolean}. We detail a few cases
  4222. here and leave the rest for the reader. The input to this function is
  4223. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4224. the enclosing \key{if}. Suppose the expression is the Boolean
  4225. \code{\#t}. Then we can perform a kind of partial evaluation
  4226. \index{partial evaluation} and translate it to the ``then'' branch
  4227. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4228. \[
  4229. \key{\#t} \quad\Rightarrow\quad B_1,
  4230. \qquad\qquad\qquad
  4231. \key{\#f} \quad\Rightarrow\quad B_2
  4232. \]
  4233. Next, suppose the expression is a less-than comparison. We translate
  4234. it to a conditional \code{goto}. We need labels for the two branches
  4235. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4236. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4237. less-than comparison is as follows.
  4238. \[
  4239. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4240. \begin{array}{l}
  4241. \key{if}~(\key{<}~e_1~e_2) \\
  4242. \qquad\key{goto}~\ell_1\key{;}\\
  4243. \key{else}\\
  4244. \qquad\key{goto}~\ell_2\key{;}
  4245. \end{array}
  4246. \]
  4247. The case for \key{if} in \code{explicate-pred} is particularly
  4248. illuminating as it deals with the challenges that we discussed above
  4249. regarding the example of the nested \key{if} expressions. Again, we
  4250. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4251. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4252. branches of the current \key{if} inherit their context from the
  4253. current one, that is, predicate context. So we apply
  4254. \code{explicate-pred} to the ``then'' branch with the two blocks
  4255. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4256. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4257. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4258. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4259. \[
  4260. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4261. \quad\Rightarrow\quad
  4262. B_5
  4263. \]
  4264. \begin{exercise}\normalfont
  4265. Implement the pass \code{explicate-control} by adding the cases for
  4266. \key{if} to the functions for tail and assignment contexts, and
  4267. implement \code{explicate-pred} for predicate contexts. Create test
  4268. cases that exercise all of the new cases in the code for this pass.
  4269. \end{exercise}
  4270. \section{Select Instructions}
  4271. \label{sec:select-r2}
  4272. \index{instruction selection}
  4273. Recall that the \code{select-instructions} pass lowers from our
  4274. $C$-like intermediate representation to the pseudo-x86 language, which
  4275. is suitable for conducting register allocation. The pass is
  4276. implemented using three auxiliary functions, one for each of the
  4277. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4278. For $\Atm$, we have new cases for the Booleans. We take the usual
  4279. approach of encoding them as integers, with true as 1 and false as 0.
  4280. \[
  4281. \key{\#t} \Rightarrow \key{1}
  4282. \qquad
  4283. \key{\#f} \Rightarrow \key{0}
  4284. \]
  4285. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4286. be implemented in terms of \code{xorq} as we discussed at the
  4287. beginning of this section. Given an assignment
  4288. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4289. if the left-hand side $\itm{var}$ is
  4290. the same as $\Atm$, then just the \code{xorq} suffices.
  4291. \[
  4292. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4293. \quad\Rightarrow\quad
  4294. \key{xorq}~\key{\$}1\key{,}~\Var
  4295. \]
  4296. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4297. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4298. x86. Then we have
  4299. \[
  4300. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4301. \quad\Rightarrow\quad
  4302. \begin{array}{l}
  4303. \key{movq}~\Arg\key{,}~\Var\\
  4304. \key{xorq}~\key{\$}1\key{,}~\Var
  4305. \end{array}
  4306. \]
  4307. Next consider the cases for \code{eq?} and less-than comparison.
  4308. Translating these operations to x86 is slightly involved due to the
  4309. unusual nature of the \key{cmpq} instruction discussed above. We
  4310. recommend translating an assignment from \code{eq?} into the following
  4311. sequence of three instructions. \\
  4312. \begin{tabular}{lll}
  4313. \begin{minipage}{0.4\textwidth}
  4314. \begin{lstlisting}
  4315. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4316. \end{lstlisting}
  4317. \end{minipage}
  4318. &
  4319. $\Rightarrow$
  4320. &
  4321. \begin{minipage}{0.4\textwidth}
  4322. \begin{lstlisting}
  4323. cmpq |$\Arg_2$|, |$\Arg_1$|
  4324. sete %al
  4325. movzbq %al, |$\Var$|
  4326. \end{lstlisting}
  4327. \end{minipage}
  4328. \end{tabular} \\
  4329. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4330. and conditional \key{goto}. Both are straightforward to handle. A
  4331. \key{goto} becomes a jump instruction.
  4332. \[
  4333. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4334. \]
  4335. A conditional \key{goto} becomes a compare instruction followed
  4336. by a conditional jump (for ``then'') and the fall-through is
  4337. to a regular jump (for ``else'').\\
  4338. \begin{tabular}{lll}
  4339. \begin{minipage}{0.4\textwidth}
  4340. \begin{lstlisting}
  4341. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4342. goto |$\ell_1$|;
  4343. else
  4344. goto |$\ell_2$|;
  4345. \end{lstlisting}
  4346. \end{minipage}
  4347. &
  4348. $\Rightarrow$
  4349. &
  4350. \begin{minipage}{0.4\textwidth}
  4351. \begin{lstlisting}
  4352. cmpq |$\Arg_2$|, |$\Arg_1$|
  4353. je |$\ell_1$|
  4354. jmp |$\ell_2$|
  4355. \end{lstlisting}
  4356. \end{minipage}
  4357. \end{tabular} \\
  4358. \begin{exercise}\normalfont
  4359. Expand your \code{select-instructions} pass to handle the new features
  4360. of the $R_2$ language. Test the pass on all the examples you have
  4361. created and make sure that you have some test programs that use the
  4362. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4363. the output using the \code{interp-x86} interpreter
  4364. (Appendix~\ref{appendix:interp}).
  4365. \end{exercise}
  4366. \section{Register Allocation}
  4367. \label{sec:register-allocation-r2}
  4368. \index{register allocation}
  4369. The changes required for $R_2$ affect liveness analysis, building the
  4370. interference graph, and assigning homes, but the graph coloring
  4371. algorithm itself does not change.
  4372. \subsection{Liveness Analysis}
  4373. \label{sec:liveness-analysis-r2}
  4374. \index{liveness analysis}
  4375. Recall that for $R_1$ we implemented liveness analysis for a single
  4376. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4377. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4378. produces many basic blocks arranged in a control-flow graph. The first
  4379. question we need to consider is: what order should we process the
  4380. basic blocks? Recall that to perform liveness analysis, we need to
  4381. know the live-after set. If a basic block has no successor blocks
  4382. (i.e. no out-edges in the control flow graph), then it has an empty
  4383. live-after set and we can immediately apply liveness analysis to
  4384. it. If a basic block has some successors, then we need to complete
  4385. liveness analysis on those blocks first. Furthermore, we know that
  4386. the control flow graph does not contain any cycles because $R_2$ does
  4387. not include loops
  4388. %
  4389. \footnote{If we were to add loops to the language, then the CFG could
  4390. contain cycles and we would instead need to use the classic worklist
  4391. algorithm for computing the fixed point of the liveness
  4392. analysis~\citep{Aho:1986qf}.}.
  4393. %
  4394. Returning to the question of what order should we process the basic
  4395. blocks, the answer is reverse topological order. We recommend using
  4396. the \code{tsort} (topological sort) and \code{transpose} functions of
  4397. the Racket \code{graph} package to obtain this ordering.
  4398. \index{topological order}
  4399. \index{topological sort}
  4400. The next question is how to compute the live-after set of a block
  4401. given the live-before sets of all its successor blocks. (There can be
  4402. more than one because of conditional jumps.) During compilation we do
  4403. not know which way a conditional jump will go, so we do not know which
  4404. of the successor's live-before set to use. The solution to this
  4405. challenge is based on the observation that there is no harm to the
  4406. correctness of the compiler if we classify more variables as live than
  4407. the ones that are truly live during a particular execution of the
  4408. block. Thus, we can take the union of the live-before sets from all
  4409. the successors to be the live-after set for the block. Once we have
  4410. computed the live-after set, we can proceed to perform liveness
  4411. analysis on the block just as we did in
  4412. Section~\ref{sec:liveness-analysis-r1}.
  4413. The helper functions for computing the variables in an instruction's
  4414. argument and for computing the variables read-from ($R$) or written-to
  4415. ($W$) by an instruction need to be updated to handle the new kinds of
  4416. arguments and instructions in x86$_1$.
  4417. \subsection{Build Interference}
  4418. \label{sec:build-interference-r2}
  4419. Many of the new instructions in x86$_1$ can be handled in the same way
  4420. as the instructions in x86$_0$. Thus, if your code was already quite
  4421. general, it will not need to be changed to handle the new
  4422. instructions. If you code is not general enough, I recommend that you
  4423. change your code to be more general. For example, you can factor out
  4424. the computing of the the read and write sets for each kind of
  4425. instruction into two auxiliary functions.
  4426. Note that the \key{movzbq} instruction requires some special care,
  4427. just like the \key{movq} instruction. See rule number 3 in
  4428. Section~\ref{sec:build-interference}.
  4429. %% \subsection{Assign Homes}
  4430. %% \label{sec:assign-homes-r2}
  4431. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4432. %% to be updated to handle the \key{if} statement, simply by recursively
  4433. %% processing the child nodes. Hopefully your code already handles the
  4434. %% other new instructions, but if not, you can generalize your code.
  4435. \begin{exercise}\normalfont
  4436. Update the \code{register-allocation} pass so that it works for $R_2$
  4437. and test your compiler using your previously created programs on the
  4438. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4439. \end{exercise}
  4440. \section{Patch Instructions}
  4441. The second argument of the \key{cmpq} instruction must not be an
  4442. immediate value (such as an integer). So if you are comparing two
  4443. immediates, we recommend inserting a \key{movq} instruction to put the
  4444. second argument in \key{rax}.
  4445. %
  4446. The second argument of the \key{movzbq} must be a register.
  4447. %
  4448. There are no special restrictions on the x86 instructions \key{JmpIf}
  4449. and \key{Jmp}.
  4450. \begin{exercise}\normalfont
  4451. Update \code{patch-instructions} to handle the new x86 instructions.
  4452. Test your compiler using your previously created programs on the
  4453. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4454. \end{exercise}
  4455. \section{An Example Translation}
  4456. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4457. $R_2$ translated to x86, showing the results of
  4458. \code{explicate-control}, \code{select-instructions}, and the final
  4459. x86 assembly code.
  4460. \begin{figure}[tbp]
  4461. \begin{tabular}{lll}
  4462. \begin{minipage}{0.5\textwidth}
  4463. % s1_20.rkt
  4464. \begin{lstlisting}
  4465. (if (eq? (read) 1) 42 0)
  4466. \end{lstlisting}
  4467. $\Downarrow$
  4468. \begin{lstlisting}
  4469. start:
  4470. tmp7951 = (read);
  4471. if (eq? tmp7951 1) then
  4472. goto block7952;
  4473. else
  4474. goto block7953;
  4475. block7952:
  4476. return 42;
  4477. block7953:
  4478. return 0;
  4479. \end{lstlisting}
  4480. $\Downarrow$
  4481. \begin{lstlisting}
  4482. start:
  4483. callq read_int
  4484. movq %rax, tmp7951
  4485. cmpq $1, tmp7951
  4486. je block7952
  4487. jmp block7953
  4488. block7953:
  4489. movq $0, %rax
  4490. jmp conclusion
  4491. block7952:
  4492. movq $42, %rax
  4493. jmp conclusion
  4494. \end{lstlisting}
  4495. \end{minipage}
  4496. &
  4497. $\Rightarrow\qquad$
  4498. \begin{minipage}{0.4\textwidth}
  4499. \begin{lstlisting}
  4500. start:
  4501. callq read_int
  4502. movq %rax, %rcx
  4503. cmpq $1, %rcx
  4504. je block7952
  4505. jmp block7953
  4506. block7953:
  4507. movq $0, %rax
  4508. jmp conclusion
  4509. block7952:
  4510. movq $42, %rax
  4511. jmp conclusion
  4512. .globl main
  4513. main:
  4514. pushq %rbp
  4515. movq %rsp, %rbp
  4516. pushq %r13
  4517. pushq %r12
  4518. pushq %rbx
  4519. pushq %r14
  4520. subq $0, %rsp
  4521. jmp start
  4522. conclusion:
  4523. addq $0, %rsp
  4524. popq %r14
  4525. popq %rbx
  4526. popq %r12
  4527. popq %r13
  4528. popq %rbp
  4529. retq
  4530. \end{lstlisting}
  4531. \end{minipage}
  4532. \end{tabular}
  4533. \caption{Example compilation of an \key{if} expression to x86.}
  4534. \label{fig:if-example-x86}
  4535. \end{figure}
  4536. \begin{figure}[p]
  4537. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4538. \node (R2) at (0,2) {\large $R_2$};
  4539. \node (R2-2) at (3,2) {\large $R_2$};
  4540. \node (R2-3) at (6,2) {\large $R_2$};
  4541. \node (R2-4) at (9,2) {\large $R_2$};
  4542. \node (R2-5) at (9,0) {\large $R_2$};
  4543. \node (C1-1) at (3,-2) {\large $C_1$};
  4544. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4545. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4546. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4547. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4548. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4549. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4550. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4551. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4552. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4553. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4554. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4555. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4556. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4557. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4558. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4559. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4560. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4561. \end{tikzpicture}
  4562. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4563. \label{fig:R2-passes}
  4564. \end{figure}
  4565. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4566. compilation of $R_2$.
  4567. \section{Challenge: Optimize and Remove Jumps}
  4568. \label{sec:opt-jumps}
  4569. Recall that in the example output of \code{explicate-control} in
  4570. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4571. \code{block60} are trivial blocks, they do nothing but jump to another
  4572. block. The first goal of this challenge assignment is to remove those
  4573. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4574. \code{explicate-control} on the left and shows the result of bypassing
  4575. the trivial blocks on the right. Let us focus on \code{block61}. The
  4576. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4577. \code{block55}. The optimized code on the right of
  4578. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4579. \code{then} branch jumping directly to \code{block55}. The story is
  4580. similar for the \code{else} branch, as well as for the two branches in
  4581. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4582. have been optimized in this way, there are no longer any jumps to
  4583. blocks \code{block57} through \code{block60}, so they can be removed.
  4584. \begin{figure}[tbp]
  4585. \begin{tabular}{lll}
  4586. \begin{minipage}{0.4\textwidth}
  4587. \begin{lstlisting}
  4588. block62:
  4589. tmp54 = (read);
  4590. if (eq? tmp54 2) then
  4591. goto block59;
  4592. else
  4593. goto block60;
  4594. block61:
  4595. tmp53 = (read);
  4596. if (eq? tmp53 0) then
  4597. goto block57;
  4598. else
  4599. goto block58;
  4600. block60:
  4601. goto block56;
  4602. block59:
  4603. goto block55;
  4604. block58:
  4605. goto block56;
  4606. block57:
  4607. goto block55;
  4608. block56:
  4609. return (+ 700 77);
  4610. block55:
  4611. return (+ 10 32);
  4612. start:
  4613. tmp52 = (read);
  4614. if (eq? tmp52 1) then
  4615. goto block61;
  4616. else
  4617. goto block62;
  4618. \end{lstlisting}
  4619. \end{minipage}
  4620. &
  4621. $\Rightarrow$
  4622. &
  4623. \begin{minipage}{0.55\textwidth}
  4624. \begin{lstlisting}
  4625. block62:
  4626. tmp54 = (read);
  4627. if (eq? tmp54 2) then
  4628. goto block55;
  4629. else
  4630. goto block56;
  4631. block61:
  4632. tmp53 = (read);
  4633. if (eq? tmp53 0) then
  4634. goto block55;
  4635. else
  4636. goto block56;
  4637. block56:
  4638. return (+ 700 77);
  4639. block55:
  4640. return (+ 10 32);
  4641. start:
  4642. tmp52 = (read);
  4643. if (eq? tmp52 1) then
  4644. goto block61;
  4645. else
  4646. goto block62;
  4647. \end{lstlisting}
  4648. \end{minipage}
  4649. \end{tabular}
  4650. \caption{Optimize jumps by removing trivial blocks.}
  4651. \label{fig:optimize-jumps}
  4652. \end{figure}
  4653. The name of this pass is \code{optimize-jumps}. We recommend
  4654. implementing this pass in two phases. The first phrase builds a hash
  4655. table that maps labels to possibly improved labels. The second phase
  4656. changes the target of each \code{goto} to use the improved label. If
  4657. the label is for a trivial block, then the hash table should map the
  4658. label to the first non-trivial block that can be reached from this
  4659. label by jumping through trivial blocks. If the label is for a
  4660. non-trivial block, then the hash table should map the label to itself;
  4661. we do not want to change jumps to non-trivial blocks.
  4662. The first phase can be accomplished by constructing an empty hash
  4663. table, call it \code{short-cut}, and then iterating over the control
  4664. flow graph. Each time you encouter a block that is just a \code{goto},
  4665. then update the hash table, mapping the block's source to the target
  4666. of the \code{goto}. Also, the hash table may already have mapped some
  4667. labels to the block's source, to you must iterate through the hash
  4668. table and update all of those so that they instead map to the target
  4669. of the \code{goto}.
  4670. For the second phase, we recommend iterating through the $\Tail$ of
  4671. each block in the program, updating the target of every \code{goto}
  4672. according to the mapping in \code{short-cut}.
  4673. \begin{exercise}\normalfont
  4674. Implement the \code{optimize-jumps} pass as a transformation from
  4675. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4676. Check that \code{optimize-jumps} removes trivial blocks in a few
  4677. example programs. Then check that your compiler still passes all of
  4678. your tests.
  4679. \end{exercise}
  4680. There is another opportunity for optimizing jumps that is apparent in
  4681. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4682. end with a jump to \code{block7953} and there are no other jumps to
  4683. \code{block7953} in the rest of the program. In this situation we can
  4684. avoid the runtime overhead of this jump by merging \code{block7953}
  4685. into the preceeding block, in this case the \code{start} block.
  4686. Figure~\ref{fig:remove-jumps} shows the output of
  4687. \code{select-instructions} on the left and the result of this
  4688. optimization on the right.
  4689. \begin{figure}[tbp]
  4690. \begin{tabular}{lll}
  4691. \begin{minipage}{0.5\textwidth}
  4692. % s1_20.rkt
  4693. \begin{lstlisting}
  4694. start:
  4695. callq read_int
  4696. movq %rax, tmp7951
  4697. cmpq $1, tmp7951
  4698. je block7952
  4699. jmp block7953
  4700. block7953:
  4701. movq $0, %rax
  4702. jmp conclusion
  4703. block7952:
  4704. movq $42, %rax
  4705. jmp conclusion
  4706. \end{lstlisting}
  4707. \end{minipage}
  4708. &
  4709. $\Rightarrow\qquad$
  4710. \begin{minipage}{0.4\textwidth}
  4711. \begin{lstlisting}
  4712. start:
  4713. callq read_int
  4714. movq %rax, tmp7951
  4715. cmpq $1, tmp7951
  4716. je block7952
  4717. movq $0, %rax
  4718. jmp conclusion
  4719. block7952:
  4720. movq $42, %rax
  4721. jmp conclusion
  4722. \end{lstlisting}
  4723. \end{minipage}
  4724. \end{tabular}
  4725. \caption{Merging basic blocks by removing unnecessary jumps.}
  4726. \label{fig:remove-jumps}
  4727. \end{figure}
  4728. \begin{exercise}\normalfont
  4729. Implement a pass named \code{remove-jumps} that merges basic blocks
  4730. into their preceeding basic block, when there is only one preceeding
  4731. block. The pass should translate from psuedo $x86_1$ to pseudo
  4732. $x86_1$ and it should come immediately after
  4733. \code{select-instructions}. Check that \code{remove-jumps}
  4734. accomplishes the goal of merging basic blocks on several test
  4735. programs and check that your compiler passes all of your tests.
  4736. \end{exercise}
  4737. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4738. \chapter{Tuples and Garbage Collection}
  4739. \label{ch:tuples}
  4740. \index{tuple}
  4741. \index{vector}
  4742. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4743. add simple structures. \\ --Jeremy}
  4744. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4745. things to discuss in this chapter. \\ --Jeremy}
  4746. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4747. all the IR grammars are spelled out! \\ --Jeremy}
  4748. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4749. but keep type annotations on vector creation and local variables, function
  4750. parameters, etc. \\ --Jeremy}
  4751. \margincomment{\scriptsize Be more explicit about how to deal with
  4752. the root stack. \\ --Jeremy}
  4753. In this chapter we study the implementation of mutable tuples (called
  4754. ``vectors'' in Racket). This language feature is the first to use the
  4755. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  4756. indefinite, that is, a tuple lives forever from the programmer's
  4757. viewpoint. Of course, from an implementer's viewpoint, it is important
  4758. to reclaim the space associated with a tuple when it is no longer
  4759. needed, which is why we also study \emph{garbage collection}
  4760. \emph{garbage collection}
  4761. techniques in this chapter.
  4762. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4763. interpreter and type checker. The $R_3$ language extends the $R_2$
  4764. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4765. \code{void} value. The reason for including the later is that the
  4766. \code{vector-set!} operation returns a value of type
  4767. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4768. called the \code{Unit} type in the programming languages
  4769. literature. Racket's \code{Void} type is inhabited by a single value
  4770. \code{void} which corresponds to \code{unit} or \code{()} in the
  4771. literature~\citep{Pierce:2002hj}.}.
  4772. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4773. copying live objects back and forth between two halves of the
  4774. heap. The garbage collector requires coordination with the compiler so
  4775. that it can see all of the \emph{root} pointers, that is, pointers in
  4776. registers or on the procedure call stack.
  4777. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4778. discuss all the necessary changes and additions to the compiler
  4779. passes, including a new compiler pass named \code{expose-allocation}.
  4780. \section{The $R_3$ Language}
  4781. \label{sec:r3}
  4782. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4783. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4784. $R_3$ language includes three new forms: \code{vector} for creating a
  4785. tuple, \code{vector-ref} for reading an element of a tuple, and
  4786. \code{vector-set!} for writing to an element of a tuple. The program
  4787. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4788. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4789. the 3-tuple, demonstrating that tuples are first-class values. The
  4790. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4791. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4792. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4793. 1-tuple. So the result of the program is \code{42}.
  4794. \begin{figure}[tbp]
  4795. \centering
  4796. \fbox{
  4797. \begin{minipage}{0.96\textwidth}
  4798. \[
  4799. \begin{array}{lcl}
  4800. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4801. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4802. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4803. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4804. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4805. \mid (\key{and}\;\Exp\;\Exp)
  4806. \mid (\key{or}\;\Exp\;\Exp)
  4807. \mid (\key{not}\;\Exp) } \\
  4808. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4809. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4810. &\mid& (\key{vector}\;\Exp\ldots)
  4811. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4812. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4813. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4814. R_3 &::=& \Exp
  4815. \end{array}
  4816. \]
  4817. \end{minipage}
  4818. }
  4819. \caption{The concrete syntax of $R_3$, extending $R_2$
  4820. (Figure~\ref{fig:r2-concrete-syntax}).}
  4821. \label{fig:r3-concrete-syntax}
  4822. \end{figure}
  4823. \begin{figure}[tbp]
  4824. \begin{lstlisting}
  4825. (let ([t (vector 40 #t (vector 2))])
  4826. (if (vector-ref t 1)
  4827. (+ (vector-ref t 0)
  4828. (vector-ref (vector-ref t 2) 0))
  4829. 44))
  4830. \end{lstlisting}
  4831. \caption{Example program that creates tuples and reads from them.}
  4832. \label{fig:vector-eg}
  4833. \end{figure}
  4834. \begin{figure}[tp]
  4835. \centering
  4836. \fbox{
  4837. \begin{minipage}{0.96\textwidth}
  4838. \[
  4839. \begin{array}{lcl}
  4840. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4841. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4842. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4843. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4844. &\mid& \gray{ \BOOL{\itm{bool}}
  4845. \mid \AND{\Exp}{\Exp} }\\
  4846. &\mid& \gray{ \OR{\Exp}{\Exp}
  4847. \mid \NOT{\Exp} } \\
  4848. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  4849. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4850. &\mid& \VECTOR{\Exp} \\
  4851. &\mid& \VECREF{\Exp}{\Int}\\
  4852. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4853. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  4854. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4855. \end{array}
  4856. \]
  4857. \end{minipage}
  4858. }
  4859. \caption{The abstract syntax of $R_3$.}
  4860. \label{fig:r3-syntax}
  4861. \end{figure}
  4862. \index{allocate}
  4863. \index{heap allocate}
  4864. Tuples are our first encounter with heap-allocated data, which raises
  4865. several interesting issues. First, variable binding performs a
  4866. shallow-copy when dealing with tuples, which means that different
  4867. variables can refer to the same tuple, that is, different variables
  4868. can be \emph{aliases} for the same entity. Consider the following
  4869. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4870. Thus, the mutation through \code{t2} is visible when referencing the
  4871. tuple from \code{t1}, so the result of this program is \code{42}.
  4872. \index{alias}\index{mutation}
  4873. \begin{center}
  4874. \begin{minipage}{0.96\textwidth}
  4875. \begin{lstlisting}
  4876. (let ([t1 (vector 3 7)])
  4877. (let ([t2 t1])
  4878. (let ([_ (vector-set! t2 0 42)])
  4879. (vector-ref t1 0))))
  4880. \end{lstlisting}
  4881. \end{minipage}
  4882. \end{center}
  4883. The next issue concerns the lifetime of tuples. Of course, they are
  4884. created by the \code{vector} form, but when does their lifetime end?
  4885. Notice that $R_3$ does not include an operation for deleting
  4886. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  4887. of static scoping. For example, the following program returns
  4888. \code{42} even though the variable \code{w} goes out of scope prior to
  4889. the \code{vector-ref} that reads from the vector it was bound to.
  4890. \begin{center}
  4891. \begin{minipage}{0.96\textwidth}
  4892. \begin{lstlisting}
  4893. (let ([v (vector (vector 44))])
  4894. (let ([x (let ([w (vector 42)])
  4895. (let ([_ (vector-set! v 0 w)])
  4896. 0))])
  4897. (+ x (vector-ref (vector-ref v 0) 0))))
  4898. \end{lstlisting}
  4899. \end{minipage}
  4900. \end{center}
  4901. From the perspective of programmer-observable behavior, tuples live
  4902. forever. Of course, if they really lived forever, then many programs
  4903. would run out of memory.\footnote{The $R_3$ language does not have
  4904. looping or recursive functions, so it is nigh impossible to write a
  4905. program in $R_3$ that will run out of memory. However, we add
  4906. recursive functions in the next Chapter!} A Racket implementation
  4907. must therefore perform automatic garbage collection.
  4908. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4909. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4910. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4911. operations in Racket. One subtle point is that the \code{vector-set!}
  4912. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4913. can be passed around just like other values inside an $R_3$ program
  4914. and a \code{\#<void>} value can be compared for equality with another
  4915. \code{\#<void>} value. However, there are no other operations specific
  4916. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  4917. the \code{void?} predicate that returns \code{\#t} when applied to
  4918. \code{\#<void>} and \code{\#f} otherwise.
  4919. \begin{figure}[tbp]
  4920. \begin{lstlisting}
  4921. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4922. (define (interp-op op)
  4923. (match op
  4924. ...
  4925. ['vector vector]
  4926. ['vector-ref vector-ref]
  4927. ['vector-set! vector-set!]
  4928. [else (error 'interp-op "unknown operator")]))
  4929. (define (interp-exp env)
  4930. (lambda (e)
  4931. (define recur (interp-exp env))
  4932. (match e
  4933. ...
  4934. )))
  4935. (define (interp-R3 p)
  4936. (match p
  4937. [(Program '() e)
  4938. ((interp-exp '()) e)]
  4939. ))
  4940. \end{lstlisting}
  4941. \caption{Interpreter for the $R_3$ language.}
  4942. \label{fig:interp-R3}
  4943. \end{figure}
  4944. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4945. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4946. need to know which variables contain pointers into the heap, that is,
  4947. which variables contain vectors. Also, when allocating a vector, we
  4948. need to know which elements of the vector are pointers. We can obtain
  4949. this information during type checking. The type checker in
  4950. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4951. expression, it also wraps every sub-expression $e$ with the form
  4952. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4953. Subsequently, in the \code{uncover-locals} pass
  4954. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4955. propagated to all variables (including the temporaries generated by
  4956. \code{remove-complex-opera*}).
  4957. \begin{figure}[tp]
  4958. \begin{lstlisting}
  4959. (define (type-check-exp env)
  4960. (lambda (e)
  4961. (define recur (type-check-exp env))
  4962. (match e
  4963. ...
  4964. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4965. [(Prim 'vector es)
  4966. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  4967. (let ([t `(Vector ,@t*)])
  4968. (values (HasType (Prim 'vector e*) t) t))]
  4969. [(Prim 'vector-ref (list e (Int i)))
  4970. (define-values (e^ t) (recur e))
  4971. (match t
  4972. [`(Vector ,ts ...)
  4973. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4974. (error 'type-check-exp "invalid index ~a" i))
  4975. (let ([t (list-ref ts i)])
  4976. (values
  4977. (HasType (Prim 'vector-ref
  4978. (list e^ (HasType (Int i) 'Integer)))
  4979. t)
  4980. t))]
  4981. [else (error "expected a vector in vector-ref, not" t)])]
  4982. [(Prim 'eq? (list e1 e2))
  4983. (define-values (e1^ T1) (recur e1))
  4984. (define-values (e2^ T2) (recur e2))
  4985. (unless (equal? T1 T2)
  4986. (error "arguments of eq? must have the same type, but are not"
  4987. (list T1 T2)))
  4988. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4989. ...
  4990. )))
  4991. \end{lstlisting}
  4992. \caption{Type checker for the $R_3$ language.}
  4993. \label{fig:typecheck-R3}
  4994. \end{figure}
  4995. \section{Garbage Collection}
  4996. \label{sec:GC}
  4997. Here we study a relatively simple algorithm for garbage collection
  4998. that is the basis of state-of-the-art garbage
  4999. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5000. particular, we describe a two-space copying
  5001. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5002. perform the
  5003. copy~\citep{Cheney:1970aa}.
  5004. \index{copying collector}
  5005. \index{two-space copying collector}
  5006. Figure~\ref{fig:copying-collector} gives a
  5007. coarse-grained depiction of what happens in a two-space collector,
  5008. showing two time steps, prior to garbage collection (on the top) and
  5009. after garbage collection (on the bottom). In a two-space collector,
  5010. the heap is divided into two parts named the FromSpace and the
  5011. ToSpace. Initially, all allocations go to the FromSpace until there is
  5012. not enough room for the next allocation request. At that point, the
  5013. garbage collector goes to work to make more room.
  5014. \index{ToSpace}
  5015. \index{FromSpace}
  5016. The garbage collector must be careful not to reclaim tuples that will
  5017. be used by the program in the future. Of course, it is impossible in
  5018. general to predict what a program will do, but we can over approximate
  5019. the will-be-used tuples by preserving all tuples that could be
  5020. accessed by \emph{any} program given the current computer state. A
  5021. program could access any tuple whose address is in a register or on
  5022. the procedure call stack. These addresses are called the \emph{root
  5023. set}\index{root set}. In addition, a program could access any tuple that is
  5024. transitively reachable from the root set. Thus, it is safe for the
  5025. garbage collector to reclaim the tuples that are not reachable in this
  5026. way.
  5027. So the goal of the garbage collector is twofold:
  5028. \begin{enumerate}
  5029. \item preserve all tuple that are reachable from the root set via a
  5030. path of pointers, that is, the \emph{live} tuples, and
  5031. \item reclaim the memory of everything else, that is, the
  5032. \emph{garbage}.
  5033. \end{enumerate}
  5034. A copying collector accomplishes this by copying all of the live
  5035. objects from the FromSpace into the ToSpace and then performs a slight
  5036. of hand, treating the ToSpace as the new FromSpace and the old
  5037. FromSpace as the new ToSpace. In the example of
  5038. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5039. root set, one in a register and two on the stack. All of the live
  5040. objects have been copied to the ToSpace (the right-hand side of
  5041. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5042. pointer relationships. For example, the pointer in the register still
  5043. points to a 2-tuple whose first element is a 3-tuple and whose second
  5044. element is a 2-tuple. There are four tuples that are not reachable
  5045. from the root set and therefore do not get copied into the ToSpace.
  5046. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5047. created by a well-typed program in $R_3$ because it contains a
  5048. cycle. However, creating cycles will be possible once we get to $R_6$.
  5049. We design the garbage collector to deal with cycles to begin with so
  5050. we will not need to revisit this issue.
  5051. \begin{figure}[tbp]
  5052. \centering
  5053. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5054. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5055. \caption{A copying collector in action.}
  5056. \label{fig:copying-collector}
  5057. \end{figure}
  5058. There are many alternatives to copying collectors (and their bigger
  5059. siblings, the generational collectors) when its comes to garbage
  5060. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5061. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5062. collectors are that allocation is fast (just a comparison and pointer
  5063. increment), there is no fragmentation, cyclic garbage is collected,
  5064. and the time complexity of collection only depends on the amount of
  5065. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5066. main disadvantages of a two-space copying collector is that it uses a
  5067. lot of space and takes a long time to perform the copy, though these
  5068. problems are ameliorated in generational collectors. Racket and
  5069. Scheme programs tend to allocate many small objects and generate a lot
  5070. of garbage, so copying and generational collectors are a good fit.
  5071. Garbage collection is an active research topic, especially concurrent
  5072. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5073. developing new techniques and revisiting old
  5074. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5075. meet every year at the International Symposium on Memory Management to
  5076. present these findings.
  5077. \subsection{Graph Copying via Cheney's Algorithm}
  5078. \label{sec:cheney}
  5079. \index{Cheney's algorithm}
  5080. Let us take a closer look at the copying of the live objects. The
  5081. allocated objects and pointers can be viewed as a graph and we need to
  5082. copy the part of the graph that is reachable from the root set. To
  5083. make sure we copy all of the reachable vertices in the graph, we need
  5084. an exhaustive graph traversal algorithm, such as depth-first search or
  5085. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5086. such algorithms take into account the possibility of cycles by marking
  5087. which vertices have already been visited, so as to ensure termination
  5088. of the algorithm. These search algorithms also use a data structure
  5089. such as a stack or queue as a to-do list to keep track of the vertices
  5090. that need to be visited. We shall use breadth-first search and a trick
  5091. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5092. and copying tuples into the ToSpace.
  5093. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5094. copy progresses. The queue is represented by a chunk of contiguous
  5095. memory at the beginning of the ToSpace, using two pointers to track
  5096. the front and the back of the queue. The algorithm starts by copying
  5097. all tuples that are immediately reachable from the root set into the
  5098. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5099. old tuple to indicate that it has been visited. We discuss how this
  5100. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5101. pointers inside the copied tuples in the queue still point back to the
  5102. FromSpace. Once the initial queue has been created, the algorithm
  5103. enters a loop in which it repeatedly processes the tuple at the front
  5104. of the queue and pops it off the queue. To process a tuple, the
  5105. algorithm copies all the tuple that are directly reachable from it to
  5106. the ToSpace, placing them at the back of the queue. The algorithm then
  5107. updates the pointers in the popped tuple so they point to the newly
  5108. copied tuples.
  5109. \begin{figure}[tbp]
  5110. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5111. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5112. \label{fig:cheney}
  5113. \end{figure}
  5114. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5115. tuple whose second element is $42$ to the back of the queue. The other
  5116. pointer goes to a tuple that has already been copied, so we do not
  5117. need to copy it again, but we do need to update the pointer to the new
  5118. location. This can be accomplished by storing a \emph{forwarding
  5119. pointer} to the new location in the old tuple, back when we initially
  5120. copied the tuple into the ToSpace. This completes one step of the
  5121. algorithm. The algorithm continues in this way until the front of the
  5122. queue is empty, that is, until the front catches up with the back.
  5123. \subsection{Data Representation}
  5124. \label{sec:data-rep-gc}
  5125. The garbage collector places some requirements on the data
  5126. representations used by our compiler. First, the garbage collector
  5127. needs to distinguish between pointers and other kinds of data. There
  5128. are several ways to accomplish this.
  5129. \begin{enumerate}
  5130. \item Attached a tag to each object that identifies what type of
  5131. object it is~\citep{McCarthy:1960dz}.
  5132. \item Store different types of objects in different
  5133. regions~\citep{Steele:1977ab}.
  5134. \item Use type information from the program to either generate
  5135. type-specific code for collecting or to generate tables that can
  5136. guide the
  5137. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5138. \end{enumerate}
  5139. Dynamically typed languages, such as Lisp, need to tag objects
  5140. anyways, so option 1 is a natural choice for those languages.
  5141. However, $R_3$ is a statically typed language, so it would be
  5142. unfortunate to require tags on every object, especially small and
  5143. pervasive objects like integers and Booleans. Option 3 is the
  5144. best-performing choice for statically typed languages, but comes with
  5145. a relatively high implementation complexity. To keep this chapter
  5146. within a 2-week time budget, we recommend a combination of options 1
  5147. and 2, using separate strategies for the stack and the heap.
  5148. Regarding the stack, we recommend using a separate stack for pointers,
  5149. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5150. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5151. is, when a local variable needs to be spilled and is of type
  5152. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5153. stack instead of the normal procedure call stack. Furthermore, we
  5154. always spill vector-typed variables if they are live during a call to
  5155. the collector, thereby ensuring that no pointers are in registers
  5156. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5157. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5158. the data layout using a root stack. The root stack contains the two
  5159. pointers from the regular stack and also the pointer in the second
  5160. register.
  5161. \begin{figure}[tbp]
  5162. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5163. \caption{Maintaining a root stack to facilitate garbage collection.}
  5164. \label{fig:shadow-stack}
  5165. \end{figure}
  5166. The problem of distinguishing between pointers and other kinds of data
  5167. also arises inside of each tuple on the heap. We solve this problem by
  5168. attaching a tag, an extra 64-bits, to each
  5169. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5170. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5171. that we have drawn the bits in a big-endian way, from right-to-left,
  5172. with bit location 0 (the least significant bit) on the far right,
  5173. which corresponds to the direction of the x86 shifting instructions
  5174. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5175. is dedicated to specifying which elements of the tuple are pointers,
  5176. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5177. indicates there is a pointer and a 0 bit indicates some other kind of
  5178. data. The pointer mask starts at bit location 7. We have limited
  5179. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5180. the pointer mask. The tag also contains two other pieces of
  5181. information. The length of the tuple (number of elements) is stored in
  5182. bits location 1 through 6. Finally, the bit at location 0 indicates
  5183. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5184. value 1, then this tuple has not yet been copied. If the bit has
  5185. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5186. of a pointer are always zero anyways because our tuples are 8-byte
  5187. aligned.)
  5188. \begin{figure}[tbp]
  5189. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5190. \caption{Representation of tuples in the heap.}
  5191. \label{fig:tuple-rep}
  5192. \end{figure}
  5193. \subsection{Implementation of the Garbage Collector}
  5194. \label{sec:organize-gz}
  5195. \index{prelude}
  5196. An implementation of the copying collector is provided in the
  5197. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5198. interface to the garbage collector that is used by the compiler. The
  5199. \code{initialize} function creates the FromSpace, ToSpace, and root
  5200. stack and should be called in the prelude of the \code{main}
  5201. function. The \code{initialize} function puts the address of the
  5202. beginning of the FromSpace into the global variable
  5203. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5204. the address that is 1-past the last element of the FromSpace. (We use
  5205. half-open intervals to represent chunks of
  5206. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5207. points to the first element of the root stack.
  5208. As long as there is room left in the FromSpace, your generated code
  5209. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5210. %
  5211. The amount of room left in FromSpace is the difference between the
  5212. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5213. function should be called when there is not enough room left in the
  5214. FromSpace for the next allocation. The \code{collect} function takes
  5215. a pointer to the current top of the root stack (one past the last item
  5216. that was pushed) and the number of bytes that need to be
  5217. allocated. The \code{collect} function performs the copying collection
  5218. and leaves the heap in a state such that the next allocation will
  5219. succeed.
  5220. \begin{figure}[tbp]
  5221. \begin{lstlisting}
  5222. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5223. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5224. int64_t* free_ptr;
  5225. int64_t* fromspace_begin;
  5226. int64_t* fromspace_end;
  5227. int64_t** rootstack_begin;
  5228. \end{lstlisting}
  5229. \caption{The compiler's interface to the garbage collector.}
  5230. \label{fig:gc-header}
  5231. \end{figure}
  5232. %% \begin{exercise}
  5233. %% In the file \code{runtime.c} you will find the implementation of
  5234. %% \code{initialize} and a partial implementation of \code{collect}.
  5235. %% The \code{collect} function calls another function, \code{cheney},
  5236. %% to perform the actual copy, and that function is left to the reader
  5237. %% to implement. The following is the prototype for \code{cheney}.
  5238. %% \begin{lstlisting}
  5239. %% static void cheney(int64_t** rootstack_ptr);
  5240. %% \end{lstlisting}
  5241. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5242. %% rootstack (which is an array of pointers). The \code{cheney} function
  5243. %% also communicates with \code{collect} through the global
  5244. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5245. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5246. %% the ToSpace:
  5247. %% \begin{lstlisting}
  5248. %% static int64_t* tospace_begin;
  5249. %% static int64_t* tospace_end;
  5250. %% \end{lstlisting}
  5251. %% The job of the \code{cheney} function is to copy all the live
  5252. %% objects (reachable from the root stack) into the ToSpace, update
  5253. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5254. %% update the root stack so that it points to the objects in the
  5255. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5256. %% and ToSpace.
  5257. %% \end{exercise}
  5258. %% \section{Compiler Passes}
  5259. %% \label{sec:code-generation-gc}
  5260. The introduction of garbage collection has a non-trivial impact on our
  5261. compiler passes. We introduce two new compiler passes named
  5262. \code{expose-allocation} and \code{uncover-locals}. We make
  5263. significant changes to \code{select-instructions},
  5264. \code{build-interference}, \code{allocate-registers}, and
  5265. \code{print-x86} and make minor changes in severl more passes. The
  5266. following program will serve as our running example. It creates two
  5267. tuples, one nested inside the other. Both tuples have length one. The
  5268. program accesses the element in the inner tuple tuple via two vector
  5269. references.
  5270. % tests/s2_17.rkt
  5271. \begin{lstlisting}
  5272. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5273. \end{lstlisting}
  5274. \section{Shrink}
  5275. \label{sec:shrink-R3}
  5276. Recall that the \code{shrink} pass translates the primitives operators
  5277. into a smaller set of primitives. Because this pass comes after type
  5278. checking, but before the passes that require the type information in
  5279. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5280. to wrap \code{HasType} around each AST node that it generates.
  5281. \section{Expose Allocation}
  5282. \label{sec:expose-allocation}
  5283. The pass \code{expose-allocation} lowers the \code{vector} creation
  5284. form into a conditional call to the collector followed by the
  5285. allocation. We choose to place the \code{expose-allocation} pass
  5286. before \code{remove-complex-opera*} because the code generated by
  5287. \code{expose-allocation} contains complex operands. We also place
  5288. \code{expose-allocation} before \code{explicate-control} because
  5289. \code{expose-allocation} introduces new variables using \code{let},
  5290. but \code{let} is gone after \code{explicate-control}.
  5291. The output of \code{expose-allocation} is a language $R'_3$ that
  5292. extends $R_3$ with the three new forms that we use in the translation
  5293. of the \code{vector} form.
  5294. \[
  5295. \begin{array}{lcl}
  5296. \Exp &::=& \cdots
  5297. \mid (\key{collect} \,\itm{int})
  5298. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5299. \mid (\key{global-value} \,\itm{name})
  5300. \end{array}
  5301. \]
  5302. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5303. $n$ bytes. It will become a call to the \code{collect} function in
  5304. \code{runtime.c} in \code{select-instructions}. The
  5305. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5306. \index{allocate}
  5307. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5308. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5309. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5310. a global variable, such as \code{free\_ptr}.
  5311. In the following, we show the transformation for the \code{vector}
  5312. form into 1) a sequence of let-bindings for the initializing
  5313. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5314. \code{allocate}, and 4) the initialization of the vector. In the
  5315. following, \itm{len} refers to the length of the vector and
  5316. \itm{bytes} is how many total bytes need to be allocated for the
  5317. vector, which is 8 for the tag plus \itm{len} times 8.
  5318. \begin{lstlisting}
  5319. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5320. |$\Longrightarrow$|
  5321. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5322. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5323. (global-value fromspace_end))
  5324. (void)
  5325. (collect |\itm{bytes}|))])
  5326. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5327. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5328. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5329. |$v$|) ... )))) ...)
  5330. \end{lstlisting}
  5331. In the above, we suppressed all of the \code{has-type} forms in the
  5332. output for the sake of readability. The placement of the initializing
  5333. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5334. sequence of \code{vector-set!} is important, as those expressions may
  5335. trigger garbage collection and we cannot have an allocated but
  5336. uninitialized tuple on the heap during a collection.
  5337. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5338. \code{expose-allocation} pass on our running example.
  5339. \begin{figure}[tbp]
  5340. % tests/s2_17.rkt
  5341. \begin{lstlisting}
  5342. (vector-ref
  5343. (vector-ref
  5344. (let ([vecinit7976
  5345. (let ([vecinit7972 42])
  5346. (let ([collectret7974
  5347. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5348. (void)
  5349. (collect 16)
  5350. )])
  5351. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5352. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5353. alloc7971)
  5354. )
  5355. )
  5356. )
  5357. ])
  5358. (let ([collectret7978
  5359. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5360. (void)
  5361. (collect 16)
  5362. )])
  5363. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5364. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5365. alloc7975)
  5366. )
  5367. )
  5368. )
  5369. 0)
  5370. 0)
  5371. \end{lstlisting}
  5372. \caption{Output of the \code{expose-allocation} pass, minus
  5373. all of the \code{has-type} forms.}
  5374. \label{fig:expose-alloc-output}
  5375. \end{figure}
  5376. \section{Remove Complex Operands}
  5377. \label{sec:remove-complex-opera-R3}
  5378. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5379. should all be treated as complex operands. A new case for
  5380. \code{HasType} is needed and the case for \code{Prim} needs to be
  5381. handled carefully to prevent the \code{Prim} node from being separated
  5382. from its enclosing \code{HasType}.
  5383. \section{Explicate Control and the $C_2$ language}
  5384. \label{sec:explicate-control-r3}
  5385. \begin{figure}[tbp]
  5386. \fbox{
  5387. \begin{minipage}{0.96\textwidth}
  5388. \small
  5389. \[
  5390. \begin{array}{lcl}
  5391. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5392. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5393. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5394. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5395. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5396. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5397. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5398. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5399. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5400. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5401. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5402. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5403. \end{array}
  5404. \]
  5405. \end{minipage}
  5406. }
  5407. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5408. \label{fig:c2-concrete-syntax}
  5409. \end{figure}
  5410. \begin{figure}[tp]
  5411. \fbox{
  5412. \begin{minipage}{0.96\textwidth}
  5413. \small
  5414. \[
  5415. \begin{array}{lcl}
  5416. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5417. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5418. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5419. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5420. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5421. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5422. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  5423. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  5424. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5425. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5426. \mid (\key{Collect} \,\itm{int}) \\
  5427. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5428. \mid \GOTO{\itm{label}} } \\
  5429. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5430. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5431. \end{array}
  5432. \]
  5433. \end{minipage}
  5434. }
  5435. \caption{The abstract syntax of $C_2$, an extention of $C_1$
  5436. (Figure~\ref{fig:c1-syntax}).}
  5437. \label{fig:c2-syntax}
  5438. \end{figure}
  5439. The output of \code{explicate-control} is a program in the
  5440. intermediate language $C_2$, whose concrete syntax is defined in
  5441. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5442. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5443. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5444. \key{global-value} expressions and the \code{collect} statement. The
  5445. \code{explicate-control} pass can treat these new forms much like the
  5446. other forms.
  5447. \section{Uncover Locals}
  5448. \label{sec:uncover-locals-r3}
  5449. Recall that the \code{explicate-control} function collects all of the
  5450. local variables so that it can store them in the $\itm{info}$ field of
  5451. the \code{Program} structure. Also recall that we need to know the
  5452. types of all the local variables for purposes of identifying the root
  5453. set for the garbage collector. Thus, we create a pass named
  5454. \code{uncover-locals} to collect not just the variables but the
  5455. variables and their types in the form of an alist. Thanks to the
  5456. \code{HasType} nodes, the types are readily available at every
  5457. assignment to a variable. We recommend storing the resulting alist in
  5458. the $\itm{info}$ field of the program, associated with the
  5459. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5460. of the \code{uncover-locals} pass on the running example.
  5461. \begin{figure}[tbp]
  5462. % tests/s2_17.rkt
  5463. \begin{lstlisting}
  5464. locals:
  5465. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5466. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5467. collectret7974 : 'Void, initret7977 : 'Void,
  5468. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5469. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5470. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5471. vecinit7972 : 'Integer, initret7973 : 'Void,
  5472. block91:
  5473. (collect 16)
  5474. goto block89;
  5475. block90:
  5476. collectret7974 = (void);
  5477. goto block89;
  5478. block89:
  5479. alloc7971 = (allocate 1 (Vector Integer));
  5480. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5481. vecinit7976 = alloc7971;
  5482. tmp7982 = (global-value free_ptr);
  5483. tmp7983 = (+ tmp7982 16);
  5484. tmp7984 = (global-value fromspace_end);
  5485. if (< tmp7983 tmp7984) then
  5486. goto block87;
  5487. else
  5488. goto block88;
  5489. block88:
  5490. (collect 16)
  5491. goto block86;
  5492. block87:
  5493. collectret7978 = (void);
  5494. goto block86;
  5495. block86:
  5496. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5497. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5498. tmp7985 = (vector-ref alloc7975 0);
  5499. return (vector-ref tmp7985 0);
  5500. start:
  5501. vecinit7972 = 42;
  5502. tmp7979 = (global-value free_ptr);
  5503. tmp7980 = (+ tmp7979 16);
  5504. tmp7981 = (global-value fromspace_end);
  5505. if (< tmp7980 tmp7981) then
  5506. goto block90;
  5507. else
  5508. goto block91;
  5509. \end{lstlisting}
  5510. \caption{Output of \code{uncover-locals} for the running example.}
  5511. \label{fig:uncover-locals-r3}
  5512. \end{figure}
  5513. \clearpage
  5514. \section{Select Instructions and the x86$_2$ Language}
  5515. \label{sec:select-instructions-gc}
  5516. \index{instruction selection}
  5517. %% void (rep as zero)
  5518. %% allocate
  5519. %% collect (callq collect)
  5520. %% vector-ref
  5521. %% vector-set!
  5522. %% global (postpone)
  5523. In this pass we generate x86 code for most of the new operations that
  5524. were needed to compile tuples, including \code{Allocate},
  5525. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5526. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5527. the later has a different concrete syntax (see
  5528. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5529. \index{x86}
  5530. The \code{vector-ref} and \code{vector-set!} forms translate into
  5531. \code{movq} instructions. (The plus one in the offset is to get past
  5532. the tag at the beginning of the tuple representation.)
  5533. \begin{lstlisting}
  5534. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5535. |$\Longrightarrow$|
  5536. movq |$\itm{vec}'$|, %r11
  5537. movq |$-8(n+1)$|(%r11), |$\itm{lhs'}$|
  5538. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5539. |$\Longrightarrow$|
  5540. movq |$\itm{vec}'$|, %r11
  5541. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5542. movq $0, |$\itm{lhs'}$|
  5543. \end{lstlisting}
  5544. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5545. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5546. register \code{r11} ensures that offset expression
  5547. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5548. removing \code{r11} from consideration by the register allocating.
  5549. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5550. \code{rax}. Then the generated code for \code{vector-set!} would be
  5551. \begin{lstlisting}
  5552. movq |$\itm{vec}'$|, %rax
  5553. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5554. movq $0, |$\itm{lhs}'$|
  5555. \end{lstlisting}
  5556. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5557. \code{patch-instructions} would insert a move through \code{rax}
  5558. as follows.
  5559. \begin{lstlisting}
  5560. movq |$\itm{vec}'$|, %rax
  5561. movq |$\itm{arg}'$|, %rax
  5562. movq %rax, |$8(n+1)$|(%rax)
  5563. movq $0, |$\itm{lhs}'$|
  5564. \end{lstlisting}
  5565. But the above sequence of instructions does not work because we're
  5566. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5567. $\itm{arg}'$) at the same time!
  5568. We compile the \code{allocate} form to operations on the
  5569. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5570. is the next free address in the FromSpace, so we move it into the
  5571. \itm{lhs} and then move it forward by enough space for the tuple being
  5572. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5573. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5574. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5575. how the tag is organized. We recommend using the Racket operations
  5576. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5577. during compilation. The type annotation in the \code{vector} form is
  5578. used to determine the pointer mask region of the tag.
  5579. \begin{lstlisting}
  5580. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5581. |$\Longrightarrow$|
  5582. movq free_ptr(%rip), |$\itm{lhs}'$|
  5583. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5584. movq |$\itm{lhs}'$|, %r11
  5585. movq $|$\itm{tag}$|, 0(%r11)
  5586. \end{lstlisting}
  5587. The \code{collect} form is compiled to a call to the \code{collect}
  5588. function in the runtime. The arguments to \code{collect} are 1) the
  5589. top of the root stack and 2) the number of bytes that need to be
  5590. allocated. We shall use another dedicated register, \code{r15}, to
  5591. store the pointer to the top of the root stack. So \code{r15} is not
  5592. available for use by the register allocator.
  5593. \begin{lstlisting}
  5594. (collect |$\itm{bytes}$|)
  5595. |$\Longrightarrow$|
  5596. movq %r15, %rdi
  5597. movq $|\itm{bytes}|, %rsi
  5598. callq collect
  5599. \end{lstlisting}
  5600. \begin{figure}[tp]
  5601. \fbox{
  5602. \begin{minipage}{0.96\textwidth}
  5603. \[
  5604. \begin{array}{lcl}
  5605. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5606. x86_1 &::= & \gray{ \key{.globl main} }\\
  5607. & & \gray{ \key{main:} \; \Instr\ldots }
  5608. \end{array}
  5609. \]
  5610. \end{minipage}
  5611. }
  5612. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5613. \label{fig:x86-2-concrete}
  5614. \end{figure}
  5615. \begin{figure}[tp]
  5616. \fbox{
  5617. \begin{minipage}{0.96\textwidth}
  5618. \small
  5619. \[
  5620. \begin{array}{lcl}
  5621. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5622. \mid \BYTEREG{\Reg}} \\
  5623. &\mid& (\key{Global}~\Var) \\
  5624. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5625. \end{array}
  5626. \]
  5627. \end{minipage}
  5628. }
  5629. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5630. \label{fig:x86-2}
  5631. \end{figure}
  5632. The concrete and abstract syntax of the $x86_2$ language is defined in
  5633. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5634. x86$_1$ just in the addition of the form for global variables.
  5635. %
  5636. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5637. \code{select-instructions} pass on the running example.
  5638. \begin{figure}[tbp]
  5639. \centering
  5640. % tests/s2_17.rkt
  5641. \begin{minipage}[t]{0.5\textwidth}
  5642. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5643. block35:
  5644. movq free_ptr(%rip), alloc9024
  5645. addq $16, free_ptr(%rip)
  5646. movq alloc9024, %r11
  5647. movq $131, 0(%r11)
  5648. movq alloc9024, %r11
  5649. movq vecinit9025, 8(%r11)
  5650. movq $0, initret9026
  5651. movq alloc9024, %r11
  5652. movq 8(%r11), tmp9034
  5653. movq tmp9034, %r11
  5654. movq 8(%r11), %rax
  5655. jmp conclusion
  5656. block36:
  5657. movq $0, collectret9027
  5658. jmp block35
  5659. block38:
  5660. movq free_ptr(%rip), alloc9020
  5661. addq $16, free_ptr(%rip)
  5662. movq alloc9020, %r11
  5663. movq $3, 0(%r11)
  5664. movq alloc9020, %r11
  5665. movq vecinit9021, 8(%r11)
  5666. movq $0, initret9022
  5667. movq alloc9020, vecinit9025
  5668. movq free_ptr(%rip), tmp9031
  5669. movq tmp9031, tmp9032
  5670. addq $16, tmp9032
  5671. movq fromspace_end(%rip), tmp9033
  5672. cmpq tmp9033, tmp9032
  5673. jl block36
  5674. jmp block37
  5675. block37:
  5676. movq %r15, %rdi
  5677. movq $16, %rsi
  5678. callq 'collect
  5679. jmp block35
  5680. block39:
  5681. movq $0, collectret9023
  5682. jmp block38
  5683. \end{lstlisting}
  5684. \end{minipage}
  5685. \begin{minipage}[t]{0.45\textwidth}
  5686. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5687. start:
  5688. movq $42, vecinit9021
  5689. movq free_ptr(%rip), tmp9028
  5690. movq tmp9028, tmp9029
  5691. addq $16, tmp9029
  5692. movq fromspace_end(%rip), tmp9030
  5693. cmpq tmp9030, tmp9029
  5694. jl block39
  5695. jmp block40
  5696. block40:
  5697. movq %r15, %rdi
  5698. movq $16, %rsi
  5699. callq 'collect
  5700. jmp block38
  5701. \end{lstlisting}
  5702. \end{minipage}
  5703. \caption{Output of the \code{select-instructions} pass.}
  5704. \label{fig:select-instr-output-gc}
  5705. \end{figure}
  5706. \clearpage
  5707. \section{Register Allocation}
  5708. \label{sec:reg-alloc-gc}
  5709. \index{register allocation}
  5710. As discussed earlier in this chapter, the garbage collector needs to
  5711. access all the pointers in the root set, that is, all variables that
  5712. are vectors. It will be the responsibility of the register allocator
  5713. to make sure that:
  5714. \begin{enumerate}
  5715. \item the root stack is used for spilling vector-typed variables, and
  5716. \item if a vector-typed variable is live during a call to the
  5717. collector, it must be spilled to ensure it is visible to the
  5718. collector.
  5719. \end{enumerate}
  5720. The later responsibility can be handled during construction of the
  5721. inference graph, by adding interference edges between the call-live
  5722. vector-typed variables and all the callee-saved registers. (They
  5723. already interfere with the caller-saved registers.) The type
  5724. information for variables is in the \code{program} form, so we
  5725. recommend adding another parameter to the \code{build-interference}
  5726. function to communicate this alist.
  5727. The spilling of vector-typed variables to the root stack can be
  5728. handled after graph coloring, when choosing how to assign the colors
  5729. (integers) to registers and stack locations. The \code{program} output
  5730. of this pass changes to also record the number of spills to the root
  5731. stack.
  5732. % build-interference
  5733. %
  5734. % callq
  5735. % extra parameter for var->type assoc. list
  5736. % update 'program' and 'if'
  5737. % allocate-registers
  5738. % allocate spilled vectors to the rootstack
  5739. % don't change color-graph
  5740. \section{Print x86}
  5741. \label{sec:print-x86-gc}
  5742. \index{prelude}\index{conclusion}
  5743. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5744. \code{print-x86} pass on the running example. In the prelude and
  5745. conclusion of the \code{main} function, we treat the root stack very
  5746. much like the regular stack in that we move the root stack pointer
  5747. (\code{r15}) to make room for the spills to the root stack, except
  5748. that the root stack grows up instead of down. For the running
  5749. example, there was just one spill so we increment \code{r15} by 8
  5750. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5751. One issue that deserves special care is that there may be a call to
  5752. \code{collect} prior to the initializing assignments for all the
  5753. variables in the root stack. We do not want the garbage collector to
  5754. accidentally think that some uninitialized variable is a pointer that
  5755. needs to be followed. Thus, we zero-out all locations on the root
  5756. stack in the prelude of \code{main}. In
  5757. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5758. %
  5759. \lstinline{movq $0, (%r15)}
  5760. %
  5761. accomplishes this task. The garbage collector tests each root to see
  5762. if it is null prior to dereferencing it.
  5763. \begin{figure}[htbp]
  5764. \begin{minipage}[t]{0.5\textwidth}
  5765. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5766. block35:
  5767. movq free_ptr(%rip), %rcx
  5768. addq $16, free_ptr(%rip)
  5769. movq %rcx, %r11
  5770. movq $131, 0(%r11)
  5771. movq %rcx, %r11
  5772. movq -8(%r15), %rax
  5773. movq %rax, 8(%r11)
  5774. movq $0, %rdx
  5775. movq %rcx, %r11
  5776. movq 8(%r11), %rcx
  5777. movq %rcx, %r11
  5778. movq 8(%r11), %rax
  5779. jmp conclusion
  5780. block36:
  5781. movq $0, %rcx
  5782. jmp block35
  5783. block38:
  5784. movq free_ptr(%rip), %rcx
  5785. addq $16, free_ptr(%rip)
  5786. movq %rcx, %r11
  5787. movq $3, 0(%r11)
  5788. movq %rcx, %r11
  5789. movq %rbx, 8(%r11)
  5790. movq $0, %rdx
  5791. movq %rcx, -8(%r15)
  5792. movq free_ptr(%rip), %rcx
  5793. addq $16, %rcx
  5794. movq fromspace_end(%rip), %rdx
  5795. cmpq %rdx, %rcx
  5796. jl block36
  5797. movq %r15, %rdi
  5798. movq $16, %rsi
  5799. callq collect
  5800. jmp block35
  5801. block39:
  5802. movq $0, %rcx
  5803. jmp block38
  5804. \end{lstlisting}
  5805. \end{minipage}
  5806. \begin{minipage}[t]{0.45\textwidth}
  5807. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5808. start:
  5809. movq $42, %rbx
  5810. movq free_ptr(%rip), %rdx
  5811. addq $16, %rdx
  5812. movq fromspace_end(%rip), %rcx
  5813. cmpq %rcx, %rdx
  5814. jl block39
  5815. movq %r15, %rdi
  5816. movq $16, %rsi
  5817. callq collect
  5818. jmp block38
  5819. .globl main
  5820. main:
  5821. pushq %rbp
  5822. movq %rsp, %rbp
  5823. pushq %r13
  5824. pushq %r12
  5825. pushq %rbx
  5826. pushq %r14
  5827. subq $0, %rsp
  5828. movq $16384, %rdi
  5829. movq $16, %rsi
  5830. callq initialize
  5831. movq rootstack_begin(%rip), %r15
  5832. movq $0, (%r15)
  5833. addq $8, %r15
  5834. jmp start
  5835. conclusion:
  5836. subq $8, %r15
  5837. addq $0, %rsp
  5838. popq %r14
  5839. popq %rbx
  5840. popq %r12
  5841. popq %r13
  5842. popq %rbp
  5843. retq
  5844. \end{lstlisting}
  5845. \end{minipage}
  5846. \caption{Output of the \code{print-x86} pass.}
  5847. \label{fig:print-x86-output-gc}
  5848. \end{figure}
  5849. \begin{figure}[p]
  5850. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5851. \node (R3) at (0,2) {\large $R_3$};
  5852. \node (R3-2) at (3,2) {\large $R_3$};
  5853. \node (R3-3) at (6,2) {\large $R_3$};
  5854. \node (R3-4) at (9,2) {\large $R_3$};
  5855. \node (R3-5) at (9,0) {\large $R'_3$};
  5856. \node (R3-6) at (6,0) {\large $R'_3$};
  5857. \node (C2-4) at (3,-2) {\large $C_2$};
  5858. \node (C2-3) at (0,-2) {\large $C_2$};
  5859. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5860. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5861. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5862. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5863. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5864. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5865. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5866. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5867. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5868. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5869. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5870. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5871. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5872. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5873. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5874. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5875. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5876. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5877. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5878. \end{tikzpicture}
  5879. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5880. \label{fig:R3-passes}
  5881. \end{figure}
  5882. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5883. for the compilation of $R_3$.
  5884. \section{Challenge: Simple Structures}
  5885. \label{sec:simple-structures}
  5886. \index{struct}
  5887. \index{structure}
  5888. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  5889. $R^s_3$, which extends $R^3$ with support for simple structures.
  5890. Recall that a \code{struct} in Typed Racket is a user-defined data
  5891. type that contains named fields and that is heap allocated, similar to
  5892. a vector. The following is an example of a structure definition, in
  5893. this case the definition of a \code{point} type.
  5894. \begin{lstlisting}
  5895. (struct point ([x : Integer] [y : Integer]) #:mutable)
  5896. \end{lstlisting}
  5897. \begin{figure}[tbp]
  5898. \centering
  5899. \fbox{
  5900. \begin{minipage}{0.96\textwidth}
  5901. \[
  5902. \begin{array}{lcl}
  5903. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5904. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  5905. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5906. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  5907. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  5908. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5909. \mid (\key{and}\;\Exp\;\Exp)
  5910. \mid (\key{or}\;\Exp\;\Exp)
  5911. \mid (\key{not}\;\Exp) } \\
  5912. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5913. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  5914. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  5915. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  5916. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  5917. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  5918. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  5919. R_3 &::=& \Def \ldots \; \Exp
  5920. \end{array}
  5921. \]
  5922. \end{minipage}
  5923. }
  5924. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  5925. (Figure~\ref{fig:r3-concrete-syntax}).}
  5926. \label{fig:r3s-concrete-syntax}
  5927. \end{figure}
  5928. An instance of a structure is created using function call syntax, with
  5929. the name of the structure in the function position:
  5930. \begin{lstlisting}
  5931. (point 7 12)
  5932. \end{lstlisting}
  5933. Function-call syntax is also used to read the value in a field of a
  5934. structure. The function name is formed by the structure name, a dash,
  5935. and the field name. The following example uses \code{point-x} and
  5936. \code{point-y} to access the \code{x} and \code{y} fields of two point
  5937. instances.
  5938. \begin{center}
  5939. \begin{lstlisting}
  5940. (let ([pt1 (point 7 12)])
  5941. (let ([pt2 (point 4 3)])
  5942. (+ (- (point-x pt1) (point-x pt2))
  5943. (- (point-y pt1) (point-y pt2)))))
  5944. \end{lstlisting}
  5945. \end{center}
  5946. Similarly, to write to a field of a structure, use its set function,
  5947. whose name starts with \code{set-}, followed by the structure name,
  5948. then a dash, then the field name, and conclused with an exclamation
  5949. mark. The folowing example uses \code{set-point-x!} to change the
  5950. \code{x} field from \code{7} to \code{42}.
  5951. \begin{center}
  5952. \begin{lstlisting}
  5953. (let ([pt (point 7 12)])
  5954. (let ([_ (set-point-x! pt 42)])
  5955. (point-x pt)))
  5956. \end{lstlisting}
  5957. \end{center}
  5958. \begin{exercise}\normalfont
  5959. Extend your compiler with support for simple structures, compiling
  5960. $R^s_3$ to x86 assembly code. Create five new test cases that use
  5961. structures and test your compiler.
  5962. \end{exercise}
  5963. \section{Challenge: Generational Collection}
  5964. The copying collector described in Section~\ref{sec:GC} can incur
  5965. significant runtime overhead because the call to \code{collect} takes
  5966. time proportional to all of the live data. One way to reduce this
  5967. overhead is to reduce how much data is inspected in each call to
  5968. \code{collect}. In particular, researchers have observed that recently
  5969. allocated data is more likely to become garbage then data that has
  5970. survived one or more previous calls to \code{collect}. This insight
  5971. motivated the creation of \emph{generational garbage collectors}
  5972. \index{generational garbage collector} that
  5973. 1) segragates data according to its age into two or more generations,
  5974. 2) allocates less space for younger generations, so collecting them is
  5975. faster, and more space for the older generations, and 3) performs
  5976. collection on the younger generations more frequently then for older
  5977. generations~\citep{Wilson:1992fk}.
  5978. For this challenge assignment, the goal is to adapt the copying
  5979. collector implemented in \code{runtime.c} to use two generations, one
  5980. for young data and one for old data. Each generation consists of a
  5981. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  5982. \code{collect} function to use the two generations.
  5983. \begin{enumerate}
  5984. \item Copy the young generation's FromSpace to its ToSpace then switch
  5985. the role of the ToSpace and FromSpace
  5986. \item If there is enough space for the requested number of bytes in
  5987. the young FromSpace, then return from \code{collect}.
  5988. \item If there is not enough space in the young FromSpace for the
  5989. requested bytes, then move the data from the young generation to the
  5990. old one with the following steps:
  5991. \begin{enumerate}
  5992. \item If there is enough room in the old FromSpace, copy the young
  5993. FromSpace to the old FromSpace and then return.
  5994. \item If there is not enough room in the old FromSpace, then collect
  5995. the old generation by copying the old FromSpace to the old ToSpace
  5996. and swap the roles of the old FromSpace and ToSpace.
  5997. \item If there is enough room now, copy the young FromSpace to the
  5998. old FromSpace and return. Otherwise, allocate a larger FromSpace
  5999. and ToSpace for the old generation. Copy the young FromSpace and
  6000. the old FromSpace into the larger FromSpace for the old
  6001. generation and then return.
  6002. \end{enumerate}
  6003. \end{enumerate}
  6004. We recommend that you generalize the \code{cheney} function so that it
  6005. can be used for all the copies mentioned above: between the young
  6006. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6007. between the young FromSpace and old FromSpace. This can be
  6008. accomplished by adding parameters to \code{cheney} that replace its
  6009. use of the global variables \code{fromspace\_begin},
  6010. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6011. Note that the collection of the young generation does not traverse the
  6012. old generation. This introduces a potential problem: there may be
  6013. young data that is only reachable through pointers in the old
  6014. generation. If these pointers are not taken into account, the
  6015. collector could throw away young data that is live! One solution,
  6016. called \emph{pointer recording}, is to maintain a set of all the
  6017. pointers from the old generation into the new generation and consider
  6018. this set as part of the root set. To maintain this set, the compiler
  6019. must insert extra instructions around every \code{vector-set!}. If the
  6020. vector being modified is in the old generation, and if the value being
  6021. written is a pointer into the new generation, than that pointer must
  6022. be added to the set. Also, if the value being overwritten was a
  6023. pointer into the new generation, then that pointer should be removed
  6024. from the set.
  6025. \begin{exercise}\normalfont
  6026. Adapt the \code{collect} function in \code{runtime.c} to implement
  6027. generational garbage collection, as outlined in this section.
  6028. Update the code generation for \code{vector-set!} to implement
  6029. pointer recording. Make sure that your new compiler and runtime
  6030. passes your test suite.
  6031. \end{exercise}
  6032. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6033. \chapter{Functions}
  6034. \label{ch:functions}
  6035. \index{function}
  6036. This chapter studies the compilation of functions similar to those
  6037. found in the C language. This corresponds to a subset of Typed Racket
  6038. in which only top-level function definitions are allowed. This kind of
  6039. function is an important stepping stone to implementing
  6040. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6041. is the topic of Chapter~\ref{ch:lambdas}.
  6042. \section{The $R_4$ Language}
  6043. The concrete and abstract syntax for function definitions and function
  6044. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6045. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6046. $R_4$ begin with zero or more function definitions. The function
  6047. names from these definitions are in-scope for the entire program,
  6048. including all other function definitions (so the ordering of function
  6049. definitions does not matter). The concrete syntax for function
  6050. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6051. where the first expression must
  6052. evaluate to a function and the rest are the arguments.
  6053. The abstract syntax for function application is
  6054. $\APPLY{\Exp}{\Exp\ldots}$.
  6055. %% The syntax for function application does not include an explicit
  6056. %% keyword, which is error prone when using \code{match}. To alleviate
  6057. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6058. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6059. Functions are first-class in the sense that a function pointer
  6060. \index{function pointer} is data and can be stored in memory or passed
  6061. as a parameter to another function. Thus, we introduce a function
  6062. type, written
  6063. \begin{lstlisting}
  6064. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6065. \end{lstlisting}
  6066. for a function whose $n$ parameters have the types $\Type_1$ through
  6067. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6068. these functions (with respect to Racket functions) is that they are
  6069. not lexically scoped. That is, the only external entities that can be
  6070. referenced from inside a function body are other globally-defined
  6071. functions. The syntax of $R_4$ prevents functions from being nested
  6072. inside each other.
  6073. \begin{figure}[tp]
  6074. \centering
  6075. \fbox{
  6076. \begin{minipage}{0.96\textwidth}
  6077. \small
  6078. \[
  6079. \begin{array}{lcl}
  6080. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6081. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6082. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6083. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  6084. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  6085. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6086. \mid (\key{and}\;\Exp\;\Exp)
  6087. \mid (\key{or}\;\Exp\;\Exp)
  6088. \mid (\key{not}\;\Exp)} \\
  6089. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6090. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6091. (\key{vector-ref}\;\Exp\;\Int)} \\
  6092. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6093. \mid (\key{has-type}~\Exp~\Type)} \\
  6094. &\mid& (\Exp \; \Exp \ldots) \\
  6095. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp) \\
  6096. R_4 &::=& \Def \ldots \; \Exp
  6097. \end{array}
  6098. \]
  6099. \end{minipage}
  6100. }
  6101. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6102. \label{fig:r4-concrete-syntax}
  6103. \end{figure}
  6104. \begin{figure}[tp]
  6105. \centering
  6106. \fbox{
  6107. \begin{minipage}{0.96\textwidth}
  6108. \small
  6109. \[
  6110. \begin{array}{lcl}
  6111. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6112. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6113. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6114. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6115. &\mid& \gray{ \BOOL{\itm{bool}}
  6116. \mid \AND{\Exp}{\Exp} }\\
  6117. &\mid& \gray{ \OR{\Exp}{\Exp}
  6118. \mid \NOT{\Exp} } \\
  6119. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6120. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6121. &\mid& \gray{ \VECTOR{\Exp} } \\
  6122. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  6123. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  6124. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6125. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6126. \Def &::=& \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp}\\
  6127. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp}
  6128. \end{array}
  6129. \]
  6130. \end{minipage}
  6131. }
  6132. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6133. \label{fig:r4-syntax}
  6134. \end{figure}
  6135. The program in Figure~\ref{fig:r4-function-example} is a
  6136. representative example of defining and using functions in $R_4$. We
  6137. define a function \code{map-vec} that applies some other function
  6138. \code{f} to both elements of a vector and returns a new
  6139. vector containing the results. We also define a function \code{add1}.
  6140. The program applies
  6141. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6142. \code{(vector 1 42)}, from which we return the \code{42}.
  6143. \begin{figure}[tbp]
  6144. \begin{lstlisting}
  6145. (define (map-vec [f : (Integer -> Integer)]
  6146. [v : (Vector Integer Integer)])
  6147. : (Vector Integer Integer)
  6148. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6149. (define (add1 [x : Integer]) : Integer
  6150. (+ x 1))
  6151. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6152. \end{lstlisting}
  6153. \caption{Example of using functions in $R_4$.}
  6154. \label{fig:r4-function-example}
  6155. \end{figure}
  6156. The definitional interpreter for $R_4$ is in
  6157. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6158. responsible for setting up the mutual recursion between the top-level
  6159. function definitions. We use the classic back-patching \index{back-patching}
  6160. approach that uses mutable variables and makes two passes over the function
  6161. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6162. top-level environment using a mutable cons cell for each function
  6163. definition. Note that the \code{lambda} value for each function is
  6164. incomplete; it does not yet include the environment. Once the
  6165. top-level environment is constructed, we then iterate over it and
  6166. update the \code{lambda} values to use the top-level environment.
  6167. \begin{figure}[tp]
  6168. \begin{lstlisting}
  6169. (define (interp-exp env)
  6170. (lambda (e)
  6171. (define recur (interp-exp env))
  6172. (match e
  6173. ...
  6174. [(Apply fun args)
  6175. (define fun-val (recur fun))
  6176. (define arg-vals (for/list ([e args]) (recur e)))
  6177. (match fun-val
  6178. [`(lambda (,xs ...) ,body ,fun-env)
  6179. (define new-env (append (map cons xs arg-vals) fun-env))
  6180. ((interp-exp new-env) body)])]
  6181. ...
  6182. )))
  6183. (define (interp-def d)
  6184. (match d
  6185. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6186. (mcons f `(lambda ,xs ,body ()))]
  6187. ))
  6188. (define (interp-R4 p)
  6189. (match p
  6190. [(ProgramDefsExp info ds body)
  6191. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6192. (for/list ([b top-level])
  6193. (set-mcdr! b (match (mcdr b)
  6194. [`(lambda ,xs ,body ())
  6195. `(lambda ,xs ,body ,top-level)])))
  6196. ((interp-exp top-level) body))]
  6197. ))
  6198. \end{lstlisting}
  6199. \caption{Interpreter for the $R_4$ language.}
  6200. \label{fig:interp-R4}
  6201. \end{figure}
  6202. \section{Functions in x86}
  6203. \label{sec:fun-x86}
  6204. \margincomment{\tiny Make sure callee-saved registers are discussed
  6205. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6206. \margincomment{\tiny Talk about the return address on the
  6207. stack and what callq and retq does.\\ --Jeremy }
  6208. The x86 architecture provides a few features to support the
  6209. implementation of functions. We have already seen that x86 provides
  6210. labels so that one can refer to the location of an instruction, as is
  6211. needed for jump instructions. Labels can also be used to mark the
  6212. beginning of the instructions for a function. Going further, we can
  6213. obtain the address of a label by using the \key{leaq} instruction and
  6214. PC-relative addressing. For example, the following puts the
  6215. address of the \code{add1} label into the \code{rbx} register.
  6216. \begin{lstlisting}
  6217. leaq add1(%rip), %rbx
  6218. \end{lstlisting}
  6219. The instruction pointer register \key{rip} (aka. the program counter
  6220. \index{program counter}) always points to the next instruction to be
  6221. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6222. linker computes the distance $d$ between the address of \code{add1}
  6223. and where the \code{rip} would be at that moment and then changes
  6224. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6225. the address of \code{add1}.
  6226. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6227. jump to a function whose location is given by a label. To support
  6228. function calls in this chapter we instead will be jumping to a
  6229. function whose location is given by an address in a register, that is,
  6230. we need to make an \emph{indirect function call}. The x86 syntax for
  6231. this is a \code{callq} instruction but with an asterisk before the
  6232. register name.\index{indirect function call}
  6233. \begin{lstlisting}
  6234. callq *%rbx
  6235. \end{lstlisting}
  6236. \subsection{Calling Conventions}
  6237. \index{calling conventions}
  6238. The \code{callq} instruction provides partial support for implementing
  6239. functions: it pushes the return address on the stack and it jumps to
  6240. the target. However, \code{callq} does not handle
  6241. \begin{enumerate}
  6242. \item parameter passing,
  6243. \item pushing frames on the procedure call stack and popping them off,
  6244. or
  6245. \item determining how registers are shared by different functions.
  6246. \end{enumerate}
  6247. These issues require coordination between the caller and the callee,
  6248. which is often assembly code written by different programmers or
  6249. generated by different compilers. As a result, people have developed
  6250. \emph{conventions} that govern how functions calls are performed.
  6251. Here we use conventions that are compatible with those of the
  6252. \code{gcc} compiler~\citep{Matz:2013aa}.
  6253. Regarding (1) parameter passing, the convention is to use the
  6254. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  6255. \code{rcx}, \code{r8}, and \code{r9}, in that order, to pass arguments
  6256. to a function. If there are more than six arguments, then the
  6257. convention is to use space on the frame of the caller for the rest of
  6258. the arguments. However, to ease the implementation of efficient tail
  6259. calls (Section~\ref{sec:tail-call}), we arrange to never need more
  6260. than six arguments.
  6261. %
  6262. The register \code{rax} is for the return value of the function.
  6263. \index{prelude}\index{conclusion}
  6264. Regarding (2) frames \index{frame} and the procedure call stack
  6265. \index{procedure call stack}, recall from Section~\ref{sec:x86} that
  6266. the stack grows down, with each function call using a chunk of space
  6267. called a frame. The caller sets the stack pointer, register
  6268. \code{rsp}, to the last data item in its frame. The callee must not
  6269. change anything in the caller's frame, that is, anything that is at or
  6270. above the stack pointer. The callee is free to use locations that are
  6271. below the stack pointer.
  6272. Recall that we are storing variables of vector type on the root stack.
  6273. So the prelude needs to move the root stack pointer \code{r15} up and
  6274. the conclusion needs to move the root stack pointer back down. Also,
  6275. the prelude must initialize to \code{0} this frame's slots in the root
  6276. stack to signal to the garbage collector that those slots do not yet
  6277. contain a pointer to a vector. Otherwise the garbage collector will
  6278. interpret the garbage bits in those slots as memory addresses and try
  6279. to traverse them, causing serious mayhem!
  6280. Regarding (3) the sharing of registers between different functions,
  6281. recall from Section~\ref{sec:calling-conventions} that the registers
  6282. are divided into two groups, the caller-saved registers and the
  6283. callee-saved registers. The caller should assume that all the
  6284. caller-saved registers get overwritten with arbitrary values by the
  6285. callee. That is why we recommend in
  6286. Section~\ref{sec:calling-conventions} that variables that are live
  6287. during a function call should not be assigned to caller-saved
  6288. registers.
  6289. On the flip side, if the callee wants to use a callee-saved register,
  6290. the callee must save the contents of those registers on their stack
  6291. frame and then put them back prior to returning to the caller. That
  6292. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6293. the register allocator assigns a variable to a callee-saved register,
  6294. then the prelude of the \code{main} function must save that register
  6295. to the stack and the conclusion of \code{main} must restore it. This
  6296. recommendation now generalizes to all functions.
  6297. Also recall that the base pointer, register \code{rbp}, is used as a
  6298. point-of-reference within a frame, so that each local variable can be
  6299. accessed at a fixed offset from the base pointer
  6300. (Section~\ref{sec:x86}).
  6301. %
  6302. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6303. and callee frames.
  6304. \begin{figure}[tbp]
  6305. \centering
  6306. \begin{tabular}{r|r|l|l} \hline
  6307. Caller View & Callee View & Contents & Frame \\ \hline
  6308. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6309. 0(\key{\%rbp}) & & old \key{rbp} \\
  6310. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6311. \ldots & & \ldots \\
  6312. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6313. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6314. \ldots & & \ldots \\
  6315. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6316. %% & & \\
  6317. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6318. %% & \ldots & \ldots \\
  6319. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6320. \hline
  6321. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6322. & 0(\key{\%rbp}) & old \key{rbp} \\
  6323. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6324. & \ldots & \ldots \\
  6325. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6326. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6327. & \ldots & \ldots \\
  6328. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6329. \end{tabular}
  6330. \caption{Memory layout of caller and callee frames.}
  6331. \label{fig:call-frames}
  6332. \end{figure}
  6333. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6334. %% local variables and for storing the values of callee-saved registers
  6335. %% (we shall refer to all of these collectively as ``locals''), and that
  6336. %% at the beginning of a function we move the stack pointer \code{rsp}
  6337. %% down to make room for them.
  6338. %% We recommend storing the local variables
  6339. %% first and then the callee-saved registers, so that the local variables
  6340. %% can be accessed using \code{rbp} the same as before the addition of
  6341. %% functions.
  6342. %% To make additional room for passing arguments, we shall
  6343. %% move the stack pointer even further down. We count how many stack
  6344. %% arguments are needed for each function call that occurs inside the
  6345. %% body of the function and find their maximum. Adding this number to the
  6346. %% number of locals gives us how much the \code{rsp} should be moved at
  6347. %% the beginning of the function. In preparation for a function call, we
  6348. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6349. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6350. %% so on.
  6351. %% Upon calling the function, the stack arguments are retrieved by the
  6352. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6353. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6354. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6355. %% the layout of the caller and callee frames. Notice how important it is
  6356. %% that we correctly compute the maximum number of arguments needed for
  6357. %% function calls; if that number is too small then the arguments and
  6358. %% local variables will smash into each other!
  6359. \subsection{Efficient Tail Calls}
  6360. \label{sec:tail-call}
  6361. In general, the amount of stack space used by a program is determined
  6362. by the longest chain of nested function calls. That is, if function
  6363. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6364. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6365. $n$ can grow quite large in the case of recursive or mutually
  6366. recursive functions. However, in some cases we can arrange to use only
  6367. constant space, i.e. $O(1)$, instead of $O(n)$.
  6368. If a function call is the last action in a function body, then that
  6369. call is said to be a \emph{tail call}\index{tail call}.
  6370. For example, in the following
  6371. program, the recursive call to \code{tail-sum} is a tail call.
  6372. \begin{center}
  6373. \begin{lstlisting}
  6374. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6375. (if (eq? n 0)
  6376. r
  6377. (tail-sum (- n 1) (+ n r))))
  6378. (+ (tail-sum 5 0) 27)
  6379. \end{lstlisting}
  6380. \end{center}
  6381. At a tail call, the frame of the caller is no longer needed, so we
  6382. can pop the caller's frame before making the tail call. With this
  6383. approach, a recursive function that only makes tail calls will only
  6384. use $O(1)$ stack space. Functional languages like Racket typically
  6385. rely heavily on recursive functions, so they typically guarantee that
  6386. all tail calls will be optimized in this way.
  6387. \index{frame}
  6388. However, some care is needed with regards to argument passing in tail
  6389. calls. As mentioned above, for arguments beyond the sixth, the
  6390. convention is to use space in the caller's frame for passing
  6391. arguments. But for a tail call we pop the caller's frame and can no
  6392. longer use it. Another alternative is to use space in the callee's
  6393. frame for passing arguments. However, this option is also problematic
  6394. because the caller and callee's frame overlap in memory. As we begin
  6395. to copy the arguments from their sources in the caller's frame, the
  6396. target locations in the callee's frame might overlap with the sources
  6397. for later arguments! We solve this problem by not using the stack for
  6398. passing more than six arguments but instead using the heap, as we
  6399. describe in the Section~\ref{sec:limit-functions-r4}.
  6400. As mentioned above, for a tail call we pop the caller's frame prior to
  6401. making the tail call. The instructions for popping a frame are the
  6402. instructions that we usually place in the conclusion of a
  6403. function. Thus, we also need to place such code immediately before
  6404. each tail call. These instructions include restoring the callee-saved
  6405. registers, so it is good that the argument passing registers are all
  6406. caller-saved registers.
  6407. One last note regarding which instruction to use to make the tail
  6408. call. When the callee is finished, it should not return to the current
  6409. function, but it should return to the function that called the current
  6410. one. Thus, the return address that is already on the stack is the
  6411. right one, and we should not use \key{callq} to make the tail call, as
  6412. that would unnecessarily overwrite the return address. Instead we can
  6413. simply use the \key{jmp} instruction. Like the indirect function call,
  6414. we write an \emph{indirect jump}\index{indirect jump} with a register
  6415. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6416. jump target because the preceding conclusion overwrites just about
  6417. everything else.
  6418. \begin{lstlisting}
  6419. jmp *%rax
  6420. \end{lstlisting}
  6421. \section{Shrink $R_4$}
  6422. \label{sec:shrink-r4}
  6423. The \code{shrink} pass performs a minor modification to ease the
  6424. later passes. This pass introduces an explicit \code{main} function
  6425. and changes the top \code{ProgramDefsExp} form to
  6426. \code{ProgramDefs} as follows.
  6427. \begin{lstlisting}
  6428. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6429. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6430. \end{lstlisting}
  6431. where $\itm{mainDef}$ is
  6432. \begin{lstlisting}
  6433. (Def main () Integer () |$\Exp'$|)
  6434. \end{lstlisting}
  6435. \section{Reveal Functions and the $F_1$ language}
  6436. \label{sec:reveal-functions-r4}
  6437. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6438. respect: it conflates the use of function names and local
  6439. variables. This is a problem because we need to compile the use of a
  6440. function name differently than the use of a local variable; we need to
  6441. use \code{leaq} to convert the function name (a label in x86) to an
  6442. address in a register. Thus, it is a good idea to create a new pass
  6443. that changes function references from just a symbol $f$ to
  6444. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6445. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6446. \begin{figure}[tp]
  6447. \centering
  6448. \fbox{
  6449. \begin{minipage}{0.96\textwidth}
  6450. \[
  6451. \begin{array}{lcl}
  6452. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6453. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6454. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6455. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6456. &\mid& \gray{ \BOOL{\itm{bool}}
  6457. \mid \AND{\Exp}{\Exp} }\\
  6458. &\mid& \gray{ \OR{\Exp}{\Exp}
  6459. \mid \NOT{\Exp} } \\
  6460. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6461. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6462. &\mid& \gray{ \VECTOR{\Exp} } \\
  6463. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  6464. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  6465. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6466. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6467. &\mid& \FUNREF{\Var}\\
  6468. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6469. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6470. \end{array}
  6471. \]
  6472. \end{minipage}
  6473. }
  6474. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6475. (Figure~\ref{fig:r4-syntax}).}
  6476. \label{fig:f1-syntax}
  6477. \end{figure}
  6478. %% Distinguishing between calls in tail position and non-tail position
  6479. %% requires the pass to have some notion of context. We recommend using
  6480. %% two mutually recursive functions, one for processing expressions in
  6481. %% tail position and another for the rest.
  6482. Placing this pass after \code{uniquify} will make sure that there are
  6483. no local variables and functions that share the same name. On the
  6484. other hand, \code{reveal-functions} needs to come before the
  6485. \code{explicate-control} pass because that pass helps us compile
  6486. \code{FunRef} forms into assignment statements.
  6487. \section{Limit Functions}
  6488. \label{sec:limit-functions-r4}
  6489. Recall that we wish to limit the number of function parameters to six
  6490. so that we do not need to use the stack for argument passing, which
  6491. makes it easier to implement efficient tail calls. However, because
  6492. the input language $R_4$ supports arbitrary numbers of function
  6493. arguments, we have some work to do!
  6494. This pass transforms functions and function calls that involve more
  6495. than six arguments to pass the first five arguments as usual, but it
  6496. packs the rest of the arguments into a vector and passes it as the
  6497. sixth argument. So for any function call with $n$ arguments more than
  6498. six, the \code{limit-functions} pass transforms it in the following
  6499. way.
  6500. \begin{tabular}{lll}
  6501. \begin{minipage}{0.2\textwidth}
  6502. \begin{lstlisting}
  6503. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6504. \end{lstlisting}
  6505. \end{minipage}
  6506. &
  6507. $\Rightarrow$
  6508. &
  6509. \begin{minipage}{0.4\textwidth}
  6510. \begin{lstlisting}
  6511. (|$e_0$| |$e_1$| |$\ldots$| |$e_5$| (vector |$e_6$| |$\ldots$| |$e_n$|))
  6512. \end{lstlisting}
  6513. \end{minipage}
  6514. \end{tabular}
  6515. \margincomment{UNDER CONSTRUCTION --Jeremy}
  6516. In the body of the function, all occurrences of the $i$th argument in
  6517. which $i>5$ must be replaced with a \code{vector-ref}.
  6518. \section{Remove Complex Operators and Operands}
  6519. \label{sec:rco-r4}
  6520. The primary decisions to make for this pass is whether to classify
  6521. \code{fun-ref} and \code{app} as either simple or complex
  6522. expressions. Recall that a simple expression will eventually end up as
  6523. just an ``immediate'' argument of an x86 instruction. Function
  6524. application will be translated to a sequence of instructions, so
  6525. \code{app} must be classified as complex expression. Regarding
  6526. \code{fun-ref}, as discussed above, the function label needs to
  6527. be converted to an address using the \code{leaq} instruction. Thus,
  6528. even though \code{fun-ref} seems rather simple, it needs to be
  6529. classified as a complex expression so that we generate an assignment
  6530. statement with a left-hand side that can serve as the target of the
  6531. \code{leaq}.
  6532. \section{Explicate Control and the $C_3$ language}
  6533. \label{sec:explicate-control-r4}
  6534. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  6535. \key{explicate-control}. The three mutually recursive functions for
  6536. this pass, for assignment, tail, and predicate contexts, must all be
  6537. updated with cases for \code{fun-ref} and \code{app}. In
  6538. assignment and predicate contexts, \code{app} becomes \code{call},
  6539. whereas in tail position \code{app} becomes \code{tailcall}. We
  6540. recommend defining a new function for processing function definitions.
  6541. This code is similar to the case for \code{program} in $R_3$. The
  6542. top-level \code{explicate-control} function that handles the
  6543. \code{program} form of $R_4$ can then apply this new function to all
  6544. the function definitions.
  6545. \begin{figure}[tp]
  6546. \fbox{
  6547. \begin{minipage}{0.96\textwidth}
  6548. \[
  6549. \begin{array}{lcl}
  6550. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6551. \\
  6552. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6553. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  6554. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  6555. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6556. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  6557. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6558. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg\ldots) \\
  6559. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6560. \mid (\key{collect} \,\itm{int}) }\\
  6561. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6562. &\mid& \gray{(\key{goto}\,\itm{label})
  6563. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6564. &\mid& (\key{tailcall} \,\Arg\,\Arg\ldots) \\
  6565. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6566. C_3 & ::= & (\key{program}\;\itm{info}\;\Def\ldots)
  6567. \end{array}
  6568. \]
  6569. \end{minipage}
  6570. }
  6571. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  6572. \label{fig:c3-syntax}
  6573. \end{figure}
  6574. \section{Uncover Locals}
  6575. \label{sec:uncover-locals-r4}
  6576. The function for processing $\Tail$ should be updated with a case for
  6577. \code{tailcall}. We also recommend creating a new function for
  6578. processing function definitions. Each function definition in $C_3$ has
  6579. its own set of local variables, so the code for function definitions
  6580. should be similar to the case for the \code{program} form in $C_2$.
  6581. \section{Select Instructions and the x86$_3$ Language}
  6582. \label{sec:select-r4}
  6583. \index{instruction selection}
  6584. The output of select instructions is a program in the x86$_3$
  6585. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6586. \index{x86}
  6587. \begin{figure}[tp]
  6588. \fbox{
  6589. \begin{minipage}{0.96\textwidth}
  6590. \[
  6591. \begin{array}{lcl}
  6592. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6593. \mid (\key{deref}\,\Reg\,\Int) } \\
  6594. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6595. \mid (\key{global}\; \itm{name}) } \\
  6596. &\mid& (\key{fun-ref}\; \itm{label})\\
  6597. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6598. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6599. (\key{subq} \; \Arg\; \Arg) \mid
  6600. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6601. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6602. (\key{pushq}\;\Arg) \mid
  6603. (\key{popq}\;\Arg) \mid
  6604. (\key{retq}) } \\
  6605. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6606. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6607. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6608. \mid (\key{jmp} \; \itm{label})
  6609. \mid (\key{j}\itm{cc} \; \itm{label})
  6610. \mid (\key{label} \; \itm{label}) } \\
  6611. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6612. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  6613. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6614. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6615. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6616. \end{array}
  6617. \]
  6618. \end{minipage}
  6619. }
  6620. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6621. \label{fig:x86-3}
  6622. \end{figure}
  6623. \margincomment{TODO: abstract syntax for $x86_3$. -Jeremy}
  6624. An assignment of \code{FunRef} becomes a \code{leaq} instruction
  6625. as follows: \\
  6626. \begin{tabular}{lll}
  6627. \begin{minipage}{0.45\textwidth}
  6628. \begin{lstlisting}
  6629. (Assign |$\itm{lhs}$| (FunRef |$f$|))
  6630. \end{lstlisting}
  6631. \end{minipage}
  6632. &
  6633. $\Rightarrow$
  6634. &
  6635. \begin{minipage}{0.4\textwidth}
  6636. \begin{lstlisting}
  6637. (Instr 'leaq (list (FunRef |$f$|) |$\itm{lhs}'$|))
  6638. \end{lstlisting}
  6639. \end{minipage}
  6640. \end{tabular} \\
  6641. Regarding function definitions, we need to remove their parameters and
  6642. instead perform parameter passing in terms of the conventions
  6643. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  6644. in the argument passing registers, and inside the function we should
  6645. generate a \code{movq} instruction for each parameter, to move the
  6646. argument value from the appropriate register to a new local variable
  6647. with the same name as the old parameter.
  6648. Next, consider the compilation of function calls, which have the
  6649. following form upon input to \code{select-instructions}.
  6650. \begin{lstlisting}
  6651. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  6652. \end{lstlisting}
  6653. In the mirror image of handling the parameters of function
  6654. definitions, the arguments \itm{args} need to be moved to the argument
  6655. passing registers.
  6656. %
  6657. Once the instructions for parameter passing have been generated, the
  6658. function call itself can be performed with an indirect function call,
  6659. for which I recommend creating the new instruction
  6660. \code{indirect-callq}. Of course, the return value from the function
  6661. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  6662. \begin{lstlisting}
  6663. (indirect-callq |\itm{fun}|)
  6664. (movq (reg rax) |\itm{lhs}|)
  6665. \end{lstlisting}
  6666. Regarding tail calls, the parameter passing is the same as non-tail
  6667. calls: generate instructions to move the arguments into to the
  6668. argument passing registers. After that we need to pop the frame from
  6669. the procedure call stack. However, we do not yet know how big the
  6670. frame is; that gets determined during register allocation. So instead
  6671. of generating those instructions here, we invent a new instruction
  6672. that means ``pop the frame and then do an indirect jump'', which we
  6673. name \code{tail-jmp}.
  6674. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6675. using the label \code{start} for the initial block of a program, and
  6676. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6677. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  6678. can be compiled to an assignment to \code{rax} followed by a jump to
  6679. \code{conclusion}. With the addition of function definitions, we will
  6680. have a starting block and conclusion for each function, but their
  6681. labels need to be unique. We recommend prepending the function's name
  6682. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6683. labels. (Alternatively, one could \code{gensym} labels for the start
  6684. and conclusion and store them in the $\itm{info}$ field of the
  6685. function definition.)
  6686. \section{Uncover Live}
  6687. %% The rest of the passes need only minor modifications to handle the new
  6688. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6689. %% \code{leaq}.
  6690. Inside \code{uncover-live}, when computing the $W$ set (written
  6691. variables) for an \code{indirect-callq} instruction, we recommend
  6692. including all the caller-saved registers, which will have the affect
  6693. of making sure that no caller-saved register actually needs to be
  6694. saved.
  6695. \section{Build Interference Graph}
  6696. With the addition of function definitions, we compute an interference
  6697. graph for each function (not just one for the whole program).
  6698. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6699. spill vector-typed variables that are live during a call to the
  6700. \code{collect}. With the addition of functions to our language, we
  6701. need to revisit this issue. Many functions will perform allocation and
  6702. therefore have calls to the collector inside of them. Thus, we should
  6703. not only spill a vector-typed variable when it is live during a call
  6704. to \code{collect}, but we should spill the variable if it is live
  6705. during any function call. Thus, in the \code{build-interference} pass,
  6706. we recommend adding interference edges between call-live vector-typed
  6707. variables and the callee-saved registers (in addition to the usual
  6708. addition of edges between call-live variables and the caller-saved
  6709. registers).
  6710. \section{Patch Instructions}
  6711. In \code{patch-instructions}, you should deal with the x86
  6712. idiosyncrasy that the destination argument of \code{leaq} must be a
  6713. register. Additionally, you should ensure that the argument of
  6714. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  6715. code generation more convenient, because we will be trampling many
  6716. registers before the tail call (as explained below).
  6717. \section{Print x86}
  6718. For the \code{print-x86} pass, we recommend the following translations:
  6719. \begin{lstlisting}
  6720. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6721. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6722. \end{lstlisting}
  6723. Handling \code{tail-jmp} requires a bit more care. A straightforward
  6724. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  6725. is what we will want to do, but before the jump we need to pop the
  6726. current frame. So we need to restore the state of the registers to the
  6727. point they were at when the current function was called. This
  6728. sequence of instructions is the same as the code for the conclusion of
  6729. a function.
  6730. Note that your \code{print-x86} pass needs to add the code for saving
  6731. and restoring callee-saved registers, if you have not already
  6732. implemented that. This is necessary when generating code for function
  6733. definitions.
  6734. \section{An Example Translation}
  6735. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6736. function in $R_4$ to x86. The figure also includes the results of the
  6737. \code{explicate-control} and \code{select-instructions} passes. We
  6738. have omitted the \code{has-type} AST nodes for readability. Can you
  6739. see any ways to improve the translation?
  6740. \begin{figure}[tbp]
  6741. \begin{tabular}{ll}
  6742. \begin{minipage}{0.45\textwidth}
  6743. % s3_2.rkt
  6744. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6745. (program
  6746. (define (add [x : Integer]
  6747. [y : Integer])
  6748. : Integer (+ x y))
  6749. (add 40 2))
  6750. \end{lstlisting}
  6751. $\Downarrow$
  6752. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6753. (program ()
  6754. (define (add86 [x87 : Integer]
  6755. [y88 : Integer]) : Integer ()
  6756. ((add86start . (return (+ x87 y88)))))
  6757. (define (main) : Integer ()
  6758. ((mainstart .
  6759. (seq (assign tmp89 (fun-ref add86))
  6760. (tailcall tmp89 40 2))))))
  6761. \end{lstlisting}
  6762. \end{minipage}
  6763. &
  6764. $\Rightarrow$
  6765. \begin{minipage}{0.5\textwidth}
  6766. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6767. (program ()
  6768. (define (add86)
  6769. ((locals (x87 . Integer) (y88 . Integer))
  6770. (num-params . 2))
  6771. ((add86start .
  6772. (block ()
  6773. (movq (reg rcx) (var x87))
  6774. (movq (reg rdx) (var y88))
  6775. (movq (var x87) (reg rax))
  6776. (addq (var y88) (reg rax))
  6777. (jmp add86conclusion)))))
  6778. (define (main)
  6779. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6780. (num-params . 0))
  6781. ((mainstart .
  6782. (block ()
  6783. (leaq (fun-ref add86) (var tmp89))
  6784. (movq (int 40) (reg rcx))
  6785. (movq (int 2) (reg rdx))
  6786. (tail-jmp (var tmp89))))))
  6787. \end{lstlisting}
  6788. $\Downarrow$
  6789. \end{minipage}
  6790. \end{tabular}
  6791. \begin{tabular}{lll}
  6792. \begin{minipage}{0.3\textwidth}
  6793. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6794. _add90start:
  6795. movq %rcx, %rsi
  6796. movq %rdx, %rcx
  6797. movq %rsi, %rax
  6798. addq %rcx, %rax
  6799. jmp _add90conclusion
  6800. .globl _add90
  6801. .align 16
  6802. _add90:
  6803. pushq %rbp
  6804. movq %rsp, %rbp
  6805. pushq %r12
  6806. pushq %rbx
  6807. pushq %r13
  6808. pushq %r14
  6809. subq $0, %rsp
  6810. jmp _add90start
  6811. _add90conclusion:
  6812. addq $0, %rsp
  6813. popq %r14
  6814. popq %r13
  6815. popq %rbx
  6816. popq %r12
  6817. subq $0, %r15
  6818. popq %rbp
  6819. retq
  6820. \end{lstlisting}
  6821. \end{minipage}
  6822. &
  6823. \begin{minipage}{0.3\textwidth}
  6824. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6825. _mainstart:
  6826. leaq _add90(%rip), %rsi
  6827. movq $40, %rcx
  6828. movq $2, %rdx
  6829. movq %rsi, %rax
  6830. addq $0, %rsp
  6831. popq %r14
  6832. popq %r13
  6833. popq %rbx
  6834. popq %r12
  6835. subq $0, %r15
  6836. popq %rbp
  6837. jmp *%rax
  6838. .globl _main
  6839. .align 16
  6840. _main:
  6841. pushq %rbp
  6842. movq %rsp, %rbp
  6843. pushq %r12
  6844. pushq %rbx
  6845. pushq %r13
  6846. pushq %r14
  6847. subq $0, %rsp
  6848. movq $16384, %rdi
  6849. movq $16, %rsi
  6850. callq _initialize
  6851. movq _rootstack_begin(%rip), %r15
  6852. jmp _mainstart
  6853. \end{lstlisting}
  6854. \end{minipage}
  6855. &
  6856. \begin{minipage}{0.3\textwidth}
  6857. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6858. _mainconclusion:
  6859. addq $0, %rsp
  6860. popq %r14
  6861. popq %r13
  6862. popq %rbx
  6863. popq %r12
  6864. subq $0, %r15
  6865. popq %rbp
  6866. retq
  6867. \end{lstlisting}
  6868. \end{minipage}
  6869. \end{tabular}
  6870. \caption{Example compilation of a simple function to x86.}
  6871. \label{fig:add-fun}
  6872. \end{figure}
  6873. \begin{exercise}\normalfont
  6874. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6875. Create 5 new programs that use functions, including examples that pass
  6876. functions and return functions from other functions and including
  6877. recursive functions. Test your compiler on these new programs and all
  6878. of your previously created test programs.
  6879. \end{exercise}
  6880. \begin{figure}[p]
  6881. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6882. \node (R4) at (0,2) {\large $R_4$};
  6883. \node (R4-2) at (3,2) {\large $R_4$};
  6884. \node (R4-3) at (6,2) {\large $R_4$};
  6885. \node (F1-1) at (12,0) {\large $F_1$};
  6886. \node (F1-2) at (9,0) {\large $F_1$};
  6887. \node (F1-3) at (6,0) {\large $F_1$};
  6888. \node (F1-4) at (3,0) {\large $F_1$};
  6889. \node (C3-1) at (6,-2) {\large $C_3$};
  6890. \node (C3-2) at (3,-2) {\large $C_3$};
  6891. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6892. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6893. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  6894. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6895. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6896. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6897. \path[->,bend left=15] (R4) edge [above] node
  6898. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6899. \path[->,bend left=15] (R4-2) edge [above] node
  6900. {\ttfamily\footnotesize uniquify} (R4-3);
  6901. \path[->,bend left=15] (R4-3) edge [right] node
  6902. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6903. \path[->,bend left=15] (F1-1) edge [below] node
  6904. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6905. \path[->,bend right=15] (F1-2) edge [above] node
  6906. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6907. \path[->,bend right=15] (F1-3) edge [above] node
  6908. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6909. \path[->,bend left=15] (F1-4) edge [right] node
  6910. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6911. \path[->,bend left=15] (C3-1) edge [below] node
  6912. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6913. \path[->,bend right=15] (C3-2) edge [left] node
  6914. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6915. \path[->,bend left=15] (x86-2) edge [left] node
  6916. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6917. \path[->,bend right=15] (x86-2-1) edge [below] node
  6918. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6919. \path[->,bend right=15] (x86-2-2) edge [left] node
  6920. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6921. \path[->,bend left=15] (x86-3) edge [above] node
  6922. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6923. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6924. \end{tikzpicture}
  6925. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6926. \label{fig:R4-passes}
  6927. \end{figure}
  6928. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6929. the compilation of $R_4$.
  6930. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6931. \chapter{Lexically Scoped Functions}
  6932. \label{ch:lambdas}
  6933. \index{lambda}
  6934. \index{lexical scoping}
  6935. This chapter studies lexically scoped functions as they appear in
  6936. functional languages such as Racket. By lexical scoping we mean that a
  6937. function's body may refer to variables whose binding site is outside
  6938. of the function, in an enclosing scope.
  6939. %
  6940. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6941. anonymous function defined using the \key{lambda} form. The body of
  6942. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6943. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6944. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6945. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6946. returned from the function \code{f}. Below the definition of \code{f},
  6947. we have two calls to \code{f} with different arguments for \code{x},
  6948. first \code{5} then \code{3}. The functions returned from \code{f} are
  6949. bound to variables \code{g} and \code{h}. Even though these two
  6950. functions were created by the same \code{lambda}, they are really
  6951. different functions because they use different values for
  6952. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6953. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6954. the result of this program is \code{42}.
  6955. \begin{figure}[btp]
  6956. % s4_6.rkt
  6957. \begin{lstlisting}
  6958. (define (f [x : Integer]) : (Integer -> Integer)
  6959. (let ([y 4])
  6960. (lambda: ([z : Integer]) : Integer
  6961. (+ x (+ y z)))))
  6962. (let ([g (f 5)])
  6963. (let ([h (f 3)])
  6964. (+ (g 11) (h 15))))
  6965. \end{lstlisting}
  6966. \caption{Example of a lexically scoped function.}
  6967. \label{fig:lexical-scoping}
  6968. \end{figure}
  6969. \section{The $R_5$ Language}
  6970. The syntax for this language with anonymous functions and lexical
  6971. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6972. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6973. for function application. In this chapter we shall describe how to
  6974. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6975. into a combination of functions (as in $R_4$) and tuples (as in
  6976. $R_3$).
  6977. \begin{figure}[tp]
  6978. \centering
  6979. \fbox{
  6980. \begin{minipage}{0.96\textwidth}
  6981. \[
  6982. \begin{array}{lcl}
  6983. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6984. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  6985. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  6986. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6987. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6988. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6989. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6990. \mid (\key{and}\;\Exp\;\Exp)
  6991. \mid (\key{or}\;\Exp\;\Exp)
  6992. \mid (\key{not}\;\Exp) } \\
  6993. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6994. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6995. (\key{vector-ref}\;\Exp\;\Int)} \\
  6996. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6997. &\mid& \gray{(\Exp \; \Exp\ldots)} \\
  6998. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp) \\
  6999. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7000. R_5 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7001. \end{array}
  7002. \]
  7003. \end{minipage}
  7004. }
  7005. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7006. with \key{lambda}.}
  7007. \label{fig:r5-syntax}
  7008. \end{figure}
  7009. To compile lexically-scoped functions to top-level function
  7010. definitions, the compiler will need to provide special treatment to
  7011. variable occurrences such as \code{x} and \code{y} in the body of the
  7012. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  7013. of $R_4$ may not refer to variables defined outside the function. To
  7014. identify such variable occurrences, we review the standard notion of
  7015. free variable.
  7016. \begin{definition}
  7017. A variable is \emph{free with respect to an expression} $e$ if the
  7018. variable occurs inside $e$ but does not have an enclosing binding in
  7019. $e$.\index{free variable}
  7020. \end{definition}
  7021. For example, the variables \code{x}, \code{y}, and \code{z} are all
  7022. free with respect to the expression \code{(+ x (+ y z))}. On the
  7023. other hand, only \code{x} and \code{y} are free with respect to the
  7024. following expression because \code{z} is bound by the \code{lambda}.
  7025. \begin{lstlisting}
  7026. (lambda: ([z : Integer]) : Integer
  7027. (+ x (+ y z)))
  7028. \end{lstlisting}
  7029. Once we have identified the free variables of a \code{lambda}, we need
  7030. to arrange for some way to transport, at runtime, the values of those
  7031. variables from the point where the \code{lambda} was created to the
  7032. point where the \code{lambda} is applied. Referring again to
  7033. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  7034. needs to be used in the application of \code{g} to \code{11}, but the
  7035. binding of \code{x} to \code{3} needs to be used in the application of
  7036. \code{h} to \code{15}. An efficient solution to the problem, due to
  7037. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7038. free variables together with the function pointer for the lambda's
  7039. code, an arrangement called a \emph{flat closure} (which we shorten to
  7040. just ``closure'').
  7041. \index{closure}\index{flat closure}
  7042. Fortunately, we have all the ingredients to make
  7043. closures, Chapter~\ref{ch:tuples} gave us vectors and
  7044. Chapter~\ref{ch:functions} gave us function pointers. The function
  7045. pointer shall reside at index $0$ and the values for free variables
  7046. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  7047. the two closures created by the two calls to \code{f} in
  7048. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  7049. the same \key{lambda}, they share the same function pointer but differ
  7050. in the values for the free variable \code{x}.
  7051. \begin{figure}[tbp]
  7052. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7053. \caption{Example closure representation for the \key{lambda}'s
  7054. in Figure~\ref{fig:lexical-scoping}.}
  7055. \label{fig:closures}
  7056. \end{figure}
  7057. \section{Interpreting $R_5$}
  7058. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7059. $R_5$. The clause for \key{lambda} saves the current environment
  7060. inside the returned \key{lambda}. Then the clause for \key{app} uses
  7061. the environment from the \key{lambda}, the \code{lam-env}, when
  7062. interpreting the body of the \key{lambda}. The \code{lam-env}
  7063. environment is extended with the mapping of parameters to argument
  7064. values.
  7065. \begin{figure}[tbp]
  7066. \begin{lstlisting}
  7067. (define (interp-exp env)
  7068. (lambda (e)
  7069. (define recur (interp-exp env))
  7070. (match e
  7071. ...
  7072. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  7073. `(lambda ,xs ,body ,env)]
  7074. [`(app ,fun ,args ...)
  7075. (define fun-val ((interp-exp env) fun))
  7076. (define arg-vals (map (interp-exp env) args))
  7077. (match fun-val
  7078. [`(lambda (,xs ...) ,body ,lam-env)
  7079. (define new-env (append (map cons xs arg-vals) lam-env))
  7080. ((interp-exp new-env) body)]
  7081. [else (error "interp-exp, expected function, not" fun-val)])]
  7082. [else (error 'interp-exp "unrecognized expression")]
  7083. )))
  7084. \end{lstlisting}
  7085. \caption{Interpreter for $R_5$.}
  7086. \label{fig:interp-R5}
  7087. \end{figure}
  7088. \section{Type Checking $R_5$}
  7089. \label{sec:type-check-r5}
  7090. \index{type checking}
  7091. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  7092. \key{lambda} form. The body of the \key{lambda} is checked in an
  7093. environment that includes the current environment (because it is
  7094. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7095. require the body's type to match the declared return type.
  7096. \begin{figure}[tbp]
  7097. \begin{lstlisting}
  7098. (define (typecheck-R5 env)
  7099. (lambda (e)
  7100. (match e
  7101. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  7102. (define new-env (append (map cons xs Ts) env))
  7103. (define bodyT ((typecheck-R5 new-env) body))
  7104. (cond [(equal? rT bodyT)
  7105. `(,@Ts -> ,rT)]
  7106. [else
  7107. (error "mismatch in return type" bodyT rT)])]
  7108. ...
  7109. )))
  7110. \end{lstlisting}
  7111. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7112. \label{fig:typecheck-R5}
  7113. \end{figure}
  7114. \section{Closure Conversion}
  7115. \label{sec:closure-conversion}
  7116. \index{closure conversion}
  7117. The compiling of lexically-scoped functions into top-level function
  7118. definitions is accomplished in the pass \code{convert-to-closures}
  7119. that comes after \code{reveal-functions} and before
  7120. \code{limit-functions}.
  7121. As usual, we shall implement the pass as a recursive function over the
  7122. AST. All of the action is in the clauses for \key{lambda} and
  7123. \key{app}. We transform a \key{lambda} expression into an expression
  7124. that creates a closure, that is, creates a vector whose first element
  7125. is a function pointer and the rest of the elements are the free
  7126. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7127. generated to identify the function.
  7128. \begin{tabular}{lll}
  7129. \begin{minipage}{0.4\textwidth}
  7130. \begin{lstlisting}
  7131. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7132. \end{lstlisting}
  7133. \end{minipage}
  7134. &
  7135. $\Rightarrow$
  7136. &
  7137. \begin{minipage}{0.4\textwidth}
  7138. \begin{lstlisting}
  7139. (vector |\itm{name}| |\itm{fvs}| ...)
  7140. \end{lstlisting}
  7141. \end{minipage}
  7142. \end{tabular} \\
  7143. %
  7144. In addition to transforming each \key{lambda} into a \key{vector}, we
  7145. must create a top-level function definition for each \key{lambda}, as
  7146. shown below.\\
  7147. \begin{minipage}{0.8\textwidth}
  7148. \begin{lstlisting}
  7149. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7150. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7151. ...
  7152. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7153. |\itm{body'}|)...))
  7154. \end{lstlisting}
  7155. \end{minipage}\\
  7156. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7157. parameters are the normal parameters of the \key{lambda}. The types
  7158. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7159. underscore is a dummy type because it is rather difficult to give a
  7160. type to the function in the closure's type, and it does not matter.
  7161. The sequence of \key{let} forms bind the free variables to their
  7162. values obtained from the closure.
  7163. We transform function application into code that retrieves the
  7164. function pointer from the closure and then calls the function, passing
  7165. in the closure as the first argument. We bind $e'$ to a temporary
  7166. variable to avoid code duplication.
  7167. \begin{tabular}{lll}
  7168. \begin{minipage}{0.3\textwidth}
  7169. \begin{lstlisting}
  7170. (app |$e$| |\itm{es}| ...)
  7171. \end{lstlisting}
  7172. \end{minipage}
  7173. &
  7174. $\Rightarrow$
  7175. &
  7176. \begin{minipage}{0.5\textwidth}
  7177. \begin{lstlisting}
  7178. (let ([|\itm{tmp}| |$e'$|])
  7179. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7180. \end{lstlisting}
  7181. \end{minipage}
  7182. \end{tabular} \\
  7183. There is also the question of what to do with top-level function
  7184. definitions. To maintain a uniform translation of function
  7185. application, we turn function references into closures.
  7186. \begin{tabular}{lll}
  7187. \begin{minipage}{0.3\textwidth}
  7188. \begin{lstlisting}
  7189. (fun-ref |$f$|)
  7190. \end{lstlisting}
  7191. \end{minipage}
  7192. &
  7193. $\Rightarrow$
  7194. &
  7195. \begin{minipage}{0.5\textwidth}
  7196. \begin{lstlisting}
  7197. (vector (fun-ref |$f$|))
  7198. \end{lstlisting}
  7199. \end{minipage}
  7200. \end{tabular} \\
  7201. %
  7202. The top-level function definitions need to be updated as well to take
  7203. an extra closure parameter.
  7204. \section{An Example Translation}
  7205. \label{sec:example-lambda}
  7206. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  7207. conversion for the example program demonstrating lexical scoping that
  7208. we discussed at the beginning of this chapter.
  7209. \begin{figure}[h]
  7210. \begin{minipage}{0.8\textwidth}
  7211. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7212. (program
  7213. (define (f [x : Integer]) : (Integer -> Integer)
  7214. (let ([y 4])
  7215. (lambda: ([z : Integer]) : Integer
  7216. (+ x (+ y z)))))
  7217. (let ([g (f 5)])
  7218. (let ([h (f 3)])
  7219. (+ (g 11) (h 15)))))
  7220. \end{lstlisting}
  7221. $\Downarrow$
  7222. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7223. (program (type Integer)
  7224. (define (f (x : Integer)) : (Integer -> Integer)
  7225. (let ((y 4))
  7226. (lambda: ((z : Integer)) : Integer
  7227. (+ x (+ y z)))))
  7228. (let ((g (app (fun-ref f) 5)))
  7229. (let ((h (app (fun-ref f) 3)))
  7230. (+ (app g 11) (app h 15)))))
  7231. \end{lstlisting}
  7232. $\Downarrow$
  7233. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7234. (program (type Integer)
  7235. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  7236. (let ((y 4))
  7237. (vector (fun-ref lam.1) x y)))
  7238. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  7239. (let ((x (vector-ref clos.2 1)))
  7240. (let ((y (vector-ref clos.2 2)))
  7241. (+ x (+ y z)))))
  7242. (let ((g (let ((t.1 (vector (fun-ref f))))
  7243. (app (vector-ref t.1 0) t.1 5))))
  7244. (let ((h (let ((t.2 (vector (fun-ref f))))
  7245. (app (vector-ref t.2 0) t.2 3))))
  7246. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  7247. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  7248. \end{lstlisting}
  7249. \end{minipage}
  7250. \caption{Example of closure conversion.}
  7251. \label{fig:lexical-functions-example}
  7252. \end{figure}
  7253. \begin{figure}[p]
  7254. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7255. \node (R4) at (0,2) {\large $R_4$};
  7256. \node (R4-2) at (3,2) {\large $R_4$};
  7257. \node (R4-3) at (6,2) {\large $R_4$};
  7258. \node (F1-1) at (12,0) {\large $F_1$};
  7259. \node (F1-2) at (9,0) {\large $F_1$};
  7260. \node (F1-3) at (6,0) {\large $F_1$};
  7261. \node (F1-4) at (3,0) {\large $F_1$};
  7262. \node (F1-5) at (0,0) {\large $F_1$};
  7263. \node (C3-1) at (6,-2) {\large $C_3$};
  7264. \node (C3-2) at (3,-2) {\large $C_3$};
  7265. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7266. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7267. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7268. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7269. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7270. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7271. \path[->,bend left=15] (R4) edge [above] node
  7272. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7273. \path[->,bend left=15] (R4-2) edge [above] node
  7274. {\ttfamily\footnotesize uniquify} (R4-3);
  7275. \path[->] (R4-3) edge [right] node
  7276. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7277. \path[->,bend left=15] (F1-1) edge [below] node
  7278. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7279. \path[->,bend right=15] (F1-2) edge [above] node
  7280. {\ttfamily\footnotesize limit-functions} (F1-3);
  7281. \path[->,bend right=15] (F1-3) edge [above] node
  7282. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7283. \path[->,bend right=15] (F1-4) edge [above] node
  7284. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7285. \path[->] (F1-5) edge [left] node
  7286. {\ttfamily\footnotesize explicate-control} (C3-1);
  7287. \path[->,bend left=15] (C3-1) edge [below] node
  7288. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7289. \path[->,bend right=15] (C3-2) edge [left] node
  7290. {\ttfamily\footnotesize select-instr.} (x86-2);
  7291. \path[->,bend left=15] (x86-2) edge [left] node
  7292. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7293. \path[->,bend right=15] (x86-2-1) edge [below] node
  7294. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7295. \path[->,bend right=15] (x86-2-2) edge [left] node
  7296. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7297. \path[->,bend left=15] (x86-3) edge [above] node
  7298. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7299. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7300. \end{tikzpicture}
  7301. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7302. functions.}
  7303. \label{fig:R5-passes}
  7304. \end{figure}
  7305. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7306. for the compilation of $R_5$.
  7307. \begin{exercise}\normalfont
  7308. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7309. Create 5 new programs that use \key{lambda} functions and make use of
  7310. lexical scoping. Test your compiler on these new programs and all of
  7311. your previously created test programs.
  7312. \end{exercise}
  7313. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7314. \chapter{Dynamic Typing}
  7315. \label{ch:type-dynamic}
  7316. \index{dynamic typing}
  7317. In this chapter we discuss the compilation of a dynamically typed
  7318. language, named $R_7$, that is a subset of the Racket
  7319. language. (Recall that in the previous chapters we have studied
  7320. subsets of the \emph{Typed} Racket language.) In dynamically typed
  7321. languages, an expression may produce values of differing
  7322. type. Consider the following example with a conditional expression
  7323. that may return a Boolean or an integer depending on the input to the
  7324. program.
  7325. \begin{lstlisting}
  7326. (not (if (eq? (read) 1) #f 0))
  7327. \end{lstlisting}
  7328. Languages that allow expressions to produce different kinds of values
  7329. are called \emph{polymorphic}. There are many kinds of polymorphism,
  7330. such as subtype polymorphism and parametric
  7331. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we are
  7332. talking about here does not have a special name, but it is the usual
  7333. kind that arises in dynamically typed languages.
  7334. Another characteristic of dynamically typed languages is that
  7335. primitive operations, such as \code{not}, are often defined to operate
  7336. on many different types of values. In fact, in Racket, the \code{not}
  7337. operator produces a result for any kind of value: given \code{\#f} it
  7338. returns \code{\#t} and given anything else it returns \code{\#f}.
  7339. Furthermore, even when primitive operations restrict their inputs to
  7340. values of a certain type, this restriction is enforced at runtime
  7341. instead of during compilation. For example, the following vector
  7342. reference results in a run-time contract violation.
  7343. \begin{lstlisting}
  7344. (vector-ref (vector 42) #t)
  7345. \end{lstlisting}
  7346. \begin{figure}[tp]
  7347. \centering
  7348. \fbox{
  7349. \begin{minipage}{0.97\textwidth}
  7350. \[
  7351. \begin{array}{rcl}
  7352. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7353. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7354. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  7355. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  7356. &\mid& \key{\#t} \mid \key{\#f}
  7357. \mid (\key{and}\;\Exp\;\Exp)
  7358. \mid (\key{or}\;\Exp\;\Exp)
  7359. \mid (\key{not}\;\Exp) \\
  7360. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  7361. &\mid& (\key{vector}\;\Exp\ldots) \mid
  7362. (\key{vector-ref}\;\Exp\;\Exp) \\
  7363. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  7364. &\mid& (\Exp \; \Exp\ldots) \mid (\key{lambda}\; (\Var\ldots) \; \Exp) \\
  7365. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7366. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7367. \Def &::=& (\key{define}\; (\Var \; \Var\ldots) \; \Exp) \\
  7368. R_7 &::=& (\key{program} \; \Def\ldots\; \Exp)
  7369. \end{array}
  7370. \]
  7371. \end{minipage}
  7372. }
  7373. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7374. \label{fig:r7-syntax}
  7375. \end{figure}
  7376. The syntax of $R_7$, our subset of Racket, is defined in
  7377. Figure~\ref{fig:r7-syntax}.
  7378. %
  7379. The definitional interpreter for $R_7$ is given in
  7380. Figure~\ref{fig:interp-R7}.
  7381. \begin{figure}[tbp]
  7382. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7383. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  7384. (define (valid-op? op) (member op '(+ - and or not)))
  7385. (define (interp-r7 env)
  7386. (lambda (ast)
  7387. (define recur (interp-r7 env))
  7388. (match ast
  7389. [(? symbol?) (lookup ast env)]
  7390. [(? integer?) `(inject ,ast Integer)]
  7391. [#t `(inject #t Boolean)]
  7392. [#f `(inject #f Boolean)]
  7393. [`(read) `(inject ,(read-fixnum) Integer)]
  7394. [`(lambda (,xs ...) ,body)
  7395. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  7396. [`(define (,f ,xs ...) ,body)
  7397. (mcons f `(lambda ,xs ,body))]
  7398. [`(program ,ds ... ,body)
  7399. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  7400. (for/list ([b top-level])
  7401. (set-mcdr! b (match (mcdr b)
  7402. [`(lambda ,xs ,body)
  7403. `(inject (lambda ,xs ,body ,top-level)
  7404. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  7405. ((interp-r7 top-level) body))]
  7406. [`(vector ,(app recur elts) ...)
  7407. (define tys (map get-tagged-type elts))
  7408. `(inject ,(apply vector elts) (Vector ,@tys))]
  7409. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  7410. (match v1
  7411. [`(inject ,vec ,ty)
  7412. (vector-set! vec n v2)
  7413. `(inject (void) Void)])]
  7414. [`(vector-ref ,(app recur v) ,n)
  7415. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  7416. [`(let ([,x ,(app recur v)]) ,body)
  7417. ((interp-r7 (cons (cons x v) env)) body)]
  7418. [`(,op ,es ...) #:when (valid-op? op)
  7419. (interp-r7-op op (for/list ([e es]) (recur e)))]
  7420. [`(eq? ,(app recur l) ,(app recur r))
  7421. `(inject ,(equal? l r) Boolean)]
  7422. [`(if ,(app recur q) ,t ,f)
  7423. (match q
  7424. [`(inject #f Boolean) (recur f)]
  7425. [else (recur t)])]
  7426. [`(,(app recur f-val) ,(app recur vs) ...)
  7427. (match f-val
  7428. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  7429. (define new-env (append (map cons xs vs) lam-env))
  7430. ((interp-r7 new-env) body)]
  7431. [else (error "interp-r7, expected function, not" f-val)])])))
  7432. \end{lstlisting}
  7433. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  7434. \label{fig:interp-R7}
  7435. \end{figure}
  7436. Let us consider how we might compile $R_7$ to x86, thinking about the
  7437. first example above. Our bit-level representation of the Boolean
  7438. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7439. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7440. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7441. general, cannot be determined at compile time, but depends on the
  7442. runtime type of its input, as in the example above that depends on the
  7443. result of \code{(read)}.
  7444. The way around this problem is to include information about a value's
  7445. runtime type in the value itself, so that this information can be
  7446. inspected by operators such as \code{not}. In particular, we shall
  7447. steal the 3 right-most bits from our 64-bit values to encode the
  7448. runtime type. We shall use $001$ to identify integers, $100$ for
  7449. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7450. void value. We shall refer to these 3 bits as the \emph{tag} and we
  7451. define the following auxiliary function.
  7452. \begin{align*}
  7453. \itm{tagof}(\key{Integer}) &= 001 \\
  7454. \itm{tagof}(\key{Boolean}) &= 100 \\
  7455. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7456. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7457. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7458. \itm{tagof}(\key{Void}) &= 101
  7459. \end{align*}
  7460. (We shall say more about the new \key{Vectorof} type shortly.)
  7461. This stealing of 3 bits comes at some
  7462. price: our integers are reduced to ranging from $-2^{60}$ to
  7463. $2^{60}$. The stealing does not adversely affect vectors and
  7464. procedures because those values are addresses, and our addresses are
  7465. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7466. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7467. bits with the tag and we can simply zero-out the tag to recover the
  7468. original address.
  7469. In some sense, these tagged values are a new kind of value. Indeed,
  7470. we can extend our \emph{typed} language with tagged values by adding a
  7471. new type to classify them, called \key{Any}, and with operations for
  7472. creating and using tagged values, yielding the $R_6$ language that we
  7473. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7474. fundamental support for polymorphism and runtime types that we need to
  7475. support dynamic typing.
  7476. There is an interesting interaction between tagged values and garbage
  7477. collection. A variable of type \code{Any} might refer to a vector and
  7478. therefore it might be a root that needs to be inspected and copied
  7479. during garbage collection. Thus, we need to treat variables of type
  7480. \code{Any} in a similar way to variables of type \code{Vector} for
  7481. purposes of register allocation, which we discuss in
  7482. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7483. variable of type \code{Any} is spilled, it must be spilled to the root
  7484. stack. But this means that the garbage collector needs to be able to
  7485. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7486. value that points to a tuple, and (3) a tagged value that is not a
  7487. tuple. We enable this differentiation by choosing not to use the tag
  7488. $000$. Instead, that bit pattern is reserved for identifying plain old
  7489. pointers to tuples. On the other hand, if one of the first three bits
  7490. is set, then we have a tagged value, and inspecting the tag can
  7491. differentiation between vectors ($010$) and the other kinds of values.
  7492. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  7493. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7494. extend our compiler to handle the new features of $R_6$
  7495. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7496. \ref{sec:register-allocation-r6}).
  7497. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7498. \label{sec:r6-lang}
  7499. \begin{figure}[tp]
  7500. \centering
  7501. \fbox{
  7502. \begin{minipage}{0.97\textwidth}
  7503. \[
  7504. \begin{array}{lcl}
  7505. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7506. \mid (\key{Vector}\;\Type\ldots) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7507. &\mid& \gray{(\Type\ldots \; \key{->}\; \Type)} \mid \key{Any} \\
  7508. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}\ldots) \\
  7509. &\mid& (\key{Any}\ldots \; \key{->}\; \key{Any})\\
  7510. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7511. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7512. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7513. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7514. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7515. \mid (\key{and}\;\Exp\;\Exp)
  7516. \mid (\key{or}\;\Exp\;\Exp)
  7517. \mid (\key{not}\;\Exp)} \\
  7518. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7519. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7520. (\key{vector-ref}\;\Exp\;\Int)} \\
  7521. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7522. &\mid& \gray{(\Exp \; \Exp\ldots)
  7523. \mid (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7524. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7525. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7526. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7527. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7528. R_6 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7529. \end{array}
  7530. \]
  7531. \end{minipage}
  7532. }
  7533. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7534. with \key{Any}.}
  7535. \label{fig:r6-syntax}
  7536. \end{figure}
  7537. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7538. $(\key{inject}\; e\; T)$ form converts the value produced by
  7539. expression $e$ of type $T$ into a tagged value. The
  7540. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7541. expression $e$ into a value of type $T$ or else halts the program if
  7542. the type tag is equivalent to $T$. We treat
  7543. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7544. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7545. Note that in both \key{inject} and
  7546. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7547. which simplifies the implementation and corresponds with what is
  7548. needed for compiling untyped Racket. The type predicates,
  7549. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7550. if the tag corresponds to the predicate, and return \key{\#t}
  7551. otherwise.
  7552. %
  7553. Selections from the type checker for $R_6$ are shown in
  7554. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7555. Figure~\ref{fig:interp-R6}.
  7556. \begin{figure}[btp]
  7557. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7558. (define (flat-ty? ty) ...)
  7559. (define (typecheck-R6 env)
  7560. (lambda (e)
  7561. (define recur (typecheck-R6 env))
  7562. (match e
  7563. [`(inject ,e ,ty)
  7564. (unless (flat-ty? ty)
  7565. (error "may only inject a value of flat type, not ~a" ty))
  7566. (define-values (new-e e-ty) (recur e))
  7567. (cond
  7568. [(equal? e-ty ty)
  7569. (values `(inject ,new-e ,ty) 'Any)]
  7570. [else
  7571. (error "inject expected ~a to have type ~a" e ty)])]
  7572. [`(project ,e ,ty)
  7573. (unless (flat-ty? ty)
  7574. (error "may only project to a flat type, not ~a" ty))
  7575. (define-values (new-e e-ty) (recur e))
  7576. (cond
  7577. [(equal? e-ty 'Any)
  7578. (values `(project ,new-e ,ty) ty)]
  7579. [else
  7580. (error "project expected ~a to have type Any" e)])]
  7581. [`(vector-ref ,e ,i)
  7582. (define-values (new-e e-ty) (recur e))
  7583. (match e-ty
  7584. [`(Vector ,ts ...) ...]
  7585. [`(Vectorof ,ty)
  7586. (unless (exact-nonnegative-integer? i)
  7587. (error 'type-check "invalid index ~a" i))
  7588. (values `(vector-ref ,new-e ,i) ty)]
  7589. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7590. ...
  7591. )))
  7592. \end{lstlisting}
  7593. \caption{Type checker for parts of the $R_6$ language.}
  7594. \label{fig:typecheck-R6}
  7595. \end{figure}
  7596. % to do: add rules for vector-ref, etc. for Vectorof
  7597. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7598. \begin{figure}[btp]
  7599. \begin{lstlisting}
  7600. (define primitives (set 'boolean? ...))
  7601. (define (interp-op op)
  7602. (match op
  7603. ['boolean? (lambda (v)
  7604. (match v
  7605. [`(tagged ,v1 Boolean) #t]
  7606. [else #f]))]
  7607. ...))
  7608. ;; Equivalence of flat types
  7609. (define (tyeq? t1 t2)
  7610. (match `(,t1 ,t2)
  7611. [`((Vectorof Any) (Vector ,t2s ...))
  7612. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7613. [`((Vector ,t1s ...) (Vectorof Any))
  7614. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7615. [else (equal? t1 t2)]))
  7616. (define (interp-R6 env)
  7617. (lambda (ast)
  7618. (match ast
  7619. [`(inject ,e ,t)
  7620. `(tagged ,((interp-R6 env) e) ,t)]
  7621. [`(project ,e ,t2)
  7622. (define v ((interp-R6 env) e))
  7623. (match v
  7624. [`(tagged ,v1 ,t1)
  7625. (cond [(tyeq? t1 t2)
  7626. v1]
  7627. [else
  7628. (error "in project, type mismatch" t1 t2)])]
  7629. [else
  7630. (error "in project, expected tagged value" v)])]
  7631. ...)))
  7632. \end{lstlisting}
  7633. \caption{Interpreter for $R_6$.}
  7634. \label{fig:interp-R6}
  7635. \end{figure}
  7636. %\clearpage
  7637. \section{Shrinking $R_6$}
  7638. \label{sec:shrink-r6}
  7639. In the \code{shrink} pass we recommend compiling \code{project} into
  7640. an explicit \code{if} expression that uses three new operations:
  7641. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7642. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7643. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7644. value from a tagged value. Finally, the \code{exit} operation ends the
  7645. execution of the program by invoking the operating system's
  7646. \code{exit} function. So the translation for \code{project} is as
  7647. follows. (We have omitted the \code{has-type} AST nodes to make this
  7648. output more readable.)
  7649. \begin{tabular}{lll}
  7650. \begin{minipage}{0.3\textwidth}
  7651. \begin{lstlisting}
  7652. (project |$e$| |$\Type$|)
  7653. \end{lstlisting}
  7654. \end{minipage}
  7655. &
  7656. $\Rightarrow$
  7657. &
  7658. \begin{minipage}{0.5\textwidth}
  7659. \begin{lstlisting}
  7660. (let ([|$\itm{tmp}$| |$e'$|])
  7661. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7662. (value-of-any |$\itm{tmp}$|)
  7663. (exit)))
  7664. \end{lstlisting}
  7665. \end{minipage}
  7666. \end{tabular} \\
  7667. Similarly, we recommend translating the type predicates
  7668. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7669. \section{Instruction Selection for $R_6$}
  7670. \label{sec:select-r6}
  7671. \paragraph{Inject}
  7672. We recommend compiling an \key{inject} as follows if the type is
  7673. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7674. destination to the left by the number of bits specified its source
  7675. argument (in this case $3$, the length of the tag) and it preserves
  7676. the sign of the integer. We use the \key{orq} instruction to combine
  7677. the tag and the value to form the tagged value. \\
  7678. \begin{tabular}{lll}
  7679. \begin{minipage}{0.4\textwidth}
  7680. \begin{lstlisting}
  7681. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7682. \end{lstlisting}
  7683. \end{minipage}
  7684. &
  7685. $\Rightarrow$
  7686. &
  7687. \begin{minipage}{0.5\textwidth}
  7688. \begin{lstlisting}
  7689. (movq |$e'$| |\itm{lhs}'|)
  7690. (salq (int 3) |\itm{lhs}'|)
  7691. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7692. \end{lstlisting}
  7693. \end{minipage}
  7694. \end{tabular} \\
  7695. The instruction selection for vectors and procedures is different
  7696. because their is no need to shift them to the left. The rightmost 3
  7697. bits are already zeros as described above. So we just combine the
  7698. value and the tag using \key{orq}. \\
  7699. \begin{tabular}{lll}
  7700. \begin{minipage}{0.4\textwidth}
  7701. \begin{lstlisting}
  7702. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7703. \end{lstlisting}
  7704. \end{minipage}
  7705. &
  7706. $\Rightarrow$
  7707. &
  7708. \begin{minipage}{0.5\textwidth}
  7709. \begin{lstlisting}
  7710. (movq |$e'$| |\itm{lhs}'|)
  7711. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7712. \end{lstlisting}
  7713. \end{minipage}
  7714. \end{tabular}
  7715. \paragraph{Tag of Any}
  7716. Recall that the \code{tag-of-any} operation extracts the type tag from
  7717. a value of type \code{Any}. The type tag is the bottom three bits, so
  7718. we obtain the tag by taking the bitwise-and of the value with $111$
  7719. ($7$ in decimal).
  7720. \begin{tabular}{lll}
  7721. \begin{minipage}{0.4\textwidth}
  7722. \begin{lstlisting}
  7723. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7724. \end{lstlisting}
  7725. \end{minipage}
  7726. &
  7727. $\Rightarrow$
  7728. &
  7729. \begin{minipage}{0.5\textwidth}
  7730. \begin{lstlisting}
  7731. (movq |$e'$| |\itm{lhs}'|)
  7732. (andq (int 7) |\itm{lhs}'|)
  7733. \end{lstlisting}
  7734. \end{minipage}
  7735. \end{tabular}
  7736. \paragraph{Value of Any}
  7737. Like \key{inject}, the instructions for \key{value-of-any} are
  7738. different depending on whether the type $T$ is a pointer (vector or
  7739. procedure) or not (Integer or Boolean). The following shows the
  7740. instruction selection for Integer and Boolean. We produce an untagged
  7741. value by shifting it to the right by 3 bits.
  7742. %
  7743. \\
  7744. \begin{tabular}{lll}
  7745. \begin{minipage}{0.4\textwidth}
  7746. \begin{lstlisting}
  7747. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7748. \end{lstlisting}
  7749. \end{minipage}
  7750. &
  7751. $\Rightarrow$
  7752. &
  7753. \begin{minipage}{0.5\textwidth}
  7754. \begin{lstlisting}
  7755. (movq |$e'$| |\itm{lhs}'|)
  7756. (sarq (int 3) |\itm{lhs}'|)
  7757. \end{lstlisting}
  7758. \end{minipage}
  7759. \end{tabular} \\
  7760. %
  7761. In the case for vectors and procedures, there is no need to
  7762. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7763. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7764. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7765. \code{movq} into the destination $\itm{lhs}$. We then generate
  7766. \code{andq} with the tagged value to get the desired result. \\
  7767. %
  7768. \begin{tabular}{lll}
  7769. \begin{minipage}{0.4\textwidth}
  7770. \begin{lstlisting}
  7771. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7772. \end{lstlisting}
  7773. \end{minipage}
  7774. &
  7775. $\Rightarrow$
  7776. &
  7777. \begin{minipage}{0.5\textwidth}
  7778. \begin{lstlisting}
  7779. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7780. (andq |$e'$| |\itm{lhs}'|)
  7781. \end{lstlisting}
  7782. \end{minipage}
  7783. \end{tabular}
  7784. %% \paragraph{Type Predicates} We leave it to the reader to
  7785. %% devise a sequence of instructions to implement the type predicates
  7786. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7787. \section{Register Allocation for $R_6$}
  7788. \label{sec:register-allocation-r6}
  7789. \index{register allocation}
  7790. As mentioned above, a variable of type \code{Any} might refer to a
  7791. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7792. of type \code{Any} in the same way that it treats variables of type
  7793. \code{Vector} for purposes of garbage collection. In particular,
  7794. \begin{itemize}
  7795. \item If a variable of type \code{Any} is live during a function call,
  7796. then it must be spilled. One way to accomplish this is to augment
  7797. the pass \code{build-interference} to mark all variables that are
  7798. live after a \code{callq} as interfering with all the registers.
  7799. \item If a variable of type \code{Any} is spilled, it must be spilled
  7800. to the root stack instead of the normal procedure call stack.
  7801. \end{itemize}
  7802. \begin{exercise}\normalfont
  7803. Expand your compiler to handle $R_6$ as discussed in the last few
  7804. sections. Create 5 new programs that use the \code{Any} type and the
  7805. new operations (\code{inject}, \code{project}, \code{boolean?},
  7806. etc.). Test your compiler on these new programs and all of your
  7807. previously created test programs.
  7808. \end{exercise}
  7809. \section{Compiling $R_7$ to $R_6$}
  7810. \label{sec:compile-r7}
  7811. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7812. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7813. given a subexpression $e$ of $R_7$, the pass will produce an
  7814. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7815. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7816. the Boolean \code{\#t}, which must be injected to produce an
  7817. expression of type \key{Any}.
  7818. %
  7819. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7820. addition, is representative of compilation for many operations: the
  7821. arguments have type \key{Any} and must be projected to \key{Integer}
  7822. before the addition can be performed.
  7823. The compilation of \key{lambda} (third row of
  7824. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7825. produce type annotations: we simply use \key{Any}.
  7826. %
  7827. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7828. has to account for some differences in behavior between $R_7$ and
  7829. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7830. kind of values can be used in various places. For example, the
  7831. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7832. the arguments need not be of the same type (but in that case, the
  7833. result will be \code{\#f}).
  7834. \begin{figure}[btp]
  7835. \centering
  7836. \begin{tabular}{|lll|} \hline
  7837. \begin{minipage}{0.25\textwidth}
  7838. \begin{lstlisting}
  7839. #t
  7840. \end{lstlisting}
  7841. \end{minipage}
  7842. &
  7843. $\Rightarrow$
  7844. &
  7845. \begin{minipage}{0.6\textwidth}
  7846. \begin{lstlisting}
  7847. (inject #t Boolean)
  7848. \end{lstlisting}
  7849. \end{minipage}
  7850. \\[2ex]\hline
  7851. \begin{minipage}{0.25\textwidth}
  7852. \begin{lstlisting}
  7853. (+ |$e_1$| |$e_2$|)
  7854. \end{lstlisting}
  7855. \end{minipage}
  7856. &
  7857. $\Rightarrow$
  7858. &
  7859. \begin{minipage}{0.6\textwidth}
  7860. \begin{lstlisting}
  7861. (inject
  7862. (+ (project |$e'_1$| Integer)
  7863. (project |$e'_2$| Integer))
  7864. Integer)
  7865. \end{lstlisting}
  7866. \end{minipage}
  7867. \\[2ex]\hline
  7868. \begin{minipage}{0.25\textwidth}
  7869. \begin{lstlisting}
  7870. (lambda (|$x_1 \ldots$|) |$e$|)
  7871. \end{lstlisting}
  7872. \end{minipage}
  7873. &
  7874. $\Rightarrow$
  7875. &
  7876. \begin{minipage}{0.6\textwidth}
  7877. \begin{lstlisting}
  7878. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7879. (Any|$\ldots$|Any -> Any))
  7880. \end{lstlisting}
  7881. \end{minipage}
  7882. \\[2ex]\hline
  7883. \begin{minipage}{0.25\textwidth}
  7884. \begin{lstlisting}
  7885. (app |$e_0$| |$e_1 \ldots e_n$|)
  7886. \end{lstlisting}
  7887. \end{minipage}
  7888. &
  7889. $\Rightarrow$
  7890. &
  7891. \begin{minipage}{0.6\textwidth}
  7892. \begin{lstlisting}
  7893. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7894. |$e'_1 \ldots e'_n$|)
  7895. \end{lstlisting}
  7896. \end{minipage}
  7897. \\[2ex]\hline
  7898. \begin{minipage}{0.25\textwidth}
  7899. \begin{lstlisting}
  7900. (vector-ref |$e_1$| |$e_2$|)
  7901. \end{lstlisting}
  7902. \end{minipage}
  7903. &
  7904. $\Rightarrow$
  7905. &
  7906. \begin{minipage}{0.6\textwidth}
  7907. \begin{lstlisting}
  7908. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7909. (let ([tmp2 (project |$e'_2$| Integer)])
  7910. (vector-ref tmp1 tmp2)))
  7911. \end{lstlisting}
  7912. \end{minipage}
  7913. \\[2ex]\hline
  7914. \begin{minipage}{0.25\textwidth}
  7915. \begin{lstlisting}
  7916. (if |$e_1$| |$e_2$| |$e_3$|)
  7917. \end{lstlisting}
  7918. \end{minipage}
  7919. &
  7920. $\Rightarrow$
  7921. &
  7922. \begin{minipage}{0.6\textwidth}
  7923. \begin{lstlisting}
  7924. (if (eq? |$e'_1$| (inject #f Boolean))
  7925. |$e'_3$|
  7926. |$e'_2$|)
  7927. \end{lstlisting}
  7928. \end{minipage}
  7929. \\[2ex]\hline
  7930. \begin{minipage}{0.25\textwidth}
  7931. \begin{lstlisting}
  7932. (eq? |$e_1$| |$e_2$|)
  7933. \end{lstlisting}
  7934. \end{minipage}
  7935. &
  7936. $\Rightarrow$
  7937. &
  7938. \begin{minipage}{0.6\textwidth}
  7939. \begin{lstlisting}
  7940. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7941. \end{lstlisting}
  7942. \end{minipage}
  7943. \\[2ex]\hline
  7944. \end{tabular}
  7945. \caption{Compiling $R_7$ to $R_6$.}
  7946. \label{fig:compile-r7-r6}
  7947. \end{figure}
  7948. \begin{exercise}\normalfont
  7949. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7950. Create tests for $R_7$ by adapting all of your previous test programs
  7951. by removing type annotations. Add 5 more tests programs that
  7952. specifically rely on the language being dynamically typed. That is,
  7953. they should not be legal programs in a statically typed language, but
  7954. nevertheless, they should be valid $R_7$ programs that run to
  7955. completion without error.
  7956. \end{exercise}
  7957. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7958. \chapter{Gradual Typing}
  7959. \label{ch:gradual-typing}
  7960. \index{gradual typing}
  7961. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7962. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7963. \chapter{Parametric Polymorphism}
  7964. \label{ch:parametric-polymorphism}
  7965. \index{parametric polymorphism}
  7966. \index{generics}
  7967. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7968. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7969. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7970. \chapter{High-level Optimization}
  7971. \label{ch:high-level-optimization}
  7972. This chapter will present a procedure inlining pass based on the
  7973. algorithm of \citet{Waddell:1997fk}.
  7974. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7975. \chapter{Appendix}
  7976. \section{Interpreters}
  7977. \label{appendix:interp}
  7978. \index{interpreter}
  7979. We provide interpreters for each of the source languages $R_0$, $R_1$,
  7980. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  7981. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  7982. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  7983. the rest of the intermediate languages, including pseudo-x86 and x86
  7984. are in the \key{interp.rkt} file.
  7985. \section{Utility Functions}
  7986. \label{appendix:utilities}
  7987. The utility functions described here are in the \key{utilities.rkt}
  7988. file.
  7989. \paragraph{\code{interp-tests}}
  7990. The \key{interp-tests} function runs the compiler passes and the
  7991. interpreters on each of the specified tests to check whether each pass
  7992. is correct. The \key{interp-tests} function has the following
  7993. parameters:
  7994. \begin{description}
  7995. \item[name (a string)] a name to identify the compiler,
  7996. \item[typechecker] a function of exactly one argument that either
  7997. raises an error using the \code{error} function when it encounters a
  7998. type error, or returns \code{\#f} when it encounters a type
  7999. error. If there is no type error, the type checker returns the
  8000. program.
  8001. \item[passes] a list with one entry per pass. An entry is a list with
  8002. three things: a string giving the name of the pass, the function
  8003. that implements the pass (a translator from AST to AST), and a
  8004. function that implements the interpreter (a function from AST to
  8005. result value) for the language of the output of the pass.
  8006. \item[source-interp] an interpreter for the source language. The
  8007. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8008. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8009. \item[tests] a list of test numbers that specifies which tests to
  8010. run. (see below)
  8011. \end{description}
  8012. %
  8013. The \key{interp-tests} function assumes that the subdirectory
  8014. \key{tests} has a collection of Racket programs whose names all start
  8015. with the family name, followed by an underscore and then the test
  8016. number, ending with the file extension \key{.rkt}. Also, for each test
  8017. program that calls \code{read} one or more times, there is a file with
  8018. the same name except that the file extension is \key{.in} that
  8019. provides the input for the Racket program. If the test program is
  8020. expected to fail type checking, then there should be an empty file of
  8021. the same name but with extension \key{.tyerr}.
  8022. \paragraph{\code{compiler-tests}}
  8023. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8024. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8025. machine code and checks that the output is $42$. The parameters to the
  8026. \code{compiler-tests} function are similar to those of the
  8027. \code{interp-tests} function, and consist of
  8028. \begin{itemize}
  8029. \item a compiler name (a string),
  8030. \item a type checker,
  8031. \item description of the passes,
  8032. \item name of a test-family, and
  8033. \item a list of test numbers.
  8034. \end{itemize}
  8035. \paragraph{\code{compile-file}}
  8036. takes a description of the compiler passes (see the comment for
  8037. \key{interp-tests}) and returns a function that, given a program file
  8038. name (a string ending in \key{.rkt}), applies all of the passes and
  8039. writes the output to a file whose name is the same as the program file
  8040. name but with \key{.rkt} replaced with \key{.s}.
  8041. \paragraph{\code{read-program}}
  8042. takes a file path and parses that file (it must be a Racket program)
  8043. into an abstract syntax tree.
  8044. \paragraph{\code{parse-program}}
  8045. takes an S-expression representation of an abstract syntax tree and converts it into
  8046. the struct-based representation.
  8047. \paragraph{\code{assert}}
  8048. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8049. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8050. \paragraph{\code{lookup}}
  8051. % remove discussion of lookup? -Jeremy
  8052. takes a key and an alist, and returns the first value that is
  8053. associated with the given key, if there is one. If not, an error is
  8054. triggered. The alist may contain both immutable pairs (built with
  8055. \key{cons}) and mutable pairs (built with \key{mcons}).
  8056. %The \key{map2} function ...
  8057. \section{x86 Instruction Set Quick-Reference}
  8058. \label{sec:x86-quick-reference}
  8059. \index{x86}
  8060. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8061. do. We write $A \to B$ to mean that the value of $A$ is written into
  8062. location $B$. Address offsets are given in bytes. The instruction
  8063. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8064. registers (such as \code{\%rax}), or memory references (such as
  8065. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8066. reference per instruction. Other operands must be immediates or
  8067. registers.
  8068. \begin{table}[tbp]
  8069. \centering
  8070. \begin{tabular}{l|l}
  8071. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8072. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8073. \texttt{negq} $A$ & $- A \to A$ \\
  8074. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8075. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8076. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8077. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8078. \texttt{retq} & Pops the return address and jumps to it \\
  8079. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8080. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8081. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8082. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8083. be an immediate) \\
  8084. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8085. matches the condition code of the instruction, otherwise go to the
  8086. next instructions. The condition codes are \key{e} for ``equal'',
  8087. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8088. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8089. \texttt{jl} $L$ & \\
  8090. \texttt{jle} $L$ & \\
  8091. \texttt{jg} $L$ & \\
  8092. \texttt{jge} $L$ & \\
  8093. \texttt{jmp} $L$ & Jump to label $L$ \\
  8094. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8095. \texttt{movzbq} $A$, $B$ &
  8096. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8097. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8098. and the extra bytes of $B$ are set to zero.} \\
  8099. & \\
  8100. & \\
  8101. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8102. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8103. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8104. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8105. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8106. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8107. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8108. description of the condition codes. $A$ must be a single byte register
  8109. (e.g., \texttt{al} or \texttt{cl}).} \\
  8110. \texttt{setl} $A$ & \\
  8111. \texttt{setle} $A$ & \\
  8112. \texttt{setg} $A$ & \\
  8113. \texttt{setge} $A$ &
  8114. \end{tabular}
  8115. \vspace{5pt}
  8116. \caption{Quick-reference for the x86 instructions used in this book.}
  8117. \label{tab:x86-instr}
  8118. \end{table}
  8119. \cleardoublepage
  8120. \addcontentsline{toc}{chapter}{Index}
  8121. \printindex
  8122. \cleardoublepage
  8123. \bibliographystyle{plainnat}
  8124. \bibliography{all}
  8125. \addcontentsline{toc}{chapter}{Bibliography}
  8126. \end{document}
  8127. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8128. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8129. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8130. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8131. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8132. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8133. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8134. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8135. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8136. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8137. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8138. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8139. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  8140. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8141. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8142. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8143. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8144. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8145. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8146. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8147. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8148. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8149. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8150. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8151. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8152. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8153. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8154. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8155. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8156. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8157. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8158. % LocalWords: struct symtab