book.tex 252 KB

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