book.tex 250 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718
  1. \documentclass[11pt]{book}
  2. \usepackage[T1]{fontenc}
  3. \usepackage[utf8]{inputenc}
  4. \usepackage{lmodern}
  5. \usepackage{hyperref}
  6. \usepackage{graphicx}
  7. \usepackage[english]{babel}
  8. \usepackage{listings}
  9. \usepackage{amsmath}
  10. \usepackage{amsthm}
  11. \usepackage{amssymb}
  12. \usepackage{natbib}
  13. \usepackage{stmaryrd}
  14. \usepackage{xypic}
  15. \usepackage{semantic}
  16. \usepackage{wrapfig}
  17. \usepackage{multirow}
  18. \usepackage{color}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. %% For pictures
  23. \usepackage{tikz}
  24. \usetikzlibrary{arrows.meta}
  25. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  26. % Computer Modern is already the default. -Jeremy
  27. %\renewcommand{\ttdefault}{cmtt}
  28. \definecolor{comment-red}{rgb}{0.8,0,0}
  29. \if{0}
  30. % Peanut gallery comments:
  31. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  32. \newcommand{\margincomment}[1]{\marginpar{#1}}
  33. \else
  34. \newcommand{\rn}[1]{}
  35. \newcommand{\margincomment}[1]{}
  36. % \newcommand{\margincomment}[1]{}
  37. \fi
  38. \lstset{%
  39. language=Lisp,
  40. basicstyle=\ttfamily\small,
  41. escapechar=|,
  42. columns=flexible,
  43. moredelim=[is][\color{red}]{~}{~}
  44. }
  45. \newtheorem{theorem}{Theorem}
  46. \newtheorem{lemma}[theorem]{Lemma}
  47. \newtheorem{corollary}[theorem]{Corollary}
  48. \newtheorem{proposition}[theorem]{Proposition}
  49. \newtheorem{constraint}[theorem]{Constraint}
  50. \newtheorem{definition}[theorem]{Definition}
  51. \newtheorem{exercise}[theorem]{Exercise}
  52. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  53. % 'dedication' environment: To add a dedication paragraph at the start of book %
  54. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  55. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  56. \newenvironment{dedication}
  57. {
  58. \cleardoublepage
  59. \thispagestyle{empty}
  60. \vspace*{\stretch{1}}
  61. \hfill\begin{minipage}[t]{0.66\textwidth}
  62. \raggedright
  63. }
  64. {
  65. \end{minipage}
  66. \vspace*{\stretch{3}}
  67. \clearpage
  68. }
  69. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  70. % Chapter quote at the start of chapter %
  71. % Source: http://tex.stackexchange.com/a/53380 %
  72. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  73. \makeatletter
  74. \renewcommand{\@chapapp}{}% Not necessary...
  75. \newenvironment{chapquote}[2][2em]
  76. {\setlength{\@tempdima}{#1}%
  77. \def\chapquote@author{#2}%
  78. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  79. \itshape}
  80. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  81. \makeatother
  82. \input{defs}
  83. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  84. \title{\Huge \textbf{Essentials of Compilation} \\
  85. \huge An Incremental Approach}
  86. \author{\textsc{Jeremy G. Siek, Ryan R. Newton} \\
  87. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  88. Indiana University \\
  89. \\
  90. with contributions from: \\
  91. Carl Factora \\
  92. Andre Kuhlenschmidt \\
  93. Michael M. Vitousek \\
  94. Cameron Swords
  95. }
  96. \begin{document}
  97. \frontmatter
  98. \maketitle
  99. \begin{dedication}
  100. This book is dedicated to the programming language wonks at Indiana
  101. University.
  102. \end{dedication}
  103. \tableofcontents
  104. \listoffigures
  105. %\listoftables
  106. \mainmatter
  107. \if{0}
  108. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  109. \chapter*{Preface}
  110. The tradition of compiler writing at Indiana University goes back to
  111. programming language research and courses taught by Daniel Friedman in
  112. the 1970's and 1980's. Dan had conducted research on lazy evaluation
  113. in the context of Lisp~\citep{McCarthy:1960dz} and then studied
  114. continuations and macros in the context of the
  115. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of students of
  116. those courses, Kent Dybvig, went on to build Chez
  117. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  118. compiler for Scheme. After completing his Ph.D. at the University of
  119. North Carolina, Kent returned to teach at Indiana University.
  120. Throughout the 1990's and 2000's, Kent continued development of
  121. Chez Scheme and taught the compiler course.
  122. The compiler course evolved to incorporate novel pedagogical ideas
  123. while also including elements of effective real-world compilers. One
  124. of Dan's ideas was to split the compiler into many small passes over
  125. the input program and subsequent intermediate representations, so that
  126. the code for each pass would be easy to understood in isolation. (In
  127. contrast, most compilers of the time were organized into only a few
  128. monolithic passes for reasons of compile-time efficiency.) Kent and
  129. his students, Dipanwita Sarkar and Andrew Keep, developed
  130. infrastructure to support this approach and evolved the course, first
  131. to use micro-sized passes and then into even smaller nano
  132. passes~\citep{Sarkar:2004fk,Keep:2012aa}. I took this compiler course
  133. in the early 2000's, as part of my Ph.D. studies at Indiana
  134. University. Needless to say, I enjoyed the course immensely.
  135. \rn{I think that 1999 when I took it was the first micropass semester, and that
  136. that approach preceded the infrastructure work by Dipa.}
  137. One of my classmates, Abdulaziz Ghuloum, observed that the
  138. front-to-back organization of the course made it difficult for
  139. students to understand the rationale for the compiler
  140. design. Abdulaziz proposed an incremental approach in which the
  141. students build the compiler in stages; they start by implementing a
  142. complete compiler for a very small subset of the input language, then
  143. in each subsequent stage they add a feature to the input language and
  144. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  145. In this way, the students see how the language features motivate
  146. aspects of the compiler design.
  147. After graduating from Indiana University in 2005, I went on to teach
  148. at the University of Colorado. I adapted the nano pass and incremental
  149. approaches to compiling a subset of the Python
  150. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  151. on the surface but there is a large overlap in the compiler techniques
  152. required for the two languages. Thus, I was able to teach much of the
  153. same content from the Indiana compiler course. I very much enjoyed
  154. teaching the course organized in this way, and even better, many of
  155. the students learned a lot and got excited about compilers.
  156. It is now 2016 and I too have returned to teach at Indiana University.
  157. In my absence the compiler course had switched from the front-to-back
  158. organization to a back-to-front organization. Seeing how well the
  159. incremental approach worked at Colorado, I started porting and
  160. adapting the structure of the Colorado course back into the land of
  161. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  162. the course is now about compiling a subset of Racket to the x86
  163. assembly language and the compiler is implemented in
  164. Racket~\citep{plt-tr}.
  165. This is the textbook for the incremental version of the compiler
  166. course at Indiana University (Spring 2016) and it is the first
  167. textbook for an Indiana compiler course. With this book I hope to
  168. make the Indiana compiler course available to people that have not had
  169. the chance to study in Bloomington in person. Many of the compiler
  170. design decisions in this book are drawn from the assignment
  171. descriptions of \cite{Dybvig:2010aa}. I have captured what I think are
  172. the most important topics from \cite{Dybvig:2010aa} but I have omitted
  173. topics that I think are less interesting conceptually and I have made
  174. simplifications to reduce complexity. In this way, this book leans
  175. more towards pedagogy than towards the absolute efficiency of the
  176. generated code. Also, the book differs in places where I saw the
  177. opportunity to make the topics more fun, such as in relating register
  178. allocation to Sudoku (Chapter~\ref{ch:register-allocation}).
  179. \section*{Prerequisites}
  180. The material in this book is challenging but rewarding. It is meant to
  181. prepare students for a lifelong career in programming languages. I do
  182. not recommend this book for students who want to dabble in programming
  183. languages. Because the book uses the Racket language both for the
  184. implementation of the compiler and for the language that is compiled,
  185. a student should be proficient with Racket (or Scheme) prior to
  186. reading this book. There are many other excellent resources for
  187. learning Scheme and
  188. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  189. is helpful but not necessary for the student to have prior exposure to
  190. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  191. obtain from a computer systems
  192. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  193. parts of x86-64 assembly language that are needed.
  194. %\section*{Structure of book}
  195. % You might want to add short description about each chapter in this book.
  196. %\section*{About the companion website}
  197. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  198. %\begin{itemize}
  199. % \item A link to (freely downlodable) latest version of this document.
  200. % \item Link to download LaTeX source for this document.
  201. % \item Miscellaneous material (e.g. suggested readings etc).
  202. %\end{itemize}
  203. \section*{Acknowledgments}
  204. Need to give thanks to
  205. \begin{itemize}
  206. \item Bor-Yuh Evan Chang
  207. \item Kent Dybvig
  208. \item Daniel P. Friedman
  209. \item Ronald Garcia
  210. \item Abdulaziz Ghuloum
  211. \item Ryan Newton
  212. \item Dipanwita Sarkar
  213. \item Andrew Keep
  214. \item Oscar Waddell
  215. \end{itemize}
  216. \mbox{}\\
  217. \noindent Jeremy G. Siek \\
  218. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  219. \noindent Spring 2016
  220. \fi{} %% End Preface
  221. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  222. \chapter{Preliminaries}
  223. \label{ch:trees-recur}
  224. In this chapter, we review the basic tools that are needed for
  225. implementing a compiler. We use abstract syntax trees (ASTs) in the
  226. form of S-expressions to represent programs (Section~\ref{sec:ast})
  227. and pattern matching to inspect individual nodes in an AST
  228. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  229. and deconstruct entire ASTs (Section~\ref{sec:recursion}).
  230. \section{Abstract Syntax Trees}
  231. \label{sec:ast}
  232. The primary data structure that is commonly used for representing
  233. programs is the \emph{abstract syntax tree} (AST). When considering
  234. some part of a program, a compiler needs to ask what kind of part it
  235. is and what sub-parts it has. For example, the program on the left is
  236. represented by the AST on the right.
  237. \begin{center}
  238. \begin{minipage}{0.4\textwidth}
  239. \begin{lstlisting}
  240. (+ (read) (- 8))
  241. \end{lstlisting}
  242. \end{minipage}
  243. \begin{minipage}{0.4\textwidth}
  244. \begin{equation}
  245. \begin{tikzpicture}
  246. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  247. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  248. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  249. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  250. \draw[->] (plus) to (read);
  251. \draw[->] (plus) to (minus);
  252. \draw[->] (minus) to (8);
  253. \end{tikzpicture}
  254. \label{eq:arith-prog}
  255. \end{equation}
  256. \end{minipage}
  257. \end{center}
  258. We shall use the standard terminology for trees: each circle above is
  259. called a \emph{node}. The arrows connect a node to its \emph{children}
  260. (which are also nodes). The top-most node is the \emph{root}. Every
  261. node except for the root has a \emph{parent} (the node it is the child
  262. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  263. it is an \emph{internal} node.
  264. When deciding how to compile the above program, we need to know that
  265. the root node operation is addition and that it has two children:
  266. \texttt{read} and a negation. The abstract syntax tree data structure
  267. directly supports these queries and hence is a good choice. In this
  268. book, we will often write down the textual representation of a program
  269. even when we really have in mind the AST because the textual
  270. representation is more concise. We recommend that, in your mind, you
  271. always interpret programs as abstract syntax trees.
  272. \section{Grammars}
  273. \label{sec:grammar}
  274. A programming language can be thought of as a \emph{set} of programs.
  275. The set is typically infinite (one can always create larger and larger
  276. programs), so one cannot simply describe a language by listing all of
  277. the programs in the language. Instead we write down a set of rules, a
  278. \emph{grammar}, for building programs. We shall write our rules in a
  279. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  280. As an example, we describe a small language, named $R_0$, of
  281. integers and arithmetic operations. The first rule says that any
  282. integer is an expression, $\Exp$, in the language:
  283. \begin{equation}
  284. \Exp ::= \Int \label{eq:arith-int}
  285. \end{equation}
  286. Each rule has a left-hand-side and a right-hand-side. The way to read
  287. a rule is that if you have all the program parts on the
  288. right-hand-side, then you can create an AST node and categorize it
  289. according to the left-hand-side. (We do not define $\Int$ because the
  290. reader already knows what an integer is.) We make the simplifying
  291. design decision that all of the languages in this book only handle
  292. machine-representable integers (those representable with 64-bits,
  293. i.e., the range $-2^{63}$ to $2^{63}$) which corresponds to the
  294. \texttt{fixnum} datatype in Racket. A name such as $\Exp$ that is
  295. defined by the grammar rules is a \emph{non-terminal}.
  296. The second grammar rule is the \texttt{read} operation that receives
  297. an input integer from the user of the program.
  298. \begin{equation}
  299. \Exp ::= (\key{read}) \label{eq:arith-read}
  300. \end{equation}
  301. The third rule says that, given an $\Exp$ node, you can build another
  302. $\Exp$ node by negating it.
  303. \begin{equation}
  304. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  305. \end{equation}
  306. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  307. and must literally appear in the program for the rule to be
  308. applicable.
  309. We can apply the rules to build ASTs in the $R_0$
  310. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  311. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  312. an $\Exp$.
  313. \begin{center}
  314. \begin{minipage}{0.25\textwidth}
  315. \begin{lstlisting}
  316. (- 8)
  317. \end{lstlisting}
  318. \end{minipage}
  319. \begin{minipage}{0.25\textwidth}
  320. \begin{equation}
  321. \begin{tikzpicture}
  322. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  323. \node[draw, circle] (8) at (0, -1.2) {$8$};
  324. \draw[->] (minus) to (8);
  325. \end{tikzpicture}
  326. \label{eq:arith-neg8}
  327. \end{equation}
  328. \end{minipage}
  329. \end{center}
  330. The following grammar rule defines addition expressions:
  331. \begin{equation}
  332. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  333. \end{equation}
  334. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  335. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  336. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  337. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  338. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  339. If you have an AST for which the above rules do not apply, then the
  340. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  341. not in $R_0$ because there are no rules for \key{+} with only one
  342. argument, nor for \key{-} with two arguments. Whenever we define a
  343. language with a grammar, we implicitly mean for the language to be the
  344. smallest set of programs that are justified by the rules. That is, the
  345. language only includes those programs that the rules allow.
  346. The last grammar for $R_0$ states that there is a \key{program} node
  347. to mark the top of the whole program:
  348. \[
  349. R_0 ::= (\key{program} \; \Exp)
  350. \]
  351. The \code{read-program} function provided in \code{utilities.rkt}
  352. reads programs in from a file (the sequence of characters in the
  353. concrete syntax of Racket) and parses them into the abstract syntax
  354. tree. The concrete syntax does not include a \key{program} form; that
  355. is added by the \code{read-program} function as it creates the
  356. AST. See the description of \code{read-program} in
  357. Appendix~\ref{appendix:utilities} for more details.
  358. It is common to have many rules with the same left-hand side, such as
  359. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  360. for gathering several rules, as shown in
  361. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  362. called an {\em alternative}.
  363. \begin{figure}[tp]
  364. \fbox{
  365. \begin{minipage}{0.96\textwidth}
  366. \[
  367. \begin{array}{rcl}
  368. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  369. (\key{+} \; \Exp \; \Exp) \\
  370. R_0 &::=& (\key{program} \; \Exp)
  371. \end{array}
  372. \]
  373. \end{minipage}
  374. }
  375. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  376. \label{fig:r0-syntax}
  377. \end{figure}
  378. \section{S-Expressions}
  379. \label{sec:s-expr}
  380. Racket, as a descendant of Lisp, has
  381. convenient support for creating and manipulating abstract syntax trees
  382. with its \emph{symbolic expression} feature, or S-expression for
  383. short. We can create an S-expression simply by writing a backquote
  384. followed by the textual representation of the AST. (Technically
  385. speaking, this is called a \emph{quasiquote} in Racket.) For example,
  386. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  387. by the following Racket expression:
  388. \begin{center}
  389. \texttt{`(+ (read) (- 8))}
  390. \end{center}
  391. To build larger S-expressions one often needs to splice together
  392. several smaller S-expressions. Racket provides the comma operator to
  393. splice an S-expression into a larger one. For example, instead of
  394. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  395. we could have first created an S-expression for AST
  396. \eqref{eq:arith-neg8} and then spliced that into the addition
  397. S-expression.
  398. \begin{lstlisting}
  399. (define ast1.4 `(- 8))
  400. (define ast1.1 `(+ (read) ,ast1.4))
  401. \end{lstlisting}
  402. In general, the Racket expression that follows the comma (splice)
  403. can be any expression that computes an S-expression.
  404. \section{Pattern Matching}
  405. \label{sec:pattern-matching}
  406. As mentioned above, one of the operations that a compiler needs to
  407. perform on an AST is to access the children of a node. Racket
  408. provides the \texttt{match} form to access the parts of an
  409. S-expression. Consider the following example and the output on the
  410. right.
  411. \begin{center}
  412. \begin{minipage}{0.5\textwidth}
  413. \begin{lstlisting}
  414. (match ast1.1
  415. [`(,op ,child1 ,child2)
  416. (print op) (newline)
  417. (print child1) (newline)
  418. (print child2)])
  419. \end{lstlisting}
  420. \end{minipage}
  421. \vrule
  422. \begin{minipage}{0.25\textwidth}
  423. \begin{lstlisting}
  424. '+
  425. '(read)
  426. '(- 8)
  427. \end{lstlisting}
  428. \end{minipage}
  429. \end{center}
  430. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  431. parts to the three variables \texttt{op}, \texttt{child1}, and
  432. \texttt{child2}. In general, a match clause consists of a
  433. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  434. that may contain pattern-variables (preceded by a comma). The body
  435. may contain any Racket code.
  436. A \texttt{match} form may contain several clauses, as in the following
  437. function \texttt{leaf?} that recognizes when an $R_0$ node is
  438. a leaf. The \texttt{match} proceeds through the clauses in order,
  439. checking whether the pattern can match the input S-expression. The
  440. body of the first clause that matches is executed. The output of
  441. \texttt{leaf?} for several S-expressions is shown on the right. In the
  442. below \texttt{match}, we see another form of pattern: the \texttt{(?
  443. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  444. S-expression to see if it is a machine-representable integer.
  445. \begin{center}
  446. \begin{minipage}{0.5\textwidth}
  447. \begin{lstlisting}
  448. (define (leaf? arith)
  449. (match arith
  450. [(? fixnum?) #t]
  451. [`(read) #t]
  452. [`(- ,c1) #f]
  453. [`(+ ,c1 ,c2) #f]))
  454. (leaf? `(read))
  455. (leaf? `(- 8))
  456. (leaf? `(+ (read) (- 8)))
  457. \end{lstlisting}
  458. \end{minipage}
  459. \vrule
  460. \begin{minipage}{0.25\textwidth}
  461. \begin{lstlisting}
  462. #t
  463. #f
  464. #f
  465. \end{lstlisting}
  466. \end{minipage}
  467. \end{center}
  468. \section{Recursion}
  469. \label{sec:recursion}
  470. Programs are inherently recursive in that an $R_0$ AST is made
  471. up of smaller $R_0$ ASTs. Thus, the natural way to process in
  472. entire program is with a recursive function. As a first example of
  473. such a function, we define \texttt{R0?} below, which takes an
  474. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  475. sexp} is in {\tt arith}. Note that each match clause corresponds to
  476. one grammar rule for $R_0$ and the body of each clause makes a
  477. recursive call for each child node. This pattern of recursive function
  478. is so common that it has a name, \emph{structural recursion}. In
  479. general, when a recursive function is defined using a sequence of
  480. match clauses that correspond to a grammar, and each clause body makes
  481. a recursive call on each child node, then we say the function is
  482. defined by structural recursion.
  483. \begin{center}
  484. \begin{minipage}{0.7\textwidth}
  485. \begin{lstlisting}
  486. (define (R0? sexp)
  487. (match sexp
  488. [(? fixnum?) #t]
  489. [`(read) #t]
  490. [`(- ,e) (R0? e)]
  491. [`(+ ,e1 ,e2)
  492. (and (R0? e1) (R0? e2))]
  493. [`(program ,e) (R0? e)]
  494. [else #f]))
  495. (R0? `(+ (read) (- 8)))
  496. (R0? `(- (read) (+ 8)))
  497. \end{lstlisting}
  498. \end{minipage}
  499. \vrule
  500. \begin{minipage}{0.25\textwidth}
  501. \begin{lstlisting}
  502. #t
  503. #f
  504. \end{lstlisting}
  505. \end{minipage}
  506. \end{center}
  507. \section{Interpreters}
  508. \label{sec:interp-R0}
  509. The meaning, or semantics, of a program is typically defined in the
  510. specification of the language. For example, the Scheme language is
  511. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  512. defined in its reference manual~\citep{plt-tr}. In this book we use an
  513. interpreter to define the meaning of each language that we consider,
  514. following Reynold's advice in this
  515. regard~\citep{reynolds72:_def_interp}. Here we will warm up by writing
  516. an interpreter for the $R_0$ language, which will also serve as a
  517. second example of structural recursion. The \texttt{interp-R0}
  518. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  519. function is a match on the input expression \texttt{e} and there is
  520. one clause per grammar rule for $R_0$. The clauses for internal AST
  521. nodes make recursive calls to \texttt{interp-R0} on each child
  522. node. Here we make use of the \key{app} feature of Racket's
  523. \key{match} to concisely apply a function and bind the result. For
  524. example, in the case for negation, we use \key{app} to recursively
  525. apply \texttt{interp-R0} to the child node and bind the result value
  526. to variable \texttt{v}.
  527. \begin{figure}[tbp]
  528. \begin{lstlisting}
  529. (define (interp-R0 e)
  530. (match e
  531. [(? fixnum?) e]
  532. [`(read)
  533. (let ([r (read)])
  534. (cond [(fixnum? r) r]
  535. [else (error 'interp-R0 "input not an integer" r)]))]
  536. [`(- ,(app interp-R0 v))
  537. (fx- 0 v)]
  538. [`(+ ,(app interp-R0 v1) ,(app interp-R0 v2))
  539. (fx+ v1 v2)]
  540. [`(program ,(app interp-R0 v)) v]
  541. ))
  542. \end{lstlisting}
  543. \caption{Interpreter for the $R_0$ language.
  544. \rn{Having two functions here for prog/exp wouldn't take much more space.
  545. I'll change that once I get further.. but I also need to know what the story
  546. is for running this code?}}
  547. \label{fig:interp-R0}
  548. \end{figure}
  549. Let us consider the result of interpreting some example $R_0$
  550. programs. The following program simply adds two integers.
  551. \begin{lstlisting}
  552. (+ 10 32)
  553. \end{lstlisting}
  554. The result is \key{42}, as you might have expected.
  555. %
  556. The next example demonstrates that expressions may be nested within
  557. each other, in this case nesting several additions and negations.
  558. \begin{lstlisting}
  559. (+ 10 (- (+ 12 20)))
  560. \end{lstlisting}
  561. What is the result of the above program?
  562. If we interpret the AST \eqref{eq:arith-prog} and give it the input
  563. \texttt{50}
  564. \begin{lstlisting}
  565. (interp-R0 ast1.1)
  566. \end{lstlisting}
  567. we get the answer to life, the universe, and everything:
  568. \begin{lstlisting}
  569. 42
  570. \end{lstlisting}
  571. Moving on, the \key{read} operation prompts the user of the program
  572. for an integer. Given an input of \key{10}, the following program
  573. produces \key{42}.
  574. \begin{lstlisting}
  575. (+ (read) 32)
  576. \end{lstlisting}
  577. We include the \key{read} operation in $R_1$ so that a compiler for
  578. $R_1$ cannot be implemented simply by running the interpreter at
  579. compilation time to obtain the output and then generating the trivial
  580. code to return the output. (A clever student at Colorado did this the
  581. first time I taught the course.)
  582. The job of a compiler is to translate a program in one language into a
  583. program in another language so that the output program behaves the
  584. same way as the input program. This idea is depicted in the following
  585. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  586. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  587. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  588. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  589. and $P_2$ on their respective interpreters with input $i$ should yield
  590. the same output $o$.
  591. \begin{equation} \label{eq:compile-correct}
  592. \begin{tikzpicture}[baseline=(current bounding box.center)]
  593. \node (p1) at (0, 0) {$P_1$};
  594. \node (p2) at (3, 0) {$P_2$};
  595. \node (o) at (3, -2.5) {$o$};
  596. \path[->] (p1) edge [above] node {compile} (p2);
  597. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  598. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  599. \end{tikzpicture}
  600. \end{equation}
  601. In the next section we see our first example of a compiler, which is
  602. another example of structural recursion.
  603. \section{Example Compiler: a Partial Evaluator}
  604. \label{sec:partial-evaluation}
  605. In this section we consider a compiler that translates $R_0$
  606. programs into $R_0$ programs that are more efficient, that is,
  607. this compiler is an optimizer. Our optimizer will accomplish this by
  608. trying to eagerly compute the parts of the program that do not depend
  609. on any inputs. For example, given the following program
  610. \begin{lstlisting}
  611. (+ (read) (- (+ 5 3)))
  612. \end{lstlisting}
  613. our compiler will translate it into the program
  614. \begin{lstlisting}
  615. (+ (read) -8)
  616. \end{lstlisting}
  617. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  618. evaluator for the $R_0$ language. The output of the partial evaluator
  619. is an $R_0$ program, which we build up using a combination of
  620. quasiquotes and commas. (Though no quasiquote is necessary for
  621. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  622. recursion is captured in the main \texttt{pe-arith} function whereas
  623. the code for partially evaluating negation and addition is factored
  624. into two separate helper functions: \texttt{pe-neg} and
  625. \texttt{pe-add}. The input to these helper functions is the output of
  626. partially evaluating the children nodes.
  627. \begin{figure}[tbp]
  628. \begin{lstlisting}
  629. (define (pe-neg r)
  630. (cond [(fixnum? r) (fx- 0 r)]
  631. [else `(- ,r)]))
  632. (define (pe-add r1 r2)
  633. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  634. [else `(+ ,r1 ,r2)]))
  635. (define (pe-arith e)
  636. (match e
  637. [(? fixnum?) e]
  638. [`(read) `(read)]
  639. [`(- ,(app pe-arith r1))
  640. (pe-neg r1)]
  641. [`(+ ,(app pe-arith r1) ,(app pe-arith r2))
  642. (pe-add r1 r2)]))
  643. \end{lstlisting}
  644. \caption{A partial evaluator for the $R_0$ language.}
  645. \label{fig:pe-arith}
  646. \end{figure}
  647. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  648. idea of checking whether the inputs are integers and if they are, to
  649. go ahead and perform the arithmetic. Otherwise, we use quasiquote to
  650. create an AST node for the appropriate operation (either negation or
  651. addition) and use comma to splice in the child nodes.
  652. To gain some confidence that the partial evaluator is correct, we can
  653. test whether it produces programs that get the same result as the
  654. input program. That is, we can test whether it satisfies Diagram
  655. \eqref{eq:compile-correct}. The following code runs the partial
  656. evaluator on several examples and tests the output program. The
  657. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  658. \begin{lstlisting}
  659. (define (test-pe p)
  660. (assert "testing pe-arith"
  661. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  662. (test-pe `(+ (read) (- (+ 5 3))))
  663. (test-pe `(+ 1 (+ (read) 1)))
  664. (test-pe `(- (+ (read) (- 5))))
  665. \end{lstlisting}
  666. \rn{Do we like the explicit whitespace? I've never been fond of it, in part
  667. because it breaks copy/pasting. But, then again, so do most of the quotes.}
  668. \begin{exercise}
  669. \normalfont % I don't like the italics for exercises. -Jeremy
  670. We challenge the reader to improve on the simple partial evaluator in
  671. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  672. \texttt{pe-add} helper functions with functions that know more about
  673. arithmetic. For example, your partial evaluator should translate
  674. \begin{lstlisting}
  675. (+ 1 (+ (read) 1))
  676. \end{lstlisting}
  677. into
  678. \begin{lstlisting}
  679. (+ 2 (read))
  680. \end{lstlisting}
  681. To accomplish this, we recommend that your partial evaluator produce
  682. output that takes the form of the $\itm{residual}$ non-terminal in the
  683. following grammar.
  684. \[
  685. \begin{array}{lcl}
  686. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  687. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  688. \end{array}
  689. \]
  690. \end{exercise}
  691. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  692. \chapter{Compiling Integers and Variables}
  693. \label{ch:int-exp}
  694. This chapter concerns the challenge of compiling a subset of Racket,
  695. which we name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}.
  696. (Henceforth we shall refer to x86-64 simply as x86). The chapter
  697. begins with a description of the $R_1$ language (Section~\ref{sec:s0})
  698. and then a description of x86 (Section~\ref{sec:x86}). The
  699. x86 assembly language is quite large, so we only discuss what is
  700. needed for compiling $R_1$. We introduce more of x86 in later
  701. chapters. Once we have introduced $R_1$ and x86, we reflect on
  702. their differences and come up with a plan breaking down the
  703. translation from $R_1$ to x86 into a handful of steps
  704. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  705. Chapter give detailed hints regarding each step
  706. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  707. to give enough hints that the well-prepared reader can implement a
  708. compiler from $R_1$ to x86 while at the same time leaving room for
  709. some fun and creativity.
  710. \section{The $R_1$ Language}
  711. \label{sec:s0}
  712. The $R_1$ language extends the $R_0$ language
  713. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  714. the $R_1$ language is defined by the grammar in
  715. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  716. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  717. a unary operator, and \key{+} is a binary operator. In addition to
  718. variable definitions, the $R_1$ language includes the \key{program}
  719. form to mark the top of the program, which is helpful in some of the
  720. compiler passes. The $R_1$ language is rich enough to exhibit several
  721. compilation techniques but simple enough so that the reader can
  722. implement a compiler for it in a week of part-time work. To give the
  723. reader a feeling for the scale of this first compiler, the instructor
  724. solution for the $R_1$ compiler consists of 6 recursive functions and
  725. a few small helper functions that together span 256 lines of code.
  726. \begin{figure}[btp]
  727. \centering
  728. \fbox{
  729. \begin{minipage}{0.96\textwidth}
  730. \[
  731. \begin{array}{rcl}
  732. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  733. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  734. R_1 &::=& (\key{program} \; \Exp)
  735. \end{array}
  736. \]
  737. \end{minipage}
  738. }
  739. \caption{The syntax of $R_1$, a language of integers and variables.}
  740. \label{fig:r1-syntax}
  741. \end{figure}
  742. The \key{let} construct defines a variable for use within its body
  743. and initializes the variable with the value of an expression. So the
  744. following program initializes \code{x} to \code{32} and then evaluates
  745. the body \code{(+ 10 x)}, producing \code{42}.
  746. \begin{lstlisting}
  747. (program
  748. (let ([x (+ 12 20)]) (+ 10 x)))
  749. \end{lstlisting}
  750. When there are multiple \key{let}'s for the same variable, the closest
  751. enclosing \key{let} is used. That is, variable definitions overshadow
  752. prior definitions. Consider the following program with two \key{let}'s
  753. that define variables named \code{x}. Can you figure out the result?
  754. \begin{lstlisting}
  755. (program
  756. (let ([x 32]) (+ (let ([x 10]) x) x)))
  757. \end{lstlisting}
  758. For the purposes of showing which variable uses correspond to which
  759. definitions, the following shows the \code{x}'s annotated with subscripts
  760. to distinguish them. Double check that your answer for the above is
  761. the same as your answer for this annotated version of the program.
  762. \begin{lstlisting}
  763. (program
  764. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  765. \end{lstlisting}
  766. The initializing expression is always evaluated before the body of the
  767. \key{let}, so in the following, the \key{read} for \code{x} is
  768. performed before the \key{read} for \code{y}. Given the input
  769. \code{52} then \code{10}, the following produces \code{42} (and not
  770. \code{-42}).
  771. \begin{lstlisting}
  772. (program
  773. (let ([x (read)]) (let ([y (read)]) (- x y))))
  774. \end{lstlisting}
  775. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  776. language. It extends the interpreter for $R_0$ with two new
  777. \key{match} clauses for variables and for \key{let}. For \key{let},
  778. we will need a way to communicate the initializing value of a variable
  779. to all the uses of a variable. To accomplish this, we maintain a
  780. mapping from variables to values, which is traditionally called an
  781. \emph{environment}. For simplicity, here we use an association list to
  782. represent the environment. The \code{interp-R1} function takes the
  783. current environment, \code{env}, as an extra parameter. When the
  784. interpreter encounters a variable, it finds the corresponding value
  785. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  786. When the interpreter encounters a \key{let}, it evaluates the
  787. initializing expression, extends the environment with the result bound
  788. to the variable, then evaluates the body of the \key{let}.
  789. \begin{figure}[tbp]
  790. \begin{lstlisting}
  791. (define (interp-R1 env)
  792. (lambda (e)
  793. (define recur (interp-R1 env))
  794. (match e
  795. [(? symbol?) (lookup e env)]
  796. [`(let ([,x ,(app recur v)]) ,body)
  797. (define new-env (cons (cons x v) env))
  798. ((interp-R1 new-env) body)]
  799. [(? fixnum?) e]
  800. [`(read)
  801. (define r (read))
  802. (cond [(fixnum? r) r]
  803. [else (error 'interp-R1 "expected an integer" r)])]
  804. [`(- ,(app recur v))
  805. (fx- 0 v)]
  806. [`(+ ,(app recur v1) ,(app recur v2))
  807. (fx+ v1 v2)]
  808. [`(program ,e) ((interp-R1 '()) e)]
  809. )))
  810. \end{lstlisting}
  811. \caption{Interpreter for the $R_1$ language.}
  812. \label{fig:interp-R1}
  813. \end{figure}
  814. The goal for this chapter is to implement a compiler that translates
  815. any program $P_1$ in the $R_1$ language into an x86 assembly
  816. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  817. computer as the $R_1$ program running in a Racket implementation.
  818. That is, they both output the same integer $n$.
  819. \[
  820. \begin{tikzpicture}[baseline=(current bounding box.center)]
  821. \node (p1) at (0, 0) {$P_1$};
  822. \node (p2) at (4, 0) {$P_2$};
  823. \node (o) at (4, -2) {$n$};
  824. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  825. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  826. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  827. \end{tikzpicture}
  828. \]
  829. In the next section we introduce enough of the x86 assembly
  830. language to compile $R_1$.
  831. \section{The x86 Assembly Language}
  832. \label{sec:x86}
  833. An x86 program is a sequence of instructions. The program is stored in
  834. the computer's memory and the \emph{program counter} points to the
  835. address of the next instruction to be executed. For most instructions,
  836. once the instruction is executed, the program counter is incremented
  837. to point to the immediately following instruction in the program.
  838. Each instruction may refer to integer constants (called
  839. \emph{immediate values}), variables called \emph{registers}, and
  840. instructions may load and store values into memory. For our purposes,
  841. we can think of the computer's memory as a mapping of 64-bit addresses
  842. to 64-bit values. Figure~\ref{fig:x86-a} defines the syntax for the
  843. subset of the x86 assembly language needed for this chapter. (We use
  844. the AT\&T syntax expected by the GNU assembler inside \key{gcc}.)
  845. Also, Appendix~\ref{sec:x86-quick-reference} includes a
  846. quick-reference of all the x86 instructions used in this book and a
  847. short explanation of what they do.
  848. % to do: finish treatment of imulq
  849. % it's needed for vector's in R6/R7
  850. \begin{figure}[tp]
  851. \fbox{
  852. \begin{minipage}{0.96\textwidth}
  853. \[
  854. \begin{array}{lcl}
  855. \Reg &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  856. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  857. && \key{r8} \mid \key{r9} \mid \key{r10}
  858. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  859. \mid \key{r14} \mid \key{r15} \\
  860. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  861. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  862. \key{subq} \; \Arg, \Arg \mid
  863. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  864. && \key{callq} \; \mathit{label} \mid
  865. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  866. \Prog &::= & \key{.globl main}\\
  867. & & \key{main:} \; \Instr^{+}
  868. \end{array}
  869. \]
  870. \end{minipage}
  871. }
  872. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  873. \label{fig:x86-a}
  874. \end{figure}
  875. An immediate value is written using the notation \key{\$}$n$ where $n$
  876. is an integer.
  877. %
  878. A register is written with a \key{\%} followed by the register name,
  879. such as \key{\%rax}.
  880. %
  881. An access to memory is specified using the syntax $n(\key{\%}r)$,
  882. which reads register $r$ and then offsets the address by $n$ bytes
  883. (8 bits). The address is then used to either load or store to memory
  884. depending on whether it occurs as a source or destination argument of
  885. an instruction.
  886. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  887. source $s$ and destination $d$, applies the arithmetic operation, then
  888. writes the result in $d$.
  889. %
  890. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  891. result in $d$.
  892. %
  893. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  894. specified by the label.
  895. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  896. to \code{(+ 10 32)}. The \key{globl} directive says that the
  897. \key{main} procedure is externally visible, which is necessary so
  898. that the operating system can call it. The label \key{main:}
  899. indicates the beginning of the \key{main} procedure which is where
  900. the operating system starts executing this program. The instruction
  901. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  902. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  903. $10$ in \key{rax} and puts the result, $42$, back into
  904. \key{rax}. Finally, the instruction \lstinline{movq %rax, %rdi} moves the value
  905. in \key{rax} into another register, \key{rdi}, and
  906. \lstinline{callq print_int} calls the external function \code{print\_int}, which
  907. prints the value in \key{rdi}.
  908. The last two instructions---\lstinline{movq $0, %rax} and \key{retq}---finish
  909. the \key{main} function by returning the integer in \key{rax} to the
  910. operating system. The operating system interprets this integer as the program's
  911. exit code. By convention, an exit code of 0 indicates the program was
  912. successful, and all other exit codes indicate various errors. To ensure that
  913. we successfully communicate with the operating system, we explicitly move 0
  914. into \key{rax}, lest the previous value in \key{rax} be misinterpreted as an
  915. error code.
  916. %\begin{wrapfigure}{r}{2.25in}
  917. \begin{figure}[tbp]
  918. \begin{lstlisting}
  919. .globl main
  920. main:
  921. movq $10, %rax
  922. addq $32, %rax
  923. movq %rax, %rdi
  924. callq print_int
  925. movq $0, %rax
  926. retq
  927. \end{lstlisting}
  928. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  929. \label{fig:p0-x86}
  930. %\end{wrapfigure}
  931. \end{figure}
  932. %% \margincomment{Consider using italics for the texts in these figures.
  933. %% It can get confusing to differentiate them from the main text.}
  934. %% It looks pretty ugly in italics.-Jeremy
  935. Unfortunately, x86 varies in a couple ways depending on what
  936. operating system it is assembled in. The code examples shown here are
  937. correct on the Unix platform, but when assembled on Mac OS X, labels
  938. like \key{main} must be prefixed with an underscore. So the correct
  939. output for the above program on Mac would begin with:
  940. \begin{lstlisting}
  941. .globl _main
  942. _main:
  943. ...
  944. \end{lstlisting}
  945. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  946. lists an x86 program that is equivalent to $\BINOP{+}{52}{
  947. \UNIOP{-}{10} }$. To understand how this x86 program works, we
  948. need to explain a region of memory called the \emph{procedure call
  949. stack} (or \emph{stack} for short). The stack consists of a separate
  950. \emph{frame} for each procedure call. The memory layout for an
  951. individual frame is shown in Figure~\ref{fig:frame}. The register
  952. \key{rsp} is called the \emph{stack pointer} and points to the item at
  953. the top of the stack. The stack grows downward in memory, so we
  954. increase the size of the stack by subtracting from the stack
  955. pointer. The frame size is required to be a multiple of 16 bytes. The
  956. register \key{rbp} is the \emph{base pointer} which serves two
  957. purposes: 1) it saves the location of the stack pointer for the
  958. procedure that called the current one and 2) it is used to access
  959. variables associated with the current procedure. We number the
  960. variables from $1$ to $n$. Variable $1$ is stored at address
  961. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  962. %\begin{wrapfigure}{r}{2.1in}
  963. \begin{figure}[tbp]
  964. \begin{lstlisting}
  965. .globl main
  966. main:
  967. pushq %rbp
  968. movq %rsp, %rbp
  969. subq $16, %rsp
  970. movq $10, -8(%rbp)
  971. negq -8(%rbp)
  972. movq $52, %rax
  973. addq -8(%rbp), %rax
  974. movq %rax, %rdi
  975. callq print_int
  976. addq $16, %rsp
  977. movq $0, %rax
  978. popq %rbp
  979. retq
  980. \end{lstlisting}
  981. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  982. \label{fig:p1-x86}
  983. \end{figure}
  984. %\end{wrapfigure}
  985. \begin{figure}[tbp]
  986. \centering
  987. \begin{tabular}{|r|l|} \hline
  988. Position & Contents \\ \hline
  989. 8(\key{\%rbp}) & return address \\
  990. 0(\key{\%rbp}) & old \key{rbp} \\
  991. -8(\key{\%rbp}) & variable $1$ \\
  992. -16(\key{\%rbp}) & variable $2$ \\
  993. \ldots & \ldots \\
  994. 0(\key{\%rsp}) & variable $n$\\ \hline
  995. \end{tabular}
  996. \caption{Memory layout of a frame.}
  997. \label{fig:frame}
  998. \end{figure}
  999. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1000. three instructions are the typical \emph{prelude} for a procedure.
  1001. The instruction \key{pushq \%rbp} saves the base pointer for the
  1002. procedure that called the current one onto the stack and subtracts $8$
  1003. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  1004. changes the base pointer to the top of the stack. The instruction
  1005. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  1006. room for storing variables. This program just needs one variable ($8$
  1007. bytes) but because the frame size is required to be a multiple of 16
  1008. bytes, it rounds to 16 bytes.
  1009. The next four instructions carry out the work of computing
  1010. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  1011. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  1012. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  1013. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  1014. adds the contents of variable $1$ to \key{rax}, at which point
  1015. \key{rax} contains $42$.
  1016. The last six instructions are the typical \emph{conclusion} of a
  1017. procedure. The first two print the final result of the program. The
  1018. latter three are necessary to get the state of the machine back to
  1019. where it was before the current procedure was called. The \key{addq
  1020. \$16, \%rsp} instruction moves the stack pointer back to point at
  1021. the old base pointer. The amount added here needs to match the amount
  1022. that was subtracted in the prelude of the procedure. The \key{movq
  1023. \$0, \%rax} instruction ensures that the returned exit code is 0.
  1024. Then \key{popq \%rbp} returns the old base pointer to \key{rbp} and
  1025. adds $8$ to the stack pointer. The \key{retq} instruction jumps back
  1026. to the procedure that called this one and subtracts 8 from the stack
  1027. pointer.
  1028. The compiler will need a convenient representation for manipulating
  1029. x86 programs, so we define an abstract syntax for x86 in
  1030. Figure~\ref{fig:x86-ast-a}. The $\Int$ field of the \key{program} AST
  1031. node is number of bytes of stack space needed for variables in the
  1032. program. (Some of the intermediate languages will store other
  1033. information in that location for the purposes of communicating
  1034. auxiliary data from one step of the compiler to the next. )
  1035. \begin{figure}[tp]
  1036. \fbox{
  1037. \begin{minipage}{0.96\textwidth}
  1038. \[
  1039. \begin{array}{lcl}
  1040. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1041. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1042. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1043. (\key{subq} \; \Arg\; \Arg) \mid
  1044. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) \\
  1045. &\mid& (\key{callq} \; \mathit{label}) \mid
  1046. (\key{pushq}\;\Arg) \mid
  1047. (\key{popq}\;\Arg) \mid
  1048. (\key{retq}) \\
  1049. x86_0 &::= & (\key{program} \;\Int \; \Instr^{+})
  1050. \end{array}
  1051. \]
  1052. \end{minipage}
  1053. }
  1054. \caption{Abstract syntax for x86 assembly.}
  1055. \label{fig:x86-ast-a}
  1056. \end{figure}
  1057. \section{Planning the trip to x86 via the $C_0$ language}
  1058. \label{sec:plan-s0-x86}
  1059. To compile one language to another it helps to focus on the
  1060. differences between the two languages. It is these differences that
  1061. the compiler will need to bridge. What are the differences between
  1062. $R_1$ and x86 assembly? Here we list some of the most important the
  1063. differences.
  1064. \begin{enumerate}
  1065. \item x86 arithmetic instructions typically take two arguments and
  1066. update the second argument in place. In contrast, $R_1$ arithmetic
  1067. operations only read their arguments and produce a new value.
  1068. \item An argument to an $R_1$ operator can be any expression, whereas
  1069. x86 instructions restrict their arguments to integers, registers,
  1070. and memory locations.
  1071. \item An $R_1$ program can have any number of variables whereas x86
  1072. has only 16 registers.
  1073. \item Variables in $R_1$ can overshadow other variables with the same
  1074. name. The registers and memory locations of x86 all have unique
  1075. names.
  1076. \end{enumerate}
  1077. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1078. the problem into several steps, dealing with the above differences one
  1079. at a time. The main question then becomes: in what order do we tackle
  1080. these differences? This is often one of the most challenging questions
  1081. that a compiler writer must answer because some orderings may be much
  1082. more difficult to implement than others. It is difficult to know ahead
  1083. of time which orders will be better so often some trial-and-error is
  1084. involved. However, we can try to plan ahead and choose the orderings
  1085. based on this planning.
  1086. For example, to handle difference \#2 (nested expressions), we shall
  1087. introduce new variables and pull apart the nested expressions into a
  1088. sequence of assignment statements. To deal with difference \#3 we
  1089. will be replacing variables with registers and/or stack
  1090. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1091. \#3 can replace both the original variables and the new ones. Next,
  1092. consider where \#1 should fit in. Because it has to do with the format
  1093. of x86 instructions, it makes more sense after we have flattened the
  1094. nested expressions (\#2). Finally, when should we deal with \#4
  1095. (variable overshadowing)? We shall solve this problem by renaming
  1096. variables to make sure they have unique names. Recall that our plan
  1097. for \#2 involves moving nested expressions, which could be problematic
  1098. if it changes the shadowing of variables. However, if we deal with \#4
  1099. first, then it will not be an issue. Thus, we arrive at the following
  1100. ordering.
  1101. \[
  1102. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1103. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  1104. {
  1105. \node (\i) at (\p*1.5,0) {$\i$};
  1106. }
  1107. \foreach \x/\y in {4/2,2/1,1/3}
  1108. {
  1109. \draw[->] (\x) to (\y);
  1110. }
  1111. \end{tikzpicture}
  1112. \]
  1113. We further simplify the translation from $R_1$ to x86 by identifying
  1114. an intermediate language named $C_0$, roughly half-way between $R_1$
  1115. and x86, to provide a rest stop along the way. We name the language
  1116. $C_0$ because it is vaguely similar to the $C$
  1117. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1118. regarding variables and nested expressions, will be handled by two
  1119. steps, \key{uniquify} and \key{flatten}, which bring us to
  1120. $C_0$.
  1121. \[
  1122. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1123. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1124. {
  1125. \node (\p) at (\p*3,0) {\large $\i$};
  1126. }
  1127. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1128. {
  1129. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1130. }
  1131. \end{tikzpicture}
  1132. \]
  1133. Each of these steps in the compiler is implemented by a function,
  1134. typically a structurally recursive function that translates an input
  1135. AST into an output AST. We refer to such a function as a \emph{pass}
  1136. because it makes a pass over, i.e. it traverses the entire AST.
  1137. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1138. $C_0$ language supports the same operators as $R_1$ but the arguments
  1139. of operators are now restricted to just variables and integers. The
  1140. \key{let} construct of $R_1$ is replaced by an assignment statement
  1141. and there is a \key{return} construct to specify the return value of
  1142. the program. A program consists of a sequence of statements that
  1143. include at least one \key{return} statement. Each program is also
  1144. annotated with a list of variables (viz. {\tt (var*)}). At the start
  1145. of the program, these variables are uninitialized (they contain garbage)
  1146. and each variable becomes initialized on its first assignment. All of
  1147. the variables used in the program must be present in this list exactly once.
  1148. \begin{figure}[tp]
  1149. \fbox{
  1150. \begin{minipage}{0.96\textwidth}
  1151. \[
  1152. \begin{array}{lcl}
  1153. \Arg &::=& \Int \mid \Var \\
  1154. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1155. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1156. C_0 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1157. \end{array}
  1158. \]
  1159. \end{minipage}
  1160. }
  1161. \caption{The $C_0$ intermediate language.}
  1162. \label{fig:c0-syntax}
  1163. \end{figure}
  1164. To get from $C_0$ to x86 assembly it remains for us to handle
  1165. difference \#1 (the format of instructions) and difference \#3
  1166. (variables versus registers). These two differences are intertwined,
  1167. creating a bit of a Gordian Knot. To handle difference \#3, we need to
  1168. map some variables to registers (there are only 16 registers) and the
  1169. remaining variables to locations on the stack (which is unbounded). To
  1170. make good decisions regarding this mapping, we need the program to be
  1171. close to its final form (in x86 assembly) so we know exactly when
  1172. which variables are used. After all, variables that are used in
  1173. disjoint parts of the program can be assigned to the same register.
  1174. However, our choice of x86 instructions depends on whether the
  1175. variables are mapped to registers or stack locations, so we have a
  1176. circular dependency. We cut this knot by doing an optimistic selection
  1177. of instructions in the \key{select-instructions} pass, followed by the
  1178. \key{assign-homes} pass to map variables to registers or stack
  1179. locations, and conclude by finalizing the instruction selection in the
  1180. \key{patch-instructions} pass.
  1181. \[
  1182. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1183. \node (1) at (0,0) {\large $C_0$};
  1184. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  1185. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  1186. \node (4) at (9,0) {\large $\text{x86}$};
  1187. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1188. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1189. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1190. \end{tikzpicture}
  1191. \]
  1192. The \key{select-instructions} pass is optimistic in the sense that it
  1193. treats variables as if they were all mapped to registers. The
  1194. \key{select-instructions} pass generates a program that consists of
  1195. x86 instructions but that still uses variables, so it is an
  1196. intermediate language that is technically different than x86, which
  1197. explains the asterisks in the diagram above.
  1198. In this Chapter we shall take the easy road to implementing
  1199. \key{assign-homes} and simply map all variables to stack locations.
  1200. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1201. smarter approach in which we make a best-effort to map variables to
  1202. registers, resorting to the stack only when necessary.
  1203. %% \margincomment{\scriptsize I'm confused: shouldn't `select instructions' do this?
  1204. %% After all, that selects the x86 instructions. Even if it is separate,
  1205. %% if we perform `patching' before register allocation, we aren't forced to rely on
  1206. %% \key{rax} as much. This can ultimately make a more-performant result. --
  1207. %% Cam}
  1208. Once variables have been assigned to their homes, we can finalize the
  1209. instruction selection by dealing with an idiosyncrasy of x86
  1210. assembly. Many x86 instructions have two arguments but only one of the
  1211. arguments may be a memory reference (and the stack is a part of
  1212. memory). Because some variables may get mapped to stack locations,
  1213. some of our generated instructions may violate this restriction. The
  1214. purpose of the \key{patch-instructions} pass is to fix this problem by
  1215. replacing every violating instruction with a short sequence of
  1216. instructions that use the \key{rax} register. Once we have implemented
  1217. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1218. need to patch instructions will be relatively rare.
  1219. \section{Uniquify Variables}
  1220. \label{sec:uniquify-s0}
  1221. The purpose of this pass is to make sure that each \key{let} uses a
  1222. unique variable name. For example, the \code{uniquify} pass should
  1223. translate the program on the left into the program on the right. \\
  1224. \begin{tabular}{lll}
  1225. \begin{minipage}{0.4\textwidth}
  1226. \begin{lstlisting}
  1227. (program
  1228. (let ([x 32])
  1229. (+ (let ([x 10]) x) x)))
  1230. \end{lstlisting}
  1231. \end{minipage}
  1232. &
  1233. $\Rightarrow$
  1234. &
  1235. \begin{minipage}{0.4\textwidth}
  1236. \begin{lstlisting}
  1237. (program
  1238. (let ([x.1 32])
  1239. (+ (let ([x.2 10]) x.2) x.1)))
  1240. \end{lstlisting}
  1241. \end{minipage}
  1242. \end{tabular} \\
  1243. %
  1244. The following is another example translation, this time of a program
  1245. with a \key{let} nested inside the initializing expression of another
  1246. \key{let}.\\
  1247. \begin{tabular}{lll}
  1248. \begin{minipage}{0.4\textwidth}
  1249. \begin{lstlisting}
  1250. (program
  1251. (let ([x (let ([x 4])
  1252. (+ x 1))])
  1253. (+ x 2)))
  1254. \end{lstlisting}
  1255. \end{minipage}
  1256. &
  1257. $\Rightarrow$
  1258. &
  1259. \begin{minipage}{0.4\textwidth}
  1260. \begin{lstlisting}
  1261. (program
  1262. (let ([x.2 (let ([x.1 4])
  1263. (+ x.1 1))])
  1264. (+ x.2 2)))
  1265. \end{lstlisting}
  1266. \end{minipage}
  1267. \end{tabular}
  1268. We recommend implementing \code{uniquify} as a structurally recursive
  1269. function that mostly copies the input program. However, when
  1270. encountering a \key{let}, it should generate a unique name for the
  1271. variable (the Racket function \code{gensym} is handy for this) and
  1272. associate the old name with the new unique name in an association
  1273. list. The \code{uniquify} function will need to access this
  1274. association list when it gets to a variable reference, so we add
  1275. another parameter to \code{uniquify} for the association list. It is
  1276. quite common for a compiler pass to need a map to store extra
  1277. information about variables. Such maps are often called \emph{symbol
  1278. tables}.
  1279. The skeleton of the \code{uniquify} function is shown in
  1280. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1281. convenient to partially apply it to an association list and then apply
  1282. it to different expressions, as in the last clause for primitive
  1283. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1284. clause for the primitive operators, note the use of the comma-@
  1285. operator to splice a list of S-expressions into an enclosing
  1286. S-expression.
  1287. \begin{exercise}
  1288. \normalfont % I don't like the italics for exercises. -Jeremy
  1289. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1290. implement the clauses for variables and for the \key{let} construct.
  1291. \end{exercise}
  1292. \begin{figure}[tbp]
  1293. \begin{lstlisting}
  1294. (define (uniquify alist)
  1295. (lambda (e)
  1296. (match e
  1297. [(? symbol?) ___]
  1298. [(? integer?) e]
  1299. [`(let ([,x ,e]) ,body) ___]
  1300. [`(program ,e)
  1301. `(program ,((uniquify alist) e))]
  1302. [`(,op ,es ...)
  1303. `(,op ,@(map (uniquify alist) es))]
  1304. )))
  1305. \end{lstlisting}
  1306. \caption{Skeleton for the \key{uniquify} pass.}
  1307. \label{fig:uniquify-s0}
  1308. \end{figure}
  1309. \begin{exercise}
  1310. \normalfont % I don't like the italics for exercises. -Jeremy
  1311. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1312. and checking whether the output programs produce the same result as
  1313. the input programs. The $R_1$ programs should be designed to test the
  1314. most interesting parts of the \key{uniquify} pass, that is, the
  1315. programs should include \key{let} constructs, variables, and variables
  1316. that overshadow each other. The five programs should be in a
  1317. subdirectory named \key{tests} and they should have the same file name
  1318. except for a different integer at the end of the name, followed by the
  1319. ending \key{.rkt}. Use the \key{interp-tests} function
  1320. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1321. your \key{uniquify} pass on the example programs.
  1322. \end{exercise}
  1323. \section{Flatten Expressions}
  1324. \label{sec:flatten-r1}
  1325. The \code{flatten} pass will transform $R_1$ programs into $C_0$
  1326. programs. In particular, the purpose of the \code{flatten} pass is to
  1327. get rid of nested expressions, such as the \code{(- 10)} in the program
  1328. below. This can be accomplished by introducing a new variable,
  1329. assigning the nested expression to the new variable, and then using
  1330. the new variable in place of the nested expressions, as shown in the
  1331. output of \code{flatten} on the right.\\
  1332. \begin{tabular}{lll}
  1333. \begin{minipage}{0.4\textwidth}
  1334. \begin{lstlisting}
  1335. (program
  1336. (+ 52 (- 10)))
  1337. \end{lstlisting}
  1338. \end{minipage}
  1339. &
  1340. $\Rightarrow$
  1341. &
  1342. \begin{minipage}{0.4\textwidth}
  1343. \begin{lstlisting}
  1344. (program (tmp.1 tmp.2)
  1345. (assign tmp.1 (- 10))
  1346. (assign tmp.2 (+ 52 tmp.1))
  1347. (return tmp.2))
  1348. \end{lstlisting}
  1349. \end{minipage}
  1350. \end{tabular}
  1351. The clause of \code{flatten} for \key{let} is straightforward to
  1352. implement as it just requires the generation of an assignment
  1353. statement for the \key{let}-bound variable. The following shows the
  1354. result of \code{flatten} for a \key{let}. \\
  1355. \begin{tabular}{lll}
  1356. \begin{minipage}{0.4\textwidth}
  1357. \begin{lstlisting}
  1358. (program
  1359. (let ([x (+ (- 10) 11)])
  1360. (+ x 41)))
  1361. \end{lstlisting}
  1362. \end{minipage}
  1363. &
  1364. $\Rightarrow$
  1365. &
  1366. \begin{minipage}{0.4\textwidth}
  1367. \begin{lstlisting}
  1368. (program (tmp.1 x tmp.2)
  1369. (assign tmp.1 (- 10))
  1370. (assign x (+ tmp.1 11))
  1371. (assign tmp.2 (+ x 41))
  1372. (return tmp.2))
  1373. \end{lstlisting}
  1374. \end{minipage}
  1375. \end{tabular}
  1376. We recommend implementing \key{flatten} as a structurally recursive
  1377. function that returns three things, 1) the newly flattened expression,
  1378. 2) a list of assignment statements, one for each of the new variables
  1379. introduced during the flattening the expression, and 3) a list of all
  1380. the variables including both let-bound variables and the generated
  1381. temporary variables. The newly flattened expression should be an
  1382. $\Arg$ in the $C_0$ syntax (Figure~\ref{fig:c0-syntax}), that is, it
  1383. should be an integer or a variable. You can return multiple things
  1384. from a function using the \key{values} form and you can receive
  1385. multiple things from a function call using the \key{define-values}
  1386. form. If you are not familiar with these constructs, the Racket
  1387. documentation will be of help.
  1388. Also, the \key{map3} function
  1389. (Appendix~\ref{appendix:utilities}) is useful for applying a function
  1390. to each element of a list, in the case where the function returns
  1391. three values. The result of \key{map3} is three lists.
  1392. The clause of \key{flatten} for the \key{program} node needs to
  1393. recursively flatten the body of the program and the newly flattened
  1394. expression should be placed in a \key{return} statement. Remember that
  1395. the variable list in the \key{program} node should contain no duplicates.
  1396. %% The
  1397. %% \key{flatten} pass should also compute the list of variables used in
  1398. %% the program.
  1399. %% I recommend traversing the statements in the body of the
  1400. %% program (after it has been flattened) and collect all variables that
  1401. %% appear on the left-hand-side of an assignment.
  1402. %% Note that each variable
  1403. %% should only occur once in the list of variables that you place in the
  1404. %% \key{program} form.
  1405. Take special care for programs such as the following that initialize
  1406. variables with integers or other variables. It should be translated
  1407. to the program on the right \\
  1408. \begin{tabular}{lll}
  1409. \begin{minipage}{0.4\textwidth}
  1410. \begin{lstlisting}
  1411. (let ([a 42])
  1412. (let ([b a])
  1413. b))
  1414. \end{lstlisting}
  1415. \end{minipage}
  1416. &
  1417. $\Rightarrow$
  1418. &
  1419. \begin{minipage}{0.4\textwidth}
  1420. \begin{lstlisting}
  1421. (program (a b)
  1422. (assign a 42)
  1423. (assign b a)
  1424. (return b))
  1425. \end{lstlisting}
  1426. \end{minipage}
  1427. \end{tabular} \\
  1428. and not to the following, which could result from a naive
  1429. implementation of \key{flatten}.
  1430. \begin{lstlisting}
  1431. (program (tmp.1 a tmp.2 b)
  1432. (assign tmp.1 42)
  1433. (assign a tmp.1)
  1434. (assign tmp.2 a)
  1435. (assign b tmp.2)
  1436. (return b))
  1437. \end{lstlisting}
  1438. \begin{exercise}
  1439. \normalfont
  1440. Implement the \key{flatten} pass and test it on all of the example
  1441. programs that you created to test the \key{uniquify} pass and create
  1442. three new example programs that are designed to exercise all of the
  1443. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1444. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1445. test your passes on the example programs.
  1446. \end{exercise}
  1447. \section{Select Instructions}
  1448. \label{sec:select-s0}
  1449. In the \key{select-instructions} pass we begin the work of translating
  1450. from $C_0$ to x86. The target language of this pass is a pseudo-x86
  1451. language that still uses variables, so we add an AST node of the form
  1452. $\VAR{\itm{var}}$ to the x86 abstract syntax. Also, the \key{program}
  1453. form should still list the variables (similar to $C_0$):
  1454. \[
  1455. (\key{program}\;(\Var^{*})\;\Instr^{+})
  1456. \]
  1457. The \key{select-instructions} pass deals with the differing format of
  1458. arithmetic operations. For example, in $C_0$ an addition operation can
  1459. take the form below. To translate to x86, we need to use the
  1460. \key{addq} instruction which does an in-place update. So we must first
  1461. move \code{10} to \code{x}. \\
  1462. \begin{tabular}{lll}
  1463. \begin{minipage}{0.4\textwidth}
  1464. \begin{lstlisting}
  1465. (assign x (+ 10 32))
  1466. \end{lstlisting}
  1467. \end{minipage}
  1468. &
  1469. $\Rightarrow$
  1470. &
  1471. \begin{minipage}{0.4\textwidth}
  1472. \begin{lstlisting}
  1473. (movq (int 10) (var x))
  1474. (addq (int 32) (var x))
  1475. \end{lstlisting}
  1476. \end{minipage}
  1477. \end{tabular} \\
  1478. There are some cases that require special care to avoid generating
  1479. needlessly complicated code. If one of the arguments is the same as
  1480. the left-hand side of the assignment, then there is no need for the
  1481. extra move instruction. For example, the following assignment
  1482. statement can be translated into a single \key{addq} instruction.\\
  1483. \begin{tabular}{lll}
  1484. \begin{minipage}{0.4\textwidth}
  1485. \begin{lstlisting}
  1486. (assign x (+ 10 x))
  1487. \end{lstlisting}
  1488. \end{minipage}
  1489. &
  1490. $\Rightarrow$
  1491. &
  1492. \begin{minipage}{0.4\textwidth}
  1493. \begin{lstlisting}
  1494. (addq (int 10) (var x))
  1495. \end{lstlisting}
  1496. \end{minipage}
  1497. \end{tabular} \\
  1498. The \key{read} operation does not have a direct counterpart in x86
  1499. assembly, so we have instead implemented this functionality in the C
  1500. language, with the function \code{read\_int} in the file
  1501. \code{runtime.c}. In general, we refer to all of the functionality in
  1502. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1503. for short. When compiling your generated x86 assembly code, you
  1504. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1505. file'', using \code{gcc} option \code{-c}) and link it into the final
  1506. executable. For our purposes of code generation, all you need to do is
  1507. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1508. (for left-hand side) into a call to the \code{read\_int} function
  1509. followed by a move from \code{rax} to the left-hand side. The move
  1510. from \code{rax} is needed because the return value from
  1511. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1512. \begin{tabular}{lll}
  1513. \begin{minipage}{0.4\textwidth}
  1514. \begin{lstlisting}
  1515. (assign |$\itm{lhs}$| (read))
  1516. \end{lstlisting}
  1517. \end{minipage}
  1518. &
  1519. $\Rightarrow$
  1520. &
  1521. \begin{minipage}{0.4\textwidth}
  1522. \begin{lstlisting}
  1523. (callq read_int)
  1524. (movq (reg rax) (var |$\itm{lhs}$|))
  1525. \end{lstlisting}
  1526. \end{minipage}
  1527. \end{tabular} \\
  1528. Regarding the \RETURN{\Arg} statement of $C_0$, we recommend treating it
  1529. as an assignment to the \key{rax} register and let the procedure
  1530. conclusion handle the transfer of control back to the calling
  1531. procedure.
  1532. \begin{exercise}
  1533. \normalfont
  1534. Implement the \key{select-instructions} pass and test it on all of the
  1535. example programs that you created for the previous passes and create
  1536. three new example programs that are designed to exercise all of the
  1537. interesting code in this pass. Use the \key{interp-tests} function
  1538. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1539. your passes on the example programs.
  1540. \end{exercise}
  1541. \section{Assign Homes}
  1542. \label{sec:assign-s0}
  1543. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1544. \key{assign-homes} pass places all of the variables on the stack.
  1545. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1546. which after \key{select-instructions} looks like the following.
  1547. \begin{lstlisting}
  1548. (movq (int 10) (var tmp.1))
  1549. (negq (var tmp.1))
  1550. (movq (var tmp.1) (var tmp.2))
  1551. (addq (int 52) (var tmp.2))
  1552. (movq (var tmp.2) (reg rax)))
  1553. \end{lstlisting}
  1554. The variable \code{tmp.1} is assigned to stack location
  1555. \code{-8(\%rbp)}, and \code{tmp.2} is assign to \code{-16(\%rbp)}, so
  1556. the \code{assign-homes} pass translates the above to
  1557. \begin{lstlisting}
  1558. (movq (int 10) (deref rbp -16))
  1559. (negq (deref rbp -16))
  1560. (movq (deref rbp -16) (deref rbp -8))
  1561. (addq (int 52) (deref rbp -8))
  1562. (movq (deref rbp -8) (reg rax)))
  1563. \end{lstlisting}
  1564. In the process of assigning stack locations to variables, it is
  1565. convenient to compute and store the size of the frame (in bytes) in
  1566. the first field of the \key{program} node which will be needed later
  1567. to generate the procedure conclusion.
  1568. \[
  1569. (\key{program}\;\Int\;\Instr^{+})
  1570. \]
  1571. Some operating systems place restrictions on
  1572. the frame size. For example, Mac OS X requires the frame size to be a
  1573. multiple of 16 bytes.
  1574. \begin{exercise}
  1575. \normalfont Implement the \key{assign-homes} pass and test it on all
  1576. of the example programs that you created for the previous passes pass.
  1577. I recommend that \key{assign-homes} take an extra parameter that is a
  1578. mapping of variable names to homes (stack locations for now). Use the
  1579. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1580. \key{utilities.rkt} to test your passes on the example programs.
  1581. \end{exercise}
  1582. \section{Patch Instructions}
  1583. \label{sec:patch-s0}
  1584. The purpose of this pass is to make sure that each instruction adheres
  1585. to the restrictions regarding which arguments can be memory
  1586. references. For most instructions, the rule is that at most one
  1587. argument may be a memory reference.
  1588. Consider again the following example.
  1589. \begin{lstlisting}
  1590. (let ([a 42])
  1591. (let ([b a])
  1592. b))
  1593. \end{lstlisting}
  1594. After \key{assign-homes} pass, the above has been translated to
  1595. \begin{lstlisting}
  1596. (movq (int 42) (deref rbp -8))
  1597. (movq (deref rbp -8) (deref rbp -16))
  1598. (movq (deref rbp -16) (reg rax))
  1599. \end{lstlisting}
  1600. The second \key{movq} instruction is problematic because both
  1601. arguments are stack locations. We suggest fixing this problem by
  1602. moving from the source to the register \key{rax} and then from
  1603. \key{rax} to the destination, as follows.
  1604. \begin{lstlisting}
  1605. (movq (int 42) (deref rbp -8))
  1606. (movq (deref rbp -8) (reg rax))
  1607. (movq (reg rax) (deref rbp -16))
  1608. (movq (deref rbp -16) (reg rax))
  1609. \end{lstlisting}
  1610. \begin{exercise}
  1611. \normalfont
  1612. Implement the \key{patch-instructions} pass and test it on all of the
  1613. example programs that you created for the previous passes and create
  1614. three new example programs that are designed to exercise all of the
  1615. interesting code in this pass. Use the \key{interp-tests} function
  1616. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1617. your passes on the example programs.
  1618. \end{exercise}
  1619. \section{Print x86}
  1620. \label{sec:print-x86}
  1621. The last step of the compiler from $R_1$ to x86 is to convert the
  1622. x86 AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1623. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1624. \key{format} and \key{string-append} functions are useful in this
  1625. regard. The main work that this step needs to perform is to create the
  1626. \key{main} function and the standard instructions for its prelude
  1627. and conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1628. Section~\ref{sec:x86}. You need to know the number of
  1629. stack-allocated variables, for which it is suggest that you compute in
  1630. the \key{assign-homes} pass (Section~\ref{sec:assign-s0}) and store in
  1631. the $\itm{info}$ field of the \key{program} node.
  1632. Your compiled code should print the result of the program's execution by using the
  1633. \code{print\_int} function provided in \code{runtime.c}. If your compiler has been implemented correctly so far, this final result should be stored in the \key{rax} register.
  1634. We'll talk more about
  1635. how to perform function calls with arguments in general later on, but
  1636. for now, make sure that your x86 printer includes the following code as part of the conclusion:
  1637. \begin{lstlisting}
  1638. movq %rax, %rdi
  1639. callq print_int
  1640. \end{lstlisting}
  1641. These lines move the value in \key{rax} into the \key{rdi} register, which
  1642. stores the first argument to be passed into \key{print\_int}.
  1643. If you want your program to run on Mac OS X, your code needs to
  1644. determine whether or not it is running on a Mac, and prefix
  1645. underscores to labels like \key{main}. You can determine the platform
  1646. with the Racket call \code{(system-type 'os)}, which returns
  1647. \code{'macosx}, \code{'unix}, or \code{'windows}. In addition to
  1648. placing underscores on \key{main}, you need to put them in front of
  1649. \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1650. \_print\_int}).
  1651. \begin{exercise}
  1652. \normalfont Implement the \key{print-x86} pass and test it on all of
  1653. the example programs that you created for the previous passes. Use the
  1654. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1655. \key{utilities.rkt} to test your complete compiler on the example
  1656. programs.
  1657. % The following is specific to P423/P523. -Jeremy
  1658. %Mac support is optional, but your compiler has to output
  1659. %valid code for Unix machines.
  1660. \end{exercise}
  1661. \begin{figure}[p]
  1662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1663. \node (R1) at (0,2) {\large $R_1$};
  1664. \node (R1-2) at (3,2) {\large $R_1$};
  1665. \node (C0-1) at (3,0) {\large $C_0$};
  1666. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  1667. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  1668. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  1669. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  1670. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1671. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  1672. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1673. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1674. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1675. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1676. \end{tikzpicture}
  1677. \caption{Overview of the passes for compiling $R_1$. }
  1678. \label{fig:R1-passes}
  1679. \end{figure}
  1680. Figure~\ref{fig:R1-passes} provides an overview of all the compiler
  1681. passes described in this Chapter. The x86$^{*}$ language extends x86
  1682. with variables and looser rules regarding instruction arguments. The
  1683. x86$^{\dagger}$ language is the concrete syntax (string) for x86.
  1684. \margincomment{\footnotesize To do: add a challenge section. Perhaps
  1685. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1686. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1687. \chapter{Register Allocation}
  1688. \label{ch:register-allocation}
  1689. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1690. assembly by placing all variables on the stack. We can improve the
  1691. performance of the generated code considerably if we instead try to
  1692. place as many variables as possible into registers. The CPU can
  1693. access a register in a single cycle, whereas accessing the stack takes
  1694. many cycles to go to cache or many more to access main memory.
  1695. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1696. serves as a running example. We show the source program and also the
  1697. output of instruction selection. At that point the program is almost
  1698. x86 assembly but not quite; it still contains variables instead of
  1699. stack locations or registers.
  1700. \begin{figure}
  1701. \begin{minipage}{0.45\textwidth}
  1702. Source program:
  1703. \begin{lstlisting}
  1704. (program
  1705. (let ([v 1])
  1706. (let ([w 46])
  1707. (let ([x (+ v 7)])
  1708. (let ([y (+ 4 x)])
  1709. (let ([z (+ x w)])
  1710. (+ z (- y))))))))
  1711. \end{lstlisting}
  1712. \end{minipage}
  1713. \begin{minipage}{0.45\textwidth}
  1714. After instruction selection:
  1715. \begin{lstlisting}
  1716. (program (v w x y z t.1 t.2)
  1717. (movq (int 1) (var v))
  1718. (movq (int 46) (var w))
  1719. (movq (var v) (var x))
  1720. (addq (int 7) (var x))
  1721. (movq (var x) (var y))
  1722. (addq (int 4) (var y))
  1723. (movq (var x) (var z))
  1724. (addq (var w) (var z))
  1725. (movq (var y) (var t.1))
  1726. (negq (var t.1))
  1727. (movq (var z) (var t.2))
  1728. (addq (var t.1) (var t.2))
  1729. (movq (var t.2) (reg rax)))
  1730. \end{lstlisting}
  1731. \end{minipage}
  1732. \caption{An example program for register allocation.}
  1733. \label{fig:reg-eg}
  1734. \end{figure}
  1735. The goal of register allocation is to fit as many variables into
  1736. registers as possible. It is often the case that we have more
  1737. variables than registers, so we cannot map each variable to a
  1738. different register. Fortunately, it is common for different variables
  1739. to be needed during different periods of time, and in such cases
  1740. several variables can be mapped to the same register. Consider
  1741. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  1742. variable \code{x} is moved to \code{z} it is no longer needed.
  1743. Variable \code{y}, on the other hand, is used only after this point,
  1744. so \code{x} and \code{y} could share the same register. The topic of
  1745. Section~\ref{sec:liveness-analysis} is how we compute where a variable
  1746. is needed. Once we have that information, we compute which variables
  1747. are needed at the same time, i.e., which ones \emph{interfere}, and
  1748. represent this relation as graph whose vertices are variables and
  1749. edges indicate when two variables interfere with eachother
  1750. (Section~\ref{sec:build-interference}). We then model register
  1751. allocation as a graph coloring problem, which we discuss in
  1752. Section~\ref{sec:graph-coloring}.
  1753. In the event that we run out of registers despite these efforts, we
  1754. place the remaining variables on the stack, similar to what we did in
  1755. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  1756. that is assigned to a stack location, it has been \emph{spilled}. The
  1757. process of spilling variables is handled as part of the graph coloring
  1758. process described in \ref{sec:graph-coloring}.
  1759. \section{Liveness Analysis}
  1760. \label{sec:liveness-analysis}
  1761. A variable is \emph{live} if the variable is used at some later point
  1762. in the program and there is not an intervening assignment to the
  1763. variable.
  1764. %
  1765. To understand the latter condition, consider the following code
  1766. fragment in which there are two writes to \code{b}. Are \code{a} and
  1767. \code{b} both live at the same time?
  1768. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1769. (movq (int 5) (var a))
  1770. (movq (int 30) (var b))
  1771. (movq (var a) (var c))
  1772. (movq (int 10) (var b))
  1773. (addq (var b) (var c))
  1774. \end{lstlisting}
  1775. The answer is no because the value \code{30} written to \code{b} on
  1776. line 2 is never used. The variable \code{b} is read on line 5 and
  1777. there is an intervening write to \code{b} on line 4, so the read on
  1778. line 5 receives the value written on line 4, not line 2.
  1779. The live variables can be computed by traversing the instruction
  1780. sequence back to front (i.e., backwards in execution order). Let
  1781. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1782. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1783. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1784. variables before instruction $I_k$. The live variables after an
  1785. instruction are always the same as the live variables before the next
  1786. instruction.
  1787. \begin{equation*}
  1788. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1789. \end{equation*}
  1790. To start things off, there are no live variables after the last
  1791. instruction, so
  1792. \begin{equation*}
  1793. L_{\mathsf{after}}(n) = \emptyset
  1794. \end{equation*}
  1795. We then apply the following rule repeatedly, traversing the
  1796. instruction sequence back to front.
  1797. \begin{equation*}
  1798. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1799. \end{equation*}
  1800. where $W(k)$ are the variables written to by instruction $I_k$ and
  1801. $R(k)$ are the variables read by instruction $I_k$.
  1802. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1803. for the running example, with each instruction aligned with its
  1804. $L_{\mathtt{after}}$ set to make the figure easy to read.
  1805. \margincomment{JM: I think you should walk through the explanation of this formula,
  1806. connecting it back to the example from before. \\
  1807. JS: Agreed.}
  1808. \begin{figure}[tbp]
  1809. \hspace{20pt}
  1810. \begin{minipage}{0.45\textwidth}
  1811. \begin{lstlisting}[numbers=left]
  1812. (program (v w x y z t.1 t.2)
  1813. (movq (int 1) (var v))
  1814. (movq (int 46) (var w))
  1815. (movq (var v) (var x))
  1816. (addq (int 7) (var x))
  1817. (movq (var x) (var y))
  1818. (addq (int 4) (var y))
  1819. (movq (var x) (var z))
  1820. (addq (var w) (var z))
  1821. (movq (var y) (var t.1))
  1822. (negq (var t.1))
  1823. (movq (var z) (var t.2))
  1824. (addq (var t.1) (var t.2))
  1825. (movq (var t.2) (reg rax)))
  1826. \end{lstlisting}
  1827. \end{minipage}
  1828. \vrule\hspace{10pt}
  1829. \begin{minipage}{0.45\textwidth}
  1830. \begin{lstlisting}
  1831. |$\{ v \}$|
  1832. |$\{ v, w \}$|
  1833. |$\{ w, x \}$|
  1834. |$\{ w, x \}$|
  1835. |$\{ w, x, y\}$|
  1836. |$\{ w, x, y \}$|
  1837. |$\{ w, y, z \}$|
  1838. |$\{ y, z \}$|
  1839. |$\{ t.1, z \}$|
  1840. |$\{ t.1, z \}$|
  1841. |$\{t.1,t.2\}$|
  1842. |$\{t.2\}$|
  1843. |$\{\}$|
  1844. \end{lstlisting}
  1845. \end{minipage}
  1846. \caption{An example program annotated with live-after sets.}
  1847. \label{fig:live-eg}
  1848. \end{figure}
  1849. \begin{exercise}\normalfont
  1850. Implement the compiler pass named \code{uncover-live} that computes
  1851. the live-after sets. We recommend storing the live-after sets (a list
  1852. of lists of variables) in the $\itm{info}$ field of the \key{program}
  1853. node alongside the list of variables as follows.
  1854. \begin{lstlisting}
  1855. (program (|$\Var^{*}$| |$\itm{live{-}afters}$|) |$\Instr^{+}$|)
  1856. \end{lstlisting}
  1857. I recommend organizing your code to use a helper function that takes a
  1858. list of statements and an initial live-after set (typically empty) and
  1859. returns the list of statements and the list of live-after sets. For
  1860. this chapter, returning the list of statements is unnecessary, as they
  1861. will be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  1862. \key{if} statements and will need to annotate them with the live-after
  1863. sets of the two branches.
  1864. I recommend creating helper functions to 1) compute the set of
  1865. variables that appear in an argument (of an instruction), 2) compute
  1866. the variables read by an instruction which corresponds to the $R$
  1867. function discussed above, and 3) the variables written by an
  1868. instruction which corresponds to $W$.
  1869. \end{exercise}
  1870. \section{Building the Interference Graph}
  1871. \label{sec:build-interference}
  1872. Based on the liveness analysis, we know where each variable is needed.
  1873. However, during register allocation, we need to answer questions of
  1874. the specific form: are variables $u$ and $v$ live at the same time?
  1875. (And therefore cannot be assigned to the same register.) To make this
  1876. question easier to answer, we create an explicit data structure, an
  1877. \emph{interference graph}. An interference graph is an undirected
  1878. graph that has an edge between two variables if they are live at the
  1879. same time, that is, if they interfere with each other.
  1880. The most obvious way to compute the interference graph is to look at
  1881. the set of live variables between each statement in the program, and
  1882. add an edge to the graph for every pair of variables in the same set.
  1883. This approach is less than ideal for two reasons. First, it can be
  1884. rather expensive because it takes $O(n^2)$ time to look at every pair
  1885. in a set of $n$ live variables. Second, there is a special case in
  1886. which two variables that are live at the same time do not actually
  1887. interfere with each other: when they both contain the same value
  1888. because we have assigned one to the other.
  1889. A better way to compute the interference graph is given by the
  1890. following.
  1891. \begin{itemize}
  1892. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1893. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1894. d$ or $v = s$.
  1895. \item If instruction $I_k$ is not a move but some other arithmetic
  1896. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1897. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1898. \item If instruction $I_k$ is of the form (\key{callq}
  1899. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1900. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1901. \end{itemize}
  1902. \margincomment{JM: I think you could give examples of each one of these
  1903. using the example program and use those to help explain why these
  1904. rules are correct.\\
  1905. JS: Agreed.}
  1906. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  1907. the following interference for the instruction at the specified line
  1908. number.
  1909. \begin{quote}
  1910. Line 2: no interference,\\
  1911. Line 3: $w$ interferes with $v$,\\
  1912. Line 4: $x$ interferes with $w$,\\
  1913. Line 5: $x$ interferes with $w$,\\
  1914. Line 6: $y$ interferes with $w$,\\
  1915. Line 7: $y$ interferes with $w$ and $x$,\\
  1916. Line 8: $z$ interferes with $w$ and $y$,\\
  1917. Line 9: $z$ interferes with $y$, \\
  1918. Line 10: $t.1$ interferes with $z$, \\
  1919. Line 11: $t.1$ interferes with $z$, \\
  1920. Line 12: $t.2$ interferes with $t.1$, \\
  1921. Line 13: no interference. \\
  1922. Line 14: no interference.
  1923. \end{quote}
  1924. The resulting interference graph is shown in
  1925. Figure~\ref{fig:interfere}.
  1926. \begin{figure}[tbp]
  1927. \large
  1928. \[
  1929. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1930. \node (v) at (0,0) {$v$};
  1931. \node (w) at (2,0) {$w$};
  1932. \node (x) at (4,0) {$x$};
  1933. \node (t1) at (6,0) {$t.1$};
  1934. \node (y) at (2,-2) {$y$};
  1935. \node (z) at (4,-2) {$z$};
  1936. \node (t2) at (6,-2) {$t.2$};
  1937. \draw (v) to (w);
  1938. \foreach \i in {w,x,y}
  1939. {
  1940. \foreach \j in {w,x,y}
  1941. {
  1942. \draw (\i) to (\j);
  1943. }
  1944. }
  1945. \draw (z) to (w);
  1946. \draw (z) to (y);
  1947. \draw (t1) to (z);
  1948. \draw (t2) to (t1);
  1949. \end{tikzpicture}
  1950. \]
  1951. \caption{The interference graph of the example program.}
  1952. \label{fig:interfere}
  1953. \end{figure}
  1954. Our next concern is to choose a data structure for representing the
  1955. interference graph. There are many standard choices for how to
  1956. represent a graph: \emph{adjacency matrix}, \emph{adjacency list}, and
  1957. \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a data
  1958. structure is to study the algorithm that uses the data structure,
  1959. determine what operations need to be performed, and then choose the
  1960. data structure that provide the most efficient implementations of
  1961. those operations. Often times the choice of data structure can have an
  1962. effect on the time complexity of the algorithm, as it does here. If
  1963. you skim the next section, you will see that the register allocation
  1964. algorithm needs to ask the graph for all of its vertices and, given a
  1965. vertex, it needs to known all of the adjacent vertices. Thus, the
  1966. correct choice of graph representation is that of an adjacency
  1967. list. There are helper functions in \code{utilities.rkt} for
  1968. representing graphs using the adjacency list representation:
  1969. \code{make-graph}, \code{add-edge}, and \code{adjacent}
  1970. (Appendix~\ref{appendix:utilities}). In particular, those functions
  1971. use a hash table to map each vertex to the set of adjacent vertices,
  1972. and the sets are represented using Racket's \key{set}, which is also a
  1973. hash table.
  1974. \begin{exercise}\normalfont
  1975. Implement the compiler pass named \code{build-interference} according
  1976. to the algorithm suggested above. The output of this pass should
  1977. replace the live-after sets with the interference $\itm{graph}$ as
  1978. follows.
  1979. \begin{lstlisting}
  1980. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  1981. \end{lstlisting}
  1982. \end{exercise}
  1983. \section{Graph Coloring via Sudoku}
  1984. \label{sec:graph-coloring}
  1985. We now come to the main event, mapping variables to registers (or to
  1986. stack locations in the event that we run out of registers). We need
  1987. to make sure not to map two variables to the same register if the two
  1988. variables interfere with each other. In terms of the interference
  1989. graph, this means we cannot map adjacent nodes to the same register.
  1990. If we think of registers as colors, the register allocation problem
  1991. becomes the widely-studied graph coloring
  1992. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1993. The reader may be more familiar with the graph coloring problem then he
  1994. or she realizes; the popular game of Sudoku is an instance of the
  1995. graph coloring problem. The following describes how to build a graph
  1996. out of an initial Sudoku board.
  1997. \begin{itemize}
  1998. \item There is one node in the graph for each Sudoku square.
  1999. \item There is an edge between two nodes if the corresponding squares
  2000. are in the same row, in the same column, or if the squares are in
  2001. the same $3\times 3$ region.
  2002. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2003. \item Based on the initial assignment of numbers to squares in the
  2004. Sudoku board, assign the corresponding colors to the corresponding
  2005. nodes in the graph.
  2006. \end{itemize}
  2007. If you can color the remaining nodes in the graph with the nine
  2008. colors, then you have also solved the corresponding game of Sudoku.
  2009. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2010. the corresponding graph with colored vertices. We map the Sudoku
  2011. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2012. sampling of the vertices (those that are colored) because showing
  2013. edges for all of the vertices would make the graph unreadable.
  2014. \begin{figure}[tbp]
  2015. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2016. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2017. \caption{A Sudoku game board and the corresponding colored graph.}
  2018. \label{fig:sudoku-graph}
  2019. \end{figure}
  2020. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  2021. come up with an algorithm for allocating registers. For example, one
  2022. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  2023. that you use a process of elimination to determine what numbers no
  2024. longer make sense for a square, and write down those numbers in the
  2025. square (writing very small). For example, if the number $1$ is
  2026. assigned to a square, then by process of elimination, you can write
  2027. the pencil mark $1$ in all the squares in the same row, column, and
  2028. region. Many Sudoku computer games provide automatic support for
  2029. Pencil Marks. This heuristic also reduces the degree of branching in
  2030. the search tree.
  2031. The Pencil Marks technique corresponds to the notion of color
  2032. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2033. node, in Sudoku terms, is the set of colors that are no longer
  2034. available. In graph terminology, we have the following definition:
  2035. \begin{equation*}
  2036. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  2037. \text{ and } \mathrm{color}(v) = c \}
  2038. \end{equation*}
  2039. where $\mathrm{adjacent}(u)$ is the set of nodes adjacent to $u$.
  2040. Using the Pencil Marks technique leads to a simple strategy for
  2041. filling in numbers: if there is a square with only one possible number
  2042. left, then write down that number! But what if there are no squares
  2043. with only one possibility left? One brute-force approach is to just
  2044. make a guess. If that guess ultimately leads to a solution, great. If
  2045. not, backtrack to the guess and make a different guess. Of course,
  2046. backtracking can be horribly time consuming. One standard way to
  2047. reduce the amount of backtracking is to use the most-constrained-first
  2048. heuristic. That is, when making a guess, always choose a square with
  2049. the fewest possibilities left (the node with the highest saturation).
  2050. The idea is that choosing highly constrained squares earlier rather
  2051. than later is better because later there may not be any possibilities.
  2052. In some sense, register allocation is easier than Sudoku because we
  2053. can always cheat and add more numbers by mapping variables to the
  2054. stack. We say that a variable is \emph{spilled} when we decide to map
  2055. it to a stack location. We would like to minimize the time needed to
  2056. color the graph, and backtracking is expensive. Thus, it makes sense
  2057. to keep the most-constrained-first heuristic but drop the backtracking
  2058. in favor of greedy search (guess and just keep going).
  2059. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2060. greedy algorithm for register allocation based on saturation and the
  2061. most-constrained-first heuristic, which is roughly equivalent to the
  2062. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2063. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2064. as in Sudoku, the algorithm represents colors with integers, with the
  2065. first $k$ colors corresponding to the $k$ registers in a given machine
  2066. and the rest of the integers corresponding to stack locations.
  2067. \begin{figure}[btp]
  2068. \centering
  2069. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2070. Algorithm: DSATUR
  2071. Input: a graph |$G$|
  2072. Output: an assignment |$\mathrm{color}[v]$| for each node |$v \in G$|
  2073. |$W \gets \mathit{vertices}(G)$|
  2074. while |$W \neq \emptyset$| do
  2075. pick a node |$u$| from |$W$| with the highest saturation,
  2076. breaking ties randomly
  2077. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(v)\}$|
  2078. |$\mathrm{color}[u] \gets c$|
  2079. |$W \gets W - \{u\}$|
  2080. \end{lstlisting}
  2081. \caption{The saturation-based greedy graph coloring algorithm.}
  2082. \label{fig:satur-algo}
  2083. \end{figure}
  2084. With this algorithm in hand, let us return to the running example and
  2085. consider how to color the interference graph in
  2086. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2087. register allocation because we use it to patch instructions, so we
  2088. remove that vertex from the graph. Initially, all of the nodes are
  2089. not yet colored and they are unsaturated, so we annotate each of them
  2090. with a dash for their color and an empty set for the saturation.
  2091. \[
  2092. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2093. \node (v) at (0,0) {$v:-,\{\}$};
  2094. \node (w) at (3,0) {$w:-,\{\}$};
  2095. \node (x) at (6,0) {$x:-,\{\}$};
  2096. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2097. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2098. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2099. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2100. \draw (v) to (w);
  2101. \foreach \i in {w,x,y}
  2102. {
  2103. \foreach \j in {w,x,y}
  2104. {
  2105. \draw (\i) to (\j);
  2106. }
  2107. }
  2108. \draw (z) to (w);
  2109. \draw (z) to (y);
  2110. \draw (t1) to (z);
  2111. \draw (t2) to (t1);
  2112. \end{tikzpicture}
  2113. \]
  2114. We select a maximally saturated node and color it $0$. In this case we
  2115. have a 7-way tie, so we arbitrarily pick $y$. The then mark color $0$
  2116. as no longer available for $w$, $x$, and $z$ because they interfere
  2117. with $y$.
  2118. \[
  2119. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2120. \node (v) at (0,0) {$v:-,\{\}$};
  2121. \node (w) at (3,0) {$w:-,\{0\}$};
  2122. \node (x) at (6,0) {$x:-,\{0\}$};
  2123. \node (y) at (3,-1.5) {$y:0,\{\}$};
  2124. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  2125. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2126. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2127. \draw (v) to (w);
  2128. \foreach \i in {w,x,y}
  2129. {
  2130. \foreach \j in {w,x,y}
  2131. {
  2132. \draw (\i) to (\j);
  2133. }
  2134. }
  2135. \draw (z) to (w);
  2136. \draw (z) to (y);
  2137. \draw (t1) to (z);
  2138. \draw (t2) to (t1);
  2139. \end{tikzpicture}
  2140. \]
  2141. Now we repeat the process, selecting another maximally saturated node.
  2142. This time there is a three-way tie between $w$, $x$, and $z$. We color
  2143. $w$ with $1$.
  2144. \[
  2145. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2146. \node (v) at (0,0) {$v:-,\{1\}$};
  2147. \node (w) at (3,0) {$w:1,\{0\}$};
  2148. \node (x) at (6,0) {$x:-,\{0,1\}$};
  2149. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  2150. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2151. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2152. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2153. \draw (t1) to (z);
  2154. \draw (t2) to (t1);
  2155. \draw (v) to (w);
  2156. \foreach \i in {w,x,y}
  2157. {
  2158. \foreach \j in {w,x,y}
  2159. {
  2160. \draw (\i) to (\j);
  2161. }
  2162. }
  2163. \draw (z) to (w);
  2164. \draw (z) to (y);
  2165. \end{tikzpicture}
  2166. \]
  2167. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  2168. next available color which is $2$.
  2169. \[
  2170. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2171. \node (v) at (0,0) {$v:-,\{1\}$};
  2172. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2173. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2174. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2175. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2176. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2177. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2178. \draw (t1) to (z);
  2179. \draw (t2) to (t1);
  2180. \draw (v) to (w);
  2181. \foreach \i in {w,x,y}
  2182. {
  2183. \foreach \j in {w,x,y}
  2184. {
  2185. \draw (\i) to (\j);
  2186. }
  2187. }
  2188. \draw (z) to (w);
  2189. \draw (z) to (y);
  2190. \end{tikzpicture}
  2191. \]
  2192. Node $z$ is the next most highly saturated, so we color $z$ with $2$.
  2193. \[
  2194. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2195. \node (v) at (0,0) {$v:-,\{1\}$};
  2196. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2197. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2198. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2199. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2200. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2201. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2202. \draw (t1) to (z);
  2203. \draw (t2) to (t1);
  2204. \draw (v) to (w);
  2205. \foreach \i in {w,x,y}
  2206. {
  2207. \foreach \j in {w,x,y}
  2208. {
  2209. \draw (\i) to (\j);
  2210. }
  2211. }
  2212. \draw (z) to (w);
  2213. \draw (z) to (y);
  2214. \end{tikzpicture}
  2215. \]
  2216. We have a 2-way tie between $v$ and $t.1$. We choose to color $v$ with
  2217. $0$.
  2218. \[
  2219. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2220. \node (v) at (0,0) {$v:0,\{1\}$};
  2221. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2222. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2223. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2224. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2225. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2226. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2227. \draw (t1) to (z);
  2228. \draw (t2) to (t1);
  2229. \draw (v) to (w);
  2230. \foreach \i in {w,x,y}
  2231. {
  2232. \foreach \j in {w,x,y}
  2233. {
  2234. \draw (\i) to (\j);
  2235. }
  2236. }
  2237. \draw (z) to (w);
  2238. \draw (z) to (y);
  2239. \end{tikzpicture}
  2240. \]
  2241. In the last two steps of the algorithm, we color $t.1$ with $0$
  2242. then $t.2$ with $1$.
  2243. \[
  2244. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2245. \node (v) at (0,0) {$v:0,\{1\}$};
  2246. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2247. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2248. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2249. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2250. \node (t1) at (9,0) {$t.1:0,\{2,1\}$};
  2251. \node (t2) at (9,-1.5) {$t.2:1,\{0\}$};
  2252. \draw (t1) to (z);
  2253. \draw (t2) to (t1);
  2254. \draw (v) to (w);
  2255. \foreach \i in {w,x,y}
  2256. {
  2257. \foreach \j in {w,x,y}
  2258. {
  2259. \draw (\i) to (\j);
  2260. }
  2261. }
  2262. \draw (z) to (w);
  2263. \draw (z) to (y);
  2264. \end{tikzpicture}
  2265. \]
  2266. With the coloring complete, we can finalize the assignment of
  2267. variables to registers and stack locations. Recall that if we have $k$
  2268. registers, we map the first $k$ colors to registers and the rest to
  2269. stack locations. Suppose for the moment that we just have one extra
  2270. register to use for register allocation, just \key{rbx}. Then the
  2271. following is the mapping of colors to registers and stack allocations.
  2272. \[
  2273. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2274. \]
  2275. Putting this mapping together with the above coloring of the variables, we
  2276. arrive at the assignment:
  2277. \begin{gather*}
  2278. \{ v \mapsto \key{\%rbx}, \,
  2279. w \mapsto \key{-8(\%rbp)}, \,
  2280. x \mapsto \key{-16(\%rbp)}, \,
  2281. y \mapsto \key{\%rbx}, \,
  2282. z\mapsto \key{-16(\%rbp)}, \\
  2283. t.1\mapsto \key{\%rbx} ,\,
  2284. t.2\mapsto \key{-8(\%rbp)} \}
  2285. \end{gather*}
  2286. Applying this assignment to our running example
  2287. (Figure~\ref{fig:reg-eg}) yields the program on the right.\\
  2288. % why frame size of 32? -JGS
  2289. \begin{minipage}{0.4\textwidth}
  2290. \begin{lstlisting}
  2291. (program (v w x y z)
  2292. (movq (int 1) (var v))
  2293. (movq (int 46) (var w))
  2294. (movq (var v) (var x))
  2295. (addq (int 7) (var x))
  2296. (movq (var x) (var y))
  2297. (addq (int 4) (var y))
  2298. (movq (var x) (var z))
  2299. (addq (var w) (var z))
  2300. (movq (var y) (var t.1))
  2301. (negq (var t.1))
  2302. (movq (var z) (var t.2))
  2303. (addq (var t.1) (var t.2))
  2304. (movq (var t.2) (reg rax)))
  2305. \end{lstlisting}
  2306. \end{minipage}
  2307. $\Rightarrow$
  2308. \begin{minipage}{0.45\textwidth}
  2309. \begin{lstlisting}
  2310. (program 16
  2311. (movq (int 1) (reg rbx))
  2312. (movq (int 46) (deref rbp -8))
  2313. (movq (reg rbx) (deref rbp -16))
  2314. (addq (int 7) (deref rbp -16))
  2315. (movq (deref rbp -16) (reg rbx))
  2316. (addq (int 4) (reg rbx))
  2317. (movq (deref rbp -16) (deref rbp -16))
  2318. (addq (deref rbp -8) (deref rbp -16))
  2319. (movq (reg rbx) (reg rbx))
  2320. (negq (reg rbx))
  2321. (movq (deref rbp -16) (deref rbp -8))
  2322. (addq (reg rbx) (deref rbp -8))
  2323. (movq (deref rbp -8) (reg rax)))
  2324. \end{lstlisting}
  2325. \end{minipage}
  2326. The resulting program is almost an x86 program. The remaining step
  2327. is to apply the patch instructions pass. In this example, the trivial
  2328. move of \code{-16(\%rbp)} to itself is deleted and the addition of
  2329. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2330. \code{rax}. The following shows the portion of the program that
  2331. changed.
  2332. \begin{lstlisting}
  2333. (addq (int 4) (reg rbx))
  2334. (movq (deref rbp -8) (reg rax)
  2335. (addq (reg rax) (deref rbp -16))
  2336. \end{lstlisting}
  2337. An overview of all of the passes involved in register allocation is
  2338. shown in Figure~\ref{fig:reg-alloc-passes}.
  2339. \begin{figure}[p]
  2340. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2341. \node (R1) at (0,2) {\large $R_1$};
  2342. \node (R1-2) at (3,2) {\large $R_1$};
  2343. \node (C0-1) at (3,0) {\large $C_0$};
  2344. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2345. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2346. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2347. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2348. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2349. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2350. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2351. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  2352. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2353. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2354. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2355. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2356. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2357. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2358. \end{tikzpicture}
  2359. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2360. \label{fig:reg-alloc-passes}
  2361. \end{figure}
  2362. \begin{exercise}\normalfont
  2363. Implement the pass \code{allocate-registers} and test it by creating
  2364. new example programs that exercise all of the register allocation
  2365. algorithm, such as forcing variables to be spilled to the stack.
  2366. I recommend organizing our code by creating a helper function named
  2367. \code{color-graph} that takes an interference graph and a list of all
  2368. the variables in the program. This function should return a mapping of
  2369. variables to their colors. By creating this helper function, we will
  2370. be able to reuse it in Chapter~\ref{ch:functions} when we add support
  2371. for functions. Once you have obtained the coloring from
  2372. \code{color-graph}, you can assign the variables to registers or stack
  2373. locations based on their color and then use the \code{assign-homes}
  2374. function from Section~\ref{sec:assign-s0} to replace the variables
  2375. with their assigned location.
  2376. \end{exercise}
  2377. \section{Print x86 and Conventions for Registers}
  2378. \label{sec:print-x86-reg-alloc}
  2379. Recall the the \code{print-x86} pass generates the prelude and
  2380. conclusion instructions for the \code{main} function. The prelude
  2381. saved the values in \code{rbp} and \code{rsp} and the conclusion
  2382. returned those values to \code{rbp} and \code{rsp}. The reason for
  2383. this is that there are agreed-upon conventions for how different
  2384. functions share the same fixed set of registers. There is a function
  2385. inside the operating system (OS) that calls our \code{main} function,
  2386. and that OS function uses the same registers that we use in
  2387. \code{main}. The convention for x86 is that the caller is responsible
  2388. for freeing up some registers, the \emph{caller save registers}, prior
  2389. to the function call, and the callee is responsible for saving and
  2390. restoring some other registers, the \emph{callee save registers},
  2391. before and after using them. The caller save registers are
  2392. \begin{lstlisting}
  2393. rax rdx rcx rsi rdi r8 r9 r10 r11
  2394. \end{lstlisting}
  2395. while the callee save registers are
  2396. \begin{lstlisting}
  2397. rsp rbp rbx r12 r13 r14 r15
  2398. \end{lstlisting}
  2399. Another way to think about this caller/callee convention is the
  2400. following. The caller should assume that all the caller save registers
  2401. get overwritten with arbitrary values by the callee. On the other
  2402. hand, the caller can safely assume that all the callee save registers
  2403. contain the same values after the call that they did before the call.
  2404. The callee can freely use any of the caller save registers. However,
  2405. if the callee wants to use a callee save register, the callee must
  2406. arrange to put the original value back in the register prior to
  2407. returning to the caller, which is usually accomplished by saving and
  2408. restoring the value from the stack.
  2409. The upshot of these conventions is that the \code{main} function needs
  2410. to save (in the prelude) and restore (in the conclusion) any callee
  2411. save registers that get used during register allocation. The simplest
  2412. approach is to save and restore all the callee save registers. The
  2413. more efficient approach is to keep track of which callee save
  2414. registers were used and only save and restore them. Either way, make
  2415. sure to take this use of stack space into account when you round up
  2416. the size of the frame to make sure it is a multiple of 16 bytes.
  2417. \section{Challenge: Move Biasing$^{*}$}
  2418. \label{sec:move-biasing}
  2419. This section describes an optional enhancement to register allocation
  2420. for those students who are looking for an extra challenge or who have
  2421. a deeper interest in register allocation.
  2422. We return to the running example, but we remove the supposition that
  2423. we only have one register to use. So we have the following mapping of
  2424. color numbers to registers.
  2425. \[
  2426. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2427. \]
  2428. Using the same assignment that was produced by register allocator
  2429. described in the last section, we get the following program.
  2430. \begin{minipage}{0.45\textwidth}
  2431. \begin{lstlisting}
  2432. (program (v w x y z)
  2433. (movq (int 1) (var v))
  2434. (movq (int 46) (var w))
  2435. (movq (var v) (var x))
  2436. (addq (int 7) (var x))
  2437. (movq (var x) (var y))
  2438. (addq (int 4) (var y))
  2439. (movq (var x) (var z))
  2440. (addq (var w) (var z))
  2441. (movq (var y) (var t.1))
  2442. (negq (var t.1))
  2443. (movq (var z) (var t.2))
  2444. (addq (var t.1) (var t.2))
  2445. (movq (var t.2) (reg rax)))
  2446. \end{lstlisting}
  2447. \end{minipage}
  2448. $\Rightarrow$
  2449. \begin{minipage}{0.45\textwidth}
  2450. \begin{lstlisting}
  2451. (program 0
  2452. (movq (int 1) (reg rbx))
  2453. (movq (int 46) (reg rcx))
  2454. (movq (reg rbx) (reg rdx))
  2455. (addq (int 7) (reg rdx))
  2456. (movq (reg rdx) (reg rbx))
  2457. (addq (int 4) (reg rbx))
  2458. (movq (reg rdx) (reg rdx))
  2459. (addq (reg rcx) (reg rdx))
  2460. (movq (reg rbx) (reg rbx))
  2461. (negq (reg rbx))
  2462. (movq (reg rdx) (reg rcx))
  2463. (addq (reg rbx) (reg rcx))
  2464. (movq (reg rcx) (reg rax)))
  2465. \end{lstlisting}
  2466. \end{minipage}
  2467. While this allocation is quite good, we could do better. For example,
  2468. the variables \key{v} and \key{x} ended up in different registers, but
  2469. if they had been placed in the same register, then the move from
  2470. \key{v} to \key{x} could be removed.
  2471. We say that two variables $p$ and $q$ are \emph{move related} if they
  2472. participate together in a \key{movq} instruction, that is, \key{movq
  2473. p, q} or \key{movq q, p}. When the register allocator chooses a
  2474. color for a variable, it should prefer a color that has already been
  2475. used for a move-related variable (assuming that they do not
  2476. interfere). Of course, this preference should not override the
  2477. preference for registers over stack locations, but should only be used
  2478. as a tie breaker when choosing between registers or when choosing
  2479. between stack locations.
  2480. We recommend that you represent the move relationships in a graph,
  2481. similar to how we represented interference. The following is the
  2482. \emph{move graph} for our running example.
  2483. \[
  2484. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2485. \node (v) at (0,0) {$v$};
  2486. \node (w) at (3,0) {$w$};
  2487. \node (x) at (6,0) {$x$};
  2488. \node (y) at (3,-1.5) {$y$};
  2489. \node (z) at (6,-1.5) {$z$};
  2490. \node (t1) at (9,0) {$t.1$};
  2491. \node (t2) at (9,-1.5) {$t.2$};
  2492. \draw (t1) to (y);
  2493. \draw (t2) to (z);
  2494. \draw[bend left=20] (v) to (x);
  2495. \draw (x) to (y);
  2496. \draw (x) to (z);
  2497. \end{tikzpicture}
  2498. \]
  2499. Now we replay the graph coloring, pausing to see the coloring of $z$
  2500. and $v$. So we have the following coloring so far and the most
  2501. saturated vertex is $z$.
  2502. \[
  2503. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2504. \node (v) at (0,0) {$v:-,\{1\}$};
  2505. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2506. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2507. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2508. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2509. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2510. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2511. \draw (t1) to (z);
  2512. \draw (t2) to (t1);
  2513. \draw (v) to (w);
  2514. \foreach \i in {w,x,y}
  2515. {
  2516. \foreach \j in {w,x,y}
  2517. {
  2518. \draw (\i) to (\j);
  2519. }
  2520. }
  2521. \draw (z) to (w);
  2522. \draw (z) to (y);
  2523. \end{tikzpicture}
  2524. \]
  2525. Last time we chose to color $z$ with $2$, which so happens to be the
  2526. color of $x$, and $z$ is move related to $x$. This was rather lucky,
  2527. and if the program had been a little different, and say $x$ had been
  2528. already assigned to $3$, then $z$ would still get $2$ and our luck
  2529. would have run out. With move biasing, we use the fact that $z$ and
  2530. $x$ are move related to influence the choice of color for $z$, in this
  2531. case choosing $2$ because that's the color of $x$.
  2532. \[
  2533. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2534. \node (v) at (0,0) {$v:-,\{1\}$};
  2535. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2536. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2537. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2538. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2539. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2540. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2541. \draw (t1) to (z);
  2542. \draw (t2) to (t1);
  2543. \draw (v) to (w);
  2544. \foreach \i in {w,x,y}
  2545. {
  2546. \foreach \j in {w,x,y}
  2547. {
  2548. \draw (\i) to (\j);
  2549. }
  2550. }
  2551. \draw (z) to (w);
  2552. \draw (z) to (y);
  2553. \end{tikzpicture}
  2554. \]
  2555. Next we consider coloring the variable $v$, and we just need to avoid
  2556. choosing $1$ because of the interference with $w$. Last time we choose
  2557. the color $0$, simply because it was the lowest, but this time we know
  2558. that $v$ is move related to $x$, so we choose the color $2$.
  2559. \[
  2560. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2561. \node (v) at (0,0) {$v:2,\{1\}$};
  2562. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2563. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2564. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2565. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2566. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2567. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2568. \draw (t1) to (z);
  2569. \draw (t2) to (t1);
  2570. \draw (v) to (w);
  2571. \foreach \i in {w,x,y}
  2572. {
  2573. \foreach \j in {w,x,y}
  2574. {
  2575. \draw (\i) to (\j);
  2576. }
  2577. }
  2578. \draw (z) to (w);
  2579. \draw (z) to (y);
  2580. \end{tikzpicture}
  2581. \]
  2582. We apply this register assignment to the running example, on the left,
  2583. to obtain the code on right.
  2584. \begin{minipage}{0.45\textwidth}
  2585. \begin{lstlisting}
  2586. (program (v w x y z)
  2587. (movq (int 1) (var v))
  2588. (movq (int 46) (var w))
  2589. (movq (var v) (var x))
  2590. (addq (int 7) (var x))
  2591. (movq (var x) (var y))
  2592. (addq (int 4) (var y))
  2593. (movq (var x) (var z))
  2594. (addq (var w) (var z))
  2595. (movq (var y) (var t.1))
  2596. (negq (var t.1))
  2597. (movq (var z) (var t.2))
  2598. (addq (var t.1) (var t.2))
  2599. (movq (var t.2) (reg rax)))
  2600. \end{lstlisting}
  2601. \end{minipage}
  2602. $\Rightarrow$
  2603. \begin{minipage}{0.45\textwidth}
  2604. \begin{lstlisting}
  2605. (program 0
  2606. (movq (int 1) (reg rdx))
  2607. (movq (int 46) (reg rcx))
  2608. (movq (reg rdx) (reg rdx))
  2609. (addq (int 7) (reg rdx))
  2610. (movq (reg rdx) (reg rbx))
  2611. (addq (int 4) (reg rbx))
  2612. (movq (reg rdx) (reg rdx))
  2613. (addq (reg rcx) (reg rdx))
  2614. (movq (reg rbx) (reg rbx))
  2615. (negq (reg rbx))
  2616. (movq (reg rdx) (reg rcx))
  2617. (addq (reg rbx) (reg rcx))
  2618. (movq (reg rcx) (reg rax)))
  2619. \end{lstlisting}
  2620. \end{minipage}
  2621. The \code{patch-instructions} then removes the trivial moves from
  2622. \key{v} to \key{x}, from \key{x} to \key{z}, and from \key{y} to
  2623. \key{t.1}, to obtain the following result.
  2624. \begin{lstlisting}
  2625. (program 0
  2626. (movq (int 1) (reg rdx))
  2627. (movq (int 46) (reg rcx))
  2628. (addq (int 7) (reg rdx))
  2629. (movq (reg rdx) (reg rbx))
  2630. (addq (int 4) (reg rbx))
  2631. (addq (reg rcx) (reg rdx))
  2632. (negq (reg rbx))
  2633. (movq (reg rdx) (reg rcx))
  2634. (addq (reg rbx) (reg rcx))
  2635. (movq (reg rcx) (reg rax)))
  2636. \end{lstlisting}
  2637. \begin{exercise}\normalfont
  2638. Change your implementation of \code{allocate-registers} to take move
  2639. biasing into account. Make sure that your compiler still passes all of
  2640. the previous tests. Create two new tests that include at least one
  2641. opportunity for move biasing and visually inspect the output x86
  2642. programs to make sure that your move biasing is working properly.
  2643. \end{exercise}
  2644. \margincomment{\footnotesize To do: another neat challenge would be to do
  2645. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2646. \chapter{More coming soon}
  2647. \color{comment-red}{The rest of this book is undergoing some updates; it will be
  2648. released as we go along during the Fall 2016 semester. -Ryan}
  2649. \end{document}
  2650. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2651. \chapter{Booleans, Control Flow, and Type Checking}
  2652. \label{ch:bool-types}
  2653. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2654. integers. In this Chapter we add a second kind of value, the Booleans,
  2655. to create the $R_2$ language. The Boolean values \emph{true} and
  2656. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2657. Racket. We also introduce several operations that involve Booleans
  2658. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2659. \key{if} expression. With the addition of \key{if} expressions,
  2660. programs can have non-trivial control flow which has an impact on
  2661. several parts of the compiler. Also, because we now have two kinds of
  2662. values, we need to worry about programs that apply an operation to the
  2663. wrong kind of value, such as \code{(not 1)}.
  2664. There are two language design options for such situations. One option
  2665. is to signal an error and the other is to provide a wider
  2666. interpretation of the operation. The Racket language uses a mixture of
  2667. these two options, depending on the operation and the kind of
  2668. value. For example, the result of \code{(not 1)} in Racket is
  2669. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2670. the other hand, \code{(car 1)} results in a run-time error in Racket
  2671. stating that \code{car} expects a pair.
  2672. The Typed Racket language makes similar design choices as Racket,
  2673. except much of the error detection happens at compile time instead of
  2674. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2675. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2676. reports a compile-time error because the type of the argument is
  2677. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2678. For the $R_2$ language we choose to be more like Typed Racket in that
  2679. we shall perform type checking during compilation. In
  2680. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2681. is, how to compile a dynamically typed language like Racket. The
  2682. $R_2$ language is a subset of Typed Racket but by no means includes
  2683. all of Typed Racket. Furthermore, for many of the operations we shall
  2684. take a narrower interpretation than Typed Racket, for example,
  2685. rejecting \code{(not 1)}.
  2686. This chapter is organized as follows. We begin by defining the syntax
  2687. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2688. then introduce the idea of type checking and build a type checker for
  2689. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2690. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2691. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2692. how our compiler passes need to change to accommodate Booleans and
  2693. conditional control flow.
  2694. \section{The $R_2$ Language}
  2695. \label{sec:r2-lang}
  2696. The syntax of the $R_2$ language is defined in
  2697. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray) ,
  2698. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2699. \code{if} expression. Also, we expand the operators to include the
  2700. \key{and} and \key{not} on Booleans, the \key{eq?} operations for
  2701. comparing two integers or two Booleans, and the \key{<}, \key{<=},
  2702. \key{>}, and \key{>=} operations for comparing integers.
  2703. \begin{figure}[tp]
  2704. \centering
  2705. \fbox{
  2706. \begin{minipage}{0.96\textwidth}
  2707. \[
  2708. \begin{array}{lcl}
  2709. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2710. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  2711. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2712. &\mid& \key{\#t} \mid \key{\#f} \mid
  2713. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  2714. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2715. R_2 &::=& (\key{program} \; \Exp)
  2716. \end{array}
  2717. \]
  2718. \end{minipage}
  2719. }
  2720. \caption{The syntax of $R_2$, extending $R_1$ with Booleans and
  2721. conditionals.}
  2722. \label{fig:r2-syntax}
  2723. \end{figure}
  2724. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2725. the parts that are the same as the interpreter for $R_1$
  2726. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2727. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2728. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2729. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2730. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2731. operations \code{not} and \code{and} behave as you might expect, but
  2732. note that the \code{and} operation is short-circuiting. That is, given
  2733. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2734. evaluated if $e_1$ evaluates to \code{\#f}.
  2735. With the addition of the comparison operations, there are quite a few
  2736. primitive operations and the interpreter code for them is somewhat
  2737. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2738. parts into the \code{interp-op} function and the similar parts into
  2739. the one match clause shown in Figure~\ref{fig:interp-R2}. It is
  2740. important for that match clause to come last because it matches
  2741. \emph{any} compound S-expression. We do not use \code{interp-op} for
  2742. the \code{and} operation because of the short-circuiting behavior in
  2743. the order of evaluation of its arguments.
  2744. \begin{figure}[tbp]
  2745. \begin{lstlisting}
  2746. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2747. (define (interp-op op)
  2748. (match op
  2749. ['+ fx+]
  2750. ['- (lambda (n) (fx- 0 n))]
  2751. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2752. ['read read-fixnum]
  2753. ['eq? (lambda (v1 v2)
  2754. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2755. (and (boolean? v1) (boolean? v2))
  2756. (and (vector? v1) (vector? v2)))
  2757. (eq? v1 v2)]))]
  2758. ['< (lambda (v1 v2)
  2759. (cond [(and (fixnum? v1) (fixnum? v2))
  2760. (< v1 v2)]))]
  2761. ['<= (lambda (v1 v2)
  2762. (cond [(and (fixnum? v1) (fixnum? v2))
  2763. (<= v1 v2)]))]
  2764. ['> (lambda (v1 v2)
  2765. (cond [(and (fixnum? v1) (fixnum? v2))
  2766. (<= v1 v2)]))]
  2767. ['>= (lambda (v1 v2)
  2768. (cond [(and (fixnum? v1) (fixnum? v2))
  2769. (<= v1 v2)]))]
  2770. [else (error 'interp-op "unknown operator")]))
  2771. (define (interp-R2 env)
  2772. (lambda (e)
  2773. (define recur (interp-R2 env))
  2774. (match e
  2775. ...
  2776. [(? boolean?) e]
  2777. [`(if ,(app recur cnd) ,thn ,els)
  2778. (match cnd
  2779. [#t (recur thn)]
  2780. [#f (recur els)])]
  2781. [`(not ,(app recur v))
  2782. (match v [#t #f] [#f #t])]
  2783. [`(and ,(app recur v1) ,e2)
  2784. (match v1
  2785. [#t (match (recur e2) [#t #t] [#f #f])]
  2786. [#f #f])]
  2787. [`(,op ,(app recur args) ...)
  2788. #:when (set-member? primitives op)
  2789. (apply (interp-op op) args)]
  2790. )))
  2791. \end{lstlisting}
  2792. \caption{Interpreter for the $R_2$ language.}
  2793. \label{fig:interp-R2}
  2794. \end{figure}
  2795. \section{Type Checking $R_2$ Programs}
  2796. \label{sec:type-check-r2}
  2797. It is helpful to think about type checking into two complementary
  2798. ways. A type checker predicts the \emph{type} of value that will be
  2799. produced by each expression in the program. For $R_2$, we have just
  2800. two types, \key{Integer} and \key{Boolean}. So a type checker should
  2801. predict that
  2802. \begin{lstlisting}
  2803. (+ 10 (- (+ 12 20)))
  2804. \end{lstlisting}
  2805. produces an \key{Integer} while
  2806. \begin{lstlisting}
  2807. (and (not #f) #t)
  2808. \end{lstlisting}
  2809. produces a \key{Boolean}.
  2810. As mentioned at the beginning of this chapter, a type checker also
  2811. rejects programs that apply operators to the wrong type of value. Our
  2812. type checker for $R_2$ will signal an error for the following
  2813. expression because, as we have seen above, the expression \code{(+ 10
  2814. ...)} has type \key{Integer}, and we require the argument of a
  2815. \code{not} to have type \key{Boolean}.
  2816. \begin{lstlisting}
  2817. (not (+ 10 (- (+ 12 20))))
  2818. \end{lstlisting}
  2819. The type checker for $R_2$ is best implemented as a structurally
  2820. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  2821. many of the clauses for the \code{typecheck-R2} function. Given an
  2822. input expression \code{e}, the type checker either returns the type
  2823. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  2824. the type of an integer literal is \code{Integer} and the type of a
  2825. Boolean literal is \code{Boolean}. To handle variables, the type
  2826. checker, like the interpreter, uses an association list. However, in
  2827. this case the association list maps variables to types instead of
  2828. values. Consider the clause for \key{let}. We type check the
  2829. initializing expression to obtain its type \key{T} and then associate
  2830. type \code{T} with the variable \code{x}. When the type checker
  2831. encounters the use of a variable, it can lookup its type in the
  2832. association list.
  2833. \begin{figure}[tbp]
  2834. \begin{lstlisting}
  2835. (define (typecheck-R2 env)
  2836. (lambda (e)
  2837. (define recur (typecheck-R2 env e))
  2838. (match e
  2839. [(? fixnum?) 'Integer]
  2840. [(? boolean?) 'Boolean]
  2841. [(? symbol?) (lookup e env)]
  2842. [`(let ([,x ,(app recur T)]) ,body)
  2843. (define new-env (cons (cons x T) env))
  2844. (typecheck-R2 new-env body)]
  2845. ...
  2846. [`(not ,(app (typecheck-R2 env) T))
  2847. (match T
  2848. ['Boolean 'Boolean]
  2849. [else (error 'typecheck-R2 "'not' expects a Boolean" e)])]
  2850. ...
  2851. [`(program ,body)
  2852. (define ty ((typecheck-R2 '()) body))
  2853. `(program (type ,ty) ,body)]
  2854. )))
  2855. \end{lstlisting}
  2856. \caption{Skeleton of a type checker for the $R_2$ language.}
  2857. \label{fig:type-check-R2}
  2858. \end{figure}
  2859. To print the resulting value correctly, the overall type of the
  2860. program must be threaded through the remainder of the passes. We can
  2861. store the type within the \key{program} form as shown in Figure
  2862. \ref{fig:type-check-R2}. The syntax for post-typechecking $R_2$
  2863. programs as follows: \\
  2864. \fbox{
  2865. \begin{minipage}{0.87\textwidth}
  2866. \[
  2867. \begin{array}{lcl}
  2868. R_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  2869. \end{array}
  2870. \]
  2871. \end{minipage}
  2872. }
  2873. \begin{exercise}\normalfont
  2874. Complete the implementation of \code{typecheck-R2} and test it on 10
  2875. new example programs in $R_2$ that you choose based on how thoroughly
  2876. they test the type checking algorithm. Half of the example programs
  2877. should have a type error, to make sure that your type checker properly
  2878. rejects them. The other half of the example programs should not have
  2879. type errors. Your testing should check that the result of the type
  2880. checker agrees with the value returned by the interpreter, that is, if
  2881. the type checker returns \key{Integer}, then the interpreter should
  2882. return an integer. Likewise, if the type checker returns
  2883. \key{Boolean}, then the interpreter should return \code{\#t} or
  2884. \code{\#f}. Note that if your type checker does not signal an error
  2885. for a program, then interpreting that program should not encounter an
  2886. error. If it does, there is something wrong with your type checker.
  2887. \end{exercise}
  2888. \section{The $C_1$ Language}
  2889. \label{sec:c1}
  2890. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  2891. As with $R_1$, we shall compile to a C-like intermediate language, but
  2892. we need to grow that intermediate language to handle the new features
  2893. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  2894. we add logic and comparison operators to the $\Exp$ non-terminal, the
  2895. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal, and we
  2896. add an \key{if} statement. The \key{if} statement of $C_1$ includes an
  2897. \key{eq?} test, which is needed for improving code generation in
  2898. Section~\ref{sec:opt-if}. We do not include \key{and} in $C_1$
  2899. because it is not needed in the translation of the \key{and} of $R_2$.
  2900. \begin{figure}[tp]
  2901. \fbox{
  2902. \begin{minipage}{0.96\textwidth}
  2903. \[
  2904. \begin{array}{lcl}
  2905. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  2906. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2907. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  2908. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  2909. \Stmt &::=& \gray{\ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg}} \\
  2910. &\mid& \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} \\
  2911. C_1 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+})
  2912. \end{array}
  2913. \]
  2914. \end{minipage}
  2915. }
  2916. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  2917. \label{fig:c1-syntax}
  2918. \end{figure}
  2919. \section{Flatten Expressions}
  2920. \label{sec:flatten-r2}
  2921. We expand the \code{flatten} pass to handle the Boolean literals
  2922. \key{\#t} and \key{\#f}, the new logic and comparison operations, and
  2923. \key{if} expressions. We shall start with a simple example of
  2924. translating a \key{if} expression, shown below on the left. \\
  2925. \begin{tabular}{lll}
  2926. \begin{minipage}{0.4\textwidth}
  2927. \begin{lstlisting}
  2928. (program (if #f 0 42))
  2929. \end{lstlisting}
  2930. \end{minipage}
  2931. &
  2932. $\Rightarrow$
  2933. &
  2934. \begin{minipage}{0.4\textwidth}
  2935. \begin{lstlisting}
  2936. (program (if.1)
  2937. (if (eq? #t #f)
  2938. ((assign if.1 0))
  2939. ((assign if.1 42)))
  2940. (return if.1))
  2941. \end{lstlisting}
  2942. \end{minipage}
  2943. \end{tabular} \\
  2944. The value of the \key{if} expression is the value of the branch that
  2945. is selected. Recall that in the \code{flatten} pass we need to replace
  2946. arbitrary expressions with $\Arg$'s (variables or literals). In the
  2947. translation above, on the right, we have replaced the \key{if}
  2948. expression with a new variable \key{if.1}, inside \code{(return
  2949. if.1)}, and we have produced code that will assign the appropriate
  2950. value to \key{if.1} using an \code{if} statement prior to the
  2951. \code{return}. For $R_1$, the \code{flatten} pass returned a list of
  2952. assignment statements. Here, for $R_2$, we return a list of statements
  2953. that can include both \key{if} statements and assignment statements.
  2954. The next example is a bit more involved, showing what happens when
  2955. there are complex expressions (not variables or literals) in the
  2956. condition and branch expressions of an \key{if}, including nested
  2957. \key{if} expressions.
  2958. \begin{tabular}{lll}
  2959. \begin{minipage}{0.4\textwidth}
  2960. \begin{lstlisting}
  2961. (program
  2962. (if (eq? (read) 0)
  2963. 777
  2964. (+ 2 (if (eq? (read) 0)
  2965. 40
  2966. 444))))
  2967. \end{lstlisting}
  2968. \end{minipage}
  2969. &
  2970. $\Rightarrow$
  2971. &
  2972. \begin{minipage}{0.4\textwidth}
  2973. \begin{lstlisting}
  2974. (program (t.1 t.2 if.1 t.3 t.4
  2975. if.2 t.5)
  2976. (assign t.1 (read))
  2977. (assign t.2 (eq? t.1 0))
  2978. (if (eq? #t t.2)
  2979. ((assign if.1 777))
  2980. ((assign t.3 (read))
  2981. (assign t.4 (eq? t.3 0))
  2982. (if (eq? #t t.4)
  2983. ((assign if.2 40))
  2984. ((assign if.2 444)))
  2985. (assign t.5 (+ 2 if.2))
  2986. (assign if.1 t.5)))
  2987. (return if.1))
  2988. \end{lstlisting}
  2989. \end{minipage}
  2990. \end{tabular} \\
  2991. The \code{flatten} clauses for the Boolean literals and the operations
  2992. \key{not} and \key{eq?} are straightforward. However, the
  2993. \code{flatten} clause for \key{and} requires some care to properly
  2994. imitate the order of evaluation of the interpreter for $R_2$
  2995. (Figure~\ref{fig:interp-R2}). We recommend using an \key{if} statement
  2996. in the code you generate for \key{and}.
  2997. The \code{flatten} clause for \key{if} also requires some care because
  2998. the condition of the \key{if} can be an arbitrary expression in $R_2$,
  2999. but in $C_1$ the condition must be an equality predicate. For now we
  3000. recommend flattening the condition into an $\Arg$ and then comparing
  3001. it with \code{\#t}. We discuss a more efficient approach in
  3002. Section~\ref{sec:opt-if}.
  3003. \begin{exercise}\normalfont
  3004. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  3005. Boolean literals, the new logic and comparison operations, and the
  3006. \key{if} expressions. Create 4 more test cases that expose whether
  3007. your flattening code is correct. Test your \code{flatten} pass by
  3008. running the output programs with \code{interp-C}
  3009. (Appendix~\ref{appendix:interp}).
  3010. \end{exercise}
  3011. \section{XOR, Comparisons, and Control Flow in x86}
  3012. \label{sec:x86-1}
  3013. To implement the new logical operations, the comparison operations,
  3014. and the \key{if} statement, we need to delve further into the x86
  3015. language. Figure~\ref{fig:x86-2} defines the abstract syntax for a
  3016. larger subset of x86 that includes instructions for logical
  3017. operations, comparisons, and jumps.
  3018. One small challenge is that x86 does not provide an instruction that
  3019. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3020. However, the \code{xorq} instruction can be used to encode \code{not}.
  3021. The \key{xorq} instruction takes two arguments, performs a pairwise
  3022. exclusive-or operation on each bit of its arguments, and writes the
  3023. results into its second argument. Recall the truth table for
  3024. exclusive-or:
  3025. \begin{center}
  3026. \begin{tabular}{l|cc}
  3027. & 0 & 1 \\ \hline
  3028. 0 & 0 & 1 \\
  3029. 1 & 1 & 0
  3030. \end{tabular}
  3031. \end{center}
  3032. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3033. in row of the table for the bit $1$, the result is the opposite of the
  3034. second bit. Thus, the \code{not} operation can be implemented by
  3035. \code{xorq} with $1$ as the first argument: $0001
  3036. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3037. 0001 = 0000$.
  3038. \begin{figure}[tp]
  3039. \fbox{
  3040. \begin{minipage}{0.96\textwidth}
  3041. \[
  3042. \begin{array}{lcl}
  3043. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3044. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3045. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3046. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3047. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3048. (\key{subq} \; \Arg\; \Arg) \mid
  3049. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3050. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3051. (\key{pushq}\;\Arg) \mid
  3052. (\key{popq}\;\Arg) \mid
  3053. (\key{retq})} \\
  3054. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3055. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3056. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3057. \mid (\key{jmp} \; \itm{label})
  3058. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3059. &\mid& (\key{label} \; \itm{label}) \\
  3060. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3061. \end{array}
  3062. \]
  3063. \end{minipage}
  3064. }
  3065. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3066. \label{fig:x86-1}
  3067. \end{figure}
  3068. Next we consider the x86 instructions that are relevant for
  3069. compiling the comparison operations. The \key{cmpq} instruction
  3070. compares its two arguments to determine whether one argument is less
  3071. than, equal, or greater than the other argument. The \key{cmpq}
  3072. instruction is unusual regarding the order of its arguments and where
  3073. the result is placed. The argument order is backwards: if you want to
  3074. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3075. \key{cmpq} is placed in the special EFLAGS register. This register
  3076. cannot be accessed directly but it can be queried by a number of
  3077. instructions, including the \key{set} instruction. The \key{set}
  3078. instruction puts a \key{1} or \key{0} into its destination depending
  3079. on whether the comparison came out according to the condition code
  3080. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3081. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3082. The set instruction has an annoying quirk in that its destination
  3083. argument must be single byte register, such as \code{al}, which is
  3084. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3085. instruction can then be used to move from a single byte register to a
  3086. normal 64-bit register.
  3087. For compiling the \key{if} expression, the x86 instructions for
  3088. jumping are relevant. The \key{jmp} instruction updates the program
  3089. counter to point to the instruction after the indicated label. The
  3090. \key{jmp-if} instruction updates the program counter to point to the
  3091. instruction after the indicated label depending on whether the result
  3092. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3093. the \key{jmp-if} instruction falls through to the next
  3094. instruction. Our abstract syntax for \key{jmp-if} differs from the
  3095. concrete syntax for x86 to separate the instruction name from the
  3096. condition code. For example, \code{(jmp-if le foo)} corresponds to
  3097. \code{jle foo}.
  3098. \section{Select Instructions}
  3099. \label{sec:select-r2}
  3100. The \code{select-instructions} pass lowers from $C_1$ to another
  3101. intermediate representation suitable for conducting register
  3102. allocation, that is, a language close to x86$_1$.
  3103. We can take the usual approach of encoding Booleans as integers, with
  3104. true as 1 and false as 0.
  3105. \[
  3106. \key{\#t} \Rightarrow \key{1}
  3107. \qquad
  3108. \key{\#f} \Rightarrow \key{0}
  3109. \]
  3110. The \code{not} operation can be implemented in terms of \code{xorq}
  3111. as we discussed at the beginning of this section.
  3112. %% Can you think of a bit pattern that, when XOR'd with the bit
  3113. %% representation of 0 produces 1, and when XOR'd with the bit
  3114. %% representation of 1 produces 0?
  3115. Translating the \code{eq?} and the other comparison operations to x86
  3116. is slightly involved due to the unusual nature of the \key{cmpq}
  3117. instruction discussed above. We recommend translating an assignment
  3118. from \code{eq?} into the following sequence of three instructions. \\
  3119. \begin{tabular}{lll}
  3120. \begin{minipage}{0.4\textwidth}
  3121. \begin{lstlisting}
  3122. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3123. \end{lstlisting}
  3124. \end{minipage}
  3125. &
  3126. $\Rightarrow$
  3127. &
  3128. \begin{minipage}{0.4\textwidth}
  3129. \begin{lstlisting}
  3130. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3131. (set e (byte-reg al))
  3132. (movzbq (byte-reg al) |$\itm{lhs}$|)
  3133. \end{lstlisting}
  3134. \end{minipage}
  3135. \end{tabular} \\
  3136. % The translation of the \code{not} operator is not quite as simple
  3137. % as it seems. Recall that \key{notq} is a bitwise operator, not a boolean
  3138. % one. For example, the following program performs bitwise negation on
  3139. % the integer 1:
  3140. %
  3141. % \begin{tabular}{lll}
  3142. % \begin{minipage}{0.4\textwidth}
  3143. % \begin{lstlisting}
  3144. % (movq (int 1) (reg rax))
  3145. % (notq (reg rax))
  3146. % \end{lstlisting}
  3147. % \end{minipage}
  3148. % \end{tabular}
  3149. %
  3150. % After the program is run, \key{rax} does not contain 0, as you might
  3151. % hope -- it contains the binary value $111\ldots10$, which is the
  3152. % two's complement representation of $-2$. We recommend implementing boolean
  3153. % not by using \key{notq} and then masking the upper bits of the result with
  3154. % the \key{andq} instruction.
  3155. Regarding \key{if} statements, we recommend delaying when they are
  3156. lowered until the \code{patch-instructions} pass. The reason is that
  3157. for purposes of liveness analysis, \key{if} statements are easier to
  3158. deal with than jump instructions.
  3159. \begin{exercise}\normalfont
  3160. Expand your \code{select-instructions} pass to handle the new features
  3161. of the $R_2$ language. Test the pass on all the examples you have
  3162. created and make sure that you have some test programs that use the
  3163. \code{eq?} operator, creating some if necessary. Test the output of
  3164. \code{select-instructions} using the \code{interp-x86} interpreter
  3165. (Appendix~\ref{appendix:interp}).
  3166. \end{exercise}
  3167. \section{Register Allocation}
  3168. \label{sec:register-allocation-r2}
  3169. The changes required for $R_2$ affect the liveness analysis, building
  3170. the interference graph, and assigning homes, but the graph coloring
  3171. algorithm itself does not need to change.
  3172. \subsection{Liveness Analysis}
  3173. \label{sec:liveness-analysis-r2}
  3174. The addition of \key{if} statements brings up an interesting issue in
  3175. liveness analysis. Recall that liveness analysis works backwards
  3176. through the program, for each instruction it computes the variables
  3177. that are live before the instruction based on which variables are live
  3178. after the instruction. Now consider the situation for \code{(\key{if}
  3179. (\key{eq?} $e_1$ $e_2$) $\itm{thns}$ $\itm{elss}$)}, where we know
  3180. the $L_{\mathsf{after}}$ set and we need to produce the
  3181. $L_{\mathsf{before}}$ set. We can recursively perform liveness
  3182. analysis on the $\itm{thns}$ and $\itm{elss}$ branches, using
  3183. $L_{\mathsf{after}}$ as the starting point, to obtain
  3184. $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  3185. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  3186. know, during compilation, which way the branch will go, so we do not
  3187. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  3188. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  3189. the entire \key{if} statement. The solution comes from the observation
  3190. that there is no harm in identifying more variables as live than
  3191. absolutely necessary. Thus, we can take the union of the live
  3192. variables from the two branches to be the live set for the whole
  3193. \key{if}, as shown below. Of course, we also need to include the
  3194. variables that are read in $e_1$ and $e_2$.
  3195. \[
  3196. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  3197. L^{\mathsf{elss}}_{\mathsf{before}} \cup
  3198. \mathit{Vars}(e_1) \cup \mathit{Vars}(e_2)
  3199. \]
  3200. We need the live-after sets for all the instructions in both branches
  3201. of the \key{if} when we build the interference graph, so I recommend
  3202. storing that data in the \key{if} statement AST as follows:
  3203. \begin{lstlisting}
  3204. (if (eq? |$e_1$| |$e_2$|) |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  3205. \end{lstlisting}
  3206. If you wrote helper functions for computing the variables in an
  3207. instruction's argument and for computing the variables read-from ($R$)
  3208. or written-to ($W$) by an instruction, you need to be update them to
  3209. handle the new kinds of arguments and instructions in x86$_1$.
  3210. \subsection{Build Interference}
  3211. \label{sec:build-interference-r2}
  3212. Many of the new instructions, such as the logical operations, can be
  3213. handled in the same way as the arithmetic instructions. Thus, if your
  3214. code was already quite general, it will not need to be changed to
  3215. handle the logical operations. If not, I recommend that you change
  3216. your code to be more general. The \key{movzbq} instruction should be
  3217. handled like the \key{movq} instruction. The \key{if} statement is
  3218. straightforward to handle because we stored the live-after sets for
  3219. the two branches in the AST node as described above. Here we just need
  3220. to recursively process the two branches. The output of this pass can
  3221. discard the live after sets, as they are no longer needed.
  3222. \subsection{Assign Homes}
  3223. \label{sec:assign-homes-r2}
  3224. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  3225. to be updated to handle the \key{if} statement, simply by recursively
  3226. processing the child nodes. Hopefully your code already handles the
  3227. other new instructions, but if not, you can generalize your code.
  3228. \begin{exercise}\normalfont
  3229. Implement the additions to the \code{register-allocation} pass so that
  3230. it works for $R_2$ and test your compiler using your previously
  3231. created programs on the \code{interp-x86} interpreter
  3232. (Appendix~\ref{appendix:interp}).
  3233. \end{exercise}
  3234. \section{Lower Conditionals (New Pass)}
  3235. \label{sec:lower-conditionals}
  3236. In the \code{select-instructions} pass we decided to procrastinate in
  3237. the lowering of the \key{if} statement, thereby making liveness
  3238. analysis easier. Now we need to make up for that and turn the \key{if}
  3239. statement into the appropriate instruction sequence. The following
  3240. translation gives the general idea. If the condition is true, we need
  3241. to execute the $\itm{thns}$ branch and otherwise we need to execute
  3242. the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3243. jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3244. is appropriate for the comparison operator \itm{cmp}. If the
  3245. condition is false, we fall through to the $\itm{elss}$ branch. At the
  3246. end of the $\itm{elss}$ branch we need to take care to not fall
  3247. through to the $\itm{thns}$ branch. So we jump to the
  3248. $\itm{endlabel}$. All of the labels in the generated code should be
  3249. created with \code{gensym}.
  3250. \begin{tabular}{lll}
  3251. \begin{minipage}{0.4\textwidth}
  3252. \begin{lstlisting}
  3253. (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3254. \end{lstlisting}
  3255. \end{minipage}
  3256. &
  3257. $\Rightarrow$
  3258. &
  3259. \begin{minipage}{0.4\textwidth}
  3260. \begin{lstlisting}
  3261. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3262. (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3263. |$\itm{elss}$|
  3264. (jmp |$\itm{endlabel}$|)
  3265. (label |$\itm{thenlabel}$|)
  3266. |$\itm{thns}$|
  3267. (label |$\itm{endlabel}$|)
  3268. \end{lstlisting}
  3269. \end{minipage}
  3270. \end{tabular}
  3271. \begin{exercise}\normalfont
  3272. Implement the \code{lower-conditionals} pass. Test your compiler using
  3273. your previously created programs on the \code{interp-x86} interpreter
  3274. (Appendix~\ref{appendix:interp}).
  3275. \end{exercise}
  3276. \section{Patch Instructions}
  3277. There are no special restrictions on the instructions \key{jmp-if},
  3278. \key{jmp}, and \key{label}, but there is an unusual restriction on
  3279. \key{cmpq}. The second argument is not allowed to be an immediate
  3280. value (such as a literal integer). If you are comparing two
  3281. immediates, you must insert another \key{movq} instruction to put the
  3282. second argument in \key{rax}.
  3283. \begin{exercise}\normalfont
  3284. Update \code{patch-instructions} to handle the new x86 instructions.
  3285. Test your compiler using your previously created programs on the
  3286. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3287. \end{exercise}
  3288. \section{An Example Translation}
  3289. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3290. $R_2$ translated to x86, showing the results of \code{flatten},
  3291. \code{select-instructions}, and the final x86 assembly.
  3292. \begin{figure}[tbp]
  3293. \begin{tabular}{lll}
  3294. \begin{minipage}{0.5\textwidth}
  3295. \begin{lstlisting}
  3296. (program
  3297. (if (eq? (read) 1) 42 0))
  3298. \end{lstlisting}
  3299. $\Downarrow$
  3300. \begin{lstlisting}
  3301. (program (t.1 t.2 if.1)
  3302. (assign t.1 (read))
  3303. (assign t.2 (eq? t.1 1))
  3304. (if (eq? #t t.2)
  3305. ((assign if.1 42))
  3306. ((assign if.1 0)))
  3307. (return if.1))
  3308. \end{lstlisting}
  3309. $\Downarrow$
  3310. \begin{lstlisting}
  3311. (program (t.1 t.2 if.1)
  3312. (callq read_int)
  3313. (movq (reg rax) (var t.1))
  3314. (cmpq (int 1) (var t.1))
  3315. (set e (byte-reg al))
  3316. (movzbq (byte-reg al) (var t.2))
  3317. (if (eq? (int 1) (var t.2))
  3318. ((movq (int 42) (var if.1)))
  3319. ((movq (int 0) (var if.1))))
  3320. (movq (var if.1) (reg rax)))
  3321. \end{lstlisting}
  3322. \end{minipage}
  3323. &
  3324. $\Rightarrow$
  3325. \begin{minipage}{0.4\textwidth}
  3326. \begin{lstlisting}
  3327. .globl _main
  3328. _main:
  3329. pushq %rbp
  3330. movq %rsp, %rbp
  3331. pushq %r15
  3332. pushq %r14
  3333. pushq %r13
  3334. pushq %r12
  3335. pushq %rbx
  3336. subq $8, %rsp
  3337. callq _read_int
  3338. movq %rax, %rcx
  3339. cmpq $1, %rcx
  3340. sete %al
  3341. movzbq %al, %rcx
  3342. cmpq $1, %rcx
  3343. je then21288
  3344. movq $0, %rbx
  3345. jmp if_end21289
  3346. then21288:
  3347. movq $42, %rbx
  3348. if_end21289:
  3349. movq %rbx, %rax
  3350. movq %rax, %rdi
  3351. callq _print_int
  3352. movq $0, %rax
  3353. addq $8, %rsp
  3354. popq %rbx
  3355. popq %r12
  3356. popq %r13
  3357. popq %r14
  3358. popq %r15
  3359. popq %rbp
  3360. retq
  3361. \end{lstlisting}
  3362. \end{minipage}
  3363. \end{tabular}
  3364. \caption{Example compilation of an \key{if} expression to x86.}
  3365. \label{fig:if-example-x86}
  3366. \end{figure}
  3367. \begin{figure}[p]
  3368. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3369. \node (R1) at (0,2) {\large $R_1$};
  3370. \node (R1-2) at (3,2) {\large $R_1$};
  3371. \node (R1-3) at (6,2) {\large $R_1$};
  3372. \node (C1-1) at (3,0) {\large $C_1$};
  3373. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3374. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3375. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3376. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  3377. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  3378. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3379. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3380. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R1-2);
  3381. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  3382. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize\color{red} flatten} (C1-1);
  3383. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3384. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3385. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3386. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3387. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} lower-cond.} (x86-4);
  3388. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-5);
  3389. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  3390. \end{tikzpicture}
  3391. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3392. \label{fig:R2-passes}
  3393. \end{figure}
  3394. Figure~\ref{fig:R2-passes} gives an overview of all the passes needed
  3395. for the compilation of $R_2$.
  3396. \section{Challenge: Optimizing Conditions$^{*}$}
  3397. \label{sec:opt-if}
  3398. A close inspection of the x86 code generated in
  3399. Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3400. regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3401. twice using \key{cmpq} as follows.
  3402. % Wierd LaTeX bug if I remove the following. -Jeremy
  3403. % Does it have to do with page breaks?
  3404. \begin{lstlisting}
  3405. \end{lstlisting}
  3406. \begin{lstlisting}
  3407. cmpq $1, %rcx
  3408. sete %al
  3409. movzbq %al, %rcx
  3410. cmpq $1, %rcx
  3411. je then21288
  3412. \end{lstlisting}
  3413. The reason for this non-optimal code has to do with the \code{flatten}
  3414. pass earlier in this Chapter. We recommended flattening the condition
  3415. to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3416. is already an \code{eq?} test, then we would like to use that
  3417. directly. In fact, for many of the expressions of Boolean type, we can
  3418. generate more optimized code. For example, if the condition is
  3419. \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3420. all. If the condition is a \code{let}, we can optimize based on the
  3421. form of its body. If the condition is a \code{not}, then we can flip
  3422. the two branches.
  3423. %
  3424. \margincomment{\tiny We could do even better by converting to basic
  3425. blocks.\\ --Jeremy}
  3426. %
  3427. On the other hand, if the condition is a \code{and}
  3428. or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3429. code duplication.
  3430. Figure~\ref{fig:opt-if} shows an example program and the result of
  3431. applying the above suggested optimizations.
  3432. \begin{exercise}\normalfont
  3433. Change the \code{flatten} pass to improve the code that gets
  3434. generated for \code{if} expressions. We recommend writing a helper
  3435. function that recursively traverses the condition of the \code{if}.
  3436. \end{exercise}
  3437. \begin{figure}[tbp]
  3438. \begin{tabular}{lll}
  3439. \begin{minipage}{0.5\textwidth}
  3440. \begin{lstlisting}
  3441. (program
  3442. (if (let ([x 1])
  3443. (not (eq? 2 x)))
  3444. 42
  3445. 777))
  3446. \end{lstlisting}
  3447. $\Downarrow$
  3448. \begin{lstlisting}
  3449. (program (x.1 t.1 if.1)
  3450. (assign x.1 1)
  3451. (assign t.1 (read))
  3452. (if (eq? x.1 t.1)
  3453. ((assign if.1 42))
  3454. ((assign if.1 777)))
  3455. (return if.1))
  3456. \end{lstlisting}
  3457. $\Downarrow$
  3458. \begin{lstlisting}
  3459. (program (x.1 t.1 if.1)
  3460. (movq (int 1) (var x.1))
  3461. (callq read_int)
  3462. (movq (reg rax) (var t.1))
  3463. (if (eq? (var x.1) (var t.1))
  3464. ((movq (int 42) (var if.1)))
  3465. ((movq (int 777) (var if.1))))
  3466. (movq (var if.1) (reg rax)))
  3467. \end{lstlisting}
  3468. \end{minipage}
  3469. &
  3470. $\Rightarrow$
  3471. \begin{minipage}{0.4\textwidth}
  3472. \begin{lstlisting}
  3473. .globl _main
  3474. _main:
  3475. pushq %rbp
  3476. movq %rsp, %rbp
  3477. pushq %r15
  3478. pushq %r14
  3479. pushq %r13
  3480. pushq %r12
  3481. pushq %rbx
  3482. subq $8, %rsp
  3483. movq $1, %rbx
  3484. callq _read_int
  3485. movq %rax, %rcx
  3486. cmpq %rbx, %rcx
  3487. je then21288
  3488. movq $777, %r12
  3489. jmp if_end21289
  3490. then21288:
  3491. movq $42, %r12
  3492. if_end21289:
  3493. movq %r12, %rax
  3494. movq %rax, %rdi
  3495. callq _print_int
  3496. movq $0, %rax
  3497. addq $8, %rsp
  3498. popq %rbx
  3499. popq %r12
  3500. popq %r13
  3501. popq %r14
  3502. popq %r15
  3503. popq %rbp
  3504. retq
  3505. \end{lstlisting}
  3506. \end{minipage}
  3507. \end{tabular}
  3508. \caption{Example program with optimized conditionals.}
  3509. \label{fig:opt-if}
  3510. \end{figure}
  3511. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3512. \chapter{Tuples and Garbage Collection}
  3513. \label{ch:tuples}
  3514. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  3515. things to discuss in this chapter. \\ --Jeremy}
  3516. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3517. all the IR grammars are spelled out! \\ --Jeremy}
  3518. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  3519. but keep type annotations on vector creation and local variables, function
  3520. parameters, etc. \\ --Jeremy}
  3521. In this chapter we study the implementation of mutable tuples (called
  3522. ``vectors'' in Racket). This language feature is the first to use the
  3523. computer's \emph{heap} because the lifetime of a Racket tuple is
  3524. indefinite, that is, a tuple does not follow a stack (FIFO) discipline
  3525. but instead lives forever from the programmer's viewpoint. Of course,
  3526. from an implementor's viewpoint, it is important to reclaim the space
  3527. associated with tuples when they are no longer needed, which is why we
  3528. also study \emph{garbage collection} techniques in this chapter.
  3529. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3530. interpreter and type checker. The $R_3$ language extends the $R_2$
  3531. language of Chapter~\ref{ch:bool-types} with vectors and void values
  3532. (because the \code{vector-set!} operation returns a void
  3533. value). Section~\ref{sec:GC} describes a garbage collection algorithm
  3534. based on copying live objects back and forth between two halves of the
  3535. heap. The garbage collector requires coordination with the compiler so
  3536. that it can see all of the \emph{root} pointers, that is, pointers in
  3537. registers or on the procedure call stack.
  3538. Section~\ref{sec:code-generation-gc} discusses all the necessary
  3539. changes and additions to the compiler passes, including type checking,
  3540. instruction selection, register allocation, and a new compiler pass
  3541. named \code{expose-allocation}.
  3542. \section{The $R_3$ Language}
  3543. \label{sec:r3}
  3544. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3545. includes three new forms for creating a tuple, reading an element of a
  3546. tuple, and writing to an element of a tuple. The program in
  3547. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3548. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3549. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3550. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3551. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3552. $40$, to which we add the $2$, the element at index $0$ of the
  3553. 1-tuple.
  3554. \begin{figure}[tbp]
  3555. \begin{lstlisting}
  3556. (let ([t (vector 40 #t (vector 2))])
  3557. (if (vector-ref t 1)
  3558. (+ (vector-ref t 0)
  3559. (vector-ref (vector-ref t 2) 0))
  3560. 44))
  3561. \end{lstlisting}
  3562. \caption{Example program that creates tuples and reads from them.}
  3563. \label{fig:vector-eg}
  3564. \end{figure}
  3565. \begin{figure}[tbp]
  3566. \centering
  3567. \fbox{
  3568. \begin{minipage}{0.96\textwidth}
  3569. \[
  3570. \begin{array}{lcl}
  3571. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  3572. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  3573. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3574. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \\
  3575. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  3576. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  3577. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) }\\
  3578. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} } \\
  3579. &\mid& (\key{vector}\;\Exp^{+}) \mid
  3580. (\key{vector-ref}\;\Exp\;\Int) \\
  3581. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  3582. &\mid& (\key{void}) \\
  3583. R_3 &::=& (\key{program} \;(\key{type}\;\itm{type})\; \Exp)
  3584. \end{array}
  3585. \]
  3586. \end{minipage}
  3587. }
  3588. \caption{The syntax of $R_3$, extending $R_2$ with tuples.}
  3589. \label{fig:r3-syntax}
  3590. \end{figure}
  3591. Tuples are our first encounter with heap-allocated data, which raises
  3592. several interesting issues. First, variable binding performs a
  3593. shallow-copy when dealing with tuples, which means that different
  3594. variables can refer to the same tuple, i.e., different variables can
  3595. be \emph{aliases} for the same thing. Consider the following example
  3596. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  3597. the mutation through \code{t2} is visible when referencing the tuple
  3598. from \code{t1}, so the result of this program is \code{42}.
  3599. \begin{lstlisting}
  3600. (let ([t1 (vector 3 7)])
  3601. (let ([t2 t1])
  3602. (let ([_ (vector-set! t2 0 42)])
  3603. (vector-ref t1 0))))
  3604. \end{lstlisting}
  3605. The next issue concerns the lifetime of tuples. Of course, they are
  3606. created by the \code{vector} form, but when does their lifetime end?
  3607. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  3608. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  3609. is not tied to any notion of static scoping. For example, the
  3610. following program returns \code{3} even though the variable \code{t}
  3611. goes out of scope prior to accessing the vector.
  3612. \begin{lstlisting}
  3613. (vector-ref
  3614. (let ([t (vector 3 7)])
  3615. t)
  3616. 0)
  3617. \end{lstlisting}
  3618. From the perspective of programmer-observable behavior, tuples live
  3619. forever. Of course, if they really lived forever, then many programs
  3620. would run out of memory.\footnote{The $R_3$ language does not have
  3621. looping or recursive function, so it is nigh impossible to write a
  3622. program in $R_3$ that will run out of memory. However, we add
  3623. recursive functions in the next Chapter!} A Racket implementation
  3624. must therefore perform automatic garbage collection.
  3625. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  3626. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  3627. checker. The additions to the interpreter are straightforward but the
  3628. updates to the type checker deserve some explanation. As we shall see
  3629. in Section~\ref{sec:GC}, we need to know which variables are pointers
  3630. into the heap, that is, which variables are vectors. Also, when
  3631. allocating a vector, we shall need to know which elements of the
  3632. vector are pointers. We can obtain this information during type
  3633. checking and flattening. The type checker in
  3634. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  3635. expression, it also wraps every sub-expression $e$ with the form
  3636. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  3637. the flatten pass (Section~\ref{sec:flatten-gc}) this type information is
  3638. propagated to all variables (including temporaries generated during
  3639. flattening).
  3640. \begin{figure}[tbp]
  3641. \begin{lstlisting}
  3642. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  3643. (define (interp-op op)
  3644. (match op
  3645. ...
  3646. ['vector vector]
  3647. ['vector-ref vector-ref]
  3648. ['vector-set! vector-set!]
  3649. [else (error 'interp-op "unknown operator")]))
  3650. (define (interp-R3 env)
  3651. (lambda (e)
  3652. (match e
  3653. ...
  3654. [else (error 'interp-R3 "unrecognized expression")]
  3655. )))
  3656. \end{lstlisting}
  3657. \caption{Interpreter for the $R_3$ language.}
  3658. \label{fig:interp-R3}
  3659. \end{figure}
  3660. \begin{figure}[tbp]
  3661. \begin{lstlisting}
  3662. (define (typecheck-R3 env)
  3663. (lambda (e)
  3664. (match e
  3665. ...
  3666. ['(void) (values '(has-type (void) Void) 'Void)]
  3667. [`(vector ,(app (type-check env) e* t*) ...)
  3668. (let ([t `(Vector ,@t*)])
  3669. (values `(has-type (vector ,@e*) ,t) t))]
  3670. [`(vector-ref ,(app (type-check env) e t) ,i)
  3671. (match t
  3672. [`(Vector ,ts ...)
  3673. (unless (and (exact-nonnegative-integer? i)
  3674. (i . < . (length ts)))
  3675. (error 'type-check "invalid index ~a" i))
  3676. (let ([t (list-ref ts i)])
  3677. (values `(has-type (vector-ref ,e (has-type ,i Integer)) ,t)
  3678. t))]
  3679. [else (error "expected a vector in vector-ref, not" t)])]
  3680. [`(vector-set! ,(app (type-check env) e-vec^ t-vec) ,i
  3681. ,(app (type-check env) e-arg^ t-arg))
  3682. (match t-vec
  3683. [`(Vector ,ts ...)
  3684. (unless (and (exact-nonnegative-integer? i)
  3685. (i . < . (length ts)))
  3686. (error 'type-check "invalid index ~a" i))
  3687. (unless (equal? (list-ref ts i) t-arg)
  3688. (error 'type-check "type mismatch in vector-set! ~a ~a"
  3689. (list-ref ts i) t-arg))
  3690. (values `(has-type (vector-set! ,e-vec^
  3691. (has-type ,i Integer)
  3692. ,e-arg^) Void) 'Void)]
  3693. [else (error 'type-check
  3694. "expected a vector in vector-set!, not ~a" t-vec)])]
  3695. [`(eq? ,(app (type-check env) e1 t1)
  3696. ,(app (type-check env) e2 t2))
  3697. (match* (t1 t2)
  3698. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  3699. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  3700. [(other wise) ((super type-check env) e)])]
  3701. )))
  3702. \end{lstlisting}
  3703. \caption{Type checker for the $R_3$ language.}
  3704. \label{fig:typecheck-R3}
  3705. \end{figure}
  3706. \section{Garbage Collection}
  3707. \label{sec:GC}
  3708. Here we study a relatively simple algorithm for garbage collection
  3709. that is the basis of state-of-the-art garbage
  3710. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  3711. particular, we describe a two-space copying
  3712. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  3713. perform the
  3714. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  3715. coarse-grained depiction of what happens in a two-space collector,
  3716. showing two time steps, prior to garbage collection on the top and
  3717. after garbage collection on the bottom. In a two-space collector, the
  3718. heap is divided into two parts, the FromSpace and the
  3719. ToSpace. Initially, all allocations go to the FromSpace until there is
  3720. not enough room for the next allocation request. At that point, the
  3721. garbage collector goes to work to make more room.
  3722. The garbage collector must be careful not to reclaim tuples that will
  3723. be used by the program in the future. Of course, it is impossible in
  3724. general to predict what a program will do, but we can overapproximate
  3725. the will-be-used tuples by preserving all tuples that could be
  3726. accessed by \emph{any} program given the current computer state. A
  3727. program could access any tuple whose address is in a register or on
  3728. the procedure call stack. These addresses are called the \emph{root
  3729. set}. In addition, a program could access any tuple that is
  3730. transitively reachable from the root set. Thus, it is safe for the
  3731. garbage collector to reclaim the tuples that are not reachable in this
  3732. way.
  3733. %
  3734. \footnote{The sitation in Figure~\ref{fig:copying-collector}, with a
  3735. cycle, cannot be created by a well-typed program in $R_3$. However,
  3736. creating cycles will be possible once we get to $R_6$. We design
  3737. the garbage collector to deal with cycles to begin with, so we will
  3738. not need to revisit this issue.}
  3739. So the goal of the garbage collector is twofold:
  3740. \begin{enumerate}
  3741. \item preserve all tuple that are reachable from the root set via a
  3742. path of pointers, that is, the \emph{live} tuples, and
  3743. \item reclaim the memory of everything else, that is, the
  3744. \emph{garbage}.
  3745. \end{enumerate}
  3746. A copying collector accomplishes this by copying all of the live
  3747. objects into the ToSpace and then performs a slight of hand, treating
  3748. the ToSpace as the new FromSpace and the old FromSpace as the new
  3749. ToSpace. In the example of Figure~\ref{fig:copying-collector}, there
  3750. are three pointers in the root set, one in a register and two on the
  3751. stack. All of the live objects have been copied to the ToSpace (the
  3752. right-hand side of Figure~\ref{fig:copying-collector}) in a way that
  3753. preserves the pointer relationships. For example, the pointer in the
  3754. register still points to a 2-tuple whose first element is a 3-tuple
  3755. and second element is a 2-tuple. There are four tuples that are not
  3756. reachable from the root set and therefore do not get copied into the
  3757. ToSpace.
  3758. \begin{figure}[tbp]
  3759. \centering
  3760. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  3761. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  3762. \caption{A copying collector in action.}
  3763. \label{fig:copying-collector}
  3764. \end{figure}
  3765. %% \margincomment{\tiny Need to add comment somewhere about the goodness
  3766. %% of copying collection, especially that it doesn't touch
  3767. %% the garbage, so its time complexity only depends on the
  3768. %% amount of live data.\\ --Jeremy}
  3769. There are many alternatives to copying collectors (and their older
  3770. siblings, the generational collectors) when its comes to garbage
  3771. collection, such as mark-and-sweep and reference counting. The
  3772. strengths of copying collectors are that allocation is fast (just a
  3773. test and pointer increment), there is no fragmentation, cyclic garbage
  3774. is collected, and the time complexity of collection only depends on
  3775. the amount of live data, and not on the amount of
  3776. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  3777. copying collectors is that they use a lot of space, though that
  3778. problem is ameliorated in generational collectors. Racket and Scheme
  3779. programs tend to allocate many small objects and generate a lot of
  3780. garbage, so copying and generational collectors are a good fit. Of
  3781. course, garbage collection is an active research topic, especially
  3782. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  3783. continuously developing new techniques and revisiting old
  3784. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  3785. \subsection{Graph Copying via Cheney's Algorithm}
  3786. \label{sec:cheney}
  3787. Let us take a closer look at how the copy works. The allocated objects
  3788. and pointers can be viewed as a graph and we need to copy the part of
  3789. the graph that is reachable from the root set. To make sure we copy
  3790. all of the reachable vertices in the graph, we need an exhaustive
  3791. graph traversal algorithm, such as depth-first search or breadth-first
  3792. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  3793. take into account the possibility of cycles by marking which vertices
  3794. have already been visited, so as to ensure termination of the
  3795. algorithm. These search algorithms also use a data structure such as a
  3796. stack or queue as a to-do list to keep track of the vertices that need
  3797. to be visited. We shall use breadth-first search and a trick due to
  3798. \citet{Cheney:1970aa} for simultaneously representing the queue and
  3799. copying tuples into the ToSpace.
  3800. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  3801. copy progresses. The queue is represented by a chunk of contiguous
  3802. memory at the beginning of the ToSpace, using two pointers to track
  3803. the front and the back of the queue. The algorithm starts by copying
  3804. all tuples that are immediately reachable from the root set into the
  3805. ToSpace to form the initial queue. When we copy a tuple, we mark the
  3806. old tuple to indicate that it has been visited. (We discuss the
  3807. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  3808. inside the copied tuples in the queue still point back to the
  3809. FromSpace. Once the initial queue has been created, the algorithm
  3810. enters a loop in which it repeatedly processes the tuple at the front
  3811. of the queue and pops it off the queue. To process a tuple, the
  3812. algorithm copies all the tuple that are directly reachable from it to
  3813. the ToSpace, placing them at the back of the queue. The algorithm then
  3814. updates the pointers in the popped tuple so they point to the newly
  3815. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  3816. step we copy the tuple whose second element is $42$ to the back of the
  3817. queue. The other pointer goes to a tuple that has already been copied,
  3818. so we do not need to copy it again, but we do need to update the
  3819. pointer to the new location. This can be accomplished by storing a
  3820. \emph{forwarding} pointer to the new location in the old tuple, back
  3821. when we initially copied the tuple into the ToSpace. This completes
  3822. one step of the algorithm. The algorithm continues in this way until
  3823. the front of the queue is empty, that is, until the front catches up
  3824. with the back.
  3825. \begin{figure}[tbp]
  3826. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  3827. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  3828. \label{fig:cheney}
  3829. \end{figure}
  3830. \subsection{Data Representation}
  3831. \label{sec:data-rep-gc}
  3832. The garbage collector places some requirements on the data
  3833. representations used by our compiler. First, the garbage collector
  3834. needs to distinguish between pointers and other kinds of data. There
  3835. are several ways to accomplish this.
  3836. \begin{enumerate}
  3837. \item Attached a tag to each object that identifies what type of
  3838. object it is~\citep{McCarthy:1960dz}.
  3839. \item Store different types of objects in different
  3840. regions~\citep{Steele:1977ab}.
  3841. \item Use type information from the program to either generate
  3842. type-specific code for collecting or to generate tables that can
  3843. guide the
  3844. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  3845. \end{enumerate}
  3846. Dynamically typed languages, such as Lisp, need to tag objects
  3847. anyways, so option 1 is a natural choice for those languages.
  3848. However, $R_3$ is a statically typed language, so it would be
  3849. unfortunate to require tags on every object, especially small and
  3850. pervasive objects like integers and Booleans. Option 3 is the
  3851. best-performing choice for statically typed languages, but comes with
  3852. a relatively high implementation complexity. To keep this chapter to a
  3853. 2-week time budget, we recommend a combination of options 1 and 2,
  3854. with separate strategies used for the stack and the heap.
  3855. Regarding the stack, we recommend using a separate stack for
  3856. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  3857. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  3858. local variable needs to be spilled and is of type \code{(Vector
  3859. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  3860. of the normal procedure call stack. Furthermore, we always spill
  3861. vector-typed variables if they are live during a call to the
  3862. collector, thereby ensuring that no pointers are in registers during a
  3863. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  3864. Figure~\ref{fig:copying-collector} and contrasts it with the data
  3865. layout using a root stack. The root stack contains the two pointers
  3866. from the regular stack and also the pointer in the second
  3867. register.
  3868. \begin{figure}[tbp]
  3869. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  3870. \caption{Maintaining a root stack to facilitate garbage collection.}
  3871. \label{fig:shadow-stack}
  3872. \end{figure}
  3873. The problem of distinguishing between pointers and other kinds of data
  3874. also arises inside of each tuple. We solve this problem by attaching a
  3875. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  3876. in on the tags for two of the tuples in the example from
  3877. Figure~\ref{fig:copying-collector}. Part of each tag is dedicated to
  3878. specifying which elements of the tuple are pointers, the part labeled
  3879. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  3880. a pointer and a 0 bit indicates some other kind of data. The pointer
  3881. mask starts at bit location 7. We have limited tuples to a maximum
  3882. size of 50 elements, so we just need 50 bits for the pointer mask. The
  3883. tag also contains two other pieces of information. The length of the
  3884. tuple (number of elements) is stored in bits location 1 through
  3885. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  3886. to be copied to the FromSpace. If the bit has value 1, then this
  3887. tuple has not yet been copied. If the bit has value 0 then the entire
  3888. tag is in fact a forwarding pointer. (The lower 3 bits of an pointer
  3889. are always zero anyways because our tuples are 8-byte aligned.)
  3890. \begin{figure}[tbp]
  3891. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  3892. \caption{Representation for tuples in the heap.}
  3893. \label{fig:tuple-rep}
  3894. \end{figure}
  3895. \subsection{Implementation of the Garbage Collector}
  3896. \label{sec:organize-gz}
  3897. The implementation of the garbage collector needs to do a lot of
  3898. bit-level data manipulation and we need to link it with our
  3899. compiler-generated x86 code. Thus, we recommend implementing the
  3900. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  3901. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  3902. interface to the garbage collector. The \code{initialize} function
  3903. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  3904. function is meant to be called near the beginning of \code{main},
  3905. before the rest of the program executes. The \code{initialize}
  3906. function puts the address of the beginning of the FromSpace into the
  3907. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  3908. points to the address that is 1-past the last element of the
  3909. FromSpace. (We use half-open intervals to represent chunks of
  3910. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  3911. points to the first element of the root stack.
  3912. As long as there is room left in the FromSpace, your generated code
  3913. can allocate tuples simply by moving the \code{free\_ptr} forward.
  3914. %
  3915. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  3916. --Jeremy}
  3917. %
  3918. The amount of room left in FromSpace is the difference between the
  3919. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  3920. function should be called when there is not enough room left in the
  3921. FromSpace for the next allocation. The \code{collect} function takes
  3922. a pointer to the current top of the root stack (one past the last item
  3923. that was pushed) and the number of bytes that need to be
  3924. allocated. The \code{collect} function performs the copying collection
  3925. and leaves the heap in a state such that the next allocation will
  3926. succeed.
  3927. \begin{figure}[tbp]
  3928. \begin{lstlisting}
  3929. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  3930. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  3931. int64_t* free_ptr;
  3932. int64_t* fromspace_begin;
  3933. int64_t* fromspace_end;
  3934. int64_t** rootstack_begin;
  3935. \end{lstlisting}
  3936. \caption{The compiler's interface to the garbage collector.}
  3937. \label{fig:gc-header}
  3938. \end{figure}
  3939. \begin{exercise}
  3940. In the file \code{runtime.c} you will find the implementation of
  3941. \code{initialize} and a partial implementation of \code{collect}.
  3942. The \code{collect} function calls another function, \code{cheney},
  3943. to perform the actual copy, and that function is left to the reader
  3944. to implement. The following is the prototype for \code{cheney}.
  3945. \begin{lstlisting}
  3946. static void cheney(int64_t** rootstack_ptr);
  3947. \end{lstlisting}
  3948. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  3949. rootstack (which is array of pointers). The \code{cheney} function
  3950. also communicates with \code{collect} through several global
  3951. variables, the \code{framespace\_begin} and \code{framespace\_end}
  3952. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  3953. the ToSpace:
  3954. \begin{lstlisting}
  3955. static int64_t* tospace_begin;
  3956. static int64_t* tospace_end;
  3957. \end{lstlisting}
  3958. The job of the \code{cheney} function is to copy all the live
  3959. objects (reachable from the root stack) into the ToSpace, update
  3960. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  3961. update the root stack so that it points to the objects in the
  3962. ToSpace, and finally to swap the global pointers for the FromSpace
  3963. and ToSpace.
  3964. \end{exercise}
  3965. \section{Compiler Passes}
  3966. \label{sec:code-generation-gc}
  3967. The introduction of garbage collection has a non-trivial impact on our
  3968. compiler passes. We introduce one new compiler pass called
  3969. \code{expose-allocation} and make non-trivial changes to
  3970. \code{type-check}, \code{flatten}, \code{select-instructions},
  3971. \code{allocate-registers}, and \code{print-x86}. The following
  3972. program will serve as our running example. It creates two tuples, one
  3973. nested inside the other. Both tuples have length one. The example then
  3974. accesses the element in the inner tuple tuple via two vector
  3975. references.
  3976. % tests/s2_17.rkt
  3977. \begin{lstlisting}
  3978. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  3979. \end{lstlisting}
  3980. We already discuss the changes to \code{type-check} in
  3981. Section~\ref{sec:r3}, including the addition of \code{has-type}, so we
  3982. proceed to discuss the new \code{expose-allocation} pass.
  3983. \subsection{Expose Allocation (New)}
  3984. \label{sec:expose-allocation}
  3985. The pass \code{expose-allocation} lowers the \code{vector} creation
  3986. form into a conditional call to the collector followed by the
  3987. allocation. We choose to place the \code{expose-allocation} pass
  3988. before \code{flatten} because \code{expose-allocation} introduces new
  3989. variables, which can be done locally with \code{let}, but \code{let}
  3990. is gone after \code{flatten}. In the following, we show the
  3991. transformation for the \code{vector} form into let-bindings for the
  3992. intializing expressions, by a conditional \code{collect}, an
  3993. \code{allocate}, and the initialization of the vector.
  3994. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  3995. total bytes need to be allocated for the vector, which is 8 for the
  3996. tag plus \itm{len} times 8.)
  3997. \begin{lstlisting}
  3998. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  3999. |$\Longrightarrow$|
  4000. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4001. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4002. (global-value fromspace_end))
  4003. (void)
  4004. (collect |\itm{bytes}|))])
  4005. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4006. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4007. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4008. |$v$|) ... )))) ...)
  4009. \end{lstlisting}
  4010. (In the above, we suppressed all of the \code{has-type} forms in the
  4011. output for the sake of readability.) The ordering of the initializing
  4012. expressions ($e_0,\ldots,e_{n-1}$) prior to the \code{allocate} is
  4013. important, as those expressions may trigger garbage collection and we
  4014. do not want an allocated but uninitialized tuple to be present during
  4015. a garbage collection.
  4016. The output of \code{expose-allocation} is a language that extends
  4017. $R_3$ with the three new forms that we use above in the translation of
  4018. \code{vector}.
  4019. \[
  4020. \begin{array}{lcl}
  4021. \Exp &::=& \cdots
  4022. \mid (\key{collect} \,\itm{int})
  4023. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4024. \mid (\key{global-value} \,\itm{name})
  4025. \end{array}
  4026. \]
  4027. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4028. %% the beginning of the program which will instruct the garbage collector
  4029. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4030. %% two arguments of \code{initialize} specify the initial allocated space
  4031. %% for the root stack and for the heap.
  4032. %
  4033. %% The \code{expose-allocation} pass annotates all of the local variables
  4034. %% in the \code{program} form with their type.
  4035. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4036. \code{expose-allocation} pass on our running example.
  4037. \begin{figure}[tbp]
  4038. \begin{lstlisting}
  4039. (program (type Integer)
  4040. (vector-ref
  4041. (vector-ref
  4042. (let ((vecinit32990
  4043. (let ([vecinit32986 42])
  4044. (let ((collectret32988
  4045. (if (< (+ (global-value free_ptr) 16)
  4046. (global-value fromspace_end))
  4047. (void)
  4048. (collect 16))))
  4049. (let ([alloc32985
  4050. (allocate 1 (Vector Integer))])
  4051. (let ([initret32987
  4052. (vector-set! alloc32985 0 vecinit32986)])
  4053. alloc32985))))))
  4054. (let ([collectret32992
  4055. (if (< (+ (global-value free_ptr) 16)
  4056. (global-value fromspace_end))
  4057. (void)
  4058. (collect 16))])
  4059. (let ([alloc32989 (allocate 1 (Vector (Vector Integer)))])
  4060. (let ([initret32991 (vector-set! alloc32989 0 vecinit32990)])
  4061. alloc32989))))
  4062. 0)
  4063. 0))
  4064. \end{lstlisting}
  4065. \caption{Output of the \code{expose-allocation} pass, minus
  4066. all of the \code{has-type} forms.}
  4067. \label{fig:expose-alloc-output}
  4068. \end{figure}
  4069. \clearpage
  4070. \subsection{Flatten and the $C_2$ intermediate language}
  4071. \label{sec:flatten-gc}
  4072. \begin{figure}[tp]
  4073. \fbox{
  4074. \begin{minipage}{0.96\textwidth}
  4075. \[
  4076. \begin{array}{lcl}
  4077. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4078. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4079. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4080. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4081. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4082. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4083. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4084. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4085. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4086. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4087. &\mid& (\key{collect} \,\itm{int}) \\
  4088. C_2 & ::= & \gray{ (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+}) }
  4089. \end{array}
  4090. \]
  4091. \end{minipage}
  4092. }
  4093. \caption{The $C_2$ language, extending $C_1$ with support for tuples.}
  4094. \label{fig:c2-syntax}
  4095. \end{figure}
  4096. The output of \code{flatten} is a program in the intermediate language
  4097. $C_2$, whose syntax is defined in Figure~\ref{fig:c2-syntax}. The new
  4098. forms of $C_2$ include the expressions \key{allocate},
  4099. \key{vector-ref}, and \key{vector-set!}, and \key{global-value} and
  4100. the statement \code{collect}. The \code{flatten} pass can treat these
  4101. new forms much like the other forms.
  4102. Recall that the \code{flatten} function collects all of the local
  4103. variables so that it can decorate the \code{program} form with
  4104. them. Also recall that we need to know the types of all the local
  4105. variables for purposes of identifying the root set for the garbage
  4106. collector. Thus, we change \code{flatten} to collect not just the
  4107. variables, but the variables and their types in the form of an
  4108. association list. Thanks to the \code{has-type} forms, the types are
  4109. readily available. For example, consider the translation of the
  4110. \code{let} form.
  4111. \begin{lstlisting}
  4112. (let ([|$x$| (has-type |\itm{rhs}| |\itm{type}|)]) |\itm{body}|)
  4113. |$\Longrightarrow$|
  4114. (values |\itm{body'}|
  4115. (|\itm{ss_1}| (assign |$x$| |\itm{rhs'}|) |\itm{ss_2}|)
  4116. ((|$x$| . |\itm{type}|) |\itm{xt_1}| |\itm{xt_2}|))
  4117. \end{lstlisting}
  4118. where \itm{rhs'}, \itm{ss_1}, and \itm{xs_1} are the results of
  4119. recursively flattening \itm{rhs} and \itm{body'}, \itm{ss_2}, and
  4120. \itm{xs_2} are the results of recursively flattening \itm{body}. The
  4121. output on our running example is shown in Figure~\ref{fig:flatten-gc}.
  4122. \begin{figure}[tbp]
  4123. \begin{lstlisting}
  4124. '(program
  4125. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4126. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void)
  4127. (tmp94 . Integer) (tmp93 . Integer) (tmp95 . Integer)
  4128. (tmp85 Vector Integer) (tmp87 . Void) (tmp92 . Void)
  4129. (tmp00 . Void) (tmp98 . Integer) (tmp97 . Integer)
  4130. (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4131. (tmp91 . Void))
  4132. (type Integer)
  4133. (assign tmp86 42)
  4134. (assign tmp93 (global-value free_ptr))
  4135. (assign tmp94 (+ tmp93 16))
  4136. (assign tmp95 (global-value fromspace_end))
  4137. (if (< tmp94 tmp95)
  4138. ((assign tmp96 (void)))
  4139. ((collect 16) (assign tmp96 (void))))
  4140. (assign tmp88 tmp96)
  4141. (assign tmp85 (allocate 1 (Vector Integer)))
  4142. (assign tmp87 (vector-set! tmp85 0 tmp86))
  4143. (assign tmp90 tmp85)
  4144. (assign tmp97 (global-value free_ptr))
  4145. (assign tmp98 (+ tmp97 16))
  4146. (assign tmp99 (global-value fromspace_end))
  4147. (if (< tmp98 tmp99)
  4148. ((assign tmp00 (void)))
  4149. ((collect 16) (assign tmp00 (void))))
  4150. (assign tmp92 tmp00)
  4151. (assign tmp89 (allocate 1 (Vector (Vector Integer))))
  4152. (assign tmp91 (vector-set! tmp89 0 tmp90))
  4153. (assign tmp01 (vector-ref tmp89 0))
  4154. (assign tmp02 (vector-ref tmp01 0))
  4155. (return tmp02))
  4156. \end{lstlisting}
  4157. \caption{Output of \code{flatten} for the running example.}
  4158. \label{fig:flatten-gc}
  4159. \end{figure}
  4160. \clearpage
  4161. \subsection{Select Instructions}
  4162. \label{sec:select-instructions-gc}
  4163. %% void (rep as zero)
  4164. %% allocate
  4165. %% collect (callq collect)
  4166. %% vector-ref
  4167. %% vector-set!
  4168. %% global-value (postpone)
  4169. In this pass we generate x86 code for most of the new operations that
  4170. were needed to compile tuples, including \code{allocate},
  4171. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4172. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4173. The \code{vector-ref} and \code{vector-set!} forms translate into
  4174. \code{movq} instructions with the appropriate \key{deref}. (The
  4175. plus one is to get past the tag at the beginning of the tuple
  4176. representation.)
  4177. \begin{lstlisting}
  4178. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4179. |$\Longrightarrow$|
  4180. (movq |$\itm{vec}'$| (reg r11))
  4181. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4182. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4183. |$\Longrightarrow$|
  4184. (movq |$\itm{vec}'$| (reg r11))
  4185. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4186. (movq (int 0) |$\itm{lhs}$|)
  4187. \end{lstlisting}
  4188. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4189. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4190. register \code{r11} ensures that offsets are only performed with
  4191. register operands. This requires removing \code{r11} from
  4192. consideration by the register allocating.
  4193. We compile the \code{allocate} form to operations on the
  4194. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4195. is the next free address in the FromSpace, so we move it into the
  4196. \itm{lhs} and then move it forward by enough space for the tuple being
  4197. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4198. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4199. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4200. how the tag is organized. We recommend using the Racket operations
  4201. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4202. The type annoation in the \code{vector} form is used to determine the
  4203. pointer mask region of the tag.
  4204. \begin{lstlisting}
  4205. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4206. |$\Longrightarrow$|
  4207. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4208. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4209. (movq |$\itm{lhs}'$| (reg r11))
  4210. (movq (int |$\itm{tag}$|) (deref r11 0))
  4211. \end{lstlisting}
  4212. The \code{collect} form is compiled to a call to the \code{collect}
  4213. function in the runtime. The arguments to \code{collect} are the top
  4214. of the root stack and the number of bytes that need to be allocated.
  4215. We shall use a dedicated register, \code{r15}, to store the pointer to
  4216. the top of the root stack. So \code{r15} is not available for use by
  4217. the register allocator.
  4218. \begin{lstlisting}
  4219. (collect |$\itm{bytes}$|)
  4220. |$\Longrightarrow$|
  4221. (movq (reg 15) (reg rdi))
  4222. (movq |\itm{bytes}| (reg rsi))
  4223. (callq collect)
  4224. \end{lstlisting}
  4225. \begin{figure}[tp]
  4226. \fbox{
  4227. \begin{minipage}{0.96\textwidth}
  4228. \[
  4229. \begin{array}{lcl}
  4230. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4231. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4232. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4233. \mid (\key{global-value}\; \itm{name}) \\
  4234. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4235. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4236. (\key{subq} \; \Arg\; \Arg) \mid
  4237. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4238. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4239. (\key{pushq}\;\Arg) \mid
  4240. (\key{popq}\;\Arg) \mid
  4241. (\key{retq})} \\
  4242. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4243. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4244. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4245. \mid (\key{jmp} \; \itm{label})
  4246. \mid (\key{j}\itm{cc} \; \itm{label})
  4247. \mid (\key{label} \; \itm{label}) } \\
  4248. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4249. \end{array}
  4250. \]
  4251. \end{minipage}
  4252. }
  4253. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4254. \label{fig:x86-2}
  4255. \end{figure}
  4256. The syntax of the $x86_2$ language is defined in
  4257. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4258. of the form for global variables.
  4259. %
  4260. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4261. \code{select-instructions} pass on the running example.
  4262. \begin{figure}[tbp]
  4263. \centering
  4264. \begin{minipage}{0.75\textwidth}
  4265. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4266. (program
  4267. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4268. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void) (tmp94 . Integer)
  4269. (tmp93 . Integer) (tmp95 . Integer) (tmp85 Vector Integer)
  4270. (tmp87 . Void) (tmp92 . Void) (tmp00 . Void) (tmp98 . Integer)
  4271. (tmp97 . Integer) (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4272. (tmp91 . Void)) (type Integer)
  4273. (movq (int 42) (var tmp86))
  4274. (movq (global-value free_ptr) (var tmp93))
  4275. (movq (var tmp93) (var tmp94))
  4276. (addq (int 16) (var tmp94))
  4277. (movq (global-value fromspace_end) (var tmp95))
  4278. (if (< (var tmp94) (var tmp95))
  4279. ((movq (int 0) (var tmp96)))
  4280. ((movq (reg r15) (reg rdi))
  4281. (movq (int 16) (reg rsi))
  4282. (callq collect)
  4283. (movq (int 0) (var tmp96))))
  4284. (movq (var tmp96) (var tmp88))
  4285. (movq (global-value free_ptr) (var tmp85))
  4286. (addq (int 16) (global-value free_ptr))
  4287. (movq (var tmp85) (reg r11))
  4288. (movq (int 3) (deref r11 0))
  4289. (movq (var tmp85) (reg r11))
  4290. (movq (var tmp86) (deref r11 8))
  4291. (movq (int 0) (var tmp87))
  4292. (movq (var tmp85) (var tmp90))
  4293. (movq (global-value free_ptr) (var tmp97))
  4294. (movq (var tmp97) (var tmp98))
  4295. (addq (int 16) (var tmp98))
  4296. (movq (global-value fromspace_end) (var tmp99))
  4297. (if (< (var tmp98) (var tmp99))
  4298. ((movq (int 0) (var tmp00)))
  4299. ((movq (reg r15) (reg rdi))
  4300. (movq (int 16) (reg rsi))
  4301. (callq collect)
  4302. (movq (int 0) (var tmp00))))
  4303. (movq (var tmp00) (var tmp92))
  4304. (movq (global-value free_ptr) (var tmp89))
  4305. (addq (int 16) (global-value free_ptr))
  4306. (movq (var tmp89) (reg r11))
  4307. (movq (int 131) (deref r11 0))
  4308. (movq (var tmp89) (reg r11))
  4309. (movq (var tmp90) (deref r11 8))
  4310. (movq (int 0) (var tmp91))
  4311. (movq (var tmp89) (reg r11))
  4312. (movq (deref r11 8) (var tmp01))
  4313. (movq (var tmp01) (reg r11))
  4314. (movq (deref r11 8) (var tmp02))
  4315. (movq (var tmp02) (reg rax)))
  4316. \end{lstlisting}
  4317. \end{minipage}
  4318. \caption{Output of the \code{select-instructions} pass.}
  4319. \label{fig:select-instr-output-gc}
  4320. \end{figure}
  4321. \clearpage
  4322. \subsection{Register Allocation}
  4323. \label{sec:reg-alloc-gc}
  4324. As discussed earlier in this chapter, the garbage collector needs to
  4325. access all the pointers in the root set, that is, all variables that
  4326. are vectors. It will be the responsibility of the register allocator
  4327. to make sure that:
  4328. \begin{enumerate}
  4329. \item the root stack is used for spilling vector-typed variables, and
  4330. \item if a vector-typed variable is live during a call to the
  4331. collector, it must be spilled to ensure it is visible to the
  4332. collector.
  4333. \end{enumerate}
  4334. The later responsibility can be handled during construction of the
  4335. inference graph, by adding interference edges between the call-live
  4336. vector-typed variables and all the callee-save registers. (They
  4337. already interfere with the caller-save registers.) The type
  4338. information for variables is in the \code{program} form, so we
  4339. recommend adding another parameter to the \code{build-interference}
  4340. function to communicate this association list.
  4341. The spilling of vector-typed variables to the root stack can be
  4342. handled after graph coloring, when choosing how to assign the colors
  4343. (integers) to registers and stack locations. The \code{program} output
  4344. of this pass changes to also record the number of spills to the root
  4345. stack.
  4346. \[
  4347. \begin{array}{lcl}
  4348. x86_2 &::= & (\key{program} \;(\itm{stackSpills} \; \itm{rootstackSpills}) \;(\key{type}\;\itm{type})\; \Instr^{+})
  4349. \end{array}
  4350. \]
  4351. % build-interference
  4352. %
  4353. % callq
  4354. % extra parameter for var->type assoc. list
  4355. % update 'program' and 'if'
  4356. % allocate-registers
  4357. % allocate spilled vectors to the rootstack
  4358. % don't change color-graph
  4359. \subsection{Print x86}
  4360. \label{sec:print-x86-gc}
  4361. \margincomment{\scriptsize We need to show the translation to x86 and what
  4362. to do about global-value. \\ --Jeremy}
  4363. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4364. \code{print-x86} pass.
  4365. \begin{figure}[htbp]
  4366. \begin{minipage}[t]{0.5\textwidth}
  4367. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4368. .globl _main
  4369. _main:
  4370. pushq %rbp
  4371. movq %rsp, %rbp
  4372. pushq %r14
  4373. pushq %r13
  4374. pushq %r12
  4375. pushq %rbx
  4376. subq $0, %rsp
  4377. movq $16384, %rdi
  4378. movq $16, %rsi
  4379. callq _initialize
  4380. movq _rootstack_begin(%rip), %r15
  4381. movq _free_ptr(%rip), %rbx
  4382. addq $16, %rbx
  4383. cmpq _fromspace_end(%rip), %rbx
  4384. setl %al
  4385. movzbq %al, %rbx
  4386. cmpq $0, %rbx
  4387. je then30964
  4388. jmp if_end30965
  4389. then30964:
  4390. movq %r15, %rdi
  4391. movq $16, %rsi
  4392. callq _collect
  4393. if_end30965:
  4394. movq _free_ptr(%rip), %rbx
  4395. addq $16, _free_ptr(%rip)
  4396. movq %rbx, %r11
  4397. movq $3, 0(%r11)
  4398. movq %rbx, %r11
  4399. movq $42, 8(%r11)
  4400. movq _free_ptr(%rip), %rcx
  4401. addq $16, %rcx
  4402. cmpq _fromspace_end(%rip), %rcx
  4403. setl %al
  4404. movzbq %al, %rcx
  4405. cmpq $0, %rcx
  4406. je then30966
  4407. jmp if_end30967
  4408. \end{lstlisting}
  4409. \end{minipage}
  4410. \begin{minipage}[t]{0.45\textwidth}
  4411. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4412. then30966:
  4413. movq %rbx, 0(%r15)
  4414. addq $8, %r15
  4415. movq %r15, %rdi
  4416. movq $16, %rsi
  4417. callq _collect
  4418. subq $8, %r15
  4419. movq 0(%r15), %rbx
  4420. if_end30967:
  4421. movq _free_ptr(%rip), %rcx
  4422. addq $16, _free_ptr(%rip)
  4423. movq %rcx, %r11
  4424. movq $131, 0(%r11)
  4425. movq %rcx, %r11
  4426. movq %rbx, 8(%r11)
  4427. movq %rcx, %r11
  4428. movq 8(%r11), %rbx
  4429. movq %rbx, %r11
  4430. movq 8(%r11), %rbx
  4431. movq %rbx, %rax
  4432. movq %rax, %rdi
  4433. callq _print_int
  4434. movq $0, %rax
  4435. addq $0, %rsp
  4436. popq %rbx
  4437. popq %r12
  4438. popq %r13
  4439. popq %r14
  4440. popq %rbp
  4441. retq
  4442. \end{lstlisting}
  4443. \end{minipage}
  4444. \caption{Output of the \code{print-x86} pass.}
  4445. \label{fig:print-x86-output-gc}
  4446. \end{figure}
  4447. \margincomment{\scriptsize Suggest an implementation strategy
  4448. in which the students first do the code gen and test that
  4449. without GC (just use a big heap), then after that is debugged,
  4450. implement the GC. \\ --Jeremy}
  4451. \begin{figure}[p]
  4452. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4453. \node (R1) at (0,2) {\large $R_1$};
  4454. \node (R1-2) at (3,2) {\large $R_1$};
  4455. \node (R1-3) at (6,2) {\large $R_1$};
  4456. \node (C1-1) at (9,0) {\large $C_1$};
  4457. \node (C1-2) at (6,0) {\large $C_1$};
  4458. \node (C1-3) at (3,0) {\large $C_1$};
  4459. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4460. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4461. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4462. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  4463. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  4464. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4465. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4466. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize typecheck} (R1-2);
  4467. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  4468. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize flatten} (C1-1);
  4469. \path[->,bend left=15] (C1-1) edge [below] node {\ttfamily\footnotesize\color{red} expose-alloc.} (C1-2);
  4470. \path[->,bend left=15] (C1-2) edge [below] node {\ttfamily\footnotesize\color{red} uncover...roots} (C1-3);
  4471. \path[->,bend right=15] (C1-3) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4472. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4473. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4474. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4475. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  4476. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  4477. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  4478. \end{tikzpicture}
  4479. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4480. \label{fig:R3-passes}
  4481. \end{figure}
  4482. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4483. for the compilation of $R_3$.
  4484. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4485. \chapter{Functions}
  4486. \label{ch:functions}
  4487. This chapter studies the compilation of functions (aka. procedures) at
  4488. the level of abstraction of the C language. This corresponds to a
  4489. subset of Typed Racket in which only top-level function definitions
  4490. are allowed. This abstraction level is an important stepping stone to
  4491. implementing lexically-scoped functions in the form of \key{lambda}
  4492. abstractions (Chapter~\ref{ch:lambdas}).
  4493. \section{The $R_4$ Language}
  4494. The syntax for function definitions and function application
  4495. (aka. function call) is shown in Figure~\ref{fig:r4-syntax}, where we
  4496. define the $R_4$ language. Programs in $R_4$ start with zero or more
  4497. function definitions. The function names from these definitions are
  4498. in-scope for the entire program, including all other function
  4499. definitions (so the ordering of function definitions does not matter).
  4500. Functions are first-class in the sense that a function pointer is data
  4501. and can be stored in memory or passed as a parameter to another
  4502. function. Thus, we introduce a function type, written
  4503. \begin{lstlisting}
  4504. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4505. \end{lstlisting}
  4506. for a function whose $n$ parameters have the types $\Type_1$ through
  4507. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4508. these functions (with respect to Racket functions) is that they are
  4509. not lexically scoped. That is, the only external entities that can be
  4510. referenced from inside a function body are other globally-defined
  4511. functions. The syntax of $R_4$ prevents functions from being nested
  4512. inside each other; they can only be defined at the top level.
  4513. \begin{figure}[tp]
  4514. \centering
  4515. \fbox{
  4516. \begin{minipage}{0.96\textwidth}
  4517. \[
  4518. \begin{array}{lcl}
  4519. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4520. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4521. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4522. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4523. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4524. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4525. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4526. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4527. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4528. (\key{vector-ref}\;\Exp\;\Int)} \\
  4529. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4530. &\mid& (\Exp \; \Exp^{*}) \\
  4531. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4532. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4533. \end{array}
  4534. \]
  4535. \end{minipage}
  4536. }
  4537. \caption{Syntax of $R_4$, extending $R_3$ with functions.}
  4538. \label{fig:r4-syntax}
  4539. \end{figure}
  4540. The program in Figure~\ref{fig:r4-function-example} is a
  4541. representative example of defining and using functions in $R_4$. We
  4542. define a function \code{map-vec} that applies some other function
  4543. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  4544. vector containing the results. We also define a function \code{add1}
  4545. that does what its name suggests. The program then applies
  4546. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  4547. \code{(vector 1 42)}, from which we return the \code{42}.
  4548. \begin{figure}[tbp]
  4549. \begin{lstlisting}
  4550. (program
  4551. (define (map-vec [f : (Integer -> Integer)]
  4552. [v : (Vector Integer Integer)])
  4553. : (Vector Integer Integer)
  4554. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  4555. (define (add1 [x : Integer]) : Integer
  4556. (+ x 1))
  4557. (vector-ref (map-vec add1 (vector 0 41)) 1)
  4558. )
  4559. \end{lstlisting}
  4560. \caption{Example of using functions in $R_4$.}
  4561. \label{fig:r4-function-example}
  4562. \end{figure}
  4563. The definitional interpreter for $R_4$ is in
  4564. Figure~\ref{fig:interp-R4}.
  4565. \begin{figure}[tp]
  4566. \begin{lstlisting}
  4567. (define (interp-R4 env)
  4568. (lambda (e)
  4569. (match e
  4570. ....
  4571. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  4572. (cons f `(lambda ,xs ,body))]
  4573. [`(program ,ds ... ,body)
  4574. (let ([top-level (map (interp-R4 '()) ds)])
  4575. ((interp-R4 top-level) body))]
  4576. [`(,fun ,args ...)
  4577. (define arg-vals (map (interp-R4 env) args))
  4578. (define fun-val ((interp-R4 env) fun))
  4579. (match fun-val
  4580. [`(lambda (,xs ...) ,body)
  4581. (define new-env (append (map cons xs arg-vals) env))
  4582. ((interp-R4 new-env) body)]
  4583. [else (error "interp-R4, expected function, not" fun-val)]))]
  4584. [else (error 'interp-R4 "unrecognized expression")]
  4585. )))
  4586. \end{lstlisting}
  4587. \caption{Interpreter for the $R_4$ language.}
  4588. \label{fig:interp-R4}
  4589. \end{figure}
  4590. \section{Functions in x86}
  4591. \label{sec:fun-x86}
  4592. \margincomment{\tiny Make sure callee save registers are discussed
  4593. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  4594. \margincomment{\tiny Talk about the return address on the
  4595. stack and what callq and retq does.\\ --Jeremy }
  4596. The x86 architecture provides a few features to support the
  4597. implementation of functions. We have already seen that x86 provides
  4598. labels so that one can refer to the location of an instruction, as is
  4599. needed for jump instructions. Labels can also be used to mark the
  4600. beginning of the instructions for a function. Going further, we can
  4601. obtain the address of a label by using the \key{leaq} instruction and
  4602. \key{rip}-relative addressing. For example, the following puts the
  4603. address of the \code{add1} label into the \code{rbx} register.
  4604. \begin{lstlisting}
  4605. leaq add1(%rip), %rbx
  4606. \end{lstlisting}
  4607. In Sections~\ref{sec:x86} and \ref{sec:select-s0} we saw the use of
  4608. the \code{callq} instruction for jumping to a function as specified by
  4609. a label. The use of the instruction changes slightly if the function
  4610. is specified by an address in a register, that is, an \emph{indirect
  4611. function call}. The x86 syntax is to give the register name prefixed
  4612. with an asterisk.
  4613. \begin{lstlisting}
  4614. callq *%rbx
  4615. \end{lstlisting}
  4616. The x86 architecture does not directly support passing arguments to
  4617. functions; instead we use a combination of registers and stack
  4618. locations for passing arguments, following the conventions used by
  4619. \code{gcc} as described by \cite{Matz:2013aa}. Up to six arguments may
  4620. be passed in registers, using the registers \code{rdi}, \code{rsi},
  4621. \code{rdx}, \code{rcx}, \code{r8}, and \code{r9}, in that order. If
  4622. there are more than six arguments, then the rest must be placed on the
  4623. stack, which we call \emph{stack arguments}, which we discuss in later
  4624. paragraphs. The register \code{rax} is for the return value of the
  4625. function.
  4626. Recall from Section~\ref{sec:x86} that the stack is also used for
  4627. local variables and for storing the values of callee-save registers
  4628. (we shall refer to all of these collectively as ``locals''), and that
  4629. at the beginning of a function we move the stack pointer \code{rsp}
  4630. down to make room for them.
  4631. %% We recommend storing the local variables
  4632. %% first and then the callee-save registers, so that the local variables
  4633. %% can be accessed using \code{rbp} the same as before the addition of
  4634. %% functions.
  4635. To make additional room for passing arguments, we shall
  4636. move the stack pointer even further down. We count how many stack
  4637. arguments are needed for each function call that occurs inside the
  4638. body of the function and find their maximum. Adding this number to the
  4639. number of locals gives us how much the \code{rsp} should be moved at
  4640. the beginning of the function. In preparation for a function call, we
  4641. offset from \code{rsp} to set up the stack arguments. We put the first
  4642. stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  4643. so on.
  4644. Upon calling the function, the stack arguments are retrieved by the
  4645. callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  4646. is the location of the first stack argument, \code{24(\%rbp)} is the
  4647. address of the second, and so on. Figure~\ref{fig:call-frames} shows
  4648. the layout of the caller and callee frames. Notice how important it is
  4649. that we correctly compute the maximum number of arguments needed for
  4650. function calls; if that number is too small then the arguments and
  4651. local variables will smash into each other!
  4652. As discussed in Section~\ref{sec:print-x86-reg-alloc}, an x86 function
  4653. is responsible for following conventions regarding the use of
  4654. registers: the caller should assume that all the caller save registers
  4655. get overwritten with arbitrary values by the callee. Thus, the caller
  4656. should either 1) not put values that are live across a call in caller
  4657. save registers, or 2) save and restore values that are live across
  4658. calls. We shall recommend option 1). On the flip side, if the callee
  4659. wants to use a callee save register, the callee must arrange to put
  4660. the original value back in the register prior to returning to the
  4661. caller.
  4662. \begin{figure}[tbp]
  4663. \centering
  4664. \begin{tabular}{r|r|l|l} \hline
  4665. Caller View & Callee View & Contents & Frame \\ \hline
  4666. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  4667. 0(\key{\%rbp}) & & old \key{rbp} \\
  4668. -8(\key{\%rbp}) & & local $1$ \\
  4669. \ldots & & \ldots \\
  4670. $-8k$(\key{\%rbp}) & & local $k$ \\
  4671. & & \\
  4672. $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  4673. & \ldots & \ldots \\
  4674. 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\ \hline
  4675. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  4676. & 0(\key{\%rbp}) & old \key{rbp} \\
  4677. & -8(\key{\%rbp}) & local $1$ \\
  4678. & \ldots & \ldots \\
  4679. & $-8m$(\key{\%rsp}) & local $m$\\ \hline
  4680. \end{tabular}
  4681. \caption{Memory layout of caller and callee frames.}
  4682. \label{fig:call-frames}
  4683. \end{figure}
  4684. \section{The compilation of functions}
  4685. \margincomment{\scriptsize To do: discuss the need to push and
  4686. pop call-live pointers (vectors and functions)
  4687. to the root stack \\ --Jeremy}
  4688. Now that we have a good understanding of functions as they appear in
  4689. $R_4$ and the support for functions in x86, we need to plan the
  4690. changes to our compiler, that is, do we need any new passes and/or do
  4691. we need to change any existing passes? Also, do we need to add new
  4692. kinds of AST nodes to any of the intermediate languages?
  4693. \begin{figure}[tp]
  4694. \centering
  4695. \fbox{
  4696. \begin{minipage}{0.96\textwidth}
  4697. \[
  4698. \begin{array}{lcl}
  4699. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4700. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4701. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4702. &\mid& (\key{function-ref}\, \itm{label})
  4703. \mid \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4704. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4705. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4706. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4707. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4708. (\key{vector-ref}\;\Exp\;\Int)} \\
  4709. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4710. &\mid& (\key{app}\, \Exp \; \Exp^{*}) \\
  4711. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4712. F_1 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4713. \end{array}
  4714. \]
  4715. \end{minipage}
  4716. }
  4717. \caption{The $F_1$ language, an extension of $R_3$
  4718. (Figure~\ref{fig:r3-syntax}).}
  4719. \label{fig:f1-syntax}
  4720. \end{figure}
  4721. To begin with, the syntax of $R_4$ is inconvenient for purposes of
  4722. compilation because it conflates the use of function names and local
  4723. variables and it conflates the application of primitive operations and
  4724. the application of functions. This is a problem because we need to
  4725. compile the use of a function name differently than the use of a local
  4726. variable; we need to use \code{leaq} to move the function name to a
  4727. register. Similarly, the application of a function is going to require
  4728. a complex sequence of instructions, unlike the primitive
  4729. operations. Thus, it is a good idea to create a new pass that changes
  4730. function references from just a symbol $f$ to \code{(function-ref
  4731. $f$)} and that changes function application from \code{($e_0$ $e_1$
  4732. $\ldots$ $e_n$)} to the explicitly tagged AST \code{(app $e_0$ $e_1$
  4733. $\ldots$ $e_n$)}. A good name for this pass is
  4734. \code{reveal-functions} and the output language, $F_1$, is defined in
  4735. Figure~\ref{fig:f1-syntax}. Placing this pass after \code{uniquify} is
  4736. a good idea, because it will make sure that there are no local
  4737. variables and functions that share the same name. On the other hand,
  4738. \code{reveal-functions} needs to come before the \code{flatten} pass
  4739. because \code{flatten} will help us compile \code{function-ref}.
  4740. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  4741. \key{flatten}.
  4742. \begin{figure}[tp]
  4743. \fbox{
  4744. \begin{minipage}{0.96\textwidth}
  4745. \[
  4746. \begin{array}{lcl}
  4747. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  4748. \mid (\key{function-ref}\,\itm{label})\\
  4749. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4750. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4751. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4752. &\mid& \gray{ (\key{vector}\, \Arg^{+})
  4753. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  4754. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) } \\
  4755. &\mid& (\key{app} \,\Arg\,\Arg^{*}) \\
  4756. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4757. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4758. &\mid& \gray{ (\key{initialize}\,\itm{int}\,\itm{int}) }\\
  4759. &\mid& \gray{ \IF{(\key{collection-needed?}\,\itm{int})}{\Stmt^{*}}{\Stmt^{*}} } \\
  4760. &\mid& \gray{ (\key{collect} \,\itm{int}) }
  4761. \mid \gray{ (\key{allocate} \,\itm{int}) }\\
  4762. &\mid& \gray{ (\key{call-live-roots}\,(\Var^{*}) \,\Stmt^{*}) } \\
  4763. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Stmt^{+}) \\
  4764. C_3 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;(\key{defines}\,\Def^{*})\;\Stmt^{+})
  4765. \end{array}
  4766. \]
  4767. \end{minipage}
  4768. }
  4769. \caption{The $C_3$ language, extending $C_2$ with functions.}
  4770. \label{fig:c3-syntax}
  4771. \end{figure}
  4772. Because each \code{function-ref} needs to eventually become an
  4773. \code{leaq} instruction, it first needs to become an assignment
  4774. statement so there is a left-hand side in which to put the
  4775. result. This can be handled easily in the \code{flatten} pass by
  4776. categorizing \code{function-ref} as a complex expression. Then, in
  4777. the \code{select-instructions} pass, an assignment of
  4778. \code{function-ref} becomes a \code{leaq} instruction as follows: \\
  4779. \begin{tabular}{lll}
  4780. \begin{minipage}{0.45\textwidth}
  4781. \begin{lstlisting}
  4782. (assign |$\itm{lhs}$| (function-ref |$f$|))
  4783. \end{lstlisting}
  4784. \end{minipage}
  4785. &
  4786. $\Rightarrow$
  4787. &
  4788. \begin{minipage}{0.4\textwidth}
  4789. \begin{lstlisting}
  4790. (leaq (function-ref |$f$|) |$\itm{lhs}$|)
  4791. \end{lstlisting}
  4792. \end{minipage}
  4793. \end{tabular} \\
  4794. %
  4795. The output of select instructions is a program in the x86$_3$
  4796. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  4797. \begin{figure}[tp]
  4798. \fbox{
  4799. \begin{minipage}{0.96\textwidth}
  4800. \[
  4801. \begin{array}{lcl}
  4802. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4803. \mid (\key{deref}\,\itm{register}\,\Int) \mid (\key{byte-reg}\; \itm{register}) } \\
  4804. &\mid& \gray{ (\key{global-value}\; \itm{name}) } \\
  4805. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4806. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  4807. (\key{subq} \; \Arg\; \Arg) \mid
  4808. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  4809. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  4810. (\key{pushq}\;\Arg) \mid
  4811. (\key{popq}\;\Arg) \mid
  4812. (\key{retq}) } \\
  4813. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4814. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4815. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4816. \mid (\key{jmp} \; \itm{label})
  4817. \mid (\key{j}\itm{cc} \; \itm{label})
  4818. \mid (\key{label} \; \itm{label}) } \\
  4819. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{leaq}\;\Arg\;\Arg)\\
  4820. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{int} \;\itm{info}\; \Stmt^{+})\\
  4821. x86_3 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\;
  4822. (\key{defines}\,\Def^{*}) \; \Instr^{+})
  4823. \end{array}
  4824. \]
  4825. \end{minipage}
  4826. }
  4827. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  4828. \label{fig:x86-3}
  4829. \end{figure}
  4830. Next we consider compiling function definitions. The \code{flatten}
  4831. pass should handle function definitions a lot like a \code{program}
  4832. node; after all, the \code{program} node represents the \code{main}
  4833. function. So the \code{flatten} pass, in addition to flattening the
  4834. body of the function into a sequence of statements, should record the
  4835. local variables in the $\Var^{*}$ field as shown below.
  4836. \begin{lstlisting}
  4837. (define (|$f$| [|\itm{xs}| : |\itm{ts}|]|$^{*}$|) : |\itm{rt}| (|$\Var^{*}$|) |$\Stmt^{+}$|)
  4838. \end{lstlisting}
  4839. In the \code{select-instructions} pass, we need to encode the
  4840. parameter passing in terms of the conventions discussed in
  4841. Section~\ref{sec:fun-x86}. So depending on the length of the parameter
  4842. list \itm{xs}, some of them may be in registers and some of them may
  4843. be on the stack. I recommend generating \code{movq} instructions to
  4844. move the parameters from their registers and stack locations into the
  4845. variables \itm{xs}, then let register allocation handle the assignment
  4846. of those variables to homes. After this pass, the \itm{xs} can be
  4847. added to the list of local variables. As mentioned in
  4848. Section~\ref{sec:fun-x86}, we need to find out how far to move the
  4849. stack pointer to ensure we have enough space for stack arguments in
  4850. all the calls inside the body of this function. This pass is a good
  4851. place to do this and store the result in the \itm{maxStack} field of
  4852. the output \code{define} shown below.
  4853. \begin{lstlisting}
  4854. (define (|$f$|) |\itm{numParams}| (|$\Var^{*}$| |\itm{maxStack}|) |$\Instr^{+}$|)
  4855. \end{lstlisting}
  4856. Next, consider the compilation of function applications, which have
  4857. the following form at the start of \code{select-instructions}.
  4858. \begin{lstlisting}
  4859. (assign |\itm{lhs}| (app |\itm{fun}| |\itm{args}| |$\ldots$|))
  4860. \end{lstlisting}
  4861. In the mirror image of handling the parameters of function
  4862. definitions, some of the arguments \itm{args} need to be moved to the
  4863. argument passing registers and the rest should be moved to the
  4864. appropriate stack locations, as discussed in
  4865. Section~\ref{sec:fun-x86}.
  4866. %% You might want to introduce a new kind of AST node for stack
  4867. %% arguments, \code{(stack-arg $i$)} where $i$ is the index of this
  4868. %% argument with respect to the other stack arguments.
  4869. As you're generating the code for parameter passing, take note of how
  4870. many stack arguments are needed for purposes of computing the
  4871. \itm{maxStack} discussed above.
  4872. Once the instructions for parameter passing have been generated, the
  4873. function call itself can be performed with an indirect function call,
  4874. for which I recommend creating the new instruction
  4875. \code{indirect-callq}. Of course, the return value from the function
  4876. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  4877. \begin{lstlisting}
  4878. (indirect-callq |\itm{fun}|)
  4879. (movq (reg rax) |\itm{lhs}|)
  4880. \end{lstlisting}
  4881. The rest of the passes need only minor modifications to handle the new
  4882. kinds of AST nodes: \code{function-ref}, \code{indirect-callq}, and
  4883. \code{leaq}. Inside \code{uncover-live}, when computing the $W$ set
  4884. (written variables) for an \code{indirect-callq} instruction, I
  4885. recommend including all the caller save registers, which will have the
  4886. affect of making sure that no caller save register actually needs to be
  4887. saved. In \code{patch-instructions}, you should deal with the x86
  4888. idiosyncrasy that the destination argument of \code{leaq} must be a
  4889. register.
  4890. For the \code{print-x86} pass, I recommend the following translations:
  4891. \begin{lstlisting}
  4892. (function-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  4893. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  4894. \end{lstlisting}
  4895. For function definitions, the \code{print-x86} pass should add the
  4896. code for saving and restoring the callee save registers, if you
  4897. haven't already done that.
  4898. \section{An Example Translation}
  4899. Figure~\ref{fig:add-fun} shows an example translation of a simple
  4900. function in $R_4$ to x86. The figure includes the results of the
  4901. \code{flatten} and \code{select-instructions} passes. Can you see any
  4902. ways to improve the translation?
  4903. \begin{figure}[tbp]
  4904. \begin{tabular}{lll}
  4905. \begin{minipage}{0.5\textwidth}
  4906. \begin{lstlisting}
  4907. (program
  4908. (define (add [x : Integer]
  4909. [y : Integer])
  4910. : Integer (+ x y))
  4911. (add 40 2))
  4912. \end{lstlisting}
  4913. $\Downarrow$
  4914. \begin{lstlisting}
  4915. (program (t.1 t.2)
  4916. (defines
  4917. (define (add.1 [x.1 : Integer]
  4918. [y.1 : Integer])
  4919. : Integer (t.3)
  4920. (assign t.3 (+ x.1 y.1))
  4921. (return t.3)))
  4922. (assign t.1 (function-ref add.1))
  4923. (assign t.2 (app t.1 40 2))
  4924. (return t.2))
  4925. \end{lstlisting}
  4926. $\Downarrow$
  4927. \begin{lstlisting}
  4928. (program ((rs.1 t.1 t.2) 0)
  4929. (type Integer)
  4930. (defines
  4931. (define (add28545) 3
  4932. ((rs.2 x.2 y.3 t.4) 0)
  4933. (movq (reg rdi) (var rs.2))
  4934. (movq (reg rsi) (var x.2))
  4935. (movq (reg rdx) (var y.3))
  4936. (movq (var x.2) (var t.4))
  4937. (addq (var y.3) (var t.4))
  4938. (movq (var t.4) (reg rax))))
  4939. (movq (int 16384) (reg rdi))
  4940. (movq (int 16) (reg rsi))
  4941. (callq initialize)
  4942. (movq (global-value rootstack_begin)
  4943. (var rs.1))
  4944. (leaq (function-ref add28545) (var t.1))
  4945. (movq (var rs.1) (reg rdi))
  4946. (movq (int 40) (reg rsi))
  4947. (movq (int 2) (reg rdx))
  4948. (indirect-callq (var t.1))
  4949. (movq (reg rax) (var t.2))
  4950. (movq (var t.2) (reg rax)))
  4951. \end{lstlisting}
  4952. \end{minipage}
  4953. &
  4954. \begin{minipage}{0.4\textwidth}
  4955. $\Downarrow$
  4956. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4957. .globl add28545
  4958. add28545:
  4959. pushq %rbp
  4960. movq %rsp, %rbp
  4961. pushq %r15
  4962. pushq %r14
  4963. pushq %r13
  4964. pushq %r12
  4965. pushq %rbx
  4966. subq $8, %rsp
  4967. movq %rdi, %rbx
  4968. movq %rsi, %rbx
  4969. movq %rdx, %rcx
  4970. addq %rcx, %rbx
  4971. movq %rbx, %rax
  4972. addq $8, %rsp
  4973. popq %rbx
  4974. popq %r12
  4975. popq %r13
  4976. popq %r14
  4977. popq %r15
  4978. popq %rbp
  4979. retq
  4980. .globl _main
  4981. _main:
  4982. pushq %rbp
  4983. movq %rsp, %rbp
  4984. pushq %r15
  4985. pushq %r14
  4986. pushq %r13
  4987. pushq %r12
  4988. pushq %rbx
  4989. subq $8, %rsp
  4990. movq $16384, %rdi
  4991. movq $16, %rsi
  4992. callq _initialize
  4993. movq _rootstack_begin(%rip), %rcx
  4994. leaq add28545(%rip), %rbx
  4995. movq %rcx, %rdi
  4996. movq $40, %rsi
  4997. movq $2, %rdx
  4998. callq *%rbx
  4999. movq %rax, %rbx
  5000. movq %rbx, %rax
  5001. movq %rax, %rdi
  5002. callq _print_int
  5003. movq $0, %rax
  5004. addq $8, %rsp
  5005. popq %rbx
  5006. popq %r12
  5007. popq %r13
  5008. popq %r14
  5009. popq %r15
  5010. popq %rbp
  5011. retq
  5012. \end{lstlisting}
  5013. \end{minipage}
  5014. \end{tabular}
  5015. \caption{Example compilation of a simple function to x86.}
  5016. \label{fig:add-fun}
  5017. \end{figure}
  5018. \begin{exercise}\normalfont
  5019. Expand your compiler to handle $R_4$ as outlined in this section.
  5020. Create 5 new programs that use functions, including examples that pass
  5021. functions and return functions from other functions, and test your
  5022. compiler on these new programs and all of your previously created test
  5023. programs.
  5024. \end{exercise}
  5025. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5026. \chapter{Lexically Scoped Functions}
  5027. \label{ch:lambdas}
  5028. This chapter studies lexically scoped functions as they appear in
  5029. functional languages such as Racket. By lexical scoping we mean that a
  5030. function's body may refer to variables whose binding site is outside
  5031. of the function, in an enclosing scope.
  5032. %
  5033. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5034. anonymous function defined using the \key{lambda} form. The body of
  5035. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5036. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5037. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5038. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5039. returned from the function \code{f}. Below the definition of \code{f},
  5040. we have two calls to \code{f} with different arguments for \code{x},
  5041. first \code{5} then \code{3}. The functions returned from \code{f} are
  5042. bound to variables \code{g} and \code{h}. Even though these two
  5043. functions were created by the same \code{lambda}, they are really
  5044. different functions because they use different values for
  5045. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5046. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5047. the result of this program is \code{42}.
  5048. \begin{figure}[btp]
  5049. \begin{lstlisting}
  5050. (define (f [x : Integer]) : (Integer -> Integer)
  5051. (let ([y 4])
  5052. (lambda: ([z : Integer]) : Integer
  5053. (+ x (+ y z)))))
  5054. (let ([g (f 5)])
  5055. (let ([h (f 3)])
  5056. (+ (g 11) (h 15))))
  5057. \end{lstlisting}
  5058. \caption{Example of a lexically scoped function.}
  5059. \label{fig:lexical-scoping}
  5060. \end{figure}
  5061. \section{The $R_5$ Language}
  5062. The syntax for this language with anonymous functions and lexical
  5063. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5064. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5065. for function application. In this chapter we shall descibe how to
  5066. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5067. into a combination of functions (as in $R_4$) and tuples (as in
  5068. $R_3$).
  5069. \begin{figure}[tp]
  5070. \centering
  5071. \fbox{
  5072. \begin{minipage}{0.96\textwidth}
  5073. \[
  5074. \begin{array}{lcl}
  5075. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5076. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5077. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5078. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5079. \mid (\key{+} \; \Exp\;\Exp)} \\
  5080. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}
  5081. \mid \key{\#t} \mid \key{\#f} \mid
  5082. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5083. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5084. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5085. (\key{vector-ref}\;\Exp\;\Int)} \\
  5086. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5087. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5088. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5089. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5090. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5091. \end{array}
  5092. \]
  5093. \end{minipage}
  5094. }
  5095. \caption{Syntax of $R_5$, extending $R_4$ with \key{lambda}.}
  5096. \label{fig:r5-syntax}
  5097. \end{figure}
  5098. We shall describe how to compile $R_5$ to $R_4$, replacing anonymous
  5099. functions with top-level function definitions. However, our compiler
  5100. must provide special treatment to variable occurences such as \code{x}
  5101. and \code{y} in the body of the \code{lambda} of
  5102. Figure~\ref{fig:lexical-scoping}, for the functions of $R_4$ may not
  5103. refer to variables defined outside the function. To identify such
  5104. variable occurences, we review the standard notion of free variable.
  5105. \begin{definition}
  5106. A variable is \emph{free with respect to an expression} $e$ if the
  5107. variable occurs inside $e$ but does not have an enclosing binding in
  5108. $e$.
  5109. \end{definition}
  5110. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5111. free with respect to the expression \code{(+ x (+ y z))}. On the
  5112. other hand, only \code{x} and \code{y} are free with respect to the
  5113. following expression becuase \code{z} is bound by the \code{lambda}.
  5114. \begin{lstlisting}
  5115. (lambda: ([z : Integer]) : Integer
  5116. (+ x (+ y z)))
  5117. \end{lstlisting}
  5118. Once we have identified the free variables of a \code{lambda}, we need
  5119. to arrange for some way to transport, at runtime, the values of those
  5120. variables from the point where the \code{lambda} was created to the
  5121. point where the \code{lambda} is applied. Referring again to
  5122. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5123. needs to be used in the application of \code{g} to \code{11}, but the
  5124. binding of \code{x} to \code{3} needs to be used in the application of
  5125. \code{h} to \code{15}. The solution is to bundle the values of the
  5126. free variables together with the function pointer for the lambda's
  5127. code into a data structure called a \emph{closure}. Fortunately, we
  5128. already have the appropriate ingredients to make closures,
  5129. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  5130. gave us function pointers. The function pointer shall reside at index
  5131. $0$ and the values for free variables will fill in the rest of the
  5132. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  5133. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  5134. Because the two closures came from the same \key{lambda}, they share
  5135. the same code but differ in the values for free variable \code{x}.
  5136. \begin{figure}[tbp]
  5137. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  5138. \caption{Example closure representation for the \key{lambda}'s
  5139. in Figure~\ref{fig:lexical-scoping}.}
  5140. \label{fig:closures}
  5141. \end{figure}
  5142. \section{Interpreting $R_5$}
  5143. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5144. $R_5$. There are several things to worth noting. First, and most
  5145. importantly, the match clause for \key{lambda} saves the current
  5146. environment inside the returned \key{lambda}. Then the clause for
  5147. \key{app} uses the environment from the \key{lambda}, the
  5148. \code{lam-env}, when interpreting the body of the \key{lambda}. Of
  5149. course, the \code{lam-env} environment is extending with the mapping
  5150. parameters to argument values. To enable mutual recursion and allow a
  5151. unified handling of functions created with \key{lambda} and with
  5152. \key{define}, the match clause for \key{program} includes a second
  5153. pass over the top-level functions to set their environments to be the
  5154. top-level environment.
  5155. \begin{figure}[tbp]
  5156. \begin{lstlisting}
  5157. (define (interp-R5 env)
  5158. (lambda (ast)
  5159. (match ast
  5160. ...
  5161. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5162. `(lambda ,xs ,body ,env)]
  5163. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5164. (mcons f `(lambda ,xs ,body))]
  5165. [`(program ,defs ... ,body)
  5166. (let ([top-level (map (interp-R5 '()) defs)])
  5167. (for/list ([b top-level])
  5168. (set-mcdr! b (match (mcdr b)
  5169. [`(lambda ,xs ,body)
  5170. `(lambda ,xs ,body ,top-level)])))
  5171. ((interp-R5 top-level) body))]
  5172. [`(,fun ,args ...)
  5173. (define arg-vals (map (interp-R5 env) args))
  5174. (define fun-val ((interp-R5 env) fun))
  5175. (match fun-val
  5176. [`(lambda (,xs ...) ,body ,lam-env)
  5177. (define new-env (append (map cons xs arg-vals) lam-env))
  5178. ((interp-R5 new-env) body)]
  5179. [else (error "interp-R5, expected function, not" fun-val)])]
  5180. )))
  5181. \end{lstlisting}
  5182. \caption{Interpreter for $R_5$.}
  5183. \label{fig:interp-R5}
  5184. \end{figure}
  5185. \section{Type Checking $R_5$}
  5186. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5187. \key{lambda} form. The body of the \key{lambda} is checked in an
  5188. environment that includes the current environment (because it is
  5189. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5190. require the body's type to match the declared return type.
  5191. \begin{figure}[tbp]
  5192. \begin{lstlisting}
  5193. (define (typecheck-R5 env)
  5194. (lambda (e)
  5195. (match e
  5196. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5197. (define new-env (append (map cons xs Ts) env))
  5198. (define bodyT ((typecheck-R5 new-env) body))
  5199. (cond [(equal? rT bodyT)
  5200. `(,@Ts -> ,rT)]
  5201. [else
  5202. (error "mismatch in return type" bodyT rT)])]
  5203. ...
  5204. )))
  5205. \end{lstlisting}
  5206. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5207. \label{fig:typecheck-R5}
  5208. \end{figure}
  5209. \section{Closure Conversion}
  5210. The compiling of lexically-scoped functions into C-style functions is
  5211. accomplished in the pass \code{convert-to-closures} that comes after
  5212. \code{reveal-functions} and before flatten. This pass needs to treat
  5213. regular function calls differently from applying primitive operators,
  5214. and \code{reveal-functions} differentiates those two cases for us.
  5215. As usual, we shall implement the pass as a recursive function over the
  5216. AST. All of the action is in the clauses for \key{lambda} and
  5217. \key{app} (function application). We transform a \key{lambda}
  5218. expression into an expression that creates a closure, that is, creates
  5219. a vector whose first element is a function pointer and the rest of the
  5220. elements are the free variables of the \key{lambda}. The \itm{name}
  5221. is a unique symbol generated to identify the function.
  5222. \begin{tabular}{lll}
  5223. \begin{minipage}{0.4\textwidth}
  5224. \begin{lstlisting}
  5225. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5226. \end{lstlisting}
  5227. \end{minipage}
  5228. &
  5229. $\Rightarrow$
  5230. &
  5231. \begin{minipage}{0.4\textwidth}
  5232. \begin{lstlisting}
  5233. (vector |\itm{name}| |\itm{fvs}| ...)
  5234. \end{lstlisting}
  5235. \end{minipage}
  5236. \end{tabular} \\
  5237. %
  5238. In addition to transforming each \key{lambda} into a \key{vector}, we
  5239. must create a top-level function definition for each \key{lambda}, as
  5240. shown below.
  5241. \begin{lstlisting}
  5242. (define (|\itm{name}| [clos : _] |\itm{ps}| ...)
  5243. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5244. ...
  5245. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5246. |\itm{body'}|)...))
  5247. \end{lstlisting}
  5248. The \code{clos} parameter refers to the closure whereas $\itm{ps}$ are
  5249. the normal parameters of the \key{lambda}. The sequence of \key{let}
  5250. forms being the free variables to their values obtained from the
  5251. closure.
  5252. We transform function application into code that retreives the
  5253. function pointer from the closure and then calls the function, passing
  5254. in the closure as the first argument. We bind $e'$ to a temporary
  5255. variable to avoid code duplication.
  5256. \begin{tabular}{lll}
  5257. \begin{minipage}{0.3\textwidth}
  5258. \begin{lstlisting}
  5259. (app |$e$| |\itm{es}| ...)
  5260. \end{lstlisting}
  5261. \end{minipage}
  5262. &
  5263. $\Rightarrow$
  5264. &
  5265. \begin{minipage}{0.5\textwidth}
  5266. \begin{lstlisting}
  5267. (let ([|\itm{tmp}| |$e'$|])
  5268. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5269. \end{lstlisting}
  5270. \end{minipage}
  5271. \end{tabular} \\
  5272. There is also the question of what to do with top-level function
  5273. definitions. To maintain a uniform translation of function
  5274. application, we turn function references into closures.
  5275. \begin{tabular}{lll}
  5276. \begin{minipage}{0.3\textwidth}
  5277. \begin{lstlisting}
  5278. (function-ref |$f$|)
  5279. \end{lstlisting}
  5280. \end{minipage}
  5281. &
  5282. $\Rightarrow$
  5283. &
  5284. \begin{minipage}{0.5\textwidth}
  5285. \begin{lstlisting}
  5286. (vector (function-ref |$f$|))
  5287. \end{lstlisting}
  5288. \end{minipage}
  5289. \end{tabular} \\
  5290. %
  5291. The top-level function definitions need to be updated as well to take
  5292. an extra closure parameter.
  5293. \section{An Example Translation}
  5294. \label{sec:example-lambda}
  5295. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  5296. conversion for the example program demonstrating lexical scoping that
  5297. we discussed at the beginning of this chapter.
  5298. \begin{figure}[h]
  5299. \begin{minipage}{0.8\textwidth}
  5300. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5301. (program
  5302. (define (f [x : Integer]) : (Integer -> Integer)
  5303. (let ([y 4])
  5304. (lambda: ([z : Integer]) : Integer
  5305. (+ x (+ y z)))))
  5306. (let ([g (f 5)])
  5307. (let ([h (f 3)])
  5308. (+ (g 11) (h 15)))))
  5309. \end{lstlisting}
  5310. $\Downarrow$
  5311. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5312. (program (type Integer)
  5313. (define (f (x : Integer)) : (Integer -> Integer)
  5314. (let ((y 4))
  5315. (lambda: ((z : Integer)) : Integer
  5316. (+ x (+ y z)))))
  5317. (let ((g (app (function-ref f) 5)))
  5318. (let ((h (app (function-ref f) 3)))
  5319. (+ (app g 11) (app h 15)))))
  5320. \end{lstlisting}
  5321. $\Downarrow$
  5322. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5323. (program (type Integer)
  5324. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  5325. (let ((y 4))
  5326. (vector (function-ref lam.1) x y)))
  5327. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  5328. (let ((x (vector-ref clos.2 1)))
  5329. (let ((y (vector-ref clos.2 2)))
  5330. (+ x (+ y z)))))
  5331. (let ((g (let ((t.1 (vector (function-ref f))))
  5332. (app (vector-ref t.1 0) t.1 5))))
  5333. (let ((h (let ((t.2 (vector (function-ref f))))
  5334. (app (vector-ref t.2 0) t.2 3))))
  5335. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  5336. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  5337. \end{lstlisting}
  5338. \end{minipage}
  5339. \caption{Example of closure conversion.}
  5340. \label{fig:lexical-functions-example}
  5341. \end{figure}
  5342. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5343. \chapter{Dynamic Typing}
  5344. \label{ch:type-dynamic}
  5345. In this chapter we discuss the compilation of a dynamically typed
  5346. language, named $R_7$, that is a subset of the Racket language. (In
  5347. the previous chapters we have studied subsets of the \emph{Typed}
  5348. Racket language.) In dynamically typed languages, an expression may
  5349. produce values of differing type. Consider the following example with
  5350. a conditional expression that may return a Boolean or an integer
  5351. depending on the input to the program.
  5352. \begin{lstlisting}
  5353. (not (if (eq? (read) 1) #f 0))
  5354. \end{lstlisting}
  5355. Languages that allow expressions to produce different kinds of values
  5356. are called \emph{polymorphic}, and there are many kinds of
  5357. polymorphism, such as subtype polymorphism~\citep{Cardelli:1985kx} and
  5358. parametric polymorphism (Chapter~\ref{ch:parametric-polymorphism}).
  5359. Another characteristic of dynamically typed languages is that
  5360. primitive operations, such as \code{not}, are often defined to operate
  5361. on many different types of values. In fact, in Racket, the \code{not}
  5362. operator produces a result for any kind of value: given \code{\#f} it
  5363. returns \code{\#t} and given anything else it returns \code{\#f}.
  5364. Furthermore, even when primitive operations restrict their inputs to
  5365. values of a certain type, this restriction is enforced at runtime
  5366. instead of during compilation. For example, the following vector
  5367. reference results in a run-time contract violation.
  5368. \begin{lstlisting}
  5369. (vector-ref (vector 42) #t)
  5370. \end{lstlisting}
  5371. Let us consider how we might compile untyped Racket to x86, thinking
  5372. about the first example above. Our bit-level representation of the
  5373. Boolean \code{\#f} is zero and similarly for the integer \code{0}.
  5374. However, \code{(not \#f)} should produce \code{\#t} whereas \code{(not
  5375. 0)} should produce \code{\#f}. Furthermore, the behavior of
  5376. \code{not}, in general, cannot be determined at compile time, but
  5377. depends on the runtime type of its input, as in the example above that
  5378. depends on the result of \code{(read)}.
  5379. The way around this problem is to include information about a value's
  5380. runtime type in the value itself, so that this information can be
  5381. inspected by operators such as \code{not}. In particular, we shall
  5382. steal the 3 right-most bits from our 64-bit values to encode the
  5383. runtime type. We shall use $001$ to identify integers, $100$ for
  5384. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  5385. void value. We shall refer to these 3 bits as the \emph{tag} and we
  5386. define the following auxilliary function.
  5387. \begin{align*}
  5388. \itm{tagof}(\key{Integer}) &= 001 \\
  5389. \itm{tagof}(\key{Boolean}) &= 100 \\
  5390. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  5391. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  5392. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  5393. \itm{tagof}(\key{Void}) &= 101
  5394. \end{align*}
  5395. (We shall say more about the new \key{Vectorof} type shortly.)
  5396. This stealing of 3 bits comes at some
  5397. price: our integers are reduced to ranging from $-2^{60}$ to
  5398. $2^{60}$. The stealing does not adversely affect vectors and
  5399. procedures because those values are addresses, and our addresses are
  5400. 8-byte aligned so the rightmost 3 bits are unused, they are always
  5401. $000$. Thus, we do not lose information by overwriting the rightmost 3
  5402. bits with the tag and we can simply zero-out the tag to recover the
  5403. original address.
  5404. In some sense, these tagged values are a new kind of value. Indeed,
  5405. we can extend our \emph{typed} language with tagged values by adding a
  5406. new type to classify them, called \key{Any}, and with operations for
  5407. creating and using tagged values, creating the $R_6$ language defined
  5408. in Section~\ref{sec:r6-lang}. Thus, $R_6$ provides the fundamental
  5409. support for polymorphism and runtime types that we need to support
  5410. dynamic typing.
  5411. We shall implement our untyped language $R_7$ by compiling it to
  5412. $R_6$. We define $R_7$ in Section~\ref{sec:r7-lang} and describe the
  5413. compilation of $R_6$ and $R_7$ in the remainder of this chapter.
  5414. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  5415. \label{sec:r6-lang}
  5416. \begin{figure}[tp]
  5417. \centering
  5418. \fbox{
  5419. \begin{minipage}{0.97\textwidth}
  5420. \[
  5421. \begin{array}{lcl}
  5422. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5423. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  5424. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  5425. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  5426. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  5427. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5428. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5429. \mid (\key{+} \; \Exp\;\Exp)} \\
  5430. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  5431. &\mid& \gray{\key{\#t} \mid \key{\#f} \mid
  5432. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5433. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5434. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5435. (\key{vector-ref}\;\Exp\;\Int)} \\
  5436. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5437. &\mid& \gray{(\Exp \; \Exp^{*})
  5438. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5439. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  5440. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  5441. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  5442. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5443. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5444. \end{array}
  5445. \]
  5446. \end{minipage}
  5447. }
  5448. \caption{Syntax of $R_6$, extending $R_5$ with \key{Any}.}
  5449. \label{fig:r6-syntax}
  5450. \end{figure}
  5451. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  5452. $(\key{inject}\; e\; T)$ form converts the value produced by
  5453. expression $e$ of type $T$ into a tagged value. The
  5454. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  5455. expression $e$ into a value of type $T$ or else halts the program if
  5456. the type tag does not match $T$. Note that in both \key{inject} and
  5457. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  5458. which simplifies the implementation and corresponds with what is
  5459. needed for compiling untyped Racket. The type predicates,
  5460. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  5461. if the tag corresponds to the predicate, and return \key{\#t}
  5462. otherwise.
  5463. %
  5464. The type checker for $R_6$ is given in Figure~\ref{fig:typecheck-R6}.
  5465. \begin{figure}[tbp]
  5466. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5467. (define type-predicates
  5468. (set 'boolean? 'integer? 'vector? 'procedure?))
  5469. (define (typecheck-R6 env)
  5470. (lambda (e)
  5471. (define recur (typecheck-R6 env))
  5472. (match e
  5473. [`(inject ,(app recur new-e e-ty) ,ty)
  5474. (cond
  5475. [(equal? e-ty ty)
  5476. (values `(inject ,new-e ,ty) 'Any)]
  5477. [else
  5478. (error "inject expected ~a to have type ~a" e ty)])]
  5479. [`(project ,(app recur new-e e-ty) ,ty)
  5480. (cond
  5481. [(equal? e-ty 'Any)
  5482. (values `(project ,new-e ,ty) ty)]
  5483. [else
  5484. (error "project expected ~a to have type Any" e)])]
  5485. [`(,pred ,e) #:when (set-member? type-predicates pred)
  5486. (define-values (new-e e-ty) (recur e))
  5487. (cond
  5488. [(equal? e-ty 'Any)
  5489. (values `(,pred ,new-e) 'Boolean)]
  5490. [else
  5491. (error "predicate expected arg of type Any, not" e-ty)])]
  5492. [`(vector-ref ,(app recur e t) ,i)
  5493. (match t
  5494. [`(Vector ,ts ...) ...]
  5495. [`(Vectorof ,t)
  5496. (unless (exact-nonnegative-integer? i)
  5497. (error 'type-check "invalid index ~a" i))
  5498. (values `(vector-ref ,e ,i) t)]
  5499. [else (error "expected a vector in vector-ref, not" t)])]
  5500. [`(vector-set! ,(app recur e-vec^ t-vec) ,i
  5501. ,(app recur e-arg^ t-arg))
  5502. (match t-vec
  5503. [`(Vector ,ts ...) ...]
  5504. [`(Vectorof ,t)
  5505. (unless (exact-nonnegative-integer? i)
  5506. (error 'type-check "invalid index ~a" i))
  5507. (unless (equal? t t-arg)
  5508. (error 'type-check "type mismatch in vector-set! ~a ~a"
  5509. t t-arg))
  5510. (values `(vector-set! ,e-vec^
  5511. ,i
  5512. ,e-arg^) 'Void)]
  5513. [else (error 'type-check
  5514. "expected a vector in vector-set!, not ~a"
  5515. t-vec)])]
  5516. ...
  5517. )))
  5518. \end{lstlisting}
  5519. \caption{Type checker for the $R_6$ language.}
  5520. \label{fig:typecheck-R6}
  5521. \end{figure}
  5522. % to do: add rules for vector-ref, etc. for Vectorof
  5523. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  5524. Figure~\ref{fig:interp-R6} shows the definitional interpreter
  5525. for $R_6$.
  5526. \begin{figure}[tbp]
  5527. \begin{lstlisting}
  5528. (define primitives (set 'boolean? ...))
  5529. (define (interp-op op)
  5530. (match op
  5531. ['boolean? (lambda (v)
  5532. (match v
  5533. [`(tagged ,v1 Boolean) #t]
  5534. [else #f]))]
  5535. ...))
  5536. (define (interp-R6 env)
  5537. (lambda (ast)
  5538. (match ast
  5539. [`(inject ,e ,t)
  5540. `(tagged ,((interp-R6 env) e) ,t)]
  5541. [`(project ,e ,t2)
  5542. (define v ((interp-R6 env) e))
  5543. (match v
  5544. [`(tagged ,v1 ,t1)
  5545. (cond [(equal? t1 t2)
  5546. v1]
  5547. [else
  5548. (error "in project, type mismatch" t1 t2)])]
  5549. [else
  5550. (error "in project, expected tagged value" v)])]
  5551. ...)))
  5552. \end{lstlisting}
  5553. \caption{Interpreter for $R_6$.}
  5554. \label{fig:interp-R6}
  5555. \end{figure}
  5556. \section{The $R_7$ Language: Untyped Racket}
  5557. \label{sec:r7-lang}
  5558. \begin{figure}[tp]
  5559. \centering
  5560. \fbox{
  5561. \begin{minipage}{0.97\textwidth}
  5562. \[
  5563. \begin{array}{rcl}
  5564. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5565. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  5566. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  5567. &\mid& \key{\#t} \mid \key{\#f} \mid
  5568. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  5569. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  5570. &\mid& (\key{vector}\;\Exp^{+}) \mid
  5571. (\key{vector-ref}\;\Exp\;\Exp) \\
  5572. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  5573. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  5574. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  5575. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  5576. \end{array}
  5577. \]
  5578. \end{minipage}
  5579. }
  5580. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  5581. \label{fig:r7-syntax}
  5582. \end{figure}
  5583. The syntax of $R_7$, our subset of Racket, is defined in
  5584. Figure~\ref{fig:r7-syntax}.
  5585. %
  5586. The definitional interpreter for $R_7$ is given in
  5587. Figure~\ref{fig:interp-R7}.
  5588. \begin{figure}[tbp]
  5589. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5590. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  5591. (define (valid-op? op) (member op '(+ - and or not)))
  5592. (define (interp-r7 env)
  5593. (lambda (ast)
  5594. (define recur (interp-r7 env))
  5595. (match ast
  5596. [(? symbol?) (lookup ast env)]
  5597. [(? integer?) `(inject ,ast Integer)]
  5598. [#t `(inject #t Boolean)]
  5599. [#f `(inject #f Boolean)]
  5600. [`(read) `(inject ,(read-fixnum) Integer)]
  5601. [`(lambda (,xs ...) ,body)
  5602. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  5603. [`(define (,f ,xs ...) ,body)
  5604. (mcons f `(lambda ,xs ,body))]
  5605. [`(program ,ds ... ,body)
  5606. (let ([top-level (map (interp-r7 '()) ds)])
  5607. (for/list ([b top-level])
  5608. (set-mcdr! b (match (mcdr b)
  5609. [`(lambda ,xs ,body)
  5610. `(inject (lambda ,xs ,body ,top-level)
  5611. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  5612. ((interp-r7 top-level) body))]
  5613. [`(vector ,(app recur elts) ...)
  5614. (define tys (map get-tagged-type elts))
  5615. `(inject ,(apply vector elts) (Vector ,@tys))]
  5616. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  5617. (match v1
  5618. [`(inject ,vec ,ty)
  5619. (vector-set! vec n v2)
  5620. `(inject (void) Void)])]
  5621. [`(vector-ref ,(app recur v) ,n)
  5622. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  5623. [`(let ([,x ,(app recur v)]) ,body)
  5624. ((interp-r7 (cons (cons x v) env)) body)]
  5625. [`(,op ,es ...) #:when (valid-op? op)
  5626. (interp-r7-op op (map recur es))]
  5627. [`(eq? ,(app recur l) ,(app recur r))
  5628. `(inject ,(equal? l r) Boolean)]
  5629. [`(if ,(app recur q) ,t ,f)
  5630. (match q
  5631. [`(inject #f Boolean) (recur f)]
  5632. [else (recur t)])]
  5633. [`(,(app recur f-val) ,(app recur vs) ...)
  5634. (match f-val
  5635. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  5636. (define new-env (append (map cons xs vs) lam-env))
  5637. ((interp-r7 new-env) body)]
  5638. [else (error "interp-r7, expected function, not" f-val)])])))
  5639. \end{lstlisting}
  5640. \caption{Interpreter for the $R_7$ language.}
  5641. \label{fig:interp-R7}
  5642. \end{figure}
  5643. \section{Compiling $R_6$}
  5644. \label{sec:compile-r6}
  5645. Most of the compiler passes only require straightforward changes. The
  5646. interesting part is in instruction selection.
  5647. \paragraph{Inject}
  5648. We recommend compiling an \key{inject} as follows if the type is
  5649. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  5650. destination to the left by the number of bits specified by the source
  5651. ($2$) and it preserves the sign of the integer. We use the \key{orq}
  5652. instruction to combine the tag and the value to form the tagged value.
  5653. \\
  5654. \begin{tabular}{lll}
  5655. \begin{minipage}{0.4\textwidth}
  5656. \begin{lstlisting}
  5657. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5658. \end{lstlisting}
  5659. \end{minipage}
  5660. &
  5661. $\Rightarrow$
  5662. &
  5663. \begin{minipage}{0.5\textwidth}
  5664. \begin{lstlisting}
  5665. (movq |$e'$| |\itm{lhs}'|)
  5666. (salq (int 2) |\itm{lhs}'|)
  5667. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5668. \end{lstlisting}
  5669. \end{minipage}
  5670. \end{tabular} \\
  5671. The instruction selection for vectors and procedures is different
  5672. because their is no need to shift them to the left. The rightmost 3
  5673. bits are already zeros as described above. So we combine the value and
  5674. the tag using
  5675. \key{orq}. \\
  5676. \begin{tabular}{lll}
  5677. \begin{minipage}{0.4\textwidth}
  5678. \begin{lstlisting}
  5679. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5680. \end{lstlisting}
  5681. \end{minipage}
  5682. &
  5683. $\Rightarrow$
  5684. &
  5685. \begin{minipage}{0.5\textwidth}
  5686. \begin{lstlisting}
  5687. (movq |$e'$| |\itm{lhs}'|)
  5688. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5689. \end{lstlisting}
  5690. \end{minipage}
  5691. \end{tabular} \\
  5692. \paragraph{Project}
  5693. The instruction selection for \key{project} is a bit more involved.
  5694. Like \key{inject}, the instructions are different depending on whether
  5695. the type $T$ is a pointer (vector or procedure) or not (Integer or
  5696. Boolean). The following shows the instruction selection for Integer
  5697. and Boolean. We first check to see if the tag on the tagged value
  5698. matches the tag of the target type $T$. If not, we halt the program by
  5699. calling the \code{exit} function. If we have a match, we need to
  5700. produce an untagged value by shifting it to the right by 2 bits.
  5701. %
  5702. \\
  5703. \begin{tabular}{lll}
  5704. \begin{minipage}{0.4\textwidth}
  5705. \begin{lstlisting}
  5706. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5707. \end{lstlisting}
  5708. \end{minipage}
  5709. &
  5710. $\Rightarrow$
  5711. &
  5712. \begin{minipage}{0.5\textwidth}
  5713. \begin{lstlisting}
  5714. (movq |$e'$| |\itm{lhs}'|)
  5715. (andq (int 3) |\itm{lhs}'|)
  5716. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5717. ((movq |$e'$| |\itm{lhs}'|)
  5718. (sarq (int 2) |\itm{lhs}'|))
  5719. ((callq exit)))
  5720. \end{lstlisting}
  5721. \end{minipage}
  5722. \end{tabular} \\
  5723. %
  5724. The case for vectors and procedures begins in a similar way, checking
  5725. that the runtime tag matches the target type $T$ and exiting if there
  5726. is a mismatch. However, the way in which we convert the tagged value
  5727. to a value is different, as there is no need to shift. Instead we need
  5728. to zero-out the rightmost 2 bits. We accomplish this by creating the
  5729. bit pattern $\ldots 0011$, applying \code{notq} to obtain $\ldots
  5730. 1100$, and then applying \code{andq} with the tagged value get the
  5731. desired result. \\
  5732. %
  5733. \begin{tabular}{lll}
  5734. \begin{minipage}{0.4\textwidth}
  5735. \begin{lstlisting}
  5736. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5737. \end{lstlisting}
  5738. \end{minipage}
  5739. &
  5740. $\Rightarrow$
  5741. &
  5742. \begin{minipage}{0.5\textwidth}
  5743. \begin{lstlisting}
  5744. (movq |$e'$| |\itm{lhs}'|)
  5745. (andq (int 3) |\itm{lhs}'|)
  5746. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5747. ((movq (int 3) |\itm{lhs}'|)
  5748. (notq |\itm{lhs}'|)
  5749. (andq |$e'$| |\itm{lhs}'|))
  5750. ((callq exit)))
  5751. \end{lstlisting}
  5752. \end{minipage}
  5753. \end{tabular} \\
  5754. \paragraph{Type Predicates} We leave it to the reader to
  5755. devise a sequence of instructions to implement the type predicates
  5756. \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  5757. \section{Compiling $R_7$ to $R_6$}
  5758. \label{sec:compile-r7}
  5759. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  5760. $R_7$ forms into $R_6$. An important invariant of this pass is that
  5761. given a subexpression $e$ of $R_7$, the pass will produce an
  5762. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  5763. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  5764. the Boolean \code{\#t}, which must be injected to produce an
  5765. expression of type \key{Any}.
  5766. %
  5767. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  5768. addition, is representative of compilation for many operations: the
  5769. arguments have type \key{Any} and must be projected to \key{Integer}
  5770. before the addition can be performed.
  5771. %
  5772. The compilation of \key{lambda} (third row of
  5773. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  5774. produce type annotations, we simply use \key{Any}.
  5775. %
  5776. The compilation of \code{if}, \code{eq?}, and \code{and} all
  5777. demonstrate how this pass has to account for some differences in
  5778. behavior between $R_7$ and $R_6$. The $R_7$ language is more
  5779. permissive than $R_6$ regarding what kind of values can be used in
  5780. various places. For example, the condition of an \key{if} does not
  5781. have to be a Boolean. Similarly, the arguments of \key{and} do not
  5782. need to be Boolean. For \key{eq?}, the arguments need not be of the
  5783. same type.
  5784. \begin{figure}[tbp]
  5785. \centering
  5786. \begin{tabular}{|lll|} \hline
  5787. \begin{minipage}{0.25\textwidth}
  5788. \begin{lstlisting}
  5789. #t
  5790. \end{lstlisting}
  5791. \end{minipage}
  5792. &
  5793. $\Rightarrow$
  5794. &
  5795. \begin{minipage}{0.6\textwidth}
  5796. \begin{lstlisting}
  5797. (inject #t Boolean)
  5798. \end{lstlisting}
  5799. \end{minipage}
  5800. \\[2ex]\hline
  5801. \begin{minipage}{0.25\textwidth}
  5802. \begin{lstlisting}
  5803. (+ |$e_1$| |$e_2$|)
  5804. \end{lstlisting}
  5805. \end{minipage}
  5806. &
  5807. $\Rightarrow$
  5808. &
  5809. \begin{minipage}{0.6\textwidth}
  5810. \begin{lstlisting}
  5811. (inject
  5812. (+ (project |$e'_1$| Integer)
  5813. (project |$e'_2$| Integer))
  5814. Integer)
  5815. \end{lstlisting}
  5816. \end{minipage}
  5817. \\[2ex]\hline
  5818. \begin{minipage}{0.25\textwidth}
  5819. \begin{lstlisting}
  5820. (lambda (|$x_1 \ldots$|) |$e$|)
  5821. \end{lstlisting}
  5822. \end{minipage}
  5823. &
  5824. $\Rightarrow$
  5825. &
  5826. \begin{minipage}{0.6\textwidth}
  5827. \begin{lstlisting}
  5828. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  5829. (Any|$\ldots$|Any -> Any))
  5830. \end{lstlisting}
  5831. \end{minipage}
  5832. \\[2ex]\hline
  5833. \begin{minipage}{0.25\textwidth}
  5834. \begin{lstlisting}
  5835. (app |$e_0$| |$e_1 \ldots e_n$|)
  5836. \end{lstlisting}
  5837. \end{minipage}
  5838. &
  5839. $\Rightarrow$
  5840. &
  5841. \begin{minipage}{0.6\textwidth}
  5842. \begin{lstlisting}
  5843. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  5844. |$e'_1 \ldots e'_n$|)
  5845. \end{lstlisting}
  5846. \end{minipage}
  5847. \\[2ex]\hline
  5848. \begin{minipage}{0.25\textwidth}
  5849. \begin{lstlisting}
  5850. (vector-ref |$e_1$| |$e_2$|)
  5851. \end{lstlisting}
  5852. \end{minipage}
  5853. &
  5854. $\Rightarrow$
  5855. &
  5856. \begin{minipage}{0.6\textwidth}
  5857. \begin{lstlisting}
  5858. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  5859. (let ([tmp2 (project |$e'_2$| Integer)])
  5860. (vector-ref tmp1 tmp2)))
  5861. \end{lstlisting}
  5862. \end{minipage}
  5863. \\[2ex]\hline
  5864. \begin{minipage}{0.25\textwidth}
  5865. \begin{lstlisting}
  5866. (if |$e_1$| |$e_2$| |$e_3$|)
  5867. \end{lstlisting}
  5868. \end{minipage}
  5869. &
  5870. $\Rightarrow$
  5871. &
  5872. \begin{minipage}{0.6\textwidth}
  5873. \begin{lstlisting}
  5874. (if (eq? |$e'_1$| (inject #f Boolean))
  5875. |$e'_3$|
  5876. |$e'_2$|)
  5877. \end{lstlisting}
  5878. \end{minipage}
  5879. \\[2ex]\hline
  5880. \begin{minipage}{0.25\textwidth}
  5881. \begin{lstlisting}
  5882. (eq? |$e_1$| |$e_2$|)
  5883. \end{lstlisting}
  5884. \end{minipage}
  5885. &
  5886. $\Rightarrow$
  5887. &
  5888. \begin{minipage}{0.6\textwidth}
  5889. \begin{lstlisting}
  5890. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  5891. \end{lstlisting}
  5892. \end{minipage}
  5893. \\[2ex]\hline
  5894. \begin{minipage}{0.25\textwidth}
  5895. \begin{lstlisting}
  5896. (and |$e_1$| |$e_2$|)
  5897. \end{lstlisting}
  5898. \end{minipage}
  5899. &
  5900. $\Rightarrow$
  5901. &
  5902. \begin{minipage}{0.6\textwidth}
  5903. \begin{lstlisting}
  5904. (let ([tmp |$e'_1$|])
  5905. (if (eq? tmp (inject #f Boolean))
  5906. tmp
  5907. |$e'_2$|))
  5908. \end{lstlisting}
  5909. \end{minipage} \\\hline
  5910. \end{tabular} \\
  5911. \caption{Compiling $R_7$ to $R_6$.}
  5912. \label{fig:compile-r7-r6}
  5913. \end{figure}
  5914. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5915. \chapter{Gradual Typing}
  5916. \label{ch:gradual-typing}
  5917. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  5918. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5919. \chapter{Parametric Polymorphism}
  5920. \label{ch:parametric-polymorphism}
  5921. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  5922. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  5923. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5924. \chapter{High-level Optimization}
  5925. \label{ch:high-level-optimization}
  5926. This chapter will present a procedure inlining pass based on the
  5927. algorithm of \citet{Waddell:1997fk}.
  5928. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5929. \chapter{Appendix}
  5930. \section{Interpreters}
  5931. \label{appendix:interp}
  5932. We provide several interpreters in the \key{interp.rkt} file. The
  5933. \key{interp-scheme} function takes an AST in one of the Racket-like
  5934. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  5935. the program, returning the result value. The \key{interp-C} function
  5936. interprets an AST for a program in one of the C-like languages ($C_0,
  5937. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  5938. for an x86 program.
  5939. \section{Utility Functions}
  5940. \label{appendix:utilities}
  5941. The utility function described in this section can be found in the
  5942. \key{utilities.rkt} file.
  5943. The \key{read-program} function takes a file path and parses that file
  5944. (it must be a Racket program) into an abstract syntax tree (as an
  5945. S-expression) with a \key{program} AST at the top.
  5946. The \key{assert} function displays the error message \key{msg} if the
  5947. Boolean \key{bool} is false.
  5948. \begin{lstlisting}
  5949. (define (assert msg bool) ...)
  5950. \end{lstlisting}
  5951. The \key{lookup} function ...
  5952. The \key{map2} function ...
  5953. \subsection{Graphs}
  5954. \begin{itemize}
  5955. \item The \code{make-graph} function takes a list of vertices
  5956. (symbols) and returns a graph.
  5957. \item The \code{add-edge} function takes a graph and two vertices and
  5958. adds an edge to the graph that connects the two vertices. The graph
  5959. is updated in-place. There is no return value for this function.
  5960. \item The \code{adjacent} function takes a graph and a vertex and
  5961. returns the set of vertices that are adjacent to the given
  5962. vertex. The return value is a Racket \code{hash-set} so it can be
  5963. used with functions from the \code{racket/set} module.
  5964. \item The \code{vertices} function takes a graph and returns the list
  5965. of vertices in the graph.
  5966. \end{itemize}
  5967. \subsection{Testing}
  5968. The \key{interp-tests} function takes a compiler name (a string), a
  5969. description of the passes, an interpreter for the source language, a
  5970. test family name (a string), and a list of test numbers, and runs the
  5971. compiler passes and the interpreters to check whether the passes
  5972. correct. The description of the passes is a list with one entry per
  5973. pass. An entry is a list with three things: a string giving the name
  5974. of the pass, the function that implements the pass (a translator from
  5975. AST to AST), and a function that implements the interpreter (a
  5976. function from AST to result value) for the language of the output of
  5977. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  5978. good choice. The \key{interp-tests} function assumes that the
  5979. subdirectory \key{tests} has a bunch of Scheme programs whose names
  5980. all start with the family name, followed by an underscore and then the
  5981. test number, ending in \key{.scm}. Also, for each Scheme program there
  5982. is a file with the same number except that it ends with \key{.in} that
  5983. provides the input for the Scheme program.
  5984. \begin{lstlisting}
  5985. (define (interp-tests name passes test-family test-nums) ...
  5986. \end{lstlisting}
  5987. The compiler-tests function takes a compiler name (a string) a
  5988. description of the passes (see the comment for \key{interp-tests}) a
  5989. test family name (a string), and a list of test numbers (see the
  5990. comment for interp-tests), and runs the compiler to generate x86 (a
  5991. \key{.s} file) and then runs gcc to generate machine code. It runs
  5992. the machine code and checks that the output is 42.
  5993. \begin{lstlisting}
  5994. (define (compiler-tests name passes test-family test-nums) ...)
  5995. \end{lstlisting}
  5996. The compile-file function takes a description of the compiler passes
  5997. (see the comment for \key{interp-tests}) and returns a function that,
  5998. given a program file name (a string ending in \key{.scm}), applies all
  5999. of the passes and writes the output to a file whose name is the same
  6000. as the program file name but with \key{.scm} replaced with \key{.s}.
  6001. \begin{lstlisting}
  6002. (define (compile-file passes)
  6003. (lambda (prog-file-name) ...))
  6004. \end{lstlisting}
  6005. \section{x86 Instruction Set Quick-Reference}
  6006. \label{sec:x86-quick-reference}
  6007. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  6008. do. We write $A \to B$ to mean that the value of $A$ is written into
  6009. location $B$. Address offsets are given in bytes. The instruction
  6010. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  6011. registers (such as $\%rax$), or memory references (such as
  6012. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  6013. reference per instruction. Other operands must be immediates or
  6014. registers.
  6015. \begin{table}[tbp]
  6016. \centering
  6017. \begin{tabular}{l|l}
  6018. \textbf{Instruction} & \textbf{Operation} \\ \hline
  6019. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  6020. \texttt{negq} $A$ & $- A \to A$ \\
  6021. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  6022. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  6023. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  6024. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  6025. \texttt{retq} & Pops the return address and jumps to it \\
  6026. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  6027. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  6028. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  6029. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set flag \\
  6030. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag matches
  6031. the condition code, otherwise go to the next instructions.
  6032. The condition codes are \key{e} for ``equal'',
  6033. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6034. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6035. \texttt{jl} $L$ & \\
  6036. \texttt{jle} $L$ & \\
  6037. \texttt{jg} $L$ & \\
  6038. \texttt{jge} $L$ & \\
  6039. \texttt{jmp} $L$ & Jump to label $L$ \\
  6040. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6041. \texttt{movzbq} $A$, $B$ &
  6042. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6043. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6044. and the extra bytes of $B$ are set to zero.} \\
  6045. & \\
  6046. & \\
  6047. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6048. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6049. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6050. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6051. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6052. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6053. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6054. description of the condition codes. $A$ must be a single byte register
  6055. (e.g., \texttt{al} or \texttt{cl}).} \\
  6056. \texttt{setl} $A$ & \\
  6057. \texttt{setle} $A$ & \\
  6058. \texttt{setg} $A$ & \\
  6059. \texttt{setge} $A$ &
  6060. \end{tabular}
  6061. \vspace{5pt}
  6062. \caption{Quick-reference for the x86 instructions used in this book.}
  6063. \label{tab:x86-instr}
  6064. \end{table}
  6065. \bibliographystyle{plainnat}
  6066. \bibliography{all}
  6067. \end{document}
  6068. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6069. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6070. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6071. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6072. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6073. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6074. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6075. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6076. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6077. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6078. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6079. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6080. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6081. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6082. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6083. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6084. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6085. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6086. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6087. %% LocalWords: len prev rootlen heaplen setl lt