book.tex 257 KB

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