book.tex 296 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{multirow}
  49. \usepackage{color}
  50. \definecolor{lightgray}{gray}{1}
  51. \newcommand{\black}[1]{{\color{black} #1}}
  52. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  53. %% For pictures
  54. \usepackage{tikz}
  55. \usetikzlibrary{arrows.meta}
  56. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  57. % Computer Modern is already the default. -Jeremy
  58. %\renewcommand{\ttdefault}{cmtt}
  59. \definecolor{comment-red}{rgb}{0.8,0,0}
  60. \if{0}
  61. % Peanut gallery comments:
  62. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  63. \newcommand{\margincomment}[1]{\marginpar{#1}}
  64. \else
  65. \newcommand{\rn}[1]{}
  66. \newcommand{\margincomment}[1]{}
  67. \fi
  68. \lstset{%
  69. language=Lisp,
  70. basicstyle=\ttfamily\small,
  71. morekeywords={seq,assign,program,block,define,lambda,match},
  72. escapechar=|,
  73. columns=flexible,
  74. moredelim=[is][\color{red}]{~}{~}
  75. }
  76. \newtheorem{theorem}{Theorem}
  77. \newtheorem{lemma}[theorem]{Lemma}
  78. \newtheorem{corollary}[theorem]{Corollary}
  79. \newtheorem{proposition}[theorem]{Proposition}
  80. \newtheorem{constraint}[theorem]{Constraint}
  81. \newtheorem{definition}[theorem]{Definition}
  82. \newtheorem{exercise}[theorem]{Exercise}
  83. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  84. % 'dedication' environment: To add a dedication paragraph at the start of book %
  85. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. \newenvironment{dedication}
  88. {
  89. \cleardoublepage
  90. \thispagestyle{empty}
  91. \vspace*{\stretch{1}}
  92. \hfill\begin{minipage}[t]{0.66\textwidth}
  93. \raggedright
  94. }
  95. {
  96. \end{minipage}
  97. \vspace*{\stretch{3}}
  98. \clearpage
  99. }
  100. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  101. % Chapter quote at the start of chapter %
  102. % Source: http://tex.stackexchange.com/a/53380 %
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. \makeatletter
  105. \renewcommand{\@chapapp}{}% Not necessary...
  106. \newenvironment{chapquote}[2][2em]
  107. {\setlength{\@tempdima}{#1}%
  108. \def\chapquote@author{#2}%
  109. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  110. \itshape}
  111. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  112. \makeatother
  113. \input{defs}
  114. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  115. \title{\Huge \textbf{Essentials of Compilation} \\
  116. \huge An Incremental Approach}
  117. \author{\textsc{Jeremy G. Siek} \\
  118. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  119. Indiana University \\
  120. \\
  121. with contributions from: \\
  122. Carl Factora \\
  123. Andre Kuhlenschmidt \\
  124. Ryan R. Newton \\
  125. Ryan Scott \\
  126. Cameron Swords \\
  127. Michael M. Vitousek \\
  128. Michael Vollmer
  129. }
  130. \begin{document}
  131. \frontmatter
  132. \maketitle
  133. \begin{dedication}
  134. This book is dedicated to the programming language wonks at Indiana
  135. University.
  136. \end{dedication}
  137. \tableofcontents
  138. \listoffigures
  139. %\listoftables
  140. \mainmatter
  141. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  142. \chapter*{Preface}
  143. The tradition of compiler writing at Indiana University goes back to
  144. research and courses about programming languages by Daniel Friedman in
  145. the 1970's and 1980's. Dan conducted research on lazy
  146. evaluation~\citep{Friedman:1976aa} in the context of
  147. Lisp~\citep{McCarthy:1960dz} and then studied
  148. continuations~\citep{Felleisen:kx} and
  149. macros~\citep{Kohlbecker:1986dk} in the context of the
  150. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  151. of those courses, Kent Dybvig, went on to build Chez
  152. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  153. compiler for Scheme. After completing his Ph.D. at the University of
  154. North Carolina, Kent returned to teach at Indiana University.
  155. Throughout the 1990's and 2000's, Kent continued development of Chez
  156. Scheme and taught the compiler course.
  157. The compiler course evolved to incorporate novel pedagogical ideas
  158. while also including elements of effective real-world compilers. One
  159. of Dan's ideas was to split the compiler into many small ``passes'' so
  160. that the code for each pass would be easy to understood in isolation.
  161. (In contrast, most compilers of the time were organized into only a
  162. few monolithic passes for reasons of compile-time efficiency.) Kent,
  163. with later help from his students Dipanwita Sarkar and Andrew Keep,
  164. developed infrastructure to support this approach and evolved the
  165. course, first to use micro-sized passes and then into even smaller
  166. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  167. student in this compiler course in the early 2000's, as part of his
  168. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  169. the course immensely!
  170. During that time, another student named Abdulaziz Ghuloum observed
  171. that the front-to-back organization of the course made it difficult
  172. for students to understand the rationale for the compiler
  173. design. Abdulaziz proposed an incremental approach in which the
  174. students build the compiler in stages; they start by implementing a
  175. complete compiler for a very small subset of the input language and in
  176. each subsequent stage they add a language feature and add or modify
  177. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  178. the students see how the language features motivate aspects of the
  179. compiler design.
  180. After graduating from Indiana University in 2005, Jeremy went on to
  181. teach at the University of Colorado. He adapted the nano pass and
  182. incremental approaches to compiling a subset of the Python
  183. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  184. on the surface but there is a large overlap in the compiler techniques
  185. required for the two languages. Thus, Jeremy was able to teach much of
  186. the same content from the Indiana compiler course. He very much
  187. enjoyed teaching the course organized in this way, and even better,
  188. many of the students learned a lot and got excited about compilers.
  189. Jeremy returned to teach at Indiana University in 2013. In his
  190. absence the compiler course had switched from the front-to-back
  191. organization to a back-to-front organization. Seeing how well the
  192. incremental approach worked at Colorado, he started porting and
  193. adapting the structure of the Colorado course back into the land of
  194. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  195. the course is now about compiling a subset of Racket (and Typed
  196. Racket) to the x86 assembly language. The compiler is implemented in
  197. Racket 7.1~\citep{plt-tr}.
  198. This is the textbook for the incremental version of the compiler
  199. course at Indiana University (Spring 2016 - present) and it is the
  200. first open textbook for an Indiana compiler course. With this book we
  201. hope to make the Indiana compiler course available to people that have
  202. not had the chance to study in Bloomington in person. Many of the
  203. compiler design decisions in this book are drawn from the assignment
  204. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  205. are the most important topics from \cite{Dybvig:2010aa} but we have
  206. omitted topics that we think are less interesting conceptually and we
  207. have made simplifications to reduce complexity. In this way, this
  208. book leans more towards pedagogy than towards the efficiency of the
  209. generated code. Also, the book differs in places where we saw the
  210. opportunity to make the topics more fun, such as in relating register
  211. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  212. \section*{Prerequisites}
  213. The material in this book is challenging but rewarding. It is meant to
  214. prepare students for a lifelong career in programming languages.
  215. The book uses the Racket language both for the implementation of the
  216. compiler and for the language that is compiled, so a student should be
  217. proficient with Racket (or Scheme) prior to reading this book. There
  218. are many excellent resources for learning Scheme and
  219. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  220. is helpful but not necessary for the student to have prior exposure to
  221. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  222. obtain from a computer systems
  223. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  224. parts of x86-64 assembly language that are needed.
  225. %\section*{Structure of book}
  226. % You might want to add short description about each chapter in this book.
  227. %\section*{About the companion website}
  228. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  229. %\begin{itemize}
  230. % \item A link to (freely downlodable) latest version of this document.
  231. % \item Link to download LaTeX source for this document.
  232. % \item Miscellaneous material (e.g. suggested readings etc).
  233. %\end{itemize}
  234. \section*{Acknowledgments}
  235. Many people have contributed to the ideas, techniques, organization,
  236. and teaching of the materials in this book. We especially thank the
  237. following people.
  238. \begin{itemize}
  239. \item Bor-Yuh Evan Chang
  240. \item Kent Dybvig
  241. \item Daniel P. Friedman
  242. \item Ronald Garcia
  243. \item Abdulaziz Ghuloum
  244. \item Jay McCarthy
  245. \item Dipanwita Sarkar
  246. \item Andrew Keep
  247. \item Oscar Waddell
  248. \item Michael Wollowski
  249. \end{itemize}
  250. \mbox{}\\
  251. \noindent Jeremy G. Siek \\
  252. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  253. %\noindent Spring 2016
  254. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  255. \chapter{Preliminaries}
  256. \label{ch:trees-recur}
  257. In this chapter we review the basic tools that are needed to implement
  258. a compiler. We use \emph{abstract syntax trees} (ASTs), which are data
  259. structures in computer memory, in contrast to how programs are
  260. typically stored in text files on disk, as \emph{concrete syntax}.
  261. %
  262. ASTs can be represented in many different ways, depending on the programming
  263. language used to write the compiler.
  264. %
  265. Because this book uses Racket (\url{http://racket-lang.org}), a
  266. descendant of Lisp, we can use S-expressions to conveniently represent
  267. ASTs (Section~\ref{sec:ast}). We use grammars to defined the abstract
  268. syntax of programming languages (Section~\ref{sec:grammar}) and
  269. pattern matching to inspect individual nodes in an AST
  270. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  271. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  272. chapter provides an brief introduction to these ideas.
  273. \section{Abstract Syntax Trees and S-expressions}
  274. \label{sec:ast}
  275. The primary data structure that is commonly used for representing
  276. programs is the \emph{abstract syntax tree} (AST). When considering
  277. some part of a program, a compiler needs to ask what kind of thing it
  278. is and what sub-parts it contains. For example, the program on the
  279. left, represented by an S-expression, corresponds to the AST on the
  280. right.
  281. \begin{center}
  282. \begin{minipage}{0.4\textwidth}
  283. \begin{lstlisting}
  284. (+ (read) (- 8))
  285. \end{lstlisting}
  286. \end{minipage}
  287. \begin{minipage}{0.4\textwidth}
  288. \begin{equation}
  289. \begin{tikzpicture}
  290. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  291. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  292. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  293. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  294. \draw[->] (plus) to (read);
  295. \draw[->] (plus) to (minus);
  296. \draw[->] (minus) to (8);
  297. \end{tikzpicture}
  298. \label{eq:arith-prog}
  299. \end{equation}
  300. \end{minipage}
  301. \end{center}
  302. We shall use the standard terminology for trees: each circle above is
  303. called a \emph{node}. The arrows connect a node to its \emph{children}
  304. (which are also nodes). The top-most node is the \emph{root}. Every
  305. node except for the root has a \emph{parent} (the node it is the child
  306. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  307. it is an \emph{internal} node.
  308. Recall that an \emph{symbolic expression} (S-expression) is either
  309. \begin{enumerate}
  310. \item an atom, or
  311. \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  312. where $e_1$ and $e_2$ are each an S-expression.
  313. \end{enumerate}
  314. An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  315. null value \code{'()}, etc. We can create an S-expression in Racket
  316. simply by writing a backquote (called a quasi-quote in Racket)
  317. followed by the textual representation of the S-expression. It is
  318. quite common to use S-expressions to represent a list, such as $a, b
  319. ,c$ in the following way:
  320. \begin{lstlisting}
  321. `(a . (b . (c . ())))
  322. \end{lstlisting}
  323. Each element of the list is in the first slot of a pair, and the
  324. second slot is either the rest of the list or the null value, to mark
  325. the end of the list. Such lists are so common that Racket provides
  326. special notation for them that removes the need for the periods
  327. and so many parenthesis:
  328. \begin{lstlisting}
  329. `(a b c)
  330. \end{lstlisting}
  331. The following expression creates an S-expression that represents AST
  332. \eqref{eq:arith-prog}.
  333. \begin{lstlisting}
  334. `(+ (read) (- 8))
  335. \end{lstlisting}
  336. When using S-expressions to represent ASTs, the convention is to
  337. represent each AST node as a list and to put the operation symbol at
  338. the front of the list. The rest of the list contains the children. So
  339. in the above case, the root AST node has operation \code{`+} and its
  340. two children are \code{`(read)} and \code{`(- 8)}, just as in the
  341. diagram \eqref{eq:arith-prog}.
  342. To build larger S-expressions one often needs to splice together
  343. several smaller S-expressions. Racket provides the comma operator to
  344. splice an S-expression into a larger one. For example, instead of
  345. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  346. we could have first created an S-expression for AST
  347. \eqref{eq:arith-neg8} and then spliced that into the addition
  348. S-expression.
  349. \begin{lstlisting}
  350. (define ast1.4 `(- 8))
  351. (define ast1.1 `(+ (read) ,ast1.4))
  352. \end{lstlisting}
  353. In general, the Racket expression that follows the comma (splice)
  354. can be any expression that produces an S-expression.
  355. When deciding how to compile program \eqref{eq:arith-prog}, we need to
  356. know that the operation associated with the root node is addition and
  357. that it has two children: \texttt{read} and a negation. The AST data
  358. structure directly supports these queries, as we shall see in
  359. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  360. in compilers. In this book, we often write down the S-expression
  361. representation of a program even when we really have in mind the AST
  362. because the S-expression is more concise. We recommend that, in your
  363. mind, you always think of programs as abstract syntax trees.
  364. \section{Grammars}
  365. \label{sec:grammar}
  366. A programming language can be thought of as a \emph{set} of programs.
  367. The set is typically infinite (one can always create larger and larger
  368. programs), so one cannot simply describe a language by listing all of
  369. the programs in the language. Instead we write down a set of rules, a
  370. \emph{grammar}, for building programs. We shall write our rules in a
  371. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  372. As an example, we describe a small language, named $R_0$, that
  373. consists of integers and arithmetic operations. The first grammar rule
  374. says that any integer is an expression:
  375. \begin{equation}
  376. \Exp ::= \Int \label{eq:arith-int}
  377. \end{equation}
  378. %
  379. Each rule has a left-hand-side and a right-hand-side. The way to read
  380. a rule is that if you have all the program parts on the
  381. right-hand-side, then you can create an AST node and categorize it
  382. according to the left-hand-side.
  383. %
  384. A name such as $\Exp$ that is
  385. defined by the grammar rules is a \emph{non-terminal}.
  386. %
  387. The name $\Int$ is a also a non-terminal, however, we do not define
  388. $\Int$ because the reader already knows what an integer is.
  389. %
  390. Further, we make the simplifying design decision that all of the languages in
  391. this book only handle machine-representable integers. On most modern machines
  392. this corresponds to integers represented with 64-bits, i.e., the in range
  393. $-2^{63}$ to $2^{63}-1$.
  394. %
  395. However, we restrict this range further to match the Racket \texttt{fixnum}
  396. datatype, which allows 63-bit integers on a 64-bit machine.
  397. The second grammar rule is the \texttt{read} operation that receives
  398. an input integer from the user of the program.
  399. \begin{equation}
  400. \Exp ::= (\key{read}) \label{eq:arith-read}
  401. \end{equation}
  402. The third rule says that, given an $\Exp$ node, you can build another
  403. $\Exp$ node by negating it.
  404. \begin{equation}
  405. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  406. \end{equation}
  407. Symbols in typewriter font such as \key{-} and \key{read} are
  408. \emph{terminal} symbols and must literally appear in the program for
  409. the rule to be applicable.
  410. We can apply the rules to build ASTs in the $R_0$
  411. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  412. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  413. an $\Exp$.
  414. \begin{center}
  415. \begin{minipage}{0.25\textwidth}
  416. \begin{lstlisting}
  417. (- 8)
  418. \end{lstlisting}
  419. \end{minipage}
  420. \begin{minipage}{0.25\textwidth}
  421. \begin{equation}
  422. \begin{tikzpicture}
  423. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  424. \node[draw, circle] (8) at (0, -1.2) {$8$};
  425. \draw[->] (minus) to (8);
  426. \end{tikzpicture}
  427. \label{eq:arith-neg8}
  428. \end{equation}
  429. \end{minipage}
  430. \end{center}
  431. The next grammar rule defines addition expressions:
  432. \begin{equation}
  433. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  434. \end{equation}
  435. We can now see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  436. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  437. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  438. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  439. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  440. If you have an AST for which the above rules do not apply, then the
  441. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  442. not in $R_0$ because there are no rules for \key{+} with only one
  443. argument, nor for \key{-} with two arguments. Whenever we define a
  444. language with a grammar, we mean for the language to only include
  445. those programs that are justified by the rules.
  446. The last grammar rule for $R_0$ states that there is a \key{program}
  447. node to mark the top of the whole program:
  448. \[
  449. R_0 ::= (\key{program} \; \Exp)
  450. \]
  451. The \code{read-program} function provided in \code{utilities.rkt}
  452. reads programs in from a file (the sequence of characters in the
  453. concrete syntax of Racket) and parses them into the abstract syntax
  454. tree. The concrete syntax does not include a \key{program} form; that
  455. is added by the \code{read-program} function as it creates the
  456. AST. See the description of \code{read-program} in
  457. Appendix~\ref{appendix:utilities} for more details.
  458. It is common to have many rules with the same left-hand side, such as
  459. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  460. for gathering several rules, as shown in
  461. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  462. called an {\em alternative}.
  463. \begin{figure}[tp]
  464. \fbox{
  465. \begin{minipage}{0.96\textwidth}
  466. \[
  467. \begin{array}{rcl}
  468. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  469. (\key{+} \; \Exp \; \Exp) \\
  470. R_0 &::=& (\key{program} \; \Exp)
  471. \end{array}
  472. \]
  473. \end{minipage}
  474. }
  475. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  476. \label{fig:r0-syntax}
  477. \end{figure}
  478. \section{Pattern Matching}
  479. \label{sec:pattern-matching}
  480. As mentioned above, compilers often need to access the children of an
  481. AST node. Racket provides the \texttt{match} form to access the parts
  482. of an S-expression. Consider the following example and the output on
  483. the right.
  484. \begin{center}
  485. \begin{minipage}{0.5\textwidth}
  486. \begin{lstlisting}
  487. (match ast1.1
  488. [`(,op ,child1 ,child2)
  489. (print op) (newline)
  490. (print child1) (newline)
  491. (print child2)])
  492. \end{lstlisting}
  493. \end{minipage}
  494. \vrule
  495. \begin{minipage}{0.25\textwidth}
  496. \begin{lstlisting}
  497. '+
  498. '(read)
  499. '(- 8)
  500. \end{lstlisting}
  501. \end{minipage}
  502. \end{center}
  503. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  504. parts to the three variables \texttt{op}, \texttt{child1}, and
  505. \texttt{child2}. In general, a match clause consists of a
  506. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  507. that may also contain pattern-variables (each one preceded by a comma).
  508. %
  509. The pattern is not the same thing as a quasiquote expression used to
  510. \emph{construct} ASTs, however, the similarity is intentional:
  511. constructing and deconstructing ASTs uses similar syntax.
  512. %
  513. While the pattern uses a restricted syntax, the body of the match
  514. clause may contain any Racket code whatsoever.
  515. A \code{match} form may contain several clauses, as in the following
  516. function \code{leaf?} that recognizes when an $R_0$ node is
  517. a leaf. The \code{match} proceeds through the clauses in order,
  518. checking whether the pattern can match the input S-expression. The
  519. body of the first clause that matches is executed. The output of
  520. \code{leaf?} for several S-expressions is shown on the right. In the
  521. below \code{match}, we see another form of pattern: the
  522. pattern \code{(? fixnum?)} applies the predicate \code{fixnum?} to the input
  523. S-expression to see if it is a machine-representable integer.
  524. \begin{center}
  525. \begin{minipage}{0.5\textwidth}
  526. \begin{lstlisting}
  527. (define (leaf? arith)
  528. (match arith
  529. [(? fixnum?) #t]
  530. [`(read) #t]
  531. [`(- ,c1) #f]
  532. [`(+ ,c1 ,c2) #f]))
  533. (leaf? `(read))
  534. (leaf? `(- 8))
  535. (leaf? `(+ (read) (- 8)))
  536. \end{lstlisting}
  537. \end{minipage}
  538. \vrule
  539. \begin{minipage}{0.25\textwidth}
  540. \begin{lstlisting}
  541. #t
  542. #f
  543. #f
  544. \end{lstlisting}
  545. \end{minipage}
  546. \end{center}
  547. When writing a \code{match}, we always refer to the grammar definition
  548. for the language and identify which non-terminal we're expecting to
  549. match against, then we make sure that 1) we have one clause for each
  550. alternative of that non-terminal and 2) that the pattern in each
  551. clause corresponds to the corresponding right-hand side of a grammar
  552. rule. For the \code{match} in the \code{leaf?} function, we refer to
  553. the grammar for $R\_0$ in Figure~\ref{fig:r0-syntax}. The $\Exp$
  554. non-terminal has 4 alternatives, so the \code{match} has 4 clauses.
  555. The pattern in each clause corresponds to the right-hand side of a
  556. grammar rule. For example, the pattern \code{`(+ ,c1 ,c2)} corresponds
  557. to the right-hand side $(\key{+} \; \Exp \; \Exp)$. When translating
  558. from grammars to patterns, replace non-terminals such as $\Exp$ with
  559. pattern variables (a comma followed by a variable name of your
  560. choice).
  561. \section{Recursion}
  562. \label{sec:recursion}
  563. Programs are inherently recursive. For example, an $R_0$ expression is
  564. often made of smaller expressions. Thus, the natural way to process an
  565. entire program is with a recursive function. As a first example of
  566. such a recursive function, we define \texttt{exp?} below, which takes
  567. an arbitrary S-expression and determines whether or not it is an $R_0$
  568. expression. As discussed in the previous section, each match clause
  569. corresponds to one grammar rule. The body of each clause makes a
  570. recursive call for each child node. This kind of recursive function is
  571. so common that it has a name: \emph{structural recursion}. In
  572. general, when a recursive function is defined using a sequence of
  573. match clauses that correspond to a grammar, and the body of each
  574. clause makes a recursive call on each child node, then we say the
  575. function is defined by structural recursion\footnote{This principle of
  576. structuring code according to the data definition is advocated in
  577. the book \emph{How to Design Programs}
  578. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  579. define a second function, named \code{R0?}, that determines whether an
  580. S-expression is an $R_0$ program. In general we can expect to write
  581. one recursive function to handle each non-terminal in the grammar.
  582. %
  583. \begin{center}
  584. \begin{minipage}{0.7\textwidth}
  585. \begin{lstlisting}
  586. (define (exp? sexp)
  587. (match sexp
  588. [(? fixnum?) #t]
  589. [`(read) #t]
  590. [`(- ,e) (exp? e)]
  591. [`(+ ,e1 ,e2)
  592. (and (exp? e1) (exp? e2))]
  593. [else #f]))
  594. (define (R0? sexp)
  595. (match sexp
  596. [`(program ,e) (exp? e)]
  597. [else #f]))
  598. (R0? `(program (+ (read) (- 8))))
  599. (R0? `(program (- (read) (+ 8))))
  600. \end{lstlisting}
  601. \end{minipage}
  602. \vrule
  603. \begin{minipage}{0.25\textwidth}
  604. \begin{lstlisting}
  605. #t
  606. #f
  607. \end{lstlisting}
  608. \end{minipage}
  609. \end{center}
  610. You may be tempted to merge the two functions into one, like this:
  611. \begin{center}
  612. \begin{minipage}{0.5\textwidth}
  613. \begin{lstlisting}
  614. (define (R0? sexp)
  615. (match sexp
  616. [(? fixnum?) #t]
  617. [`(read) #t]
  618. [`(- ,e) (R0? e)]
  619. [`(+ ,e1 ,e2) (and (R0? e1) (R0? e2))]
  620. [`(program ,e) (R0? e)]
  621. [else #f]))
  622. \end{lstlisting}
  623. \end{minipage}
  624. \end{center}
  625. %
  626. Sometimes such a trick will save a few lines of code, especially when it comes
  627. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  628. recommended because it can get you into trouble.
  629. %
  630. For instance, the above function is subtly wrong:
  631. \lstinline{(R0? `(program (program 3)))} will return true, when it
  632. should return false.
  633. %% NOTE FIXME - must check for consistency on this issue throughout.
  634. \section{Interpreters}
  635. \label{sec:interp-R0}
  636. The meaning, or semantics, of a program is typically defined in the
  637. specification of the language. For example, the Scheme language is
  638. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  639. defined in its reference manual~\citep{plt-tr}. In this book we use an
  640. interpreter to define the meaning of each language that we consider,
  641. following Reynolds' advice in this
  642. regard~\citep{reynolds72:_def_interp}. An interpreter that is
  643. designated (by some people) as the definition of a language is called
  644. a \emph{definitional interpreter}. Here we warm up by creating a
  645. definitional interpreter for the $R_0$ language, which serves as a
  646. second example of structural recursion. The \texttt{interp-R0}
  647. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  648. function is a match on the input program followed by a call to the
  649. \lstinline{interp-exp} helper function, which in turn has one match
  650. clause per grammar rule for $R_0$ expressions.
  651. \begin{figure}[tbp]
  652. \begin{lstlisting}
  653. (define (interp-exp e)
  654. (match e
  655. [(? fixnum?) e]
  656. [`(read)
  657. (let ([r (read)])
  658. (cond [(fixnum? r) r]
  659. [else (error 'interp-R0 "input not an integer" r)]))]
  660. [`(- ,e1) (fx- 0 (interp-exp e1))]
  661. [`(+ ,e1 ,e2) (fx+ (interp-exp e1) (interp-exp e2))]
  662. ))
  663. (define (interp-R0 p)
  664. (match p
  665. [`(program ,e) (interp-exp e)]))
  666. \end{lstlisting}
  667. \caption{Interpreter for the $R_0$ language.}
  668. \label{fig:interp-R0}
  669. \end{figure}
  670. Let us consider the result of interpreting a few $R_0$ programs. The
  671. following program adds two integers.
  672. \begin{lstlisting}
  673. (+ 10 32)
  674. \end{lstlisting}
  675. The result is \key{42}. (We wrote the above program in concrete syntax,
  676. whereas the parsed abstract syntax is \lstinline{(program (+ 10 32))}.)
  677. The next example demonstrates that expressions may be nested within
  678. each other, in this case nesting several additions and negations.
  679. \begin{lstlisting}
  680. (+ 10 (- (+ 12 20)))
  681. \end{lstlisting}
  682. What is the result of the above program?
  683. As mentioned previously, the $R_0$ language does not support
  684. arbitrarily-large integers, but only $63$-bit integers, so we
  685. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  686. in Racket. What happens when we run the following program?
  687. \begin{lstlisting}
  688. (define large 999999999999999999)
  689. (interp-R0 `(program (+ (+ (+ ,large ,large) (+ ,large ,large))
  690. (+ (+ ,large ,large) (+ ,large ,large)))))
  691. \end{lstlisting}
  692. It produces an error:
  693. \begin{lstlisting}
  694. fx+: result is not a fixnum
  695. \end{lstlisting}
  696. We establish the convention that if running the definitional
  697. interpreter on a program produces an error, then the meaning of that
  698. program is \emph{unspecified}. That means a compiler for the language
  699. is under no obligations regarding that program; it may or may not
  700. produce an executable, and if it does, that executable can do
  701. anything. This convention applies to the languages defined in this
  702. book, as a way to simplify the student's task of implementing them,
  703. but this convention is not applicable to all programming languages.
  704. Moving on to the last feature of the $R_0$ language, the \key{read}
  705. operation prompts the user of the program for an integer. Recall that
  706. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  707. \code{8}. So if we run
  708. \begin{lstlisting}
  709. (interp-R0 ast1.1)
  710. \end{lstlisting}
  711. and the input the integer \code{50} we get the answer to life, the
  712. universe, and everything: \code{42}.
  713. We include the \key{read} operation in $R_0$ so a clever student
  714. cannot implement a compiler for $R_0$ that simply runs the interpreter
  715. during compilation to obtain the output and then generates the trivial
  716. code to produce the output. (Yes, a clever student did this in a
  717. previous version of the course.)
  718. The job of a compiler is to translate a program in one language into a
  719. program in another language so that the output program behaves the
  720. same way as the input program does according to its definitional
  721. interpreter. This idea is depicted in the following diagram. Suppose
  722. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  723. interpreter for each language. Suppose that the compiler translates
  724. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  725. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  726. respective interpreters with input $i$ should yield the same output
  727. $o$.
  728. \begin{equation} \label{eq:compile-correct}
  729. \begin{tikzpicture}[baseline=(current bounding box.center)]
  730. \node (p1) at (0, 0) {$P_1$};
  731. \node (p2) at (3, 0) {$P_2$};
  732. \node (o) at (3, -2.5) {$o$};
  733. \path[->] (p1) edge [above] node {compile} (p2);
  734. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  735. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  736. \end{tikzpicture}
  737. \end{equation}
  738. In the next section we see our first example of a compiler.
  739. \section{Example Compiler: a Partial Evaluator}
  740. \label{sec:partial-evaluation}
  741. In this section we consider a compiler that translates $R_0$
  742. programs into $R_0$ programs that may be more efficient, that is,
  743. this compiler is an optimizer. Our optimizer will accomplish this by
  744. trying to eagerly compute the parts of the program that do not depend
  745. on any inputs. For example, given the following program
  746. \begin{lstlisting}
  747. (+ (read) (- (+ 5 3)))
  748. \end{lstlisting}
  749. our compiler will translate it into the program
  750. \begin{lstlisting}
  751. (+ (read) -8)
  752. \end{lstlisting}
  753. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  754. evaluator for the $R_0$ language. The output of the partial evaluator
  755. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  756. recursion over $\Exp$ is captured in the \code{pe-exp} function
  757. whereas the code for partially evaluating the negation and addition
  758. operations is factored into two separate helper functions:
  759. \code{pe-neg} and \code{pe-add}. The input to these helper
  760. functions is the output of partially evaluating the children.
  761. \begin{figure}[tbp]
  762. \begin{lstlisting}
  763. (define (pe-neg r)
  764. (cond [(fixnum? r) (fx- 0 r)]
  765. [else `(- ,r)]))
  766. (define (pe-add r1 r2)
  767. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  768. [else `(+ ,r1 ,r2)]))
  769. (define (pe-exp e)
  770. (match e
  771. [(? fixnum?) e]
  772. [`(read) `(read)]
  773. [`(- ,e1) (pe-neg (pe-exp e1))]
  774. [`(+ ,e1 ,e2) (pe-add (pe-exp e1) (pe-exp e2))]
  775. ))
  776. (define (pe-R0 p)
  777. (match p
  778. [`(program ,e) `(program ,(pe-exp e))]
  779. ))
  780. \end{lstlisting}
  781. \caption{A partial evaluator for $R_0$ expressions.}
  782. \label{fig:pe-arith}
  783. \end{figure}
  784. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  785. arguments are integers and if they are, perform the appropriate
  786. arithmetic. Otherwise, they use quasiquote to create an AST node for
  787. the operation (either negation or addition) and use comma to splice in
  788. the children.
  789. To gain some confidence that the partial evaluator is correct, we can
  790. test whether it produces programs that get the same result as the
  791. input programs. That is, we can test whether it satisfies Diagram
  792. \eqref{eq:compile-correct}. The following code runs the partial
  793. evaluator on several examples and tests the output program. The
  794. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.\\
  795. \begin{minipage}{1.0\textwidth}
  796. \begin{lstlisting}
  797. (define (test-pe p)
  798. (assert "testing pe-R0"
  799. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  800. (test-pe `(+ (read) (- (+ 5 3))))
  801. (test-pe `(+ 1 (+ (read) 1)))
  802. (test-pe `(- (+ (read) (- 5))))
  803. \end{lstlisting}
  804. \end{minipage}
  805. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  806. \chapter{Integers and Variables}
  807. \label{ch:int-exp}
  808. This chapter is about compiling the subset of Racket that includes
  809. integer arithmetic and local variable binding, which we name $R_1$, to
  810. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  811. to x86-64 simply as x86. The chapter begins with a description of the
  812. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  813. (Section~\ref{sec:x86}). The x86 assembly language is quite large, so
  814. we discuss only what is needed for compiling $R_1$. We introduce more
  815. of x86 in later chapters. Once we have introduced $R_1$ and x86, we
  816. reflect on their differences and come up with a plan to break down the
  817. translation from $R_1$ to x86 into a handful of steps
  818. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  819. chapter give detailed hints regarding each step
  820. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  821. to give enough hints that the well-prepared reader, together with some
  822. friends, can implement a compiler from $R_1$ to x86 in a couple weeks
  823. while at the same time leaving room for some fun and creativity. To
  824. give the reader a feeling for the scale of this first compiler, the
  825. instructor solution for the $R_1$ compiler is less than 500 lines of
  826. code.
  827. \section{The $R_1$ Language}
  828. \label{sec:s0}
  829. The $R_1$ language extends the $R_0$ language
  830. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  831. the $R_1$ language is defined by the grammar in
  832. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  833. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  834. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  835. the $R_1$ language includes the \key{program} construct to mark the
  836. top of the program, which is helpful in some of the compiler passes.
  837. The $\itm{info}$ field of the \key{program} construct contains an
  838. association list that is used to communicate auxiliary data from one
  839. compiler pass the next. Despite the simplicity of the $R_1$ language,
  840. it is rich enough to exhibit several compilation techniques.
  841. \begin{figure}[btp]
  842. \centering
  843. \fbox{
  844. \begin{minipage}{0.96\textwidth}
  845. \[
  846. \begin{array}{rcl}
  847. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  848. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  849. R_1 &::=& (\key{program} \;\itm{info}\; \Exp)
  850. \end{array}
  851. \]
  852. \end{minipage}
  853. }
  854. \caption{The syntax of $R_1$, a language of integers and variables.}
  855. \label{fig:r1-syntax}
  856. \end{figure}
  857. Let us dive further into the syntax and semantics of the $R_1$
  858. language. The \key{let} construct defines a variable for use within
  859. its body and initializes the variable with the value of an expression.
  860. So the following program initializes \code{x} to \code{32} and then
  861. evaluates the body \code{(+ 10 x)}, producing \code{42}.
  862. \begin{lstlisting}
  863. (program ()
  864. (let ([x (+ 12 20)]) (+ 10 x)))
  865. \end{lstlisting}
  866. When there are multiple \key{let}'s for the same variable, the closest
  867. enclosing \key{let} is used. That is, variable definitions overshadow
  868. prior definitions. Consider the following program with two \key{let}'s
  869. that define variables named \code{x}. Can you figure out the result?
  870. \begin{lstlisting}
  871. (program ()
  872. (let ([x 32]) (+ (let ([x 10]) x) x)))
  873. \end{lstlisting}
  874. For the purposes of showing which variable uses correspond to which
  875. definitions, the following shows the \code{x}'s annotated with subscripts
  876. to distinguish them. Double check that your answer for the above is
  877. the same as your answer for this annotated version of the program.
  878. \begin{lstlisting}
  879. (program ()
  880. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  881. \end{lstlisting}
  882. The initializing expression is always evaluated before the body of the
  883. \key{let}, so in the following, the \key{read} for \code{x} is
  884. performed before the \key{read} for \code{y}. Given the input
  885. \code{52} then \code{10}, the following produces \code{42} (and not
  886. \code{-42}).
  887. \begin{lstlisting}
  888. (program ()
  889. (let ([x (read)]) (let ([y (read)]) (+ x (- y)))))
  890. \end{lstlisting}
  891. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  892. $R_1$ language. It extends the interpreter for $R_0$ with two new
  893. \key{match} clauses for variables and for \key{let}. For \key{let},
  894. we need a way to communicate the value of a variable to all the uses
  895. of a variable. To accomplish this, we maintain a mapping from
  896. variables to values, which is called an \emph{environment}. For
  897. simplicity, here we use an association list to represent the
  898. environment. The \code{interp-R1} function takes the current
  899. environment, \code{env}, as an extra parameter. When the interpreter
  900. encounters a variable, it finds the corresponding value using the
  901. \code{lookup} function (Appendix~\ref{appendix:utilities}). When the
  902. interpreter encounters a \key{let}, it evaluates the initializing
  903. expression, extends the environment with the result value bound to the
  904. variable, then evaluates the body of the \key{let}.
  905. \begin{figure}[tbp]
  906. \begin{lstlisting}
  907. (define (interp-exp env)
  908. (lambda (e)
  909. (match e
  910. [(? fixnum?) e]
  911. [`(read)
  912. (define r (read))
  913. (cond [(fixnum? r) r]
  914. [else (error 'interp-R1 "expected an integer" r)])]
  915. [`(- ,e)
  916. (define v ((interp-exp env) e))
  917. (fx- 0 v)]
  918. [`(+ ,e1 ,e2)
  919. (define v1 ((interp-exp env) e1))
  920. (define v2 ((interp-exp env) e2))
  921. (fx+ v1 v2)]
  922. [(? symbol?) (lookup e env)]
  923. [`(let ([,x ,e]) ,body)
  924. (define new-env (cons (cons x ((interp-exp env) e)) env))
  925. ((interp-exp new-env) body)]
  926. )))
  927. (define (interp-R1 env)
  928. (lambda (p)
  929. (match p
  930. [`(program ,info ,e) ((interp-exp '()) e)])))
  931. \end{lstlisting}
  932. \caption{Interpreter for the $R_1$ language.}
  933. \label{fig:interp-R1}
  934. \end{figure}
  935. The goal for this chapter is to implement a compiler that translates
  936. any program $P_1$ written in the $R_1$ language into an x86 assembly
  937. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  938. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  939. is, they both output the same integer $n$. We depict this correctness
  940. criteria in the following diagram.
  941. \[
  942. \begin{tikzpicture}[baseline=(current bounding box.center)]
  943. \node (p1) at (0, 0) {$P_1$};
  944. \node (p2) at (4, 0) {$P_2$};
  945. \node (o) at (4, -2) {$n$};
  946. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  947. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  948. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  949. \end{tikzpicture}
  950. \]
  951. In the next section we introduce enough of the x86 assembly
  952. language to compile $R_1$.
  953. \section{The x86 Assembly Language}
  954. \label{sec:x86}
  955. Figure~\ref{fig:x86-a} defines the syntax for the
  956. subset of the x86 assembly language needed for this chapter.
  957. %
  958. An x86 program is a sequence of instructions. The program is stored in
  959. the computer's memory and the computer has a \emph{program counter}
  960. that points to the address of the next instruction to be executed. For
  961. most instructions, once the instruction is executed, the program
  962. counter is incremented to point to the immediately following
  963. instruction in memory. Most x86 instructions take two operands, where
  964. each operand is either an integer constant (called \emph{immediate
  965. value}), a \emph{register}, or a \emph{memory} location. A register
  966. is a special kind of variable. Each one holds a 64-bit value; there
  967. are 16 registers in the computer and their names are given in
  968. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  969. addresses to 64-bit values%
  970. \footnote{This simple story suffices for describing how sequential
  971. programs access memory but is not sufficient for multi-threaded
  972. programs. However, multi-threaded execution is beyond the scope of
  973. this book.}.
  974. %
  975. We use the AT\&T syntax expected by the GNU assembler, which comes
  976. with the \key{gcc} compiler that we use for compiling assembly code to
  977. machine code.
  978. %
  979. Appendix~\ref{sec:x86-quick-reference} is a quick-reference of all the
  980. x86 instructions used in this book with a short explanation of what
  981. they do.
  982. % to do: finish treatment of imulq
  983. % it's needed for vector's in R6/R7
  984. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  985. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  986. && \key{r8} \mid \key{r9} \mid \key{r10}
  987. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  988. \mid \key{r14} \mid \key{r15}}
  989. \begin{figure}[tp]
  990. \fbox{
  991. \begin{minipage}{0.96\textwidth}
  992. \[
  993. \begin{array}{lcl}
  994. \Reg &::=& \allregisters{} \\
  995. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  996. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  997. \key{subq} \; \Arg, \Arg \mid
  998. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  999. && \key{callq} \; \mathit{label} \mid
  1000. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1001. \Prog &::= & \key{.globl main}\\
  1002. & & \key{main:} \; \Instr^{+}
  1003. \end{array}
  1004. \]
  1005. \end{minipage}
  1006. }
  1007. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1008. \label{fig:x86-a}
  1009. \end{figure}
  1010. An immediate value is written using the notation \key{\$}$n$ where $n$
  1011. is an integer.
  1012. %
  1013. A register is written with a \key{\%} followed by the register name,
  1014. such as \key{\%rax}.
  1015. %
  1016. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1017. which obtains the address stored in register $r$ and then adds $n$
  1018. bytes to the address. The resulting address is used to either load or
  1019. store to memory depending on whether it occurs as a source or
  1020. destination argument of an instruction.
  1021. An arithmetic instruction such as $\key{addq}\,s,\,d$ reads from the
  1022. source $s$ and destination $d$, applies the arithmetic operation, then
  1023. writes the result back to the destination $d$.
  1024. %
  1025. The move instruction $\key{movq}\,s\,d$ reads from $s$ and stores the
  1026. result in $d$.
  1027. %
  1028. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1029. specified by the label. We discuss procedure calls in more detail
  1030. later in this chapter and in Chapter~\ref{ch:functions}.
  1031. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1032. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1033. \key{main} procedure is externally visible, which is necessary so
  1034. that the operating system can call it. The label \key{main:}
  1035. indicates the beginning of the \key{main} procedure which is where
  1036. the operating system starts executing this program. The instruction
  1037. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1038. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1039. $10$ in \key{rax} and puts the result, $42$, back into
  1040. \key{rax}.
  1041. %
  1042. The last instruction, \key{retq}, finishes the \key{main} function by
  1043. returning the integer in \key{rax} to the operating system. The
  1044. operating system interprets this integer as the program's exit
  1045. code. By convention, an exit code of 0 indicates the program was
  1046. successful, and all other exit codes indicate various errors.
  1047. Nevertheless, we return the result of the program as the exit code.
  1048. %\begin{wrapfigure}{r}{2.25in}
  1049. \begin{figure}[tbp]
  1050. \begin{lstlisting}
  1051. .globl main
  1052. main:
  1053. movq $10, %rax
  1054. addq $32, %rax
  1055. retq
  1056. \end{lstlisting}
  1057. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1058. \label{fig:p0-x86}
  1059. %\end{wrapfigure}
  1060. \end{figure}
  1061. Unfortunately, x86 varies in a couple ways depending on what operating
  1062. system it is assembled in. The code examples shown here are correct on
  1063. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1064. labels like \key{main} must be prefixed with an underscore, as in
  1065. \key{\_main}.
  1066. We exhibit the use of memory for storing intermediate results in the
  1067. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1068. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1069. region of memory called the \emph{procedure call stack} (or
  1070. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1071. for each procedure call. The memory layout for an individual frame is
  1072. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1073. \emph{stack pointer} and points to the item at the top of the
  1074. stack. The stack grows downward in memory, so we increase the size of
  1075. the stack by subtracting from the stack pointer. Some operating
  1076. systems require the frame size to be a multiple of 16 bytes. In the
  1077. context of a procedure call, the \emph{return address} is the next
  1078. instruction after the call instruction on the caller side. During a
  1079. function call, the return address is pushed onto the stack. The
  1080. register \key{rbp} is the \emph{base pointer} which serves two
  1081. purposes: 1) it saves the location of the stack pointer for the
  1082. calling procedure and 2) it is used to access variables associated
  1083. with the current procedure. The base pointer of the calling procedure
  1084. is pushed onto the stack after the return address. We number the
  1085. variables from $1$ to $n$. Variable $1$ is stored at address
  1086. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1087. \begin{figure}[tbp]
  1088. \begin{lstlisting}
  1089. start:
  1090. movq $10, -8(%rbp)
  1091. negq -8(%rbp)
  1092. movq -8(%rbp), %rax
  1093. addq $52, %rax
  1094. jmp conclusion
  1095. .globl main
  1096. main:
  1097. pushq %rbp
  1098. movq %rsp, %rbp
  1099. subq $16, %rsp
  1100. jmp start
  1101. conclusion:
  1102. addq $16, %rsp
  1103. popq %rbp
  1104. retq
  1105. \end{lstlisting}
  1106. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1107. \label{fig:p1-x86}
  1108. \end{figure}
  1109. \begin{figure}[tbp]
  1110. \centering
  1111. \begin{tabular}{|r|l|} \hline
  1112. Position & Contents \\ \hline
  1113. 8(\key{\%rbp}) & return address \\
  1114. 0(\key{\%rbp}) & old \key{rbp} \\
  1115. -8(\key{\%rbp}) & variable $1$ \\
  1116. -16(\key{\%rbp}) & variable $2$ \\
  1117. \ldots & \ldots \\
  1118. 0(\key{\%rsp}) & variable $n$\\ \hline
  1119. \end{tabular}
  1120. \caption{Memory layout of a frame.}
  1121. \label{fig:frame}
  1122. \end{figure}
  1123. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1124. three instructions are the typical \emph{prelude} for a procedure.
  1125. The instruction \key{pushq \%rbp} saves the base pointer for the
  1126. caller onto the stack and subtracts $8$ from the stack pointer. The
  1127. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1128. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1129. stack pointer down to make enough room for storing variables. This
  1130. program needs one variable ($8$ bytes) but because the frame size is
  1131. required to be a multiple of 16 bytes, the space for variables is
  1132. rounded to 16 bytes.
  1133. The four instructions under the label \code{start} carry out the work
  1134. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1135. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1136. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1137. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1138. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1139. \key{rax}, at which point \key{rax} contains $42$.
  1140. The three instructions under the label \code{conclusion} are the
  1141. typical \emph{finale} of a procedure. The first two instructions are
  1142. necessary to get the state of the machine back to where it was at the
  1143. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1144. moves the stack pointer back to point at the old base pointer. The
  1145. amount added here needs to match the amount that was subtracted in the
  1146. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1147. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1148. instruction, \key{retq}, jumps back to the procedure that called this
  1149. one and adds 8 to the stack pointer, which returns the stack pointer
  1150. to where it was prior to the procedure call.
  1151. The compiler will need a convenient representation for manipulating
  1152. x86 programs, so we define an abstract syntax for x86 in
  1153. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1154. a subscript $0$ because later we introduce extended versions of this
  1155. assembly language. The main difference compared to the concrete syntax
  1156. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1157. instructions to appear anywhere, but instead organizes instructions
  1158. into groups called \emph{blocks} and associates a label with every
  1159. block, which is why the \key{program} form includes an association
  1160. list mapping labels to blocks. The reason for this organization
  1161. becomes apparent in Chapter~\ref{ch:bool-types}.
  1162. \begin{figure}[tp]
  1163. \fbox{
  1164. \begin{minipage}{0.96\textwidth}
  1165. \[
  1166. \begin{array}{lcl}
  1167. \itm{register} &::=& \allregisters{} \\
  1168. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1169. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1170. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1171. (\key{subq} \; \Arg\; \Arg) \mid
  1172. (\key{movq} \; \Arg\; \Arg) \mid
  1173. (\key{retq})\\
  1174. &\mid& (\key{negq} \; \Arg) \mid
  1175. (\key{callq} \; \mathit{label}) \mid
  1176. (\key{pushq}\;\Arg) \mid
  1177. (\key{popq}\;\Arg) \\
  1178. \Block &::= & (\key{block} \;\itm{info}\; \Instr^{+}) \\
  1179. x86_0 &::= & (\key{program} \;\itm{info} \; ((\itm{label} \,\key{.}\, \Block)^{+}))
  1180. \end{array}
  1181. \]
  1182. \end{minipage}
  1183. }
  1184. \caption{Abstract syntax for $x86_0$ assembly.}
  1185. \label{fig:x86-ast-a}
  1186. \end{figure}
  1187. \section{Planning the trip to x86 via the $C_0$ language}
  1188. \label{sec:plan-s0-x86}
  1189. To compile one language to another it helps to focus on the
  1190. differences between the two languages because the compiler will need
  1191. to bridge those differences. What are the differences between $R_1$
  1192. and x86 assembly? Here we list some of the most important ones.
  1193. \begin{enumerate}
  1194. \item[(a)] x86 arithmetic instructions typically have two arguments
  1195. and update the second argument in place. In contrast, $R_1$
  1196. arithmetic operations take two arguments and produce a new value.
  1197. An x86 instruction may have at most one memory-accessing argument.
  1198. Furthermore, some instructions place special restrictions on their
  1199. arguments.
  1200. \item[(b)] An argument to an $R_1$ operator can be any expression,
  1201. whereas x86 instructions restrict their arguments to be integers
  1202. constants, registers, and memory locations.
  1203. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1204. sequence of instructions and jumps to labeled positions, whereas in
  1205. $R_1$ the order of evaluation is a left-to-right depth-first
  1206. traversal of the abstract syntax tree.
  1207. \item[(d)] An $R_1$ program can have any number of variables whereas
  1208. x86 has 16 registers and the procedure calls stack.
  1209. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1210. same name. The registers and memory locations of x86 all have unique
  1211. names or addresses.
  1212. \end{enumerate}
  1213. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1214. the problem into several steps, dealing with the above differences one
  1215. at a time. Each of these steps is called a \emph{pass} of the
  1216. compiler, because step traverses (passes over) the AST of the program.
  1217. %
  1218. We begin by sketching how we might implement each pass, and give them
  1219. names. We then figure out an ordering of the passes and the
  1220. input/output language for each pass. The very first pass has $R_1$ as
  1221. its input language and the last pass has x86 as its output
  1222. language. In between we can choose whichever language is most
  1223. convenient for expressing the output of each pass, whether that be
  1224. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1225. Finally, to implement each pass we write one recursive function per
  1226. non-terminal in the grammar of the input language of the pass.
  1227. \begin{description}
  1228. \item[Pass \key{select-instructions}] To handle the difference between
  1229. $R_1$ operations and x86 instructions we shall convert each $R_1$
  1230. operation to a short sequence of instructions that accomplishes the
  1231. same task.
  1232. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1233. subexpression (i.e. operator and operand, and hence \key{opera*}) is
  1234. a \emph{simple expression} (a variable or integer), we shall
  1235. introduce temporary variables to hold the results of subexpressions.
  1236. \item[Pass \key{explicate-control}] To make the execution order of the
  1237. program explicit, we shall convert from the abstract syntax tree
  1238. representation into a \emph{control-flow graph} in which each node
  1239. contains a sequence of statements and the edges between nodes say
  1240. where to go next.
  1241. \item[Pass \key{assign-homes}] To handle the difference between the
  1242. variables in $R_1$ versus the registers and stack location in x86,
  1243. we assignment of each variable to a register or stack location.
  1244. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1245. by renaming every variable to a unique name, so that shadowing no
  1246. longer occurs.
  1247. \end{description}
  1248. The next question is: in what order should we apply these passes? This
  1249. question can be challenging because it is difficult to know ahead of
  1250. time which orders will be better (easier to implement, produce more
  1251. efficient code, etc.) so often some trial-and-error is
  1252. involved. Nevertheless, we can try to plan ahead and make educated
  1253. choices regarding the ordering.
  1254. Let us consider the ordering of \key{uniquify} and
  1255. \key{remove-complex-opera*}. The assignment of subexpressions to
  1256. temporary variables involves introducing new variables and moving
  1257. subexpressions, which might change the shadowing of variables and
  1258. inadvertently change the behavior of the program. But if we apply
  1259. \key{uniquify} first, this will not be an issue. Of course, this means
  1260. that in \key{remove-complex-opera*}, we need to ensure that the
  1261. temporary variables that it creates are unique.
  1262. What should be the ordering of \key{explicate-control} with respect to
  1263. \key{uniquify}? The \key{uniquify} pass should come first because
  1264. \key{explicate-control} changes all the \key{let}-bound variables to
  1265. become local variables whose scope is the entire program, which would
  1266. confuse variables with the same name.
  1267. %
  1268. Likewise, we place \key{explicate-control} after
  1269. \key{remove-complex-opera*} because \key{explicate-control} removes
  1270. the \key{let} form, but it is convenient to use \key{let} in the
  1271. output of \key{remove-complex-opera*}.
  1272. %
  1273. Regarding \key{assign-homes}, it is helpful to place
  1274. \key{explicate-control} first because \key{explicate-control} changes
  1275. \key{let}-bound variables into program-scope variables. Instead of
  1276. traversing the entire program for \key{let}-bound variables,
  1277. \key{assign-homes} can read them off from the $\itm{info}$ of the
  1278. \key{program} AST node.
  1279. Last, we need to decide on the ordering of \key{select-instructions}
  1280. and \key{assign-homes}. These two passes are intertwined, creating a
  1281. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1282. have already determined which instructions will be used, because x86
  1283. instructions have restrictions about which of their arguments can be
  1284. registers versus stack locations. For example, one can give
  1285. preferential treatment to variables that occur in register-argument
  1286. positions. On the other hand, it may turn out to be impossible to make
  1287. sure that all such variables are assigned to registers, and then one
  1288. must redo the selection of instructions. Some compilers handle this
  1289. problem by iteratively repeating these two passes until a good
  1290. solution is found. We shall use a simpler approach in which
  1291. \key{select-instructions} comes first, followed by the
  1292. \key{assign-homes}, followed by a third pass, named
  1293. \key{patch-instructions}, that uses a reserved register to patch-up
  1294. outstanding problems regarding instructions with too many memory
  1295. accesses. The disadvantage of this approach a reduction in runtime
  1296. efficiency.
  1297. \begin{figure}[tbp]
  1298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1299. \node (R1) at (0,2) {\large $R_1$};
  1300. \node (R1-2) at (3,2) {\large $R_1$};
  1301. \node (R1-3) at (6,2) {\large $R_1$};
  1302. %\node (C0-1) at (6,0) {\large $C_0$};
  1303. \node (C0-2) at (3,0) {\large $C_0$};
  1304. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1305. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1306. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1307. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1308. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1309. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1310. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1311. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1312. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1313. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1314. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1315. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1316. \end{tikzpicture}
  1317. \caption{Overview of the passes for compiling $R_1$. }
  1318. \label{fig:R1-passes}
  1319. \end{figure}
  1320. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1321. passes in the form of a graph. Each pass is an edge and the
  1322. input/output language of each pass is a node in the graph. The output
  1323. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1324. are still in the $R_1$ language, but the output of the pass
  1325. \key{explicate-control} is in a different language that is designed to
  1326. make the order of evaluation explicit in its syntax, which we
  1327. introduce in the next section. The last pass in
  1328. Figure~\ref{fig:R1-passes} is \key{print-x86}, which converts from the
  1329. abstract syntax of $\text{x86}_0$ to the concrete (textual) syntax of
  1330. x86.
  1331. In the next sections we discuss the $C_0$ language and the
  1332. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1333. remainder of this chapter gives hints regarding the implementation of
  1334. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1335. \subsection{The $C_0$ Intermediate Language}
  1336. The output of \key{explicate-control} is similar to the $C$
  1337. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1338. categories for expressions and statements, so we name it $C_0$. The
  1339. syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}.
  1340. %
  1341. The $C_0$ language supports the same operators as $R_1$ but the
  1342. arguments of operators are now restricted to just variables and
  1343. integers, thanks to the \key{remove-complex-opera*} pass. In the
  1344. literature this style of intermediate language is called
  1345. administrative normal form, or ANF for
  1346. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{let}
  1347. expressions, $C_0$ has assignment statements which can be executed in
  1348. sequence using the \key{seq} construct. A sequence of statements
  1349. always ends with \key{return}, a guarantee that is baked into the
  1350. grammar rules for the \itm{tail} non-terminal. The naming of this
  1351. non-terminal comes from the term \emph{tail position}, which refers to
  1352. an expression that is the last one to execute within a function. (A
  1353. expression in tail position may contain subexpressions, and those may
  1354. or may not be in tail position depending on the kind of expression.)
  1355. A $C_0$ program consists of an association list mapping labels to
  1356. tails. This is overkill for the present chapter, as we do not yet need
  1357. to introduce \key{goto} for jumping to labels, but it saves us from
  1358. having to change the syntax of the program construct in
  1359. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1360. \key{start}, and the whole program is it's tail.
  1361. %
  1362. The $\itm{info}$ field of the program construct, after the
  1363. \key{explicate-control} pass, contains a mapping from the symbol
  1364. \key{locals} to a list of variables, that is, a list of all the
  1365. variables used in the program. At the start of the program, these
  1366. variables are uninitialized; they become initialized on their first
  1367. assignment.
  1368. \begin{figure}[tbp]
  1369. \fbox{
  1370. \begin{minipage}{0.96\textwidth}
  1371. \[
  1372. \begin{array}{lcl}
  1373. \Arg &::=& \Int \mid \Var \\
  1374. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1375. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1376. \Tail &::= & \RETURN{\Exp} \mid (\key{seq}\; \Stmt\; \Tail) \\
  1377. C_0 & ::= & (\key{program}\;\itm{info}\;((\itm{label}\,\key{.}\,\Tail)^{+}))
  1378. \end{array}
  1379. \]
  1380. \end{minipage}
  1381. }
  1382. \caption{The $C_0$ intermediate language.}
  1383. \label{fig:c0-syntax}
  1384. \end{figure}
  1385. %% The \key{select-instructions} pass is optimistic in the sense that it
  1386. %% treats variables as if they were all mapped to registers. The
  1387. %% \key{select-instructions} pass generates a program that consists of
  1388. %% x86 instructions but that still uses variables, so it is an
  1389. %% intermediate language that is technically different than x86, which
  1390. %% explains the asterisks in the diagram above.
  1391. %% In this Chapter we shall take the easy road to implementing
  1392. %% \key{assign-homes} and simply map all variables to stack locations.
  1393. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1394. %% smarter approach in which we make a best-effort to map variables to
  1395. %% registers, resorting to the stack only when necessary.
  1396. %% Once variables have been assigned to their homes, we can finalize the
  1397. %% instruction selection by dealing with an idiosyncrasy of x86
  1398. %% assembly. Many x86 instructions have two arguments but only one of the
  1399. %% arguments may be a memory reference (and the stack is a part of
  1400. %% memory). Because some variables may get mapped to stack locations,
  1401. %% some of our generated instructions may violate this restriction. The
  1402. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1403. %% replacing every violating instruction with a short sequence of
  1404. %% instructions that use the \key{rax} register. Once we have implemented
  1405. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1406. %% need to patch instructions will be relatively rare.
  1407. \subsection{The dialects of x86}
  1408. The x86$^{*}_0$ language, pronounced ``pseudo-x86'', is the output of
  1409. the pass \key{select-instructions}. It extends $x86_0$ with an unbound
  1410. number program-scope variables and has looser rules regarding
  1411. instruction arguments. The x86$^{\dagger}$ language, the output of
  1412. \key{print-x86}, is the concrete syntax for x86.
  1413. \section{Uniquify Variables}
  1414. \label{sec:uniquify-s0}
  1415. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1416. programs in which every \key{let} uses a unique variable name. For
  1417. example, the \code{uniquify} pass should translate the program on the
  1418. left into the program on the right. \\
  1419. \begin{tabular}{lll}
  1420. \begin{minipage}{0.4\textwidth}
  1421. \begin{lstlisting}
  1422. (program ()
  1423. (let ([x 32])
  1424. (+ (let ([x 10]) x) x)))
  1425. \end{lstlisting}
  1426. \end{minipage}
  1427. &
  1428. $\Rightarrow$
  1429. &
  1430. \begin{minipage}{0.4\textwidth}
  1431. \begin{lstlisting}
  1432. (program ()
  1433. (let ([x.1 32])
  1434. (+ (let ([x.2 10]) x.2) x.1)))
  1435. \end{lstlisting}
  1436. \end{minipage}
  1437. \end{tabular} \\
  1438. %
  1439. The following is another example translation, this time of a program
  1440. with a \key{let} nested inside the initializing expression of another
  1441. \key{let}.\\
  1442. \begin{tabular}{lll}
  1443. \begin{minipage}{0.4\textwidth}
  1444. \begin{lstlisting}
  1445. (program ()
  1446. (let ([x (let ([x 4])
  1447. (+ x 1))])
  1448. (+ x 2)))
  1449. \end{lstlisting}
  1450. \end{minipage}
  1451. &
  1452. $\Rightarrow$
  1453. &
  1454. \begin{minipage}{0.4\textwidth}
  1455. \begin{lstlisting}
  1456. (program ()
  1457. (let ([x.2 (let ([x.1 4])
  1458. (+ x.1 1))])
  1459. (+ x.2 2)))
  1460. \end{lstlisting}
  1461. \end{minipage}
  1462. \end{tabular}
  1463. We recommend implementing \code{uniquify} by creating a function named
  1464. \code{uniquify-exp} that is structurally recursive function and mostly
  1465. just copies the input program. However, when encountering a \key{let},
  1466. it should generate a unique name for the variable (the Racket function
  1467. \code{gensym} is handy for this) and associate the old name with the
  1468. new unique name in an association list. The \code{uniquify-exp}
  1469. function will need to access this association list when it gets to a
  1470. variable reference, so we add another parameter to \code{uniquify-exp}
  1471. for the association list. It is quite common for a compiler pass to
  1472. need a map to store extra information about variables. Such maps are
  1473. traditionally called \emph{symbol tables}.
  1474. The skeleton of the \code{uniquify-exp} function is shown in
  1475. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1476. convenient to partially apply it to an association list and then apply
  1477. it to different expressions, as in the last clause for primitive
  1478. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1479. clause for the primitive operators, note the use of the comma-\code{@}
  1480. operator to splice a list of S-expressions into an enclosing
  1481. S-expression.
  1482. \begin{exercise}
  1483. \normalfont % I don't like the italics for exercises. -Jeremy
  1484. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1485. implement the clauses for variables and for the \key{let} construct.
  1486. \end{exercise}
  1487. \begin{figure}[tbp]
  1488. \begin{lstlisting}
  1489. (define (uniquify-exp symtab)
  1490. (lambda (e)
  1491. (match e
  1492. [(? symbol?) ___]
  1493. [(? integer?) e]
  1494. [`(let ([,x ,e]) ,body) ___]
  1495. [`(,op ,es ...)
  1496. `(,op ,@(for/list ([e es]) ((uniquify-exp symtab) e)))]
  1497. )))
  1498. (define (uniquify p)
  1499. (match p
  1500. [`(program ,info ,e)
  1501. `(program ,info ,((uniquify-exp '()) e))]
  1502. )))
  1503. \end{lstlisting}
  1504. \caption{Skeleton for the \key{uniquify} pass.}
  1505. \label{fig:uniquify-s0}
  1506. \end{figure}
  1507. \begin{exercise}
  1508. \normalfont % I don't like the italics for exercises. -Jeremy
  1509. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1510. and checking whether the output programs produce the same result as
  1511. the input programs. The $R_1$ programs should be designed to test the
  1512. most interesting parts of the \key{uniquify} pass, that is, the
  1513. programs should include \key{let} constructs, variables, and variables
  1514. that overshadow each other. The five programs should be in a
  1515. subdirectory named \key{tests} and they should have the same file name
  1516. except for a different integer at the end of the name, followed by the
  1517. ending \key{.rkt}. Use the \key{interp-tests} function
  1518. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1519. your \key{uniquify} pass on the example programs. See the
  1520. \key{run-tests.rkt} script in the student support code for an example
  1521. of how to use \key{interp-tests}.
  1522. \end{exercise}
  1523. \section{Remove Complex Operands}
  1524. \label{sec:remove-complex-opera-r1}
  1525. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1526. $R_1$ programs in which the arguments of operations are simple
  1527. expressions. Put another way, this pass removes complex operands,
  1528. such as the expression \code{(- 10)} in the program below. This is
  1529. accomplished by introducing a new \key{let}-bound variable, binding
  1530. the complex operand to the new variable, and then using the new
  1531. variable in place of the complex operand, as shown in the output of
  1532. \code{remove-complex-opera*} on the right.\\
  1533. \begin{tabular}{lll}
  1534. \begin{minipage}{0.4\textwidth}
  1535. % s0_19.rkt
  1536. \begin{lstlisting}
  1537. (program ()
  1538. (+ 52 (- 10)))
  1539. \end{lstlisting}
  1540. \end{minipage}
  1541. &
  1542. $\Rightarrow$
  1543. &
  1544. \begin{minipage}{0.4\textwidth}
  1545. \begin{lstlisting}
  1546. (program ()
  1547. (let ([tmp.1 (- 10)])
  1548. (+ 52 tmp.1)))
  1549. \end{lstlisting}
  1550. \end{minipage}
  1551. \end{tabular}
  1552. We recommend implementing this pass with two mutually recursive
  1553. functions, \code{rco-arg} and \code{rco-exp}. The idea is to apply
  1554. \code{rco-arg} to subexpressions that need to become simple and to
  1555. apply \code{rco-exp} to subexpressions can stay complex. Both
  1556. functions take an $R_1$ expression as input. The \code{rco-exp}
  1557. function returns an expression. The \code{rco-arg} function returns
  1558. two things: a simple expression and association list mapping temporary
  1559. variables to complex subexpressions. You can return multiple things
  1560. from a function using Racket's \key{values} form and you can receive
  1561. multiple things from a function call using the \key{define-values}
  1562. form. If you are not familiar with these constructs, review the Racket
  1563. documentation. Also, the \key{for/lists} construct is useful for
  1564. applying a function to each element of a list, in the case where the
  1565. function returns multiple values.
  1566. The following shows the output of \code{rco-arg} on the expression
  1567. \code{(- 10)}.
  1568. \begin{tabular}{lll}
  1569. \begin{minipage}{0.4\textwidth}
  1570. \begin{lstlisting}
  1571. (rco-arg `(- 10))
  1572. \end{lstlisting}
  1573. \end{minipage}
  1574. &
  1575. $\Rightarrow$
  1576. &
  1577. \begin{minipage}{0.4\textwidth}
  1578. \begin{lstlisting}
  1579. (values `tmp.1
  1580. `((tmp.1 . (- 10))))
  1581. \end{lstlisting}
  1582. \end{minipage}
  1583. \end{tabular}
  1584. Take special care of programs such as the next one that \key{let}-bind
  1585. variables with integers or other variables. You should leave them
  1586. unchanged, as shown in to the program on the right \\
  1587. \begin{tabular}{lll}
  1588. \begin{minipage}{0.4\textwidth}
  1589. % s0_20.rkt
  1590. \begin{lstlisting}
  1591. (program ()
  1592. (let ([a 42])
  1593. (let ([b a])
  1594. b)))
  1595. \end{lstlisting}
  1596. \end{minipage}
  1597. &
  1598. $\Rightarrow$
  1599. &
  1600. \begin{minipage}{0.4\textwidth}
  1601. \begin{lstlisting}
  1602. (program ()
  1603. (let ([a 42])
  1604. (let ([b a])
  1605. b)))
  1606. \end{lstlisting}
  1607. \end{minipage}
  1608. \end{tabular} \\
  1609. A careless implementation of \key{rco-exp} and \key{rco-arg} might
  1610. produce the following output.\\
  1611. \begin{minipage}{0.4\textwidth}
  1612. \begin{lstlisting}
  1613. (program ()
  1614. (let ([tmp.1 42])
  1615. (let ([a tmp.1])
  1616. (let ([tmp.2 a])
  1617. (let ([b tmp.2])
  1618. b)))))
  1619. \end{lstlisting}
  1620. \end{minipage}
  1621. \begin{exercise}
  1622. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1623. it on all of the example programs that you created to test the
  1624. \key{uniquify} pass and create three new example programs that are
  1625. designed to exercise all of the interesting code in the
  1626. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1627. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1628. your passes on the example programs.
  1629. \end{exercise}
  1630. \section{Explicate Control}
  1631. \label{sec:explicate-control-r1}
  1632. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1633. programs that make the order of execution explicit in their
  1634. syntax. For now this amounts to flattening \key{let} constructs into a
  1635. sequence of assignment statements. For example, consider the following
  1636. $R_1$ program.
  1637. % s0_11.rkt
  1638. \begin{lstlisting}
  1639. (program ()
  1640. (let ([y (let ([x 20])
  1641. (+ x (let ([x 22]) x)))])
  1642. y))
  1643. \end{lstlisting}
  1644. %
  1645. The output of the previous pass and of \code{explicate-control} is
  1646. shown below. Recall that the right-hand-side of a \key{let} executes
  1647. before its body, so the order of evaluation for this program is to
  1648. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1649. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1650. output of \code{explicate-control} makes this ordering explicit.\\
  1651. \begin{tabular}{lll}
  1652. \begin{minipage}{0.4\textwidth}
  1653. \begin{lstlisting}
  1654. (program ()
  1655. (let ([y (let ([x.1 20])
  1656. (let ([x.2 22])
  1657. (+ x.1 x.2)))])
  1658. y))
  1659. \end{lstlisting}
  1660. \end{minipage}
  1661. &
  1662. $\Rightarrow$
  1663. &
  1664. \begin{minipage}{0.4\textwidth}
  1665. \begin{lstlisting}
  1666. (program ((locals . (y x.1 x.2)))
  1667. ((start .
  1668. (seq (assign x.1 20)
  1669. (seq (assign x.2 22)
  1670. (seq (assign y (+ x.1 x.2))
  1671. (return y)))))))
  1672. \end{lstlisting}
  1673. \end{minipage}
  1674. \end{tabular}
  1675. We recommend implementing \code{explicate-control} using two mutually
  1676. recursive functions: \code{explicate-control-tail} and
  1677. \code{explicate-control-assign}. The \code{explicate-control-tail}
  1678. function should be applied to expressions in tail position whereas
  1679. \code{explicate-control-assign} should be applied to expressions that
  1680. occur on the right-hand-side of a \key{let}.
  1681. \code{explicate-control-tail} takes an $R_1$ expression as input and
  1682. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1683. of formerly \key{let}-bound variables. The
  1684. \code{explicate-control-assign} function takes an $R_1$ expression,
  1685. the variable that it is to be assigned to, and $C_0$ code (a $\Tail$)
  1686. that should come after the assignment (e.g., the code generated for
  1687. the body of the \key{let}). It returns a $\Tail$ and a list of
  1688. variables. The top-level \code{explicate-control} function should
  1689. invoke \code{explicate-control-tail} on the body of the \key{program}
  1690. and then associate the \code{locals} symbol with the resulting list of
  1691. variables in the $\itm{info}$ field, as in the above example.
  1692. %% \section{Uncover Locals}
  1693. %% \label{sec:uncover-locals-r1}
  1694. %% The pass \code{uncover-locals} simply collects all of the variables in
  1695. %% the program and places then in the $\itm{info}$ of the program
  1696. %% construct. Here is the output for the example program of the last
  1697. %% section.
  1698. %% \begin{minipage}{0.4\textwidth}
  1699. %% \begin{lstlisting}
  1700. %% (program ((locals . (x.1 x.2 y)))
  1701. %% ((start .
  1702. %% (seq (assign x.1 20)
  1703. %% (seq (assign x.2 22)
  1704. %% (seq (assign y (+ x.1 x.2))
  1705. %% (return y)))))))
  1706. %% \end{lstlisting}
  1707. %% \end{minipage}
  1708. \section{Select Instructions}
  1709. \label{sec:select-r1}
  1710. In the \code{select-instructions} pass we begin the work of
  1711. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1712. this pass is a pseudo-x86 language that still uses variables, so we
  1713. add an AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$
  1714. abstract syntax of Figure~\ref{fig:x86-ast-a}. We recommend
  1715. implementing the \code{select-instructions} in terms of three
  1716. auxiliary functions, one for each of the non-terminals of $C_0$:
  1717. $\Arg$, $\Stmt$, and $\Tail$.
  1718. The cases for $\itm{arg}$ are straightforward, simply put variables
  1719. and integer literals into the s-expression format expected of
  1720. pseudo-x86, \code{(var $x$)} and \code{(int $n$)}, respectively.
  1721. Next we consider the cases for $\itm{stmt}$, starting with arithmetic
  1722. operations. For example, in $C_0$ an addition operation can take the
  1723. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1724. need to use the \key{addq} instruction which does an in-place
  1725. update. So we must first move \code{10} to \code{x}. \\
  1726. \begin{tabular}{lll}
  1727. \begin{minipage}{0.4\textwidth}
  1728. \begin{lstlisting}
  1729. (assign x (+ 10 32))
  1730. \end{lstlisting}
  1731. \end{minipage}
  1732. &
  1733. $\Rightarrow$
  1734. &
  1735. \begin{minipage}{0.4\textwidth}
  1736. \begin{lstlisting}
  1737. (movq (int 10) (var x))
  1738. (addq (int 32) (var x))
  1739. \end{lstlisting}
  1740. \end{minipage}
  1741. \end{tabular} \\
  1742. %
  1743. There are cases that require special care to avoid generating
  1744. needlessly complicated code. If one of the arguments of the addition
  1745. is the same as the left-hand side of the assignment, then there is no
  1746. need for the extra move instruction. For example, the following
  1747. assignment statement can be translated into a single \key{addq}
  1748. instruction.\\
  1749. \begin{tabular}{lll}
  1750. \begin{minipage}{0.4\textwidth}
  1751. \begin{lstlisting}
  1752. (assign x (+ 10 x))
  1753. \end{lstlisting}
  1754. \end{minipage}
  1755. &
  1756. $\Rightarrow$
  1757. &
  1758. \begin{minipage}{0.4\textwidth}
  1759. \begin{lstlisting}
  1760. (addq (int 10) (var x))
  1761. \end{lstlisting}
  1762. \end{minipage}
  1763. \end{tabular} \\
  1764. The \key{read} operation does not have a direct counterpart in x86
  1765. assembly, so we have instead implemented this functionality in the C
  1766. language, with the function \code{read\_int} in the file
  1767. \code{runtime.c}. In general, we refer to all of the functionality in
  1768. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1769. for short. When compiling your generated x86 assembly code, you need
  1770. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1771. using \code{gcc} option \code{-c}) and link it into the
  1772. executable. For our purposes of code generation, all you need to do is
  1773. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1774. (for left-hand side) into a call to the \code{read\_int} function
  1775. followed by a move from \code{rax} to the left-hand side. The move
  1776. from \code{rax} is needed because the return value from
  1777. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1778. \begin{tabular}{lll}
  1779. \begin{minipage}{0.4\textwidth}
  1780. \begin{lstlisting}
  1781. (assign |$\itm{lhs}$| (read))
  1782. \end{lstlisting}
  1783. \end{minipage}
  1784. &
  1785. $\Rightarrow$
  1786. &
  1787. \begin{minipage}{0.4\textwidth}
  1788. \begin{lstlisting}
  1789. (callq read_int)
  1790. (movq (reg rax) (var |$\itm{lhs}$|))
  1791. \end{lstlisting}
  1792. \end{minipage}
  1793. \end{tabular} \\
  1794. There are two cases for the $\Tail$ non-terminal: \key{return} and
  1795. \key{seq}. Regarding \RETURN{e}, we recommend treating it as an
  1796. assignment to the \key{rax} register followed by a jump to the
  1797. conclusion of the program (so the conclusion needs to be labeled).
  1798. For $(\key{seq}\,s\,t)$, we the statement $s$ and tail $t$ recursively
  1799. and append the resulting instructions.
  1800. \begin{exercise}
  1801. \normalfont
  1802. Implement the \key{select-instructions} pass and test it on all of the
  1803. example programs that you created for the previous passes and create
  1804. three new example programs that are designed to exercise all of the
  1805. interesting code in this pass. Use the \key{interp-tests} function
  1806. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1807. your passes on the example programs.
  1808. \end{exercise}
  1809. \section{Assign Homes}
  1810. \label{sec:assign-r1}
  1811. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1812. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1813. Thus, the \key{assign-homes} pass is responsible for placing all of
  1814. the program variables in registers or on the stack. For runtime
  1815. efficiency, it is better to place variables in registers, but as there
  1816. are only 16 registers, some programs must necessarily place some
  1817. variables on the stack. In this chapter we focus on the mechanics of
  1818. placing variables on the stack. We study an algorithm for placing
  1819. variables in registers in Chapter~\ref{ch:register-allocation-r1}.
  1820. Consider again the following $R_1$ program.
  1821. % s0_20.rkt
  1822. \begin{lstlisting}
  1823. (program ()
  1824. (let ([a 42])
  1825. (let ([b a])
  1826. b)))
  1827. \end{lstlisting}
  1828. For reference, we repeat the output of \code{select-instructions} on
  1829. the left and show the output of \code{assign-homes} on the right.
  1830. Recall that \key{explicate-control} associated the list of
  1831. variables with the \code{locals} symbol in the program's $\itm{info}$
  1832. field, so \code{assign-homes} has convenient access to the them. In
  1833. this example, we assign variable \code{a} to stack location
  1834. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1835. \begin{tabular}{l}
  1836. \begin{minipage}{0.4\textwidth}
  1837. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1838. (program ((locals . (a b)))
  1839. ((start .
  1840. (block ()
  1841. (movq (int 42) (var a))
  1842. (movq (var a) (var b))
  1843. (movq (var b) (reg rax))
  1844. (jmp conclusion)))))
  1845. \end{lstlisting}
  1846. \end{minipage}
  1847. {$\Rightarrow$}
  1848. \begin{minipage}{0.4\textwidth}
  1849. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1850. (program ((stack-space . 16))
  1851. ((start .
  1852. (block ()
  1853. (movq (int 42) (deref rbp -8))
  1854. (movq (deref rbp -8) (deref rbp -16))
  1855. (movq (deref rbp -16) (reg rax))
  1856. (jmp conclusion)))))
  1857. \end{lstlisting}
  1858. \end{minipage}
  1859. \end{tabular} \\
  1860. In the process of assigning variables to stack locations, it is
  1861. convenient to compute and store the size of the frame (in bytes) in
  1862. the $\itm{info}$ field of the \key{program} node, with the key
  1863. \code{stack-space}, which will be needed later to generate the
  1864. procedure conclusion. Some operating systems place restrictions on
  1865. the frame size. For example, Mac OS X requires the frame size to be a
  1866. multiple of 16 bytes.
  1867. \begin{exercise}
  1868. \normalfont Implement the \key{assign-homes} pass and test it on all
  1869. of the example programs that you created for the previous passes pass.
  1870. We recommend that \key{assign-homes} take an extra parameter that is a
  1871. mapping of variable names to homes (stack locations for now). Use the
  1872. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1873. \key{utilities.rkt} to test your passes on the example programs.
  1874. \end{exercise}
  1875. \section{Patch Instructions}
  1876. \label{sec:patch-s0}
  1877. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  1878. programs to $\text{x86}_0$ programs by making sure that each
  1879. instruction adheres to the restrictions of the x86 assembly language.
  1880. In particular, at most one argument of an instruction may be a memory
  1881. reference.
  1882. We return to the following running example.
  1883. % s0_20.rkt
  1884. \begin{lstlisting}
  1885. (let ([a 42])
  1886. (let ([b a])
  1887. b))
  1888. \end{lstlisting}
  1889. After the \key{assign-homes} pass, the above program has been translated to
  1890. the following. \\
  1891. \begin{minipage}{0.5\textwidth}
  1892. \begin{lstlisting}
  1893. (program ((stack-space . 16))
  1894. ((start .
  1895. (block ()
  1896. (movq (int 42) (deref rbp -8))
  1897. (movq (deref rbp -8) (deref rbp -16))
  1898. (movq (deref rbp -16) (reg rax))
  1899. (jmp conclusion)))))
  1900. \end{lstlisting}
  1901. \end{minipage}\\
  1902. The second \key{movq} instruction is problematic because both
  1903. arguments are stack locations. We suggest fixing this problem by
  1904. moving from the source location to the register \key{rax} and then
  1905. from \key{rax} to the destination location, as follows.
  1906. \begin{lstlisting}
  1907. (movq (deref rbp -8) (reg rax))
  1908. (movq (reg rax) (deref rbp -16))
  1909. \end{lstlisting}
  1910. \begin{exercise}
  1911. \normalfont
  1912. Implement the \key{patch-instructions} pass and test it on all of the
  1913. example programs that you created for the previous passes and create
  1914. three new example programs that are designed to exercise all of the
  1915. interesting code in this pass. Use the \key{interp-tests} function
  1916. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1917. your passes on the example programs.
  1918. \end{exercise}
  1919. \section{Print x86}
  1920. \label{sec:print-x86}
  1921. The last step of the compiler from $R_1$ to x86 is to convert the
  1922. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  1923. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1924. \key{format} and \key{string-append} functions are useful in this
  1925. regard. The main work that this step needs to perform is to create the
  1926. \key{main} function and the standard instructions for its prelude and
  1927. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1928. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  1929. variables, so we suggest computing it in the \key{assign-homes} pass
  1930. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  1931. of the \key{program} node.
  1932. %% Your compiled code should print the result of the program's execution
  1933. %% by using the \code{print\_int} function provided in
  1934. %% \code{runtime.c}. If your compiler has been implemented correctly so
  1935. %% far, this final result should be stored in the \key{rax} register.
  1936. %% We'll talk more about how to perform function calls with arguments in
  1937. %% general later on, but for now, place the following after the compiled
  1938. %% code for the $R_1$ program but before the conclusion:
  1939. %% \begin{lstlisting}
  1940. %% movq %rax, %rdi
  1941. %% callq print_int
  1942. %% \end{lstlisting}
  1943. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  1944. %% stores the first argument to be passed into \key{print\_int}.
  1945. If you want your program to run on Mac OS X, your code needs to
  1946. determine whether or not it is running on a Mac, and prefix
  1947. underscores to labels like \key{main}. You can determine the platform
  1948. with the Racket call \code{(system-type 'os)}, which returns
  1949. \code{'macosx}, \code{'unix}, or \code{'windows}.
  1950. %% In addition to
  1951. %% placing underscores on \key{main}, you need to put them in front of
  1952. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1953. %% \_print\_int}).
  1954. \begin{exercise}
  1955. \normalfont Implement the \key{print-x86} pass and test it on all of
  1956. the example programs that you created for the previous passes. Use the
  1957. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1958. \key{utilities.rkt} to test your complete compiler on the example
  1959. programs. See the \key{run-tests.rkt} script in the student support
  1960. code for an example of how to use \key{compiler-tests}. Also, remember
  1961. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  1962. \key{gcc}.
  1963. \end{exercise}
  1964. \section{Challenge: Partial Evaluator for $R_1$}
  1965. \label{sec:pe-R1}
  1966. This section describes optional challenge exercises that involve
  1967. adapting and improving the partial evaluator for $R_0$ that was
  1968. introduced in Section~\ref{sec:partial-evaluation}.
  1969. \begin{exercise}\label{ex:pe-R1}
  1970. \normalfont
  1971. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  1972. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  1973. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  1974. and variables to the $R_0$ language, so you will need to add cases for
  1975. them in the \code{pe-exp} function. Also, note that the \key{program}
  1976. form changes slightly to include an $\itm{info}$ field. Once
  1977. complete, add the partial evaluation pass to the front of your
  1978. compiler and make sure that your compiler still passes all of the
  1979. tests.
  1980. \end{exercise}
  1981. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  1982. \begin{exercise}
  1983. \normalfont
  1984. Improve on the partial evaluator by replacing the \code{pe-neg} and
  1985. \code{pe-add} auxiliary functions with functions that know more about
  1986. arithmetic. For example, your partial evaluator should translate
  1987. \begin{lstlisting}
  1988. (+ 1 (+ (read) 1))
  1989. \end{lstlisting}
  1990. into
  1991. \begin{lstlisting}
  1992. (+ 2 (read))
  1993. \end{lstlisting}
  1994. To accomplish this, the \code{pe-exp} function should produce output
  1995. in the form of the $\itm{residual}$ non-terminal of the following
  1996. grammar.
  1997. \[
  1998. \begin{array}{lcl}
  1999. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2000. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2001. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2002. \end{array}
  2003. \]
  2004. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2005. that their inputs are $\itm{residual}$ expressions and they should
  2006. return $\itm{residual}$ expressions. Once the improvements are
  2007. complete, make sure that your compiler still passes all of the tests.
  2008. After all, fast code is useless if it produces incorrect results!
  2009. \end{exercise}
  2010. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2011. \chapter{Register Allocation}
  2012. \label{ch:register-allocation-r1}
  2013. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2014. make our life easier. However, we can improve the performance of the
  2015. generated code if we instead place some variables into registers. The
  2016. CPU can access a register in a single cycle, whereas accessing the
  2017. stack takes many cycles if the relevant data is in cache or many more
  2018. to access main memory if the data is not in cache.
  2019. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2020. serves as a running example. We show the source program and also the
  2021. output of instruction selection. At that point the program is almost
  2022. x86 assembly but not quite; it still contains variables instead of
  2023. stack locations or registers.
  2024. \begin{figure}
  2025. \begin{minipage}{0.45\textwidth}
  2026. Example $R_1$ program:
  2027. % s0_22.rkt
  2028. \begin{lstlisting}
  2029. (program ()
  2030. (let ([v 1])
  2031. (let ([w 46])
  2032. (let ([x (+ v 7)])
  2033. (let ([y (+ 4 x)])
  2034. (let ([z (+ x w)])
  2035. (+ z (- y))))))))
  2036. \end{lstlisting}
  2037. \end{minipage}
  2038. \begin{minipage}{0.45\textwidth}
  2039. After instruction selection:
  2040. \begin{lstlisting}
  2041. (program
  2042. ((locals . (v w x y z t.1)))
  2043. ((start .
  2044. (block ()
  2045. (movq (int 1) (var v))
  2046. (movq (int 46) (var w))
  2047. (movq (var v) (var x))
  2048. (addq (int 7) (var x))
  2049. (movq (var x) (var y))
  2050. (addq (int 4) (var y))
  2051. (movq (var x) (var z))
  2052. (addq (var w) (var z))
  2053. (movq (var y) (var t.1))
  2054. (negq (var t.1))
  2055. (movq (var z) (reg rax))
  2056. (addq (var t.1) (reg rax))
  2057. (jmp conclusion)))))
  2058. \end{lstlisting}
  2059. \end{minipage}
  2060. \caption{An example program for register allocation.}
  2061. \label{fig:reg-eg}
  2062. \end{figure}
  2063. The goal of register allocation is to fit as many variables into
  2064. registers as possible. A program sometimes has more variables than
  2065. registers, so we cannot map each variable to a different
  2066. register. Fortunately, it is common for different variables to be
  2067. needed during different periods of time during program execution, and
  2068. in such cases several variables can be mapped to the same register.
  2069. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2070. After the variable \code{x} is moved to \code{z} it is no longer
  2071. needed. Variable \code{y}, on the other hand, is used only after this
  2072. point, so \code{x} and \code{y} could share the same register. The
  2073. topic of Section~\ref{sec:liveness-analysis-r1} is how we compute
  2074. where a variable is needed. Once we have that information, we compute
  2075. which variables are needed at the same time, i.e., which ones
  2076. \emph{interfere}, and represent this relation as graph whose vertices
  2077. are variables and edges indicate when two variables interfere with
  2078. each other (Section~\ref{sec:build-interference}). We then model
  2079. register allocation as a graph coloring problem, which we discuss in
  2080. Section~\ref{sec:graph-coloring}.
  2081. In the event that we run out of registers despite these efforts, we
  2082. place the remaining variables on the stack, similar to what we did in
  2083. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  2084. that is assigned to a stack location, it has been \emph{spilled}. The
  2085. process of spilling variables is handled as part of the graph coloring
  2086. process described in \ref{sec:graph-coloring}.
  2087. \section{Registers and Calling Conventions}
  2088. \label{sec:calling-conventions}
  2089. As we perform register allocation, we will need to be aware of the
  2090. conventions that govern the way in which registers interact with
  2091. function calls. The convention for x86 is that the caller is
  2092. responsible for freeing up some registers, the \emph{caller-saved
  2093. registers}, prior to the function call, and the callee is
  2094. responsible for saving and restoring some other registers, the
  2095. \emph{callee-saved registers}, before and after using them. The
  2096. caller-saved registers are
  2097. \begin{lstlisting}
  2098. rax rdx rcx rsi rdi r8 r9 r10 r11
  2099. \end{lstlisting}
  2100. while the callee-saved registers are
  2101. \begin{lstlisting}
  2102. rsp rbp rbx r12 r13 r14 r15
  2103. \end{lstlisting}
  2104. Another way to think about this caller/callee convention is the
  2105. following. The caller should assume that all the caller-saved registers
  2106. get overwritten with arbitrary values by the callee. On the other
  2107. hand, the caller can safely assume that all the callee-saved registers
  2108. contain the same values after the call that they did before the call.
  2109. The callee can freely use any of the caller-saved registers. However,
  2110. if the callee wants to use a callee-saved register, the callee must
  2111. arrange to put the original value back in the register prior to
  2112. returning to the caller, which is usually accomplished by saving and
  2113. restoring the value from the stack.
  2114. \section{Liveness Analysis}
  2115. \label{sec:liveness-analysis-r1}
  2116. A variable is \emph{live} if the variable is used at some later point
  2117. in the program and there is not an intervening assignment to the
  2118. variable.
  2119. %
  2120. To understand the latter condition, consider the following code
  2121. fragment in which there are two writes to \code{b}. Are \code{a} and
  2122. \code{b} both live at the same time?
  2123. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2124. (movq (int 5) (var a))
  2125. (movq (int 30) (var b))
  2126. (movq (var a) (var c))
  2127. (movq (int 10) (var b))
  2128. (addq (var b) (var c))
  2129. \end{lstlisting}
  2130. The answer is no because the value \code{30} written to \code{b} on
  2131. line 2 is never used. The variable \code{b} is read on line 5 and
  2132. there is an intervening write to \code{b} on line 4, so the read on
  2133. line 5 receives the value written on line 4, not line 2.
  2134. The live variables can be computed by traversing the instruction
  2135. sequence back to front (i.e., backwards in execution order). Let
  2136. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2137. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2138. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2139. variables before instruction $I_k$. The live variables after an
  2140. instruction are always the same as the live variables before the next
  2141. instruction.
  2142. \begin{equation*}
  2143. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2144. \end{equation*}
  2145. To start things off, there are no live variables after the last
  2146. instruction, so
  2147. \begin{equation*}
  2148. L_{\mathsf{after}}(n) = \emptyset
  2149. \end{equation*}
  2150. We then apply the following rule repeatedly, traversing the
  2151. instruction sequence back to front.
  2152. \begin{equation*}
  2153. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2154. \end{equation*}
  2155. where $W(k)$ are the variables written to by instruction $I_k$ and
  2156. $R(k)$ are the variables read by instruction $I_k$.
  2157. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2158. for the running example, with each instruction aligned with its
  2159. $L_{\mathtt{after}}$ set to make the figure easy to read.
  2160. \margincomment{JM: I think you should walk through the explanation of this formula,
  2161. connecting it back to the example from before. \\
  2162. JS: Agreed.}
  2163. \begin{figure}[tbp]
  2164. \hspace{20pt}
  2165. \begin{minipage}{0.45\textwidth}
  2166. \begin{lstlisting}[numbers=left]
  2167. (block ()
  2168. (movq (int 1) (var v))
  2169. (movq (int 46) (var w))
  2170. (movq (var v) (var x))
  2171. (addq (int 7) (var x))
  2172. (movq (var x) (var y))
  2173. (addq (int 4) (var y))
  2174. (movq (var x) (var z))
  2175. (addq (var w) (var z))
  2176. (movq (var y) (var t.1))
  2177. (negq (var t.1))
  2178. (movq (var z) (reg rax))
  2179. (addq (var t.1) (reg rax))
  2180. (jmp conclusion))
  2181. \end{lstlisting}
  2182. \end{minipage}
  2183. \vrule\hspace{10pt}
  2184. \begin{minipage}{0.45\textwidth}
  2185. \begin{lstlisting}
  2186. |$\{\}$|
  2187. |$\{v \}$|
  2188. |$\{v,w\}$|
  2189. |$\{w,x\}$|
  2190. |$\{w,x\}$|
  2191. |$\{w,x,y\}$|
  2192. |$\{w,x,y\}$|
  2193. |$\{w,y,z\}$|
  2194. |$\{y,z\}$|
  2195. |$\{z,t.1\}$|
  2196. |$\{z,t.1\}$|
  2197. |$\{t.1\}$|
  2198. |$\{\}$|
  2199. |$\{\}$|
  2200. \end{lstlisting}
  2201. \end{minipage}
  2202. \caption{An example block annotated with live-after sets.}
  2203. \label{fig:live-eg}
  2204. \end{figure}
  2205. \begin{exercise}\normalfont
  2206. Implement the compiler pass named \code{uncover-live} that computes
  2207. the live-after sets. We recommend storing the live-after sets (a list
  2208. of lists of variables) in the $\itm{info}$ field of the \key{block}
  2209. construct.
  2210. %
  2211. We recommend organizing your code to use a helper function that takes
  2212. a list of instructions and an initial live-after set (typically empty)
  2213. and returns the list of live-after sets.
  2214. %
  2215. We recommend creating helper functions to 1) compute the set of
  2216. variables that appear in an argument (of an instruction), 2) compute
  2217. the variables read by an instruction which corresponds to the $R$
  2218. function discussed above, and 3) the variables written by an
  2219. instruction which corresponds to $W$.
  2220. \end{exercise}
  2221. \section{Building the Interference Graph}
  2222. \label{sec:build-interference}
  2223. Based on the liveness analysis, we know where each variable is needed.
  2224. However, during register allocation, we need to answer questions of
  2225. the specific form: are variables $u$ and $v$ live at the same time?
  2226. (And therefore cannot be assigned to the same register.) To make this
  2227. question easier to answer, we create an explicit data structure, an
  2228. \emph{interference graph}. An interference graph is an undirected
  2229. graph that has an edge between two variables if they are live at the
  2230. same time, that is, if they interfere with each other.
  2231. The most obvious way to compute the interference graph is to look at
  2232. the set of live variables between each statement in the program, and
  2233. add an edge to the graph for every pair of variables in the same set.
  2234. This approach is less than ideal for two reasons. First, it can be
  2235. rather expensive because it takes $O(n^2)$ time to look at every pair
  2236. in a set of $n$ live variables. Second, there is a special case in
  2237. which two variables that are live at the same time do not actually
  2238. interfere with each other: when they both contain the same value
  2239. because we have assigned one to the other.
  2240. A better way to compute the interference graph is to focus on the
  2241. writes. That is, for each instruction, create an edge between the
  2242. variable being written to and all the \emph{other} live variables.
  2243. (One should not create self edges.) For a \key{callq} instruction,
  2244. think of all caller-saved registers as being written to, so and edge
  2245. must be added between every live variable and every caller-saved
  2246. register. For \key{movq}, we deal with the above-mentioned special
  2247. case by not adding an edge between a live variable $v$ and destination
  2248. $d$ if $v$ matches the source of the move. So we have the following
  2249. three rules.
  2250. \begin{enumerate}
  2251. \item If instruction $I_k$ is an arithmetic instruction such as
  2252. (\key{addq} $s$\, $d$), then add the edge $(d,v)$ for every $v \in
  2253. L_{\mathsf{after}}(k)$ unless $v = d$.
  2254. \item If instruction $I_k$ is of the form (\key{callq}
  2255. $\mathit{label}$), then add an edge $(r,v)$ for every caller-saved
  2256. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2257. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  2258. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2259. d$ or $v = s$.
  2260. \end{enumerate}
  2261. \margincomment{JM: I think you could give examples of each one of these
  2262. using the example program and use those to help explain why these
  2263. rules are correct.\\
  2264. JS: Agreed.}
  2265. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2266. the following interference for the instruction at the specified line
  2267. number.
  2268. \begin{quote}
  2269. Line 2: no interference,\\
  2270. Line 3: $w$ interferes with $v$,\\
  2271. Line 4: $x$ interferes with $w$,\\
  2272. Line 5: $x$ interferes with $w$,\\
  2273. Line 6: $y$ interferes with $w$,\\
  2274. Line 7: $y$ interferes with $w$ and $x$,\\
  2275. Line 8: $z$ interferes with $w$ and $y$,\\
  2276. Line 9: $z$ interferes with $y$, \\
  2277. Line 10: $t.1$ interferes with $z$, \\
  2278. Line 11: $t.1$ interferes with $z$, \\
  2279. Line 12: no interference, \\
  2280. Line 13: no interference. \\
  2281. Line 14: no interference.
  2282. \end{quote}
  2283. The resulting interference graph is shown in
  2284. Figure~\ref{fig:interfere}.
  2285. \begin{figure}[tbp]
  2286. \large
  2287. \[
  2288. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2289. \node (v) at (0,0) {$v$};
  2290. \node (w) at (2,0) {$w$};
  2291. \node (x) at (4,0) {$x$};
  2292. \node (t1) at (6,-2) {$t.1$};
  2293. \node (y) at (2,-2) {$y$};
  2294. \node (z) at (4,-2) {$z$};
  2295. \draw (v) to (w);
  2296. \foreach \i in {w,x,y}
  2297. {
  2298. \foreach \j in {w,x,y}
  2299. {
  2300. \draw (\i) to (\j);
  2301. }
  2302. }
  2303. \draw (z) to (w);
  2304. \draw (z) to (y);
  2305. \draw (t1) to (z);
  2306. \end{tikzpicture}
  2307. \]
  2308. \caption{The interference graph of the example program.}
  2309. \label{fig:interfere}
  2310. \end{figure}
  2311. %% Our next concern is to choose a data structure for representing the
  2312. %% interference graph. There are many choices for how to represent a
  2313. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2314. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2315. %% data structure is to study the algorithm that uses the data structure,
  2316. %% determine what operations need to be performed, and then choose the
  2317. %% data structure that provide the most efficient implementations of
  2318. %% those operations. Often times the choice of data structure can have an
  2319. %% effect on the time complexity of the algorithm, as it does here. If
  2320. %% you skim the next section, you will see that the register allocation
  2321. %% algorithm needs to ask the graph for all of its vertices and, given a
  2322. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2323. %% correct choice of graph representation is that of an adjacency
  2324. %% list. There are helper functions in \code{utilities.rkt} for
  2325. %% representing graphs using the adjacency list representation:
  2326. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2327. %% (Appendix~\ref{appendix:utilities}).
  2328. %% %
  2329. %% \margincomment{\footnotesize To do: change to use the
  2330. %% Racket graph library. \\ --Jeremy}
  2331. %% %
  2332. %% In particular, those functions use a hash table to map each vertex to
  2333. %% the set of adjacent vertices, and the sets are represented using
  2334. %% Racket's \key{set}, which is also a hash table.
  2335. \begin{exercise}\normalfont
  2336. Implement the compiler pass named \code{build-interference} according
  2337. to the algorithm suggested above. We recommend using the Racket
  2338. \code{graph} package to create and inspect the interference graph.
  2339. The output graph of this pass should be stored in the $\itm{info}$
  2340. field of the program, under the key \code{conflicts}.
  2341. \end{exercise}
  2342. \section{Graph Coloring via Sudoku}
  2343. \label{sec:graph-coloring}
  2344. We now come to the main event, mapping variables to registers (or to
  2345. stack locations in the event that we run out of registers). We need
  2346. to make sure not to map two variables to the same register if the two
  2347. variables interfere with each other. In terms of the interference
  2348. graph, this means that adjacent vertices must be mapped to different
  2349. registers. If we think of registers as colors, the register
  2350. allocation problem becomes the widely-studied graph coloring
  2351. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2352. The reader may be more familiar with the graph coloring problem than he
  2353. or she realizes; the popular game of Sudoku is an instance of the
  2354. graph coloring problem. The following describes how to build a graph
  2355. out of an initial Sudoku board.
  2356. \begin{itemize}
  2357. \item There is one vertex in the graph for each Sudoku square.
  2358. \item There is an edge between two vertices if the corresponding squares
  2359. are in the same row, in the same column, or if the squares are in
  2360. the same $3\times 3$ region.
  2361. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2362. \item Based on the initial assignment of numbers to squares in the
  2363. Sudoku board, assign the corresponding colors to the corresponding
  2364. vertices in the graph.
  2365. \end{itemize}
  2366. If you can color the remaining vertices in the graph with the nine
  2367. colors, then you have also solved the corresponding game of Sudoku.
  2368. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2369. the corresponding graph with colored vertices. We map the Sudoku
  2370. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2371. sampling of the vertices (those that are colored) because showing
  2372. edges for all of the vertices would make the graph unreadable.
  2373. \begin{figure}[tbp]
  2374. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2375. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2376. \caption{A Sudoku game board and the corresponding colored graph.}
  2377. \label{fig:sudoku-graph}
  2378. \end{figure}
  2379. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2380. strategies to come up with an algorithm for allocating registers. For
  2381. example, one of the basic techniques for Sudoku is called Pencil
  2382. Marks. The idea is that you use a process of elimination to determine
  2383. what numbers no longer make sense for a square, and write down those
  2384. numbers in the square (writing very small). For example, if the number
  2385. $1$ is assigned to a square, then by process of elimination, you can
  2386. write the pencil mark $1$ in all the squares in the same row, column,
  2387. and region. Many Sudoku computer games provide automatic support for
  2388. Pencil Marks.
  2389. %
  2390. The Pencil Marks technique corresponds to the notion of color
  2391. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2392. vertex, in Sudoku terms, is the set of colors that are no longer
  2393. available. In graph terminology, we have the following definition:
  2394. \begin{equation*}
  2395. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2396. \text{ and } \mathrm{color}(v) = c \}
  2397. \end{equation*}
  2398. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2399. edge with $u$.
  2400. Using the Pencil Marks technique leads to a simple strategy for
  2401. filling in numbers: if there is a square with only one possible number
  2402. left, then write down that number! But what if there are no squares
  2403. with only one possibility left? One brute-force approach is to just
  2404. make a guess. If that guess ultimately leads to a solution, great. If
  2405. not, backtrack to the guess and make a different guess. One good
  2406. thing about Pencil Marks is that it reduces the degree of branching in
  2407. the search tree. Nevertheless, backtracking can be horribly time
  2408. consuming. One way to reduce the amount of backtracking is to use the
  2409. most-constrained-first heuristic. That is, when making a guess, always
  2410. choose a square with the fewest possibilities left (the vertex with
  2411. the highest saturation). The idea is that choosing highly constrained
  2412. squares earlier rather than later is better because later there may
  2413. not be any possibilities.
  2414. In some sense, register allocation is easier than Sudoku because we
  2415. can always cheat and add more numbers by mapping variables to the
  2416. stack. We say that a variable is \emph{spilled} when we decide to map
  2417. it to a stack location. We would like to minimize the time needed to
  2418. color the graph, and backtracking is expensive. Thus, it makes sense
  2419. to keep the most-constrained-first heuristic but drop the backtracking
  2420. in favor of greedy search (guess and just keep going).
  2421. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2422. greedy algorithm for register allocation based on saturation and the
  2423. most-constrained-first heuristic, which is roughly equivalent to the
  2424. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2425. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2426. as in Sudoku, the algorithm represents colors with integers, with the
  2427. first $k$ colors corresponding to the $k$ registers in a given machine
  2428. and the rest of the integers corresponding to stack locations.
  2429. \begin{figure}[btp]
  2430. \centering
  2431. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2432. Algorithm: DSATUR
  2433. Input: a graph |$G$|
  2434. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2435. |$W \gets \mathit{vertices}(G)$|
  2436. while |$W \neq \emptyset$| do
  2437. pick a vertex |$u$| from |$W$| with the highest saturation,
  2438. breaking ties randomly
  2439. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2440. |$\mathrm{color}[u] \gets c$|
  2441. |$W \gets W - \{u\}$|
  2442. \end{lstlisting}
  2443. \caption{The saturation-based greedy graph coloring algorithm.}
  2444. \label{fig:satur-algo}
  2445. \end{figure}
  2446. With this algorithm in hand, let us return to the running example and
  2447. consider how to color the interference graph in
  2448. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2449. register allocation because we use it to patch instructions, so we
  2450. remove that vertex from the graph. Initially, all of the vertices are
  2451. not yet colored and they are unsaturated, so we annotate each of them
  2452. with a dash for their color and an empty set for the saturation.
  2453. \[
  2454. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2455. \node (v) at (0,0) {$v:-,\{\}$};
  2456. \node (w) at (3,0) {$w:-,\{\}$};
  2457. \node (x) at (6,0) {$x:-,\{\}$};
  2458. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2459. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2460. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2461. \draw (v) to (w);
  2462. \foreach \i in {w,x,y}
  2463. {
  2464. \foreach \j in {w,x,y}
  2465. {
  2466. \draw (\i) to (\j);
  2467. }
  2468. }
  2469. \draw (z) to (w);
  2470. \draw (z) to (y);
  2471. \draw (t1) to (z);
  2472. \end{tikzpicture}
  2473. \]
  2474. We select a maximally saturated vertex and color it $0$. In this case we
  2475. have a 7-way tie, so we arbitrarily pick $t.1$. The then mark color $0$
  2476. as no longer available for $z$ because it interferes
  2477. with $t.1$.
  2478. \[
  2479. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2480. \node (v) at (0,0) {$v:-,\{\}$};
  2481. \node (w) at (3,0) {$w:-,\{\}$};
  2482. \node (x) at (6,0) {$x:-,\{\}$};
  2483. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2484. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2485. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2486. \draw (v) to (w);
  2487. \foreach \i in {w,x,y}
  2488. {
  2489. \foreach \j in {w,x,y}
  2490. {
  2491. \draw (\i) to (\j);
  2492. }
  2493. }
  2494. \draw (z) to (w);
  2495. \draw (z) to (y);
  2496. \draw (t1) to (z);
  2497. \end{tikzpicture}
  2498. \]
  2499. Now we repeat the process, selecting another maximally saturated
  2500. vertex, which in this case is $z$. We color $z$ with $1$.
  2501. \[
  2502. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2503. \node (v) at (0,0) {$v:-,\{\}$};
  2504. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2505. \node (x) at (6,0) {$x:-,\{\}$};
  2506. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2507. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2508. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2509. \draw (t1) to (z);
  2510. \draw (v) to (w);
  2511. \foreach \i in {w,x,y}
  2512. {
  2513. \foreach \j in {w,x,y}
  2514. {
  2515. \draw (\i) to (\j);
  2516. }
  2517. }
  2518. \draw (z) to (w);
  2519. \draw (z) to (y);
  2520. \end{tikzpicture}
  2521. \]
  2522. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2523. first available color, which is $0$.
  2524. \[
  2525. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2526. \node (v) at (0,0) {$v:-,\{\}$};
  2527. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2528. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2529. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2530. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2531. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2532. \draw (t1) to (z);
  2533. \draw (v) to (w);
  2534. \foreach \i in {w,x,y}
  2535. {
  2536. \foreach \j in {w,x,y}
  2537. {
  2538. \draw (\i) to (\j);
  2539. }
  2540. }
  2541. \draw (z) to (w);
  2542. \draw (z) to (y);
  2543. \end{tikzpicture}
  2544. \]
  2545. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2546. \[
  2547. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2548. \node (v) at (0,0) {$v:-,\{2\}$};
  2549. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2550. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2551. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2552. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2553. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2554. \draw (t1) to (z);
  2555. \draw (v) to (w);
  2556. \foreach \i in {w,x,y}
  2557. {
  2558. \foreach \j in {w,x,y}
  2559. {
  2560. \draw (\i) to (\j);
  2561. }
  2562. }
  2563. \draw (z) to (w);
  2564. \draw (z) to (y);
  2565. \end{tikzpicture}
  2566. \]
  2567. Now $x$ has the highest saturation, so we color it $1$.
  2568. \[
  2569. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2570. \node (v) at (0,0) {$v:-,\{2\}$};
  2571. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2572. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2573. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2574. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2575. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2576. \draw (t1) to (z);
  2577. \draw (v) to (w);
  2578. \foreach \i in {w,x,y}
  2579. {
  2580. \foreach \j in {w,x,y}
  2581. {
  2582. \draw (\i) to (\j);
  2583. }
  2584. }
  2585. \draw (z) to (w);
  2586. \draw (z) to (y);
  2587. \end{tikzpicture}
  2588. \]
  2589. In the last step of the algorithm, we color $v$ with $0$.
  2590. \[
  2591. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2592. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2593. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2594. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2595. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2596. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2597. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2598. \draw (t1) to (z);
  2599. \draw (v) to (w);
  2600. \foreach \i in {w,x,y}
  2601. {
  2602. \foreach \j in {w,x,y}
  2603. {
  2604. \draw (\i) to (\j);
  2605. }
  2606. }
  2607. \draw (z) to (w);
  2608. \draw (z) to (y);
  2609. \end{tikzpicture}
  2610. \]
  2611. With the coloring complete, we can finalize the assignment of
  2612. variables to registers and stack locations. Recall that if we have $k$
  2613. registers, we map the first $k$ colors to registers and the rest to
  2614. stack locations. Suppose for the moment that we have just one
  2615. register to use for register allocation, \key{rcx}. Then the following
  2616. is the mapping of colors to registers and stack allocations.
  2617. \[
  2618. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2619. \]
  2620. Putting this mapping together with the above coloring of the variables, we
  2621. arrive at the assignment:
  2622. \begin{gather*}
  2623. \{ v \mapsto \key{\%rcx}, \,
  2624. w \mapsto \key{-16(\%rbp)}, \,
  2625. x \mapsto \key{-8(\%rbp)}, \\
  2626. y \mapsto \key{\%rcx}, \,
  2627. z\mapsto \key{-8(\%rbp)},
  2628. t.1\mapsto \key{\%rcx} \}
  2629. \end{gather*}
  2630. Applying this assignment to our running example, on the left, yields
  2631. the program on the right.\\
  2632. % why frame size of 32? -JGS
  2633. \begin{minipage}{0.4\textwidth}
  2634. \begin{lstlisting}
  2635. (block ()
  2636. (movq (int 1) (var v))
  2637. (movq (int 46) (var w))
  2638. (movq (var v) (var x))
  2639. (addq (int 7) (var x))
  2640. (movq (var x) (var y))
  2641. (addq (int 4) (var y))
  2642. (movq (var x) (var z))
  2643. (addq (var w) (var z))
  2644. (movq (var y) (var t.1))
  2645. (negq (var t.1))
  2646. (movq (var z) (reg rax))
  2647. (addq (var t.1) (reg rax))
  2648. (jmp conclusion))
  2649. \end{lstlisting}
  2650. \end{minipage}
  2651. $\Rightarrow$
  2652. \begin{minipage}{0.45\textwidth}
  2653. \begin{lstlisting}
  2654. (block ()
  2655. (movq (int 1) (reg rcx))
  2656. (movq (int 46) (deref rbp -16))
  2657. (movq (reg rcx) (deref rbp -8))
  2658. (addq (int 7) (deref rbp -8))
  2659. (movq (deref rbp -8) (reg rcx))
  2660. (addq (int 4) (reg rcx))
  2661. (movq (deref rbp -8) (deref rbp -8))
  2662. (addq (deref rbp -16) (deref rbp -8))
  2663. (movq (reg rcx) (reg rcx))
  2664. (negq (reg rcx))
  2665. (movq (deref rbp -8) (reg rax))
  2666. (addq (reg rcx) (reg rax))
  2667. (jmp conclusion))
  2668. \end{lstlisting}
  2669. \end{minipage}
  2670. The resulting program is almost an x86 program. The remaining step
  2671. is to apply the patch instructions pass. In this example, the trivial
  2672. move of \code{-8(\%rbp)} to itself is deleted and the addition of
  2673. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2674. \code{rax} as follows.
  2675. \begin{lstlisting}
  2676. (movq (deref rbp -16) (reg rax)
  2677. (addq (reg rax) (deref rbp -8))
  2678. \end{lstlisting}
  2679. An overview of all of the passes involved in register allocation is
  2680. shown in Figure~\ref{fig:reg-alloc-passes}.
  2681. \begin{figure}[tbp]
  2682. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2683. \node (R1) at (0,2) {\large $R_1$};
  2684. \node (R1-2) at (3,2) {\large $R_1$};
  2685. \node (R1-3) at (6,2) {\large $R_1$};
  2686. \node (C0-1) at (6,0) {\large $C_0$};
  2687. \node (C0-2) at (3,0) {\large $C_0$};
  2688. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2689. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2690. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2691. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2692. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2693. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2694. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2695. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2696. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2697. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2698. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2699. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2700. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2701. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2702. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2703. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2704. \end{tikzpicture}
  2705. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2706. \label{fig:reg-alloc-passes}
  2707. \end{figure}
  2708. \begin{exercise}\normalfont
  2709. Implement the pass \code{allocate-registers}, which should come
  2710. after the \code{build-interference} pass. The three new passes,
  2711. \code{uncover-live}, \code{build-interference}, and
  2712. \code{allocate-registers} replace the \code{assign-homes} pass of
  2713. Section~\ref{sec:assign-r1}.
  2714. We recommend that you create a helper function named
  2715. \code{color-graph} that takes an interference graph and a list of
  2716. all the variables in the program. This function should return a
  2717. mapping of variables to their colors (represented as natural
  2718. numbers). By creating this helper function, you will be able to
  2719. reuse it in Chapter~\ref{ch:functions} when you add support for
  2720. functions.
  2721. Once you have obtained the coloring from \code{color-graph}, you can
  2722. assign the variables to registers or stack locations and then reuse
  2723. code from the \code{assign-homes} pass from
  2724. Section~\ref{sec:assign-r1} to replace the variables with their
  2725. assigned location.
  2726. Test your updated compiler by creating new example programs that
  2727. exercise all of the register allocation algorithm, such as forcing
  2728. variables to be spilled to the stack.
  2729. \end{exercise}
  2730. \section{Print x86 and Conventions for Registers}
  2731. \label{sec:print-x86-reg-alloc}
  2732. Recall the \code{print-x86} pass generates the prelude and
  2733. conclusion instructions for the \code{main} function.
  2734. %
  2735. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2736. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2737. reason for this is that our \code{main} function must adhere to the
  2738. x86 calling conventions that we described in
  2739. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2740. function needs to restore (in the conclusion) any callee-saved
  2741. registers that get used during register allocation. The simplest
  2742. approach is to save and restore all of the callee-saved registers. The
  2743. more efficient approach is to keep track of which callee-saved
  2744. registers were used and only save and restore them. Either way, make
  2745. sure to take this use of stack space into account when you are
  2746. calculating the size of the frame. Also, don't forget that the size of
  2747. the frame needs to be a multiple of 16 bytes.
  2748. \section{Challenge: Move Biasing$^{*}$}
  2749. \label{sec:move-biasing}
  2750. This section describes an optional enhancement to register allocation
  2751. for those students who are looking for an extra challenge or who have
  2752. a deeper interest in register allocation.
  2753. We return to the running example, but we remove the supposition that
  2754. we only have one register to use. So we have the following mapping of
  2755. color numbers to registers.
  2756. \[
  2757. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2758. \]
  2759. Using the same assignment that was produced by register allocator
  2760. described in the last section, we get the following program.
  2761. \begin{minipage}{0.45\textwidth}
  2762. \begin{lstlisting}
  2763. (block ()
  2764. (movq (int 1) (var v))
  2765. (movq (int 46) (var w))
  2766. (movq (var v) (var x))
  2767. (addq (int 7) (var x))
  2768. (movq (var x) (var y))
  2769. (addq (int 4) (var y))
  2770. (movq (var x) (var z))
  2771. (addq (var w) (var z))
  2772. (movq (var y) (var t.1))
  2773. (negq (var t.1))
  2774. (movq (var z) (reg rax))
  2775. (addq (var t.1) (reg rax))
  2776. (jmp conclusion))
  2777. \end{lstlisting}
  2778. \end{minipage}
  2779. $\Rightarrow$
  2780. \begin{minipage}{0.45\textwidth}
  2781. \begin{lstlisting}
  2782. (block ()
  2783. (movq (int 1) (reg rbx))
  2784. (movq (int 46) (reg rdx))
  2785. (movq (reg rbx) (reg rcx))
  2786. (addq (int 7) (reg rcx))
  2787. (movq (reg rcx) (reg rbx))
  2788. (addq (int 4) (reg rbx))
  2789. (movq (reg rcx) (reg rcx))
  2790. (addq (reg rdx) (reg rcx))
  2791. (movq (reg rbx) (reg rbx))
  2792. (negq (reg rbx))
  2793. (movq (reg rcx) (reg rax))
  2794. (addq (reg rbx) (reg rax))
  2795. (jmp conclusion))
  2796. \end{lstlisting}
  2797. \end{minipage}
  2798. While this allocation is quite good, we could do better. For example,
  2799. the variables \key{v} and \key{x} ended up in different registers, but
  2800. if they had been placed in the same register, then the move from
  2801. \key{v} to \key{x} could be removed.
  2802. We say that two variables $p$ and $q$ are \emph{move related} if they
  2803. participate together in a \key{movq} instruction, that is, \key{movq}
  2804. $p$, $q$ or \key{movq} $q$, $p$. When the register allocator chooses a
  2805. color for a variable, it should prefer a color that has already been
  2806. used for a move-related variable (assuming that they do not
  2807. interfere). Of course, this preference should not override the
  2808. preference for registers over stack locations, but should only be used
  2809. as a tie breaker when choosing between registers or when choosing
  2810. between stack locations.
  2811. We recommend that you represent the move relationships in a graph,
  2812. similar to how we represented interference. The following is the
  2813. \emph{move graph} for our running example.
  2814. \[
  2815. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2816. \node (v) at (0,0) {$v$};
  2817. \node (w) at (3,0) {$w$};
  2818. \node (x) at (6,0) {$x$};
  2819. \node (y) at (3,-1.5) {$y$};
  2820. \node (z) at (6,-1.5) {$z$};
  2821. \node (t1) at (9,-1.5) {$t.1$};
  2822. \draw[bend left=15] (t1) to (y);
  2823. \draw[bend left=15] (v) to (x);
  2824. \draw (x) to (y);
  2825. \draw (x) to (z);
  2826. \end{tikzpicture}
  2827. \]
  2828. Now we replay the graph coloring, pausing to see the coloring of $x$
  2829. and $v$. So we have the following coloring and the most saturated
  2830. vertex is $x$.
  2831. \[
  2832. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2833. \node (v) at (0,0) {$v:-,\{2\}$};
  2834. \node (w) at (3,0) {$w:2,\{0,1\}$};
  2835. \node (x) at (6,0) {$x:-,\{0,2\}$};
  2836. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2837. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2838. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2839. \draw (t1) to (z);
  2840. \draw (v) to (w);
  2841. \foreach \i in {w,x,y}
  2842. {
  2843. \foreach \j in {w,x,y}
  2844. {
  2845. \draw (\i) to (\j);
  2846. }
  2847. }
  2848. \draw (z) to (w);
  2849. \draw (z) to (y);
  2850. \end{tikzpicture}
  2851. \]
  2852. Last time we chose to color $x$ with $1$,
  2853. %
  2854. which so happens to be the color of $z$, and $x$ is move related to
  2855. $z$. This was rather lucky, and if the program had been a little
  2856. different, and say $z$ had been already assigned to $2$, then $x$
  2857. would still get $1$ and our luck would have run out. With move
  2858. biasing, we use the fact that $x$ and $z$ are move related to
  2859. influence the choice of color for $x$, in this case choosing $1$
  2860. because that's the color of $z$.
  2861. \[
  2862. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2863. \node (v) at (0,0) {$v:-,\{2\}$};
  2864. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2865. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2866. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2867. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2868. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2869. \draw (t1) to (z);
  2870. \draw (v) to (w);
  2871. \foreach \i in {w,x,y}
  2872. {
  2873. \foreach \j in {w,x,y}
  2874. {
  2875. \draw (\i) to (\j);
  2876. }
  2877. }
  2878. \draw (z) to (w);
  2879. \draw (z) to (y);
  2880. \end{tikzpicture}
  2881. \]
  2882. Next we consider coloring the variable $v$, and we just need to avoid
  2883. choosing $2$ because of the interference with $w$. Last time we choose
  2884. the color $0$, simply because it was the lowest, but this time we know
  2885. that $v$ is move related to $x$, so we choose the color $1$.
  2886. \[
  2887. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2888. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  2889. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2890. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2891. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2892. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2893. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2894. \draw (t1) to (z);
  2895. \draw (v) to (w);
  2896. \foreach \i in {w,x,y}
  2897. {
  2898. \foreach \j in {w,x,y}
  2899. {
  2900. \draw (\i) to (\j);
  2901. }
  2902. }
  2903. \draw (z) to (w);
  2904. \draw (z) to (y);
  2905. \end{tikzpicture}
  2906. \]
  2907. We apply this register assignment to the running example, on the left,
  2908. to obtain the code on right.
  2909. \begin{minipage}{0.45\textwidth}
  2910. \begin{lstlisting}
  2911. (block ()
  2912. (movq (int 1) (var v))
  2913. (movq (int 46) (var w))
  2914. (movq (var v) (var x))
  2915. (addq (int 7) (var x))
  2916. (movq (var x) (var y))
  2917. (addq (int 4) (var y))
  2918. (movq (var x) (var z))
  2919. (addq (var w) (var z))
  2920. (movq (var y) (var t.1))
  2921. (negq (var t.1))
  2922. (movq (var z) (reg rax))
  2923. (addq (var t.1) (reg rax))
  2924. (jmp conclusion))
  2925. \end{lstlisting}
  2926. \end{minipage}
  2927. $\Rightarrow$
  2928. \begin{minipage}{0.45\textwidth}
  2929. \begin{lstlisting}
  2930. (block ()
  2931. (movq (int 1) (reg rcx))
  2932. (movq (int 46) (reg rbx))
  2933. (movq (reg rcx) (reg rcx))
  2934. (addq (int 7) (reg rcx))
  2935. (movq (reg rcx) (reg rdx))
  2936. (addq (int 4) (reg rdx))
  2937. (movq (reg rcx) (reg rcx))
  2938. (addq (reg rbx) (reg rcx))
  2939. (movq (reg rdx) (reg rbx))
  2940. (negq (reg rbx))
  2941. (movq (reg rcx) (reg rax))
  2942. (addq (reg rbx) (reg rax))
  2943. (jmp conclusion))
  2944. \end{lstlisting}
  2945. \end{minipage}
  2946. The \code{patch-instructions} then removes the trivial moves from
  2947. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  2948. result.
  2949. \begin{minipage}{0.45\textwidth}
  2950. \begin{lstlisting}
  2951. (block ()
  2952. (movq (int 1) (reg rcx))
  2953. (movq (int 46) (reg rbx))
  2954. (addq (int 7) (reg rcx))
  2955. (movq (reg rcx) (reg rdx))
  2956. (addq (int 4) (reg rdx))
  2957. (addq (reg rbx) (reg rcx))
  2958. (movq (reg rdx) (reg rbx))
  2959. (negq (reg rbx))
  2960. (movq (reg rcx) (reg rax))
  2961. (addq (reg rbx) (reg rax))
  2962. (jmp conclusion))
  2963. \end{lstlisting}
  2964. \end{minipage}
  2965. \begin{exercise}\normalfont
  2966. Change your implementation of \code{allocate-registers} to take move
  2967. biasing into account. Make sure that your compiler still passes all of
  2968. the previous tests. Create two new tests that include at least one
  2969. opportunity for move biasing and visually inspect the output x86
  2970. programs to make sure that your move biasing is working properly.
  2971. \end{exercise}
  2972. \margincomment{\footnotesize To do: another neat challenge would be to do
  2973. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2974. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2975. \chapter{Booleans and Control Flow}
  2976. \label{ch:bool-types}
  2977. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2978. integers. In this Chapter we add a second kind of value, the Booleans,
  2979. to create the $R_2$ language. The Boolean values \emph{true} and
  2980. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2981. Racket. We also introduce several operations that involve Booleans
  2982. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2983. \key{if} expression. With the addition of \key{if} expressions,
  2984. programs can have non-trivial control flow which has an impact on
  2985. several parts of the compiler. Also, because we now have two kinds of
  2986. values, we need to worry about programs that apply an operation to the
  2987. wrong kind of value, such as \code{(not 1)}.
  2988. There are two language design options for such situations. One option
  2989. is to signal an error and the other is to provide a wider
  2990. interpretation of the operation. The Racket language uses a mixture of
  2991. these two options, depending on the operation and the kind of
  2992. value. For example, the result of \code{(not 1)} in Racket is
  2993. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2994. the other hand, \code{(car 1)} results in a run-time error in Racket
  2995. stating that \code{car} expects a pair.
  2996. The Typed Racket language makes similar design choices as Racket,
  2997. except much of the error detection happens at compile time instead of
  2998. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2999. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3000. reports a compile-time error because Typed Racket expects the type of
  3001. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3002. For the $R_2$ language we choose to be more like Typed Racket in that
  3003. we shall perform type checking during compilation. In
  3004. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3005. is, how to compile a dynamically typed language like Racket. The
  3006. $R_2$ language is a subset of Typed Racket but by no means includes
  3007. all of Typed Racket. Furthermore, for many of the operations we shall
  3008. take a narrower interpretation than Typed Racket, for example,
  3009. rejecting \code{(not 1)}.
  3010. This chapter is organized as follows. We begin by defining the syntax
  3011. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3012. then introduce the idea of type checking and build a type checker for
  3013. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3014. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3015. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  3016. how our compiler passes need to change to accommodate Booleans and
  3017. conditional control flow.
  3018. \section{The $R_2$ Language}
  3019. \label{sec:r2-lang}
  3020. The syntax of the $R_2$ language is defined in
  3021. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray),
  3022. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  3023. \code{if} expression. Also, we expand the operators to include
  3024. subtraction, \key{and}, \key{or} and \key{not}, the \key{eq?}
  3025. operations for comparing two integers or two Booleans, and the
  3026. \key{<}, \key{<=}, \key{>}, and \key{>=} operations for comparing
  3027. integers.
  3028. \begin{figure}[tp]
  3029. \centering
  3030. \fbox{
  3031. \begin{minipage}{0.96\textwidth}
  3032. \[
  3033. \begin{array}{lcl}
  3034. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3035. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \mid (\key{-}\;\Exp\;\Exp) \\
  3036. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  3037. &\mid& \key{\#t} \mid \key{\#f}
  3038. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3039. \mid (\key{not}\;\Exp) \\
  3040. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  3041. R_2 &::=& (\key{program} \; \itm{info}\; \Exp)
  3042. \end{array}
  3043. \]
  3044. \end{minipage}
  3045. }
  3046. \caption{The syntax of $R_2$, extending $R_1$
  3047. (Figure~\ref{fig:r1-syntax}) with Booleans and conditionals.}
  3048. \label{fig:r2-syntax}
  3049. \end{figure}
  3050. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3051. the parts that are the same as the interpreter for $R_1$
  3052. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3053. simply evaluate to themselves. The conditional expression $(\key{if}\,
  3054. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  3055. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3056. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3057. operations \code{not} and \code{and} behave as you might expect, but
  3058. note that the \code{and} operation is short-circuiting. That is, given
  3059. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3060. evaluated if $e_1$ evaluates to \code{\#f}.
  3061. With the addition of the comparison operations, there are quite a few
  3062. primitive operations and the interpreter code for them is somewhat
  3063. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  3064. parts into the \code{interp-op} function and the similar parts into
  3065. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  3066. use \code{interp-op} for the \code{and} operation because of the
  3067. short-circuiting behavior in the order of evaluation of its arguments.
  3068. \begin{figure}[tbp]
  3069. \begin{lstlisting}
  3070. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  3071. (define (interp-op op)
  3072. (match op
  3073. ...
  3074. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3075. ['eq? (lambda (v1 v2)
  3076. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3077. (and (boolean? v1) (boolean? v2)))
  3078. (eq? v1 v2)]))]
  3079. ['< (lambda (v1 v2)
  3080. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3081. ['<= (lambda (v1 v2)
  3082. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3083. ['> (lambda (v1 v2)
  3084. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3085. ['>= (lambda (v1 v2)
  3086. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3087. [else (error 'interp-op "unknown operator")]))
  3088. (define (interp-exp env)
  3089. (lambda (e)
  3090. (define recur (interp-exp env))
  3091. (match e
  3092. ...
  3093. [(? boolean?) e]
  3094. [`(if ,cnd ,thn ,els)
  3095. (define b (recur cnd))
  3096. (match b
  3097. [#t (recur thn)]
  3098. [#f (recur els)])]
  3099. [`(and ,e1 ,e2)
  3100. (define v1 (recur e1))
  3101. (match v1
  3102. [#t (match (recur e2) [#t #t] [#f #f])]
  3103. [#f #f])]
  3104. [`(,op ,args ...)
  3105. #:when (set-member? primitives op)
  3106. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3107. )))
  3108. (define (interp-R2 env)
  3109. (lambda (p)
  3110. (match p
  3111. [`(program ,info ,e)
  3112. ((interp-exp '()) e)])))
  3113. \end{lstlisting}
  3114. \caption{Interpreter for the $R_2$ language.}
  3115. \label{fig:interp-R2}
  3116. \end{figure}
  3117. \section{Type Checking $R_2$ Programs}
  3118. \label{sec:type-check-r2}
  3119. It is helpful to think about type checking in two complementary
  3120. ways. A type checker predicts the \emph{type} of value that will be
  3121. produced by each expression in the program. For $R_2$, we have just
  3122. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3123. predict that
  3124. \begin{lstlisting}
  3125. (+ 10 (- (+ 12 20)))
  3126. \end{lstlisting}
  3127. produces an \key{Integer} while
  3128. \begin{lstlisting}
  3129. (and (not #f) #t)
  3130. \end{lstlisting}
  3131. produces a \key{Boolean}.
  3132. As mentioned at the beginning of this chapter, a type checker also
  3133. rejects programs that apply operators to the wrong type of value. Our
  3134. type checker for $R_2$ will signal an error for the following
  3135. expression because, as we have seen above, the expression \code{(+ 10
  3136. ...)} has type \key{Integer}, and we require the argument of a
  3137. \code{not} to have type \key{Boolean}.
  3138. \begin{lstlisting}
  3139. (not (+ 10 (- (+ 12 20))))
  3140. \end{lstlisting}
  3141. The type checker for $R_2$ is best implemented as a structurally
  3142. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3143. many of the clauses for the \code{type-check-exp} function. Given an
  3144. input expression \code{e}, the type checker either returns the type
  3145. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3146. the type of an integer literal is \code{Integer} and the type of a
  3147. Boolean literal is \code{Boolean}. To handle variables, the type
  3148. checker, like the interpreter, uses an association list. However, in
  3149. this case the association list maps variables to types instead of
  3150. values. Consider the clause for \key{let}. We type check the
  3151. initializing expression to obtain its type \key{T} and then associate
  3152. type \code{T} with the variable \code{x}. When the type checker
  3153. encounters the use of a variable, it can find its type in the
  3154. association list.
  3155. \begin{figure}[tbp]
  3156. \begin{lstlisting}
  3157. (define (type-check-exp env)
  3158. (lambda (e)
  3159. (define recur (type-check-exp env))
  3160. (match e
  3161. [(? fixnum?) 'Integer]
  3162. [(? boolean?) 'Boolean]
  3163. [(? symbol? x) (dict-ref env x)]
  3164. [`(read) 'Integer]
  3165. [`(let ([,x ,e]) ,body)
  3166. (define T (recur e))
  3167. (define new-env (cons (cons x T) env))
  3168. (type-check-exp new-env body)]
  3169. ...
  3170. [`(not ,e)
  3171. (match (recur e)
  3172. ['Boolean 'Boolean]
  3173. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  3174. ...
  3175. )))
  3176. (define (type-check-R2 env)
  3177. (lambda (e)
  3178. (match e
  3179. [`(program ,info ,body)
  3180. (define ty ((type-check-exp '()) body))
  3181. `(program ,info ,body)]
  3182. )))
  3183. \end{lstlisting}
  3184. \caption{Skeleton of a type checker for the $R_2$ language.}
  3185. \label{fig:type-check-R2}
  3186. \end{figure}
  3187. %% To print the resulting value correctly, the overall type of the
  3188. %% program must be threaded through the remainder of the passes. We can
  3189. %% store the type within the \key{program} form as shown in Figure
  3190. %% \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3191. %% intermediate language produced by the type checker, which we define as
  3192. %% follows: \\[1ex]
  3193. %% \fbox{
  3194. %% \begin{minipage}{0.87\textwidth}
  3195. %% \[
  3196. %% \begin{array}{lcl}
  3197. %% R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3198. %% \end{array}
  3199. %% \]
  3200. %% \end{minipage}
  3201. %% }
  3202. \begin{exercise}\normalfont
  3203. Complete the implementation of \code{type-check-R2} and test it on 10
  3204. new example programs in $R_2$ that you choose based on how thoroughly
  3205. they test the type checking algorithm. Half of the example programs
  3206. should have a type error, to make sure that your type checker properly
  3207. rejects them. The other half of the example programs should not have
  3208. type errors. Your testing should check that the result of the type
  3209. checker agrees with the value returned by the interpreter, that is, if
  3210. the type checker returns \key{Integer}, then the interpreter should
  3211. return an integer. Likewise, if the type checker returns
  3212. \key{Boolean}, then the interpreter should return \code{\#t} or
  3213. \code{\#f}. Note that if your type checker does not signal an error
  3214. for a program, then interpreting that program should not encounter an
  3215. error. If it does, there is something wrong with your type checker.
  3216. \end{exercise}
  3217. \section{Shrink the $R_2$ Language}
  3218. \label{sec:shrink-r2}
  3219. The $R_2$ language includes several operators that are easily
  3220. expressible in terms of other operators. For example, subtraction is
  3221. expressible in terms of addition and negation.
  3222. \[
  3223. (\key{-}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3224. \]
  3225. Several of the comparison operations are expressible in terms of
  3226. less-than and logical negation.
  3227. \[
  3228. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad
  3229. \LET{t_1}{e_1}{(\key{not}\;(\key{<}\;e_2\;t_1))}
  3230. \]
  3231. By performing these translations near the front-end of the compiler,
  3232. the later passes of the compiler will not need to deal with these
  3233. constructs, making those passes shorter. On the other hand, sometimes
  3234. these translations make it more difficult to generate the most
  3235. efficient code with respect to the number of instructions. However,
  3236. these differences typically do not affect the number of accesses to
  3237. memory, which is the primary factor that determines execution time on
  3238. modern computer architectures.
  3239. \begin{exercise}\normalfont
  3240. Implement the pass \code{shrink} that removes subtraction,
  3241. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3242. by translating them to other constructs in $R_2$. Create tests to
  3243. make sure that the behavior of all of these constructs stays the
  3244. same after translation.
  3245. \end{exercise}
  3246. \section{XOR, Comparisons, and Control Flow in x86}
  3247. \label{sec:x86-1}
  3248. To implement the new logical operations, the comparison operations,
  3249. and the \key{if} expression, we need to delve further into the x86
  3250. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3251. larger subset of x86 that includes instructions for logical
  3252. operations, comparisons, and jumps.
  3253. One small challenge is that x86 does not provide an instruction that
  3254. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3255. However, the \code{xorq} instruction can be used to encode \code{not}.
  3256. The \key{xorq} instruction takes two arguments, performs a pairwise
  3257. exclusive-or operation on each bit of its arguments, and writes the
  3258. results into its second argument. Recall the truth table for
  3259. exclusive-or:
  3260. \begin{center}
  3261. \begin{tabular}{l|cc}
  3262. & 0 & 1 \\ \hline
  3263. 0 & 0 & 1 \\
  3264. 1 & 1 & 0
  3265. \end{tabular}
  3266. \end{center}
  3267. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3268. in row of the table for the bit $1$, the result is the opposite of the
  3269. second bit. Thus, the \code{not} operation can be implemented by
  3270. \code{xorq} with $1$ as the first argument: $0001
  3271. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3272. 0001 = 0000$.
  3273. \begin{figure}[tp]
  3274. \fbox{
  3275. \begin{minipage}{0.96\textwidth}
  3276. \[
  3277. \begin{array}{lcl}
  3278. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3279. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3280. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3281. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3282. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3283. (\key{subq} \; \Arg\; \Arg) \mid
  3284. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3285. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3286. (\key{pushq}\;\Arg) \mid
  3287. (\key{popq}\;\Arg) \mid
  3288. (\key{retq})} \\
  3289. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3290. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3291. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3292. \mid (\key{jmp} \; \itm{label})
  3293. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3294. &\mid& (\key{label} \; \itm{label}) \\
  3295. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3296. \end{array}
  3297. \]
  3298. \end{minipage}
  3299. }
  3300. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3301. \label{fig:x86-1}
  3302. \end{figure}
  3303. Next we consider the x86 instructions that are relevant for
  3304. compiling the comparison operations. The \key{cmpq} instruction
  3305. compares its two arguments to determine whether one argument is less
  3306. than, equal, or greater than the other argument. The \key{cmpq}
  3307. instruction is unusual regarding the order of its arguments and where
  3308. the result is placed. The argument order is backwards: if you want to
  3309. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3310. \key{cmpq} is placed in the special EFLAGS register. This register
  3311. cannot be accessed directly but it can be queried by a number of
  3312. instructions, including the \key{set} instruction. The \key{set}
  3313. instruction puts a \key{1} or \key{0} into its destination depending
  3314. on whether the comparison came out according to the condition code
  3315. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3316. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3317. The set instruction has an annoying quirk in that its destination
  3318. argument must be single byte register, such as \code{al}, which is
  3319. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3320. instruction can then be used to move from a single byte register to a
  3321. normal 64-bit register.
  3322. For compiling the \key{if} expression, the x86 instructions for
  3323. jumping are relevant. The \key{jmp} instruction updates the program
  3324. counter to point to the instruction after the indicated label. The
  3325. \key{jmp-if} instruction updates the program counter to point to the
  3326. instruction after the indicated label depending on whether the result
  3327. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3328. the \key{jmp-if} instruction falls through to the next
  3329. instruction. Because the \key{jmp-if} instruction relies on the EFLAGS
  3330. register, it is quite common for the \key{jmp-if} to be immediately
  3331. preceded by a \key{cmpq} instruction, to set the EFLAGS register.
  3332. Our abstract syntax for \key{jmp-if} differs from the concrete syntax
  3333. for x86 to separate the instruction name from the condition code. For
  3334. example, \code{(jmp-if le foo)} corresponds to \code{jle foo}.
  3335. \section{The $C_1$ Intermediate Language}
  3336. \label{sec:c1}
  3337. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3338. language, but we need to grow that intermediate language to handle the
  3339. new features in $R_2$: Booleans and conditional expressions.
  3340. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3341. logic and comparison operators to the $\Exp$ non-terminal, the
  3342. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3343. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3344. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3345. goto's in the grammar for $\Tail$. This means that a sequence of
  3346. statements may now end with a \code{goto} or a conditional
  3347. \code{goto}, which jumps to one of two labeled pieces of code
  3348. depending on the outcome of the comparison. In
  3349. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3350. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3351. and \key{goto}'s.
  3352. \begin{figure}[tp]
  3353. \fbox{
  3354. \begin{minipage}{0.96\textwidth}
  3355. \[
  3356. \begin{array}{lcl}
  3357. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3358. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3359. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3360. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3361. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3362. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  3363. &\mid& (\key{goto}\,\itm{label}) \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})} \\
  3364. C_1 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  3365. \end{array}
  3366. \]
  3367. \end{minipage}
  3368. }
  3369. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3370. \label{fig:c1-syntax}
  3371. \end{figure}
  3372. \section{Explicate Control}
  3373. \label{sec:explicate-control-r2}
  3374. Recall that the purpose of \code{explicate-control} is to make the
  3375. order of evaluation explicit in the syntax of the program. With the
  3376. addition of \key{if} in $R_2$, things get more interesting.
  3377. As a motivating example, consider the following program that has an
  3378. \key{if} expression nested in the predicate of another \key{if}.
  3379. % s1_38.rkt
  3380. \begin{lstlisting}
  3381. (program ()
  3382. (if (if (eq? (read) 1)
  3383. (eq? (read) 0)
  3384. (eq? (read) 2))
  3385. (+ 10 32)
  3386. (+ 700 77)))
  3387. \end{lstlisting}
  3388. %
  3389. The naive way to compile \key{if} and \key{eq?} would be to handle
  3390. each of them in isolation, regardless of their context. Each
  3391. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3392. by a couple instructions to move the result from the EFLAGS register
  3393. into a general purpose register or stack location. Each \key{if} would
  3394. be translated into the combination of a \key{cmpq} and \key{jmp-if}.
  3395. However, if we take context into account we can do better and reduce
  3396. the use of \key{cmpq} and EFLAG-accessing instructions.
  3397. One idea is to try and reorganize the code at the level of $R_2$,
  3398. pushing the outer \key{if} inside the inner one. This would yield the
  3399. following code.
  3400. \begin{lstlisting}
  3401. (if (eq? (read) 1)
  3402. (if (eq? (read) 0)
  3403. (+ 10 32)
  3404. (+ 700 77))
  3405. (if (eq? (read) 2))
  3406. (+ 10 32)
  3407. (+ 700 77))
  3408. \end{lstlisting}
  3409. Unfortunately, this approach duplicates the two branches, and a
  3410. compiler must never duplicate code!
  3411. We need a way to perform the above transformation, but without
  3412. duplicating code. The solution is straightforward if we think at the
  3413. level of x86 assembly: we can label the code for each of the branches
  3414. and insert \key{goto}'s in all the places that need to execute the
  3415. branches. Put another way, we need to move away from abstract syntax
  3416. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3417. use a standard program representation called a \emph{control flow
  3418. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3419. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3420. each edge represents a jump to another block. The \key{program}
  3421. construct of $C_0$ and $C_1$ represents a control flow graph as an
  3422. association list mapping labels to basic blocks. Each block is
  3423. represented by the $\Tail$ non-terminal.
  3424. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3425. \code{remove-complex-opera*} pass and then the
  3426. \code{explicate-control} pass on the example program. We shall walk
  3427. through the output program and then discuss the algorithm.
  3428. %
  3429. Following the order of evaluation in the output of
  3430. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3431. comparison to \code{1} from the predicate of the inner \key{if}. In
  3432. the output of \code{explicate-control}, in the \code{start} block,
  3433. this becomes a \code{(read)} followed by a conditional goto to either
  3434. \code{block61} or \code{block62}. Each of these contains the
  3435. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3436. 1)}, respectively. Regarding \code{block61}, we start with the
  3437. \code{(read)} and comparison to \code{0} and then have a conditional
  3438. goto, either to \code{block59} or \code{block60}, which indirectly
  3439. take us to \code{block55} and \code{block56}, the two branches of the
  3440. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3441. story for \code{block62} is similar.
  3442. \begin{figure}[tbp]
  3443. \begin{tabular}{lll}
  3444. \begin{minipage}{0.4\textwidth}
  3445. \begin{lstlisting}
  3446. (program ()
  3447. (if (if (eq? (read) 1)
  3448. (eq? (read) 0)
  3449. (eq? (read) 2))
  3450. (+ 10 32)
  3451. (+ 700 77)))
  3452. \end{lstlisting}
  3453. \hspace{40pt}$\Downarrow$
  3454. \begin{lstlisting}
  3455. (program ()
  3456. (if (if (let ([tmp52 (read)])
  3457. (eq? tmp52 1))
  3458. (let ([tmp53 (read)])
  3459. (eq? tmp53 0))
  3460. (let ([tmp54 (read)])
  3461. (eq? tmp54 2)))
  3462. (+ 10 32)
  3463. (+ 700 77)))
  3464. \end{lstlisting}
  3465. \end{minipage}
  3466. &
  3467. $\Rightarrow$
  3468. &
  3469. \begin{minipage}{0.55\textwidth}
  3470. \begin{lstlisting}
  3471. (program ()
  3472. ((block62 .
  3473. (seq (assign tmp54 (read))
  3474. (if (eq? tmp54 2)
  3475. (goto block59)
  3476. (goto block60))))
  3477. (block61 .
  3478. (seq (assign tmp53 (read))
  3479. (if (eq? tmp53 0)
  3480. (goto block57)
  3481. (goto block58))))
  3482. (block60 . (goto block56))
  3483. (block59 . (goto block55))
  3484. (block58 . (goto block56))
  3485. (block57 . (goto block55))
  3486. (block56 . (return (+ 700 77)))
  3487. (block55 . (return (+ 10 32)))
  3488. (start .
  3489. (seq (assign tmp52 (read))
  3490. (if (eq? tmp52 1)
  3491. (goto block61)
  3492. (goto block62))))))
  3493. \end{lstlisting}
  3494. \end{minipage}
  3495. \end{tabular}
  3496. \caption{Example translation from $R_2$ to $C_1$
  3497. via the \code{explicate-control}.}
  3498. \label{fig:explicate-control-s1-38}
  3499. \end{figure}
  3500. The nice thing about the output of \code{explicate-control} is that
  3501. there are no unnecessary uses of \code{eq?} and every use of
  3502. \code{eq?} is part of a conditional jump. The down-side of this output
  3503. is that it includes trivial blocks, such as \code{block57} through
  3504. \code{block60}, that only jump to another block. We discuss a solution
  3505. to this problem in Section~\ref{sec:opt-jumps}.
  3506. Recall that in Section~\ref{sec:explicate-control-r1} we implement the
  3507. \code{explicate-control} pass for $R_1$ using two mutually recursive
  3508. functions, \code{explicate-control-tail} and
  3509. \code{explicate-control-assign}. The former function translated
  3510. expressions in tail position whereas the later function translated
  3511. expressions on the right-hand-side of a \key{let}. With the addition
  3512. of \key{if} expression in $R_2$ we have a new kind of context to deal
  3513. with: the predicate position of the \key{if}. So we shall need another
  3514. function, \code{explicate-control-pred}, that takes an $R_2$
  3515. expression and two pieces of $C_1$ code (two $\Tail$'s) for the
  3516. then-branch and else-branch. The output of
  3517. \code{explicate-control-pred} is a $C_1$ $\Tail$. However, these
  3518. three functions also need to construct the control-flow graph, which we
  3519. recommend they do via updates to a global variable. Next we consider
  3520. the specific additions to the tail and assign functions, and some of
  3521. cases for the pred function.
  3522. The \code{explicate-control-tail} function needs an additional case
  3523. for \key{if}. The branches of the \key{if} inherit the current
  3524. context, so they are in tail position. Let $B_1$ be the result of
  3525. \code{explicate-control-tail} on the $\itm{thn}$ branch and $B_2$ be
  3526. the result of apply \code{explicate-control-tail} to the $\itm{else}$
  3527. branch. Then the \key{if} translates to the block $B_3$ which is the
  3528. result of applying \code{explicate-control-pred} to the predicate
  3529. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3530. \[
  3531. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3532. \]
  3533. Next we consider the case for \key{if} in the
  3534. \code{explicate-control-assign} function. So the context of the
  3535. \key{if} is an assignment to some variable $x$ and then the control
  3536. continues to some block $B_1$. The code that we generate for both the
  3537. $\itm{thn}$ and $\itm{els}$ branches shall both need to continue to
  3538. $B_1$, so we add $B_1$ to the control flow graph with a fresh label
  3539. $\ell_1$. Again, the branches of the \key{if} inherit the current
  3540. context, so that are in assignment positions. Let $B_2$ be the result
  3541. of applying \code{explicate-control-assign} to the $\itm{thn}$ branch,
  3542. variable $x$, and the block \code{(goto $\ell_1$)}. Let $B_3$ be the
  3543. result of applying \code{explicate-control-assign} to the $\itm{else}$
  3544. branch, variable $x$, and the block \code{(goto $\ell_1$)}. The
  3545. \key{if} translates to the block $B_4$ which is the result of applying
  3546. \code{explicate-control-pred} to the predicate $\itm{cnd}$ and the
  3547. blocks $B_2$ and $B_3$.
  3548. \[
  3549. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3550. \]
  3551. The function \code{explicate-control-pred} will need a case for every
  3552. expression that can have type \code{Boolean}. We detail a few cases
  3553. here and leave the rest for the reader. The input to this function is
  3554. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3555. enclosing \key{if}. One of the base cases of this function is when the
  3556. expression is a less-than comparison. We translate it to a
  3557. conditional \code{goto}. We need labels for the two branches $B_1$ and
  3558. $B_2$, so we add them to the control flow graph and obtain some labels
  3559. $\ell_1$ and $\ell_2$. The translation of the less-than comparison is
  3560. as follows.
  3561. \[
  3562. (\key{<}\;e_1\;e_2) \quad\Rightarrow\quad
  3563. (\key{if}\;(\key{<}\;e_1\;e_2)\;(\key{goto}\;\ell_1)\;(\key{goto}\;\ell_2))
  3564. \]
  3565. The case for \key{if} in \code{explicate-control-pred} is particularly
  3566. illuminating, as it deals with the challenges that we discussed above
  3567. regarding the example of the nested \key{if} expressions. Again, we
  3568. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3569. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3570. and $\itm{els}$ of the current \key{if} inherit their context from the
  3571. current one, i.e., predicate context. So we apply
  3572. \code{explicate-control-pred} to $\itm{thn}$ with the two blocks
  3573. \code{(goto $\ell_1$)} and \code{(goto $\ell_2$)}, to obtain $B_3$.
  3574. Similarly for the $\itm{els}$ branch, to obtain $B_4$.
  3575. Finally, we apply \code{explicate-control-pred} to
  3576. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3577. to obtain the result $B_5$.
  3578. \[
  3579. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3580. \quad\Rightarrow\quad
  3581. B_5
  3582. \]
  3583. \begin{exercise}\normalfont
  3584. Implement the pass \code{explicate-code} by adding the cases for
  3585. \key{if} to the functions for tail and assignment contexts, and
  3586. implement the function for predicate contexts. Create test cases
  3587. that exercise all of the new cases in the code for this pass.
  3588. \end{exercise}
  3589. \section{Select Instructions}
  3590. \label{sec:select-r2}
  3591. Recall that the \code{select-instructions} pass lowers from our
  3592. $C$-like intermediate representation to the pseudo-x86 language, which
  3593. is suitable for conducting register allocation. The pass is
  3594. implemented using three auxiliary functions, one for each of the
  3595. non-terminals $\Arg$, $\Stmt$, and $\Tail$.
  3596. For $\Arg$, we have new cases for the Booleans. We take the usual
  3597. approach of encoding them as integers, with true as 1 and false as 0.
  3598. \[
  3599. \key{\#t} \Rightarrow \key{1}
  3600. \qquad
  3601. \key{\#f} \Rightarrow \key{0}
  3602. \]
  3603. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3604. be implemented in terms of \code{xorq} as we discussed at the
  3605. beginning of this section. Given an assignment \code{(assign
  3606. $\itm{lhs}$ (not $\Arg$))}, if the left-hand side $\itm{lhs}$ is
  3607. the same as $\Arg$, then just the \code{xorq} suffices:
  3608. \[
  3609. (\key{assign}\; x\; (\key{not}\; x))
  3610. \quad\Rightarrow\quad
  3611. ((\key{xorq}\;(\key{int}\;1)\;x'))
  3612. \]
  3613. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3614. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3615. $\Arg$. Then we have
  3616. \[
  3617. (\key{assign}\; \itm{lhs}\; (\key{not}\; \Arg))
  3618. \quad\Rightarrow\quad
  3619. ((\key{movq}\; \Arg'\; \itm{lhs}') \; (\key{xorq}\;(\key{int}\;1)\;\itm{lhs}'))
  3620. \]
  3621. Next consider the cases for \code{eq?} and less-than comparison.
  3622. Translating these operations to x86 is slightly involved due to the
  3623. unusual nature of the \key{cmpq} instruction discussed above. We
  3624. recommend translating an assignment from \code{eq?} into the following
  3625. sequence of three instructions. \\
  3626. \begin{tabular}{lll}
  3627. \begin{minipage}{0.4\textwidth}
  3628. \begin{lstlisting}
  3629. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3630. \end{lstlisting}
  3631. \end{minipage}
  3632. &
  3633. $\Rightarrow$
  3634. &
  3635. \begin{minipage}{0.4\textwidth}
  3636. \begin{lstlisting}
  3637. (cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3638. (set e (byte-reg al))
  3639. (movzbq (byte-reg al) |$\itm{lhs}'$|)
  3640. \end{lstlisting}
  3641. \end{minipage}
  3642. \end{tabular} \\
  3643. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3644. \key{goto} and conditional \key{goto}. Both are straightforward
  3645. to handle. A \key{goto} becomes a jump instruction.
  3646. \[
  3647. (\key{goto}\; \ell) \quad \Rightarrow \quad ((\key{jmp} \;\ell))
  3648. \]
  3649. A conditional \key{goto} becomes a compare instruction followed
  3650. by a conditional jump (for ``then'') and the fall-through is
  3651. to a regular jump (for ``else'').\\
  3652. \begin{tabular}{lll}
  3653. \begin{minipage}{0.4\textwidth}
  3654. \begin{lstlisting}
  3655. (if (eq? |$\Arg_1$| |$\Arg_2$|)
  3656. (goto |$\ell_1$|)
  3657. (goto |$\ell_2$|))
  3658. \end{lstlisting}
  3659. \end{minipage}
  3660. &
  3661. $\Rightarrow$
  3662. &
  3663. \begin{minipage}{0.4\textwidth}
  3664. \begin{lstlisting}
  3665. ((cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3666. (jmp-if e |$\ell_1$|)
  3667. (jmp |$\ell_2$|))
  3668. \end{lstlisting}
  3669. \end{minipage}
  3670. \end{tabular} \\
  3671. \begin{exercise}\normalfont
  3672. Expand your \code{select-instructions} pass to handle the new features
  3673. of the $R_2$ language. Test the pass on all the examples you have
  3674. created and make sure that you have some test programs that use the
  3675. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3676. the output using the \code{interp-x86} interpreter
  3677. (Appendix~\ref{appendix:interp}).
  3678. \end{exercise}
  3679. \section{Register Allocation}
  3680. \label{sec:register-allocation-r2}
  3681. The changes required for $R_2$ affect the liveness analysis, building
  3682. the interference graph, and assigning homes, but the graph coloring
  3683. algorithm itself does not need to change.
  3684. \subsection{Liveness Analysis}
  3685. \label{sec:liveness-analysis-r2}
  3686. Recall that for $R_1$ we implemented liveness analysis for a single
  3687. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3688. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3689. now produces many basic blocks arranged in a control-flow graph. The
  3690. first question we need to consider is in what order should we process
  3691. the basic blocks? Recall that to perform liveness analysis, we need to
  3692. know the live-after set. If a basic block has no successor blocks,
  3693. then it has an empty live-after set and we can immediately apply
  3694. liveness analysis to it. If a basic block has some successors, then we
  3695. need to complete liveness analysis on those blocks first.
  3696. Furthermore, we know that the control flow graph does not contain any
  3697. cycles (it is a DAG, that is, a directed acyclic graph)\footnote{If we
  3698. were to add loops to the language, then the CFG could contain cycles
  3699. and we would instead need to use the classic worklist algorithm for
  3700. computing the fixed point of the liveness
  3701. analysis~\citep{Aho:1986qf}.}. What all this amounts to is that we
  3702. need to process the basic blocks in reverse topological order. We
  3703. recommend using the \code{tsort} and \code{transpose} functions of the
  3704. Racket \code{graph} package to obtain this ordering.
  3705. The next question is how to compute the live-after set of a block
  3706. given the live-before sets of all its successor blocks. During
  3707. compilation we do not know which way the branch will go, so we do not
  3708. know which of the successor's live-before set to use. The solution
  3709. comes from the observation that there is no harm in identifying more
  3710. variables as live than absolutely necessary. Thus, we can take the
  3711. union of the live-before sets from all the successors to be the
  3712. live-after set for the block. Once we have computed the live-after
  3713. set, we can proceed to perform liveness analysis on the block just as
  3714. we did in Section~\ref{sec:liveness-analysis-r1}.
  3715. The helper functions for computing the variables in an instruction's
  3716. argument and for computing the variables read-from ($R$) or written-to
  3717. ($W$) by an instruction need to be updated to handle the new kinds of
  3718. arguments and instructions in x86$_1$.
  3719. \subsection{Build Interference}
  3720. \label{sec:build-interference-r2}
  3721. Many of the new instructions in x86$_1$ can be handled in the same way
  3722. as the instructions in x86$_0$. Thus, if your code was already quite
  3723. general, it will not need to be changed to handle the new
  3724. instructions. If not, I recommend that you change your code to be more
  3725. general. The \key{movzbq} instruction should be handled like the
  3726. \key{movq} instruction.
  3727. %% \subsection{Assign Homes}
  3728. %% \label{sec:assign-homes-r2}
  3729. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3730. %% to be updated to handle the \key{if} statement, simply by recursively
  3731. %% processing the child nodes. Hopefully your code already handles the
  3732. %% other new instructions, but if not, you can generalize your code.
  3733. \begin{exercise}\normalfont
  3734. Update the \code{register-allocation} pass so that it works for $R_2$
  3735. and test your compiler using your previously created programs on the
  3736. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3737. \end{exercise}
  3738. %% \section{Lower Conditionals (New Pass)}
  3739. %% \label{sec:lower-conditionals}
  3740. %% In the \code{select-instructions} pass we decided to procrastinate in
  3741. %% the lowering of the \key{if} statement, thereby making liveness
  3742. %% analysis easier. Now we need to make up for that and turn the \key{if}
  3743. %% statement into the appropriate instruction sequence. The following
  3744. %% translation gives the general idea. If the condition is true, we need
  3745. %% to execute the $\itm{thns}$ branch and otherwise we need to execute
  3746. %% the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3747. %% jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3748. %% is appropriate for the comparison operator \itm{cmp}. If the
  3749. %% condition is false, we fall through to the $\itm{elss}$ branch. At the
  3750. %% end of the $\itm{elss}$ branch we need to take care to not fall
  3751. %% through to the $\itm{thns}$ branch. So we jump to the
  3752. %% $\itm{endlabel}$. All of the labels in the generated code should be
  3753. %% created with \code{gensym}.
  3754. %% \begin{tabular}{lll}
  3755. %% \begin{minipage}{0.4\textwidth}
  3756. %% \begin{lstlisting}
  3757. %% (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3758. %% \end{lstlisting}
  3759. %% \end{minipage}
  3760. %% &
  3761. %% $\Rightarrow$
  3762. %% &
  3763. %% \begin{minipage}{0.4\textwidth}
  3764. %% \begin{lstlisting}
  3765. %% (cmpq |$\Arg_2$| |$\Arg_1$|)
  3766. %% (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3767. %% |$\itm{elss}$|
  3768. %% (jmp |$\itm{endlabel}$|)
  3769. %% (label |$\itm{thenlabel}$|)
  3770. %% |$\itm{thns}$|
  3771. %% (label |$\itm{endlabel}$|)
  3772. %% \end{lstlisting}
  3773. %% \end{minipage}
  3774. %% \end{tabular}
  3775. %% \begin{exercise}\normalfont
  3776. %% Implement the \code{lower-conditionals} pass. Test your compiler using
  3777. %% your previously created programs on the \code{interp-x86} interpreter
  3778. %% (Appendix~\ref{appendix:interp}).
  3779. %% \end{exercise}
  3780. \section{Patch Instructions}
  3781. The second argument of the \key{cmpq} instruction must not be an
  3782. immediate value (such as a literal integer). So if you are comparing
  3783. two immediates, we recommend inserting a \key{movq} instruction to put
  3784. the second argument in \key{rax}.
  3785. %
  3786. The second argument of the \key{movzbq} must be a register.
  3787. %
  3788. There are no special restrictions on the x86 instructions
  3789. \key{jmp-if}, \key{jmp}, and \key{label}.
  3790. \begin{exercise}\normalfont
  3791. Update \code{patch-instructions} to handle the new x86 instructions.
  3792. Test your compiler using your previously created programs on the
  3793. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3794. \end{exercise}
  3795. \section{An Example Translation}
  3796. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3797. $R_2$ translated to x86, showing the results of
  3798. \code{explicate-control}, \code{select-instructions}, and the final
  3799. x86 assembly code.
  3800. \begin{figure}[tbp]
  3801. \begin{tabular}{lll}
  3802. \begin{minipage}{0.5\textwidth}
  3803. % s1_20.rkt
  3804. \begin{lstlisting}
  3805. (program ()
  3806. (if (eq? (read) 1) 42 0))
  3807. \end{lstlisting}
  3808. $\Downarrow$
  3809. \begin{lstlisting}
  3810. (program ()
  3811. ((block32 . (return 0))
  3812. (block31 . (return 42))
  3813. (start .
  3814. (seq (assign tmp30 (read))
  3815. (if (eq? tmp30 1)
  3816. (goto block31)
  3817. (goto block32))))))
  3818. \end{lstlisting}
  3819. $\Downarrow$
  3820. \begin{lstlisting}
  3821. (program ((locals . (tmp30)))
  3822. ((block32 .
  3823. (block ()
  3824. (movq (int 0) (reg rax))
  3825. (jmp conclusion)))
  3826. (block31 .
  3827. (block ()
  3828. (movq (int 42) (reg rax))
  3829. (jmp conclusion)))
  3830. (start .
  3831. (block ()
  3832. (callq read_int)
  3833. (movq (reg rax) (var tmp30))
  3834. (cmpq (int 1) (var tmp30))
  3835. (jmp-if e block31)
  3836. (jmp block32)))))
  3837. \end{lstlisting}
  3838. \end{minipage}
  3839. &
  3840. $\Rightarrow$
  3841. \begin{minipage}{0.4\textwidth}
  3842. \begin{lstlisting}
  3843. _block31:
  3844. movq $42, %rax
  3845. jmp _conclusion
  3846. _block32:
  3847. movq $0, %rax
  3848. jmp _conclusion
  3849. _start:
  3850. callq _read_int
  3851. movq %rax, %rcx
  3852. cmpq $1, %rcx
  3853. je _block31
  3854. jmp _block32
  3855. .globl _main
  3856. _main:
  3857. pushq %rbp
  3858. movq %rsp, %rbp
  3859. pushq %r12
  3860. pushq %rbx
  3861. pushq %r13
  3862. pushq %r14
  3863. subq $0, %rsp
  3864. jmp _start
  3865. _conclusion:
  3866. addq $0, %rsp
  3867. popq %r14
  3868. popq %r13
  3869. popq %rbx
  3870. popq %r12
  3871. popq %rbp
  3872. retq
  3873. \end{lstlisting}
  3874. \end{minipage}
  3875. \end{tabular}
  3876. \caption{Example compilation of an \key{if} expression to x86.}
  3877. \label{fig:if-example-x86}
  3878. \end{figure}
  3879. \begin{figure}[p]
  3880. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3881. \node (R2) at (0,2) {\large $R_2$};
  3882. \node (R2-2) at (3,2) {\large $R_2$};
  3883. \node (R2-3) at (6,2) {\large $R_2$};
  3884. \node (R2-4) at (9,2) {\large $R_2$};
  3885. \node (R2-5) at (12,2) {\large $R_2$};
  3886. \node (C1-1) at (6,0) {\large $C_1$};
  3887. \node (C1-2) at (3,0) {\large $C_1$};
  3888. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3889. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3890. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3891. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  3892. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3893. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3894. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  3895. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  3896. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  3897. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  3898. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  3899. \path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  3900. \path[->,bend right=15] (C1-2) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3901. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3902. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3903. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3904. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  3905. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  3906. \end{tikzpicture}
  3907. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3908. \label{fig:R2-passes}
  3909. \end{figure}
  3910. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  3911. compilation of $R_2$.
  3912. \section{Challenge: Optimize Jumps$^{*}$}
  3913. \label{sec:opt-jumps}
  3914. UNDER CONSTRUCTION
  3915. %% \section{Challenge: Optimizing Conditions$^{*}$}
  3916. %% \label{sec:opt-if}
  3917. %% A close inspection of the x86 code generated in
  3918. %% Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3919. %% regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3920. %% twice using \key{cmpq} as follows.
  3921. %% % Wierd LaTeX bug if I remove the following. -Jeremy
  3922. %% % Does it have to do with page breaks?
  3923. %% \begin{lstlisting}
  3924. %% \end{lstlisting}
  3925. %% \begin{lstlisting}
  3926. %% cmpq $1, %rcx
  3927. %% sete %al
  3928. %% movzbq %al, %rcx
  3929. %% cmpq $1, %rcx
  3930. %% je then21288
  3931. %% \end{lstlisting}
  3932. %% The reason for this non-optimal code has to do with the \code{flatten}
  3933. %% pass earlier in this Chapter. We recommended flattening the condition
  3934. %% to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3935. %% is already an \code{eq?} test, then we would like to use that
  3936. %% directly. In fact, for many of the expressions of Boolean type, we can
  3937. %% generate more optimized code. For example, if the condition is
  3938. %% \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3939. %% all. If the condition is a \code{let}, we can optimize based on the
  3940. %% form of its body. If the condition is a \code{not}, then we can flip
  3941. %% the two branches.
  3942. %% %
  3943. %% \margincomment{\tiny We could do even better by converting to basic
  3944. %% blocks.\\ --Jeremy}
  3945. %% %
  3946. %% On the other hand, if the condition is a \code{and}
  3947. %% or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3948. %% code duplication.
  3949. %% Figure~\ref{fig:opt-if} shows an example program and the result of
  3950. %% applying the above suggested optimizations.
  3951. %% \begin{exercise}\normalfont
  3952. %% Change the \code{flatten} pass to improve the code that gets
  3953. %% generated for \code{if} expressions. We recommend writing a helper
  3954. %% function that recursively traverses the condition of the \code{if}.
  3955. %% \end{exercise}
  3956. %% \begin{figure}[tbp]
  3957. %% \begin{tabular}{lll}
  3958. %% \begin{minipage}{0.5\textwidth}
  3959. %% \begin{lstlisting}
  3960. %% (program
  3961. %% (if (let ([x 1])
  3962. %% (not (eq? x (read))))
  3963. %% 777
  3964. %% 42))
  3965. %% \end{lstlisting}
  3966. %% $\Downarrow$
  3967. %% \begin{lstlisting}
  3968. %% (program (x.1 if.2 tmp.3)
  3969. %% (type Integer)
  3970. %% (assign x.1 1)
  3971. %% (assign tmp.3 (read))
  3972. %% (if (eq? x.1 tmp.3)
  3973. %% ((assign if.2 42))
  3974. %% ((assign if.2 777)))
  3975. %% (return if.2))
  3976. %% \end{lstlisting}
  3977. %% $\Downarrow$
  3978. %% \begin{lstlisting}
  3979. %% (program (x.1 if.2 tmp.3)
  3980. %% (type Integer)
  3981. %% (movq (int 1) (var x.1))
  3982. %% (callq read_int)
  3983. %% (movq (reg rax) (var tmp.3))
  3984. %% (if (eq? (var x.1) (var tmp.3))
  3985. %% ((movq (int 42) (var if.2)))
  3986. %% ((movq (int 777) (var if.2))))
  3987. %% (movq (var if.2) (reg rax)))
  3988. %% \end{lstlisting}
  3989. %% \end{minipage}
  3990. %% &
  3991. %% $\Rightarrow$
  3992. %% \begin{minipage}{0.4\textwidth}
  3993. %% \begin{lstlisting}
  3994. %% .globl _main
  3995. %% _main:
  3996. %% pushq %rbp
  3997. %% movq %rsp, %rbp
  3998. %% pushq %r13
  3999. %% pushq %r14
  4000. %% pushq %r12
  4001. %% pushq %rbx
  4002. %% subq $0, %rsp
  4003. %% movq $1, %rbx
  4004. %% callq _read_int
  4005. %% movq %rax, %rcx
  4006. %% cmpq %rcx, %rbx
  4007. %% je then35989
  4008. %% movq $777, %rbx
  4009. %% jmp if_end35990
  4010. %% then35989:
  4011. %% movq $42, %rbx
  4012. %% if_end35990:
  4013. %% movq %rbx, %rax
  4014. %% movq %rax, %rdi
  4015. %% callq _print_int
  4016. %% movq $0, %rax
  4017. %% addq $0, %rsp
  4018. %% popq %rbx
  4019. %% popq %r12
  4020. %% popq %r14
  4021. %% popq %r13
  4022. %% popq %rbp
  4023. %% retq
  4024. %% \end{lstlisting}
  4025. %% \end{minipage}
  4026. %% \end{tabular}
  4027. %% \caption{Example program with optimized conditionals.}
  4028. %% \label{fig:opt-if}
  4029. %% \end{figure}
  4030. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4031. \chapter{Tuples and Garbage Collection}
  4032. \label{ch:tuples}
  4033. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4034. things to discuss in this chapter. \\ --Jeremy}
  4035. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4036. all the IR grammars are spelled out! \\ --Jeremy}
  4037. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4038. but keep type annotations on vector creation and local variables, function
  4039. parameters, etc. \\ --Jeremy}
  4040. \margincomment{\scriptsize Be more explicit about how to deal with
  4041. the root stack. \\ --Jeremy}
  4042. In this chapter we study the implementation of mutable tuples (called
  4043. ``vectors'' in Racket). This language feature is the first to use the
  4044. computer's \emph{heap} because the lifetime of a Racket tuple is
  4045. indefinite, that is, a tuple lives forever from the programmer's
  4046. viewpoint. Of course, from an implementer's viewpoint, it is important
  4047. to reclaim the space associated with a tuple when it is no longer
  4048. needed, which is why we also study \emph{garbage collection}
  4049. techniques in this chapter.
  4050. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4051. interpreter and type checker. The $R_3$ language extends the $R_2$
  4052. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4053. ``void'' value. The reason for including the later is that the
  4054. \code{vector-set!} operation returns a value of type
  4055. \code{Void}\footnote{This may sound contradictory, but Racket's
  4056. \code{Void} type corresponds to what is more commonly called the
  4057. \code{Unit} type. This type is inhabited by a single value that is
  4058. usually written \code{unit} or \code{()}\citep{Pierce:2002hj}.}.
  4059. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4060. copying live objects back and forth between two halves of the
  4061. heap. The garbage collector requires coordination with the compiler so
  4062. that it can see all of the \emph{root} pointers, that is, pointers in
  4063. registers or on the procedure call stack.
  4064. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4065. discuss all the necessary changes and additions to the compiler
  4066. passes, including a new compiler pass named \code{expose-allocation}.
  4067. \section{The $R_3$ Language}
  4068. \label{sec:r3}
  4069. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  4070. includes three new forms for creating a tuple, reading an element of a
  4071. tuple, and writing to an element of a tuple. The program in
  4072. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4073. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  4074. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  4075. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  4076. ``then'' branch is taken. The element at index $0$ of \code{t} is
  4077. $40$, to which we add the $2$, the element at index $0$ of the
  4078. 1-tuple.
  4079. \begin{figure}[tbp]
  4080. \begin{lstlisting}
  4081. (let ([t (vector 40 #t (vector 2))])
  4082. (if (vector-ref t 1)
  4083. (+ (vector-ref t 0)
  4084. (vector-ref (vector-ref t 2) 0))
  4085. 44))
  4086. \end{lstlisting}
  4087. \caption{Example program that creates tuples and reads from them.}
  4088. \label{fig:vector-eg}
  4089. \end{figure}
  4090. \begin{figure}[tbp]
  4091. \centering
  4092. \fbox{
  4093. \begin{minipage}{0.96\textwidth}
  4094. \[
  4095. \begin{array}{lcl}
  4096. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4097. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4098. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4099. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4100. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4101. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4102. \mid (\key{and}\;\Exp\;\Exp)
  4103. \mid (\key{or}\;\Exp\;\Exp)
  4104. \mid (\key{not}\;\Exp) } \\
  4105. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4106. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4107. &\mid& (\key{vector}\;\Exp^{+})
  4108. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4109. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4110. &\mid& (\key{void}) \\
  4111. R_3 &::=& (\key{program} \; \Exp)
  4112. \end{array}
  4113. \]
  4114. \end{minipage}
  4115. }
  4116. \caption{The syntax of $R_3$, extending $R_2$
  4117. (Figure~\ref{fig:r2-syntax}) with tuples.}
  4118. \label{fig:r3-syntax}
  4119. \end{figure}
  4120. Tuples are our first encounter with heap-allocated data, which raises
  4121. several interesting issues. First, variable binding performs a
  4122. shallow-copy when dealing with tuples, which means that different
  4123. variables can refer to the same tuple, i.e., different variables can
  4124. be \emph{aliases} for the same thing. Consider the following example
  4125. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4126. the mutation through \code{t2} is visible when referencing the tuple
  4127. from \code{t1}, so the result of this program is \code{42}.
  4128. \begin{lstlisting}
  4129. (let ([t1 (vector 3 7)])
  4130. (let ([t2 t1])
  4131. (let ([_ (vector-set! t2 0 42)])
  4132. (vector-ref t1 0))))
  4133. \end{lstlisting}
  4134. The next issue concerns the lifetime of tuples. Of course, they are
  4135. created by the \code{vector} form, but when does their lifetime end?
  4136. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4137. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4138. is not tied to any notion of static scoping. For example, the
  4139. following program returns \code{3} even though the variable \code{t}
  4140. goes out of scope prior to accessing the vector.
  4141. \begin{lstlisting}
  4142. (vector-ref
  4143. (let ([t (vector 3 7)])
  4144. t)
  4145. 0)
  4146. \end{lstlisting}
  4147. From the perspective of programmer-observable behavior, tuples live
  4148. forever. Of course, if they really lived forever, then many programs
  4149. would run out of memory.\footnote{The $R_3$ language does not have
  4150. looping or recursive function, so it is nigh impossible to write a
  4151. program in $R_3$ that will run out of memory. However, we add
  4152. recursive functions in the next Chapter!} A Racket implementation
  4153. must therefore perform automatic garbage collection.
  4154. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4155. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4156. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4157. operations in Racket. One subtle point is that the \code{vector-set!}
  4158. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4159. can be passed around just like other values inside an $R_3$ program,
  4160. but there are no operations specific to the the \code{\#<void>} value
  4161. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4162. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4163. otherwise.
  4164. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$ , which
  4165. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4166. need to know which variables are pointers into the heap, that is,
  4167. which variables are vectors. Also, when allocating a vector, we shall
  4168. need to know which elements of the vector are pointers. We can obtain
  4169. this information during type checking and when we uncover local
  4170. variables. The type checker in Figure~\ref{fig:typecheck-R3} not only
  4171. computes the type of an expression, it also wraps every sub-expression
  4172. $e$ with the form $(\key{has-type}\; e\; T)$, where $T$ is $e$'s
  4173. type. Subsequently, in the \code{uncover-locals} pass
  4174. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4175. propagated to all variables (including the temporaries generated by
  4176. \code{remove-complex-opera*}).
  4177. \begin{figure}[tbp]
  4178. \begin{lstlisting}
  4179. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4180. (define (interp-op op)
  4181. (match op
  4182. ...
  4183. ['vector vector]
  4184. ['vector-ref vector-ref]
  4185. ['vector-set! vector-set!]
  4186. [else (error 'interp-op "unknown operator")]))
  4187. (define (interp-R3 env)
  4188. (lambda (e)
  4189. (match e
  4190. ...
  4191. [else (error 'interp-R3 "unrecognized expression")]
  4192. )))
  4193. \end{lstlisting}
  4194. \caption{Interpreter for the $R_3$ language.}
  4195. \label{fig:interp-R3}
  4196. \end{figure}
  4197. \begin{figure}[tbp]
  4198. \begin{lstlisting}
  4199. (define (type-check-exp env)
  4200. (lambda (e)
  4201. (define recur (type-check-exp env))
  4202. (match e
  4203. ...
  4204. ['(void) (values '(has-type (void) Void) 'Void)]
  4205. [`(vector ,es ...)
  4206. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4207. (recur e)))
  4208. (let ([t `(Vector ,@t*)])
  4209. (debug "vector/type-check-exp finished vector" t)
  4210. (values `(has-type (vector ,@e*) ,t) t))]
  4211. [`(vector-ref ,e ,i)
  4212. (define-values (e^ t) (recur e))
  4213. (match t
  4214. [`(Vector ,ts ...)
  4215. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4216. (error 'type-check-exp "invalid index ~a" i))
  4217. (let ([t (list-ref ts i)])
  4218. (values `(has-type (vector-ref ,e^ (has-type ,i Integer)) ,t)
  4219. t))]
  4220. [else (error "expected a vector in vector-ref, not" t)])]
  4221. [`(eq? ,arg1 ,arg2)
  4222. (define-values (e1 t1) (recur arg1))
  4223. (define-values (e2 t2) (recur arg2))
  4224. (match* (t1 t2)
  4225. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  4226. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  4227. [(other wise) ((super type-check-exp env) e)])]
  4228. ...
  4229. )))
  4230. \end{lstlisting}
  4231. \caption{Type checker for the $R_3$ language.}
  4232. \label{fig:typecheck-R3}
  4233. \end{figure}
  4234. \section{Garbage Collection}
  4235. \label{sec:GC}
  4236. Here we study a relatively simple algorithm for garbage collection
  4237. that is the basis of state-of-the-art garbage
  4238. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4239. particular, we describe a two-space copying
  4240. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4241. perform the
  4242. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4243. coarse-grained depiction of what happens in a two-space collector,
  4244. showing two time steps, prior to garbage collection on the top and
  4245. after garbage collection on the bottom. In a two-space collector, the
  4246. heap is divided into two parts, the FromSpace and the
  4247. ToSpace. Initially, all allocations go to the FromSpace until there is
  4248. not enough room for the next allocation request. At that point, the
  4249. garbage collector goes to work to make more room.
  4250. The garbage collector must be careful not to reclaim tuples that will
  4251. be used by the program in the future. Of course, it is impossible in
  4252. general to predict what a program will do, but we can over approximate
  4253. the will-be-used tuples by preserving all tuples that could be
  4254. accessed by \emph{any} program given the current computer state. A
  4255. program could access any tuple whose address is in a register or on
  4256. the procedure call stack. These addresses are called the \emph{root
  4257. set}. In addition, a program could access any tuple that is
  4258. transitively reachable from the root set. Thus, it is safe for the
  4259. garbage collector to reclaim the tuples that are not reachable in this
  4260. way.
  4261. So the goal of the garbage collector is twofold:
  4262. \begin{enumerate}
  4263. \item preserve all tuple that are reachable from the root set via a
  4264. path of pointers, that is, the \emph{live} tuples, and
  4265. \item reclaim the memory of everything else, that is, the
  4266. \emph{garbage}.
  4267. \end{enumerate}
  4268. A copying collector accomplishes this by copying all of the live
  4269. objects from the FromSpace into the ToSpace and then performs a slight
  4270. of hand, treating the ToSpace as the new FromSpace and the old
  4271. FromSpace as the new ToSpace. In the example of
  4272. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4273. root set, one in a register and two on the stack. All of the live
  4274. objects have been copied to the ToSpace (the right-hand side of
  4275. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4276. pointer relationships. For example, the pointer in the register still
  4277. points to a 2-tuple whose first element is a 3-tuple and second
  4278. element is a 2-tuple. There are four tuples that are not reachable
  4279. from the root set and therefore do not get copied into the ToSpace.
  4280. (The situation in Figure~\ref{fig:copying-collector}, with a
  4281. cycle, cannot be created by a well-typed program in $R_3$. However,
  4282. creating cycles will be possible once we get to $R_6$. We design
  4283. the garbage collector to deal with cycles to begin with, so we will
  4284. not need to revisit this issue.)
  4285. \begin{figure}[tbp]
  4286. \centering
  4287. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4288. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4289. \caption{A copying collector in action.}
  4290. \label{fig:copying-collector}
  4291. \end{figure}
  4292. There are many alternatives to copying collectors (and their older
  4293. siblings, the generational collectors) when its comes to garbage
  4294. collection, such as mark-and-sweep and reference counting. The
  4295. strengths of copying collectors are that allocation is fast (just a
  4296. test and pointer increment), there is no fragmentation, cyclic garbage
  4297. is collected, and the time complexity of collection only depends on
  4298. the amount of live data, and not on the amount of
  4299. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4300. copying collectors is that they use a lot of space, though that
  4301. problem is ameliorated in generational collectors. Racket and Scheme
  4302. programs tend to allocate many small objects and generate a lot of
  4303. garbage, so copying and generational collectors are a good fit. Of
  4304. course, garbage collection is an active research topic, especially
  4305. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4306. continuously developing new techniques and revisiting old
  4307. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4308. \subsection{Graph Copying via Cheney's Algorithm}
  4309. \label{sec:cheney}
  4310. Let us take a closer look at how the copy works. The allocated objects
  4311. and pointers can be viewed as a graph and we need to copy the part of
  4312. the graph that is reachable from the root set. To make sure we copy
  4313. all of the reachable vertices in the graph, we need an exhaustive
  4314. graph traversal algorithm, such as depth-first search or breadth-first
  4315. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4316. take into account the possibility of cycles by marking which vertices
  4317. have already been visited, so as to ensure termination of the
  4318. algorithm. These search algorithms also use a data structure such as a
  4319. stack or queue as a to-do list to keep track of the vertices that need
  4320. to be visited. We shall use breadth-first search and a trick due to
  4321. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4322. copying tuples into the ToSpace.
  4323. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4324. copy progresses. The queue is represented by a chunk of contiguous
  4325. memory at the beginning of the ToSpace, using two pointers to track
  4326. the front and the back of the queue. The algorithm starts by copying
  4327. all tuples that are immediately reachable from the root set into the
  4328. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4329. old tuple to indicate that it has been visited. (We discuss the
  4330. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4331. inside the copied tuples in the queue still point back to the
  4332. FromSpace. Once the initial queue has been created, the algorithm
  4333. enters a loop in which it repeatedly processes the tuple at the front
  4334. of the queue and pops it off the queue. To process a tuple, the
  4335. algorithm copies all the tuple that are directly reachable from it to
  4336. the ToSpace, placing them at the back of the queue. The algorithm then
  4337. updates the pointers in the popped tuple so they point to the newly
  4338. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4339. step we copy the tuple whose second element is $42$ to the back of the
  4340. queue. The other pointer goes to a tuple that has already been copied,
  4341. so we do not need to copy it again, but we do need to update the
  4342. pointer to the new location. This can be accomplished by storing a
  4343. \emph{forwarding} pointer to the new location in the old tuple, back
  4344. when we initially copied the tuple into the ToSpace. This completes
  4345. one step of the algorithm. The algorithm continues in this way until
  4346. the front of the queue is empty, that is, until the front catches up
  4347. with the back.
  4348. \begin{figure}[tbp]
  4349. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4350. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4351. \label{fig:cheney}
  4352. \end{figure}
  4353. \subsection{Data Representation}
  4354. \label{sec:data-rep-gc}
  4355. The garbage collector places some requirements on the data
  4356. representations used by our compiler. First, the garbage collector
  4357. needs to distinguish between pointers and other kinds of data. There
  4358. are several ways to accomplish this.
  4359. \begin{enumerate}
  4360. \item Attached a tag to each object that identifies what type of
  4361. object it is~\citep{McCarthy:1960dz}.
  4362. \item Store different types of objects in different
  4363. regions~\citep{Steele:1977ab}.
  4364. \item Use type information from the program to either generate
  4365. type-specific code for collecting or to generate tables that can
  4366. guide the
  4367. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4368. \end{enumerate}
  4369. Dynamically typed languages, such as Lisp, need to tag objects
  4370. anyways, so option 1 is a natural choice for those languages.
  4371. However, $R_3$ is a statically typed language, so it would be
  4372. unfortunate to require tags on every object, especially small and
  4373. pervasive objects like integers and Booleans. Option 3 is the
  4374. best-performing choice for statically typed languages, but comes with
  4375. a relatively high implementation complexity. To keep this chapter to a
  4376. 2-week time budget, we recommend a combination of options 1 and 2,
  4377. with separate strategies used for the stack and the heap.
  4378. Regarding the stack, we recommend using a separate stack for
  4379. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4380. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4381. local variable needs to be spilled and is of type \code{(Vector
  4382. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4383. of the normal procedure call stack. Furthermore, we always spill
  4384. vector-typed variables if they are live during a call to the
  4385. collector, thereby ensuring that no pointers are in registers during a
  4386. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4387. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4388. layout using a root stack. The root stack contains the two pointers
  4389. from the regular stack and also the pointer in the second
  4390. register.
  4391. \begin{figure}[tbp]
  4392. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4393. \caption{Maintaining a root stack to facilitate garbage collection.}
  4394. \label{fig:shadow-stack}
  4395. \end{figure}
  4396. The problem of distinguishing between pointers and other kinds of data
  4397. also arises inside of each tuple. We solve this problem by attaching a
  4398. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4399. in on the tags for two of the tuples in the example from
  4400. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4401. in a big-endian way, from right-to-left, with bit location 0 (the
  4402. least significant bit) on the far right, which corresponds to the
  4403. directional of the x86 shifting instructions \key{salq} (shift
  4404. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4405. specifying which elements of the tuple are pointers, the part labeled
  4406. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4407. a pointer and a 0 bit indicates some other kind of data. The pointer
  4408. mask starts at bit location 7. We have limited tuples to a maximum
  4409. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4410. tag also contains two other pieces of information. The length of the
  4411. tuple (number of elements) is stored in bits location 1 through
  4412. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4413. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4414. has not yet been copied. If the bit has value 0 then the entire tag
  4415. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4416. always zero anyways because our tuples are 8-byte aligned.)
  4417. \begin{figure}[tbp]
  4418. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4419. \caption{Representation for tuples in the heap.}
  4420. \label{fig:tuple-rep}
  4421. \end{figure}
  4422. \subsection{Implementation of the Garbage Collector}
  4423. \label{sec:organize-gz}
  4424. The implementation of the garbage collector needs to do a lot of
  4425. bit-level data manipulation and we need to link it with our
  4426. compiler-generated x86 code. Thus, we recommend implementing the
  4427. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4428. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4429. interface to the garbage collector. The \code{initialize} function
  4430. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4431. function is meant to be called near the beginning of \code{main},
  4432. before the rest of the program executes. The \code{initialize}
  4433. function puts the address of the beginning of the FromSpace into the
  4434. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4435. points to the address that is 1-past the last element of the
  4436. FromSpace. (We use half-open intervals to represent chunks of
  4437. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4438. points to the first element of the root stack.
  4439. As long as there is room left in the FromSpace, your generated code
  4440. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4441. %
  4442. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4443. --Jeremy}
  4444. %
  4445. The amount of room left in FromSpace is the difference between the
  4446. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4447. function should be called when there is not enough room left in the
  4448. FromSpace for the next allocation. The \code{collect} function takes
  4449. a pointer to the current top of the root stack (one past the last item
  4450. that was pushed) and the number of bytes that need to be
  4451. allocated. The \code{collect} function performs the copying collection
  4452. and leaves the heap in a state such that the next allocation will
  4453. succeed.
  4454. \begin{figure}[tbp]
  4455. \begin{lstlisting}
  4456. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4457. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4458. int64_t* free_ptr;
  4459. int64_t* fromspace_begin;
  4460. int64_t* fromspace_end;
  4461. int64_t** rootstack_begin;
  4462. \end{lstlisting}
  4463. \caption{The compiler's interface to the garbage collector.}
  4464. \label{fig:gc-header}
  4465. \end{figure}
  4466. \begin{exercise}
  4467. In the file \code{runtime.c} you will find the implementation of
  4468. \code{initialize} and a partial implementation of \code{collect}.
  4469. The \code{collect} function calls another function, \code{cheney},
  4470. to perform the actual copy, and that function is left to the reader
  4471. to implement. The following is the prototype for \code{cheney}.
  4472. \begin{lstlisting}
  4473. static void cheney(int64_t** rootstack_ptr);
  4474. \end{lstlisting}
  4475. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4476. rootstack (which is an array of pointers). The \code{cheney} function
  4477. also communicates with \code{collect} through the global
  4478. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4479. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4480. the ToSpace:
  4481. \begin{lstlisting}
  4482. static int64_t* tospace_begin;
  4483. static int64_t* tospace_end;
  4484. \end{lstlisting}
  4485. The job of the \code{cheney} function is to copy all the live
  4486. objects (reachable from the root stack) into the ToSpace, update
  4487. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4488. update the root stack so that it points to the objects in the
  4489. ToSpace, and finally to swap the global pointers for the FromSpace
  4490. and ToSpace.
  4491. \end{exercise}
  4492. %% \section{Compiler Passes}
  4493. %% \label{sec:code-generation-gc}
  4494. The introduction of garbage collection has a non-trivial impact on our
  4495. compiler passes. We introduce one new compiler pass called
  4496. \code{expose-allocation} and make non-trivial changes to
  4497. \code{type-check}, \code{flatten}, \code{select-instructions},
  4498. \code{allocate-registers}, and \code{print-x86}. The following
  4499. program will serve as our running example. It creates two tuples, one
  4500. nested inside the other. Both tuples have length one. The example then
  4501. accesses the element in the inner tuple tuple via two vector
  4502. references.
  4503. % tests/s2_17.rkt
  4504. \begin{lstlisting}
  4505. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4506. \end{lstlisting}
  4507. Next we proceed to discuss the new \code{expose-allocation} pass.
  4508. \section{Expose Allocation}
  4509. \label{sec:expose-allocation}
  4510. The pass \code{expose-allocation} lowers the \code{vector} creation
  4511. form into a conditional call to the collector followed by the
  4512. allocation. We choose to place the \code{expose-allocation} pass
  4513. before \code{flatten} because \code{expose-allocation} introduces new
  4514. variables, which can be done locally with \code{let}, but \code{let}
  4515. is gone after \code{flatten}. In the following, we show the
  4516. transformation for the \code{vector} form into let-bindings for the
  4517. initializing expressions, by a conditional \code{collect}, an
  4518. \code{allocate}, and the initialization of the vector.
  4519. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4520. total bytes need to be allocated for the vector, which is 8 for the
  4521. tag plus \itm{len} times 8.)
  4522. \begin{lstlisting}
  4523. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4524. |$\Longrightarrow$|
  4525. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4526. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4527. (global-value fromspace_end))
  4528. (void)
  4529. (collect |\itm{bytes}|))])
  4530. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4531. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4532. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4533. |$v$|) ... )))) ...)
  4534. \end{lstlisting}
  4535. (In the above, we suppressed all of the \code{has-type} forms in the
  4536. output for the sake of readability.) The placement of the initializing
  4537. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4538. the sequence of \code{vector-set!}'s is important, as those expressions
  4539. may trigger garbage collection and we do not want an allocated but
  4540. uninitialized tuple to be present during a garbage collection.
  4541. The output of \code{expose-allocation} is a language that extends
  4542. $R_3$ with the three new forms that we use above in the translation of
  4543. \code{vector}.
  4544. \[
  4545. \begin{array}{lcl}
  4546. \Exp &::=& \cdots
  4547. \mid (\key{collect} \,\itm{int})
  4548. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4549. \mid (\key{global-value} \,\itm{name})
  4550. \end{array}
  4551. \]
  4552. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4553. %% the beginning of the program which will instruct the garbage collector
  4554. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4555. %% two arguments of \code{initialize} specify the initial allocated space
  4556. %% for the root stack and for the heap.
  4557. %
  4558. %% The \code{expose-allocation} pass annotates all of the local variables
  4559. %% in the \code{program} form with their type.
  4560. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4561. \code{expose-allocation} pass on our running example.
  4562. \begin{figure}[tbp]
  4563. \begin{lstlisting}
  4564. (program ()
  4565. (vector-ref
  4566. (vector-ref
  4567. (let ((vecinit48
  4568. (let ((vecinit44 42))
  4569. (let ((collectret46
  4570. (if (<
  4571. (+ (global-value free_ptr) 16)
  4572. (global-value fromspace_end))
  4573. (void)
  4574. (collect 16))))
  4575. (let ((alloc43 (allocate 1 (Vector Integer))))
  4576. (let ((initret45 (vector-set! alloc43 0 vecinit44)))
  4577. alloc43))))))
  4578. (let ((collectret50
  4579. (if (< (+ (global-value free_ptr) 16)
  4580. (global-value fromspace_end))
  4581. (void)
  4582. (collect 16))))
  4583. (let ((alloc47 (allocate 1 (Vector (Vector Integer)))))
  4584. (let ((initret49 (vector-set! alloc47 0 vecinit48)))
  4585. alloc47))))
  4586. 0)
  4587. 0))
  4588. \end{lstlisting}
  4589. \caption{Output of the \code{expose-allocation} pass, minus
  4590. all of the \code{has-type} forms.}
  4591. \label{fig:expose-alloc-output}
  4592. \end{figure}
  4593. %\clearpage
  4594. \section{Explicate Control and the $C_2$ language}
  4595. \label{sec:explicate-control-r3}
  4596. \begin{figure}[tp]
  4597. \fbox{
  4598. \begin{minipage}{0.96\textwidth}
  4599. \[
  4600. \begin{array}{lcl}
  4601. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4602. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4603. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4604. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4605. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4606. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4607. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4608. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4609. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4610. \mid (\key{collect} \,\itm{int}) \\
  4611. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4612. &\mid& \gray{(\key{goto}\,\itm{label})
  4613. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4614. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4615. \end{array}
  4616. \]
  4617. \end{minipage}
  4618. }
  4619. \caption{The $C_2$ language, extending $C_1$
  4620. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4621. \label{fig:c2-syntax}
  4622. \end{figure}
  4623. The output of \code{explicate-control} is a program in the
  4624. intermediate language $C_2$, whose syntax is defined in
  4625. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4626. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4627. \key{global-value} expressions and the \code{collect} statement. The
  4628. \code{explicate-control} pass can treat these new forms much like the
  4629. other forms.
  4630. \section{Uncover Locals}
  4631. \label{sec:uncover-locals-r3}
  4632. Recall that the \code{uncover-locals} function collects all of the
  4633. local variables so that it can store them in the $\itm{info}$ field of
  4634. the \code{program} form. Also recall that we need to know the types of
  4635. all the local variables for purposes of identifying the root set for
  4636. the garbage collector. Thus, we change \code{uncover-locals} to
  4637. collect not just the variables, but the variables and their types in
  4638. the form of an association list. Thanks to the \code{has-type} forms,
  4639. the types are readily available. Figure~\ref{fig:uncover-locals-r3}
  4640. lists the output of the \code{uncover-locals} pass on the running
  4641. example.
  4642. \begin{figure}[tbp]
  4643. \begin{lstlisting}
  4644. (program
  4645. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4646. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4647. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4648. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4649. (tmp52 . Integer) (tmp57 . (Vector Integer))
  4650. (vecinit44 . Integer) (tmp56 . Integer) (initret49 . Void)
  4651. (collectret50 . Void))))
  4652. ((block63 . (seq (collect 16) (goto block61)))
  4653. (block62 . (seq (assign collectret46 (void)) (goto block61)))
  4654. (block61 . (seq (assign alloc43 (allocate 1 (Vector Integer)))
  4655. (seq (assign initret45 (vector-set! alloc43 0 vecinit44))
  4656. (seq (assign vecinit48 alloc43)
  4657. (seq (assign tmp54 (global-value free_ptr))
  4658. (seq (assign tmp55 (+ tmp54 16))
  4659. (seq (assign tmp56 (global-value fromspace_end))
  4660. (if (< tmp55 tmp56) (goto block59) (goto block60)))))))))
  4661. (block60 . (seq (collect 16) (goto block58)))
  4662. (block59 . (seq (assign collectret50 (void)) (goto block58)))
  4663. (block58 . (seq (assign alloc47 (allocate 1 (Vector (Vector Integer))))
  4664. (seq (assign initret49 (vector-set! alloc47 0 vecinit48))
  4665. (seq (assign tmp57 (vector-ref alloc47 0))
  4666. (return (vector-ref tmp57 0))))))
  4667. (start . (seq (assign vecinit44 42)
  4668. (seq (assign tmp51 (global-value free_ptr))
  4669. (seq (assign tmp52 (+ tmp51 16))
  4670. (seq (assign tmp53 (global-value fromspace_end))
  4671. (if (< tmp52 tmp53) (goto block62) (goto block63)))))))))
  4672. \end{lstlisting}
  4673. \caption{Output of \code{uncover-locals} for the running example.}
  4674. \label{fig:uncover-locals-r3}
  4675. \end{figure}
  4676. \clearpage
  4677. \section{Select Instructions}
  4678. \label{sec:select-instructions-gc}
  4679. %% void (rep as zero)
  4680. %% allocate
  4681. %% collect (callq collect)
  4682. %% vector-ref
  4683. %% vector-set!
  4684. %% global-value (postpone)
  4685. In this pass we generate x86 code for most of the new operations that
  4686. were needed to compile tuples, including \code{allocate},
  4687. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4688. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4689. The \code{vector-ref} and \code{vector-set!} forms translate into
  4690. \code{movq} instructions with the appropriate \key{deref}. (The
  4691. plus one is to get past the tag at the beginning of the tuple
  4692. representation.)
  4693. \begin{lstlisting}
  4694. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4695. |$\Longrightarrow$|
  4696. (movq |$\itm{vec}'$| (reg r11))
  4697. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4698. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4699. |$\Longrightarrow$|
  4700. (movq |$\itm{vec}'$| (reg r11))
  4701. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4702. (movq (int 0) |$\itm{lhs}$|)
  4703. \end{lstlisting}
  4704. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4705. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4706. register \code{r11} ensures that offsets are only performed with
  4707. register operands. This requires removing \code{r11} from
  4708. consideration by the register allocating.
  4709. We compile the \code{allocate} form to operations on the
  4710. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4711. is the next free address in the FromSpace, so we move it into the
  4712. \itm{lhs} and then move it forward by enough space for the tuple being
  4713. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4714. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4715. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4716. how the tag is organized. We recommend using the Racket operations
  4717. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4718. The type annotation in the \code{vector} form is used to determine the
  4719. pointer mask region of the tag.
  4720. \begin{lstlisting}
  4721. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4722. |$\Longrightarrow$|
  4723. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4724. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4725. (movq |$\itm{lhs}'$| (reg r11))
  4726. (movq (int |$\itm{tag}$|) (deref r11 0))
  4727. \end{lstlisting}
  4728. The \code{collect} form is compiled to a call to the \code{collect}
  4729. function in the runtime. The arguments to \code{collect} are the top
  4730. of the root stack and the number of bytes that need to be allocated.
  4731. We shall use a dedicated register, \code{r15}, to store the pointer to
  4732. the top of the root stack. So \code{r15} is not available for use by
  4733. the register allocator.
  4734. \begin{lstlisting}
  4735. (collect |$\itm{bytes}$|)
  4736. |$\Longrightarrow$|
  4737. (movq (reg r15) (reg rdi))
  4738. (movq |\itm{bytes}| (reg rsi))
  4739. (callq collect)
  4740. \end{lstlisting}
  4741. \begin{figure}[tp]
  4742. \fbox{
  4743. \begin{minipage}{0.96\textwidth}
  4744. \[
  4745. \begin{array}{lcl}
  4746. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4747. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4748. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4749. \mid (\key{global-value}\; \itm{name}) \\
  4750. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4751. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4752. (\key{subq} \; \Arg\; \Arg) \mid
  4753. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4754. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4755. (\key{pushq}\;\Arg) \mid
  4756. (\key{popq}\;\Arg) \mid
  4757. (\key{retq})} \\
  4758. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4759. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4760. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4761. \mid (\key{jmp} \; \itm{label})
  4762. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  4763. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  4764. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4765. \end{array}
  4766. \]
  4767. \end{minipage}
  4768. }
  4769. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4770. \label{fig:x86-2}
  4771. \end{figure}
  4772. The syntax of the $x86_2$ language is defined in
  4773. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4774. of the form for global variables.
  4775. %
  4776. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4777. \code{select-instructions} pass on the running example.
  4778. \begin{figure}[tbp]
  4779. \centering
  4780. \begin{minipage}{0.75\textwidth}
  4781. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4782. (program
  4783. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4784. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4785. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4786. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4787. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  4788. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  4789. ((block63 . (block ()
  4790. (movq (reg r15) (reg rdi))
  4791. (movq (int 16) (reg rsi))
  4792. (callq collect)
  4793. (jmp block61)))
  4794. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  4795. (block61 . (block ()
  4796. (movq (global-value free_ptr) (var alloc43))
  4797. (addq (int 16) (global-value free_ptr))
  4798. (movq (var alloc43) (reg r11))
  4799. (movq (int 3) (deref r11 0))
  4800. (movq (var alloc43) (reg r11))
  4801. (movq (var vecinit44) (deref r11 8))
  4802. (movq (int 0) (var initret45))
  4803. (movq (var alloc43) (var vecinit48))
  4804. (movq (global-value free_ptr) (var tmp54))
  4805. (movq (var tmp54) (var tmp55))
  4806. (addq (int 16) (var tmp55))
  4807. (movq (global-value fromspace_end) (var tmp56))
  4808. (cmpq (var tmp56) (var tmp55))
  4809. (jmp-if l block59)
  4810. (jmp block60)))
  4811. (block60 . (block ()
  4812. (movq (reg r15) (reg rdi))
  4813. (movq (int 16) (reg rsi))
  4814. (callq collect)
  4815. (jmp block58))
  4816. (block59 . (block ()
  4817. (movq (int 0) (var collectret50))
  4818. (jmp block58)))
  4819. (block58 . (block ()
  4820. (movq (global-value free_ptr) (var alloc47))
  4821. (addq (int 16) (global-value free_ptr))
  4822. (movq (var alloc47) (reg r11))
  4823. (movq (int 131) (deref r11 0))
  4824. (movq (var alloc47) (reg r11))
  4825. (movq (var vecinit48) (deref r11 8))
  4826. (movq (int 0) (var initret49))
  4827. (movq (var alloc47) (reg r11))
  4828. (movq (deref r11 8) (var tmp57))
  4829. (movq (var tmp57) (reg r11))
  4830. (movq (deref r11 8) (reg rax))
  4831. (jmp conclusion)))
  4832. (start . (block ()
  4833. (movq (int 42) (var vecinit44))
  4834. (movq (global-value free_ptr) (var tmp51))
  4835. (movq (var tmp51) (var tmp52))
  4836. (addq (int 16) (var tmp52))
  4837. (movq (global-value fromspace_end) (var tmp53))
  4838. (cmpq (var tmp53) (var tmp52))
  4839. (jmp-if l block62)
  4840. (jmp block63))))))
  4841. \end{lstlisting}
  4842. \end{minipage}
  4843. \caption{Output of the \code{select-instructions} pass.}
  4844. \label{fig:select-instr-output-gc}
  4845. \end{figure}
  4846. \clearpage
  4847. \section{Register Allocation}
  4848. \label{sec:reg-alloc-gc}
  4849. As discussed earlier in this chapter, the garbage collector needs to
  4850. access all the pointers in the root set, that is, all variables that
  4851. are vectors. It will be the responsibility of the register allocator
  4852. to make sure that:
  4853. \begin{enumerate}
  4854. \item the root stack is used for spilling vector-typed variables, and
  4855. \item if a vector-typed variable is live during a call to the
  4856. collector, it must be spilled to ensure it is visible to the
  4857. collector.
  4858. \end{enumerate}
  4859. The later responsibility can be handled during construction of the
  4860. inference graph, by adding interference edges between the call-live
  4861. vector-typed variables and all the callee-saved registers. (They
  4862. already interfere with the caller-saved registers.) The type
  4863. information for variables is in the \code{program} form, so we
  4864. recommend adding another parameter to the \code{build-interference}
  4865. function to communicate this association list.
  4866. The spilling of vector-typed variables to the root stack can be
  4867. handled after graph coloring, when choosing how to assign the colors
  4868. (integers) to registers and stack locations. The \code{program} output
  4869. of this pass changes to also record the number of spills to the root
  4870. stack.
  4871. % build-interference
  4872. %
  4873. % callq
  4874. % extra parameter for var->type assoc. list
  4875. % update 'program' and 'if'
  4876. % allocate-registers
  4877. % allocate spilled vectors to the rootstack
  4878. % don't change color-graph
  4879. \section{Print x86}
  4880. \label{sec:print-x86-gc}
  4881. \margincomment{\scriptsize We need to show the translation to x86 and what
  4882. to do about global-value. \\ --Jeremy}
  4883. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4884. \code{print-x86} pass on the running example. In the prelude and
  4885. conclusion of the \code{main} function, we treat the root stack very
  4886. much like the regular stack in that we move the root stack pointer
  4887. (\code{r15}) to make room for all of the spills to the root stack,
  4888. except that the root stack grows up instead of down. For the running
  4889. example, there was just one spill so we increment \code{r15} by 8
  4890. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  4891. One issue that deserves special care is that there may be a call to
  4892. \code{collect} prior to the initializing assignments for all the
  4893. variables in the root stack. We do not want the garbage collector to
  4894. accidentally think that some uninitialized variable is a pointer that
  4895. needs to be followed. Thus, we zero-out all locations on the root
  4896. stack in the prelude of \code{main}. In
  4897. Figure~\ref{fig:print-x86-output-gc}, the instruction
  4898. %
  4899. \lstinline{movq $0, (%r15)}
  4900. %
  4901. accomplishes this task. The garbage collector tests each root to see
  4902. if it is null prior to dereferencing it.
  4903. \begin{figure}[htbp]
  4904. \begin{minipage}[t]{0.5\textwidth}
  4905. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4906. _block58:
  4907. movq _free_ptr(%rip), %rcx
  4908. addq $16, _free_ptr(%rip)
  4909. movq %rcx, %r11
  4910. movq $131, 0(%r11)
  4911. movq %rcx, %r11
  4912. movq -8(%r15), %rax
  4913. movq %rax, 8(%r11)
  4914. movq $0, %rdx
  4915. movq %rcx, %r11
  4916. movq 8(%r11), %rcx
  4917. movq %rcx, %r11
  4918. movq 8(%r11), %rax
  4919. jmp _conclusion
  4920. _block59:
  4921. movq $0, %rcx
  4922. jmp _block58
  4923. _block62:
  4924. movq $0, %rcx
  4925. jmp _block61
  4926. _block60:
  4927. movq %r15, %rdi
  4928. movq $16, %rsi
  4929. callq _collect
  4930. jmp _block58
  4931. _block63:
  4932. movq %r15, %rdi
  4933. movq $16, %rsi
  4934. callq _collect
  4935. jmp _block61
  4936. _start:
  4937. movq $42, %rbx
  4938. movq _free_ptr(%rip), %rdx
  4939. addq $16, %rdx
  4940. movq _fromspace_end(%rip), %rcx
  4941. cmpq %rcx, %rdx
  4942. jl _block62
  4943. jmp _block63
  4944. \end{lstlisting}
  4945. \end{minipage}
  4946. \begin{minipage}[t]{0.45\textwidth}
  4947. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4948. _block61:
  4949. movq _free_ptr(%rip), %rcx
  4950. addq $16, _free_ptr(%rip)
  4951. movq %rcx, %r11
  4952. movq $3, 0(%r11)
  4953. movq %rcx, %r11
  4954. movq %rbx, 8(%r11)
  4955. movq $0, %rdx
  4956. movq %rcx, -8(%r15)
  4957. movq _free_ptr(%rip), %rcx
  4958. addq $16, %rcx
  4959. movq _fromspace_end(%rip), %rdx
  4960. cmpq %rdx, %rcx
  4961. jl _block59
  4962. jmp _block60
  4963. .globl _main
  4964. _main:
  4965. pushq %rbp
  4966. movq %rsp, %rbp
  4967. pushq %r12
  4968. pushq %rbx
  4969. pushq %r13
  4970. pushq %r14
  4971. subq $0, %rsp
  4972. movq $16384, %rdi
  4973. movq $16, %rsi
  4974. callq _initialize
  4975. movq _rootstack_begin(%rip), %r15
  4976. movq $0, (%r15)
  4977. addq $8, %r15
  4978. jmp _start
  4979. _conclusion:
  4980. subq $8, %r15
  4981. addq $0, %rsp
  4982. popq %r14
  4983. popq %r13
  4984. popq %rbx
  4985. popq %r12
  4986. popq %rbp
  4987. retq
  4988. \end{lstlisting}
  4989. \end{minipage}
  4990. \caption{Output of the \code{print-x86} pass.}
  4991. \label{fig:print-x86-output-gc}
  4992. \end{figure}
  4993. \margincomment{\scriptsize Suggest an implementation strategy
  4994. in which the students first do the code gen and test that
  4995. without GC (just use a big heap), then after that is debugged,
  4996. implement the GC. \\ --Jeremy}
  4997. \begin{figure}[p]
  4998. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4999. \node (R3) at (0,2) {\large $R_3$};
  5000. \node (R3-2) at (3,2) {\large $R_3$};
  5001. \node (R3-3) at (6,2) {\large $R_3$};
  5002. \node (R3-4) at (9,2) {\large $R_3$};
  5003. \node (R3-5) at (12,2) {\large $R_3$};
  5004. \node (C2-4) at (3,0) {\large $C_2$};
  5005. \node (C2-3) at (6,0) {\large $C_2$};
  5006. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5007. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5008. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5009. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5010. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5011. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5012. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5013. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5014. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5015. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5016. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5017. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5018. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5019. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5020. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5021. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5022. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5023. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5024. \end{tikzpicture}
  5025. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5026. \label{fig:R3-passes}
  5027. \end{figure}
  5028. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5029. for the compilation of $R_3$.
  5030. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5031. \chapter{Functions}
  5032. \label{ch:functions}
  5033. This chapter studies the compilation of functions at the level of
  5034. abstraction of the C language. This corresponds to a subset of Typed
  5035. Racket in which only top-level function definitions are allowed. These
  5036. kind of functions are an important stepping stone to implementing
  5037. lexically-scoped functions in the form of \key{lambda} abstractions,
  5038. which is the topic of Chapter~\ref{ch:lambdas}.
  5039. \section{The $R_4$ Language}
  5040. The syntax for function definitions and function application is shown
  5041. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5042. Programs in $R_4$ start with zero or more function definitions. The
  5043. function names from these definitions are in-scope for the entire
  5044. program, including all other function definitions (so the ordering of
  5045. function definitions does not matter). The syntax for function
  5046. application does not include an explicit keyword, which is error prone
  5047. when using \code{match}. To alleviate this problem, we change the
  5048. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5049. during type checking.
  5050. Functions are first-class in the sense that a function pointer is data
  5051. and can be stored in memory or passed as a parameter to another
  5052. function. Thus, we introduce a function type, written
  5053. \begin{lstlisting}
  5054. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5055. \end{lstlisting}
  5056. for a function whose $n$ parameters have the types $\Type_1$ through
  5057. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5058. these functions (with respect to Racket functions) is that they are
  5059. not lexically scoped. That is, the only external entities that can be
  5060. referenced from inside a function body are other globally-defined
  5061. functions. The syntax of $R_4$ prevents functions from being nested
  5062. inside each other.
  5063. \begin{figure}[tp]
  5064. \centering
  5065. \fbox{
  5066. \begin{minipage}{0.96\textwidth}
  5067. \[
  5068. \begin{array}{lcl}
  5069. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5070. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5071. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5072. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5073. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5074. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5075. \mid (\key{and}\;\Exp\;\Exp)
  5076. \mid (\key{or}\;\Exp\;\Exp)
  5077. \mid (\key{not}\;\Exp)} \\
  5078. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5079. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5080. (\key{vector-ref}\;\Exp\;\Int)} \\
  5081. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5082. &\mid& (\Exp \; \Exp^{*}) \\
  5083. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5084. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5085. \end{array}
  5086. \]
  5087. \end{minipage}
  5088. }
  5089. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5090. with functions.}
  5091. \label{fig:r4-syntax}
  5092. \end{figure}
  5093. The program in Figure~\ref{fig:r4-function-example} is a
  5094. representative example of defining and using functions in $R_4$. We
  5095. define a function \code{map-vec} that applies some other function
  5096. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5097. vector containing the results. We also define a function \code{add1}
  5098. that does what its name suggests. The program then applies
  5099. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5100. \code{(vector 1 42)}, from which we return the \code{42}.
  5101. \begin{figure}[tbp]
  5102. \begin{lstlisting}
  5103. (program ()
  5104. (define (map-vec [f : (Integer -> Integer)]
  5105. [v : (Vector Integer Integer)])
  5106. : (Vector Integer Integer)
  5107. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5108. (define (add1 [x : Integer]) : Integer
  5109. (+ x 1))
  5110. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5111. )
  5112. \end{lstlisting}
  5113. \caption{Example of using functions in $R_4$.}
  5114. \label{fig:r4-function-example}
  5115. \end{figure}
  5116. The definitional interpreter for $R_4$ is in
  5117. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5118. responsible for setting up the mutual recursion between the top-level
  5119. function definitions. We use the classic back-patching approach that
  5120. uses mutable variables and makes two passes over the function
  5121. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5122. top-level environment using a mutable cons cell for each function
  5123. definition. Note that the \code{lambda} value for each function is
  5124. incomplete; it does not yet include the environment. Once the
  5125. top-level environment is constructed, we then iterate over it and
  5126. update the \code{lambda} value's to use the top-level environment.
  5127. \begin{figure}[tp]
  5128. \begin{lstlisting}
  5129. (define (interp-exp env)
  5130. (lambda (e)
  5131. (define recur (interp-exp env))
  5132. (match e
  5133. ...
  5134. [`(,fun ,args ...)
  5135. (define arg-vals (for/list ([e args]) (recur e)))
  5136. (define fun-val (recur fun))
  5137. (match fun-val
  5138. [`(lambda (,xs ...) ,body ,fun-env)
  5139. (define new-env (append (map cons xs arg-vals) fun-env))
  5140. ((interp-exp new-env) body)]
  5141. [else (error "interp-exp, expected function, not" fun-val)])]
  5142. [else (error 'interp-exp "unrecognized expression")]
  5143. )))
  5144. (define (interp-def d)
  5145. (match d
  5146. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5147. (mcons f `(lambda ,xs ,body ()))]
  5148. ))
  5149. (define (interp-R4 p)
  5150. (match p
  5151. [`(program ,ds ... ,body)
  5152. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5153. (for/list ([b top-level])
  5154. (set-mcdr! b (match (mcdr b)
  5155. [`(lambda ,xs ,body ())
  5156. `(lambda ,xs ,body ,top-level)])))
  5157. ((interp-exp top-level) body))]
  5158. ))
  5159. \end{lstlisting}
  5160. \caption{Interpreter for the $R_4$ language.}
  5161. \label{fig:interp-R4}
  5162. \end{figure}
  5163. \section{Functions in x86}
  5164. \label{sec:fun-x86}
  5165. \margincomment{\tiny Make sure callee-saved registers are discussed
  5166. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5167. \margincomment{\tiny Talk about the return address on the
  5168. stack and what callq and retq does.\\ --Jeremy }
  5169. The x86 architecture provides a few features to support the
  5170. implementation of functions. We have already seen that x86 provides
  5171. labels so that one can refer to the location of an instruction, as is
  5172. needed for jump instructions. Labels can also be used to mark the
  5173. beginning of the instructions for a function. Going further, we can
  5174. obtain the address of a label by using the \key{leaq} instruction and
  5175. \key{rip}-relative addressing. For example, the following puts the
  5176. address of the \code{add1} label into the \code{rbx} register.
  5177. \begin{lstlisting}
  5178. leaq add1(%rip), %rbx
  5179. \end{lstlisting}
  5180. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5181. instruction for jumping to a function whose location is given by a
  5182. label. Here we instead will be jumping to a function whose location is
  5183. given by an address, that is, we need to make an \emph{indirect
  5184. function call}. The x86 syntax is to give the register name prefixed
  5185. with an asterisk.
  5186. \begin{lstlisting}
  5187. callq *%rbx
  5188. \end{lstlisting}
  5189. \subsection{Calling Conventions}
  5190. The \code{callq} instruction provides partial support for implementing
  5191. functions, but it does not handle (1) parameter passing, (2) saving
  5192. and restoring frames on the procedure call stack, or (3) determining
  5193. how registers are shared by different functions. These issues require
  5194. coordination between the caller and the callee, which is often
  5195. assembly code written by different programmers or generated by
  5196. different compilers. As a result, people have developed
  5197. \emph{conventions} that govern how functions calls are performed.
  5198. Here we shall use the same conventions used by the \code{gcc}
  5199. compiler~\citep{Matz:2013aa}.
  5200. Regarding (1) parameter passing, the convention is to use the
  5201. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5202. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5203. than six arguments, then the convention is to use space on the frame
  5204. of the caller for the rest of the arguments. However, to ease the
  5205. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5206. we shall arrange to never have more than six arguments.
  5207. %
  5208. The register \code{rax} is for the return value of the function.
  5209. Regarding (2) frames and the procedure call stack, the convention is
  5210. that the stack grows down, with each function call using a chunk of
  5211. space called a frame. The caller sets the stack pointer, register
  5212. \code{rsp}, to the last data item in its frame. The callee must not
  5213. change anything in the caller's frame, that is, anything that is at or
  5214. above the stack pointer. The callee is free to use locations that are
  5215. below the stack pointer.
  5216. Regarding (3) the sharing of registers between different functions,
  5217. recall from Section~\ref{sec:calling-conventions} that the registers
  5218. are divided into two groups, the caller-saved registers and the
  5219. callee-saved registers. The caller should assume that all the
  5220. caller-saved registers get overwritten with arbitrary values by the
  5221. callee. Thus, the caller should either 1) not put values that are live
  5222. across a call in caller-saved registers, or 2) save and restore values
  5223. that are live across calls. We shall recommend option 1). On the flip
  5224. side, if the callee wants to use a callee-saved register, the callee
  5225. must save the contents of those registers on their stack frame and
  5226. then put them back prior to returning to the caller. The base
  5227. pointer, register \code{rbp}, is used as a point-of-reference within a
  5228. frame, so that each local variable can be accessed at a fixed offset
  5229. from the base pointer.
  5230. %
  5231. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5232. frames.
  5233. %% If we were to use stack arguments, they would be between the
  5234. %% caller locals and the callee return address.
  5235. \begin{figure}[tbp]
  5236. \centering
  5237. \begin{tabular}{r|r|l|l} \hline
  5238. Caller View & Callee View & Contents & Frame \\ \hline
  5239. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5240. 0(\key{\%rbp}) & & old \key{rbp} \\
  5241. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5242. \ldots & & \ldots \\
  5243. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5244. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5245. \ldots & & \ldots \\
  5246. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5247. %% & & \\
  5248. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5249. %% & \ldots & \ldots \\
  5250. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5251. \hline
  5252. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5253. & 0(\key{\%rbp}) & old \key{rbp} \\
  5254. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5255. & \ldots & \ldots \\
  5256. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5257. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5258. & \ldots & \ldots \\
  5259. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5260. \end{tabular}
  5261. \caption{Memory layout of caller and callee frames.}
  5262. \label{fig:call-frames}
  5263. \end{figure}
  5264. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5265. %% local variables and for storing the values of callee-saved registers
  5266. %% (we shall refer to all of these collectively as ``locals''), and that
  5267. %% at the beginning of a function we move the stack pointer \code{rsp}
  5268. %% down to make room for them.
  5269. %% We recommend storing the local variables
  5270. %% first and then the callee-saved registers, so that the local variables
  5271. %% can be accessed using \code{rbp} the same as before the addition of
  5272. %% functions.
  5273. %% To make additional room for passing arguments, we shall
  5274. %% move the stack pointer even further down. We count how many stack
  5275. %% arguments are needed for each function call that occurs inside the
  5276. %% body of the function and find their maximum. Adding this number to the
  5277. %% number of locals gives us how much the \code{rsp} should be moved at
  5278. %% the beginning of the function. In preparation for a function call, we
  5279. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5280. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5281. %% so on.
  5282. %% Upon calling the function, the stack arguments are retrieved by the
  5283. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5284. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5285. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5286. %% the layout of the caller and callee frames. Notice how important it is
  5287. %% that we correctly compute the maximum number of arguments needed for
  5288. %% function calls; if that number is too small then the arguments and
  5289. %% local variables will smash into each other!
  5290. \subsection{Efficient Tail Calls}
  5291. \label{sec:tail-call}
  5292. In general, the amount of stack space used by a program is determined
  5293. by the longest chain of nested function calls. That is, if function
  5294. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5295. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5296. $n$ can grow quite large in the case of recursive or mutually
  5297. recursive functions. However, in some cases we can arrange to use only
  5298. constant space, i.e. $O(1)$, instead of $O(n)$.
  5299. If a function call is the last action in a function body, then that
  5300. call is said to be a \emph{tail call}. In such situations, the frame
  5301. of the caller is no longer needed, so we can pop the caller's frame
  5302. before making the tail call. With this approach, a recursive function
  5303. that only makes tail calls will only use $O(1)$ stack space.
  5304. Functional languages like Racket typically rely heavily on recursive
  5305. functions, so they typically guarantee that all tail calls will be
  5306. optimized in this way.
  5307. However, some care is needed with regards to argument passing in tail
  5308. calls. As mentioned above, for arguments beyond the sixth, the
  5309. convention is to use space in the caller's frame for passing
  5310. arguments. But here we've popped the caller's frame and can no longer
  5311. use it. Another alternative is to use space in the callee's frame for
  5312. passing arguments. However, this option is also problematic because
  5313. the caller and callee's frame overlap in memory. As we begin to copy
  5314. the arguments from their sources in the caller's frame, the target
  5315. locations in the callee's frame might overlap with the sources for
  5316. later arguments! We solve this problem by not using the stack for
  5317. parameter passing but instead use the heap, as we describe in the
  5318. Section~\ref{sec:limit-functions-r4}.
  5319. As mentioned above, for a tail call we pop the caller's frame prior to
  5320. making the tail call. The instructions for popping a frame are the
  5321. instructions that we usually place in the conclusion of a
  5322. function. Thus, we also need to place such code immediately before
  5323. each tail call. These instructions include restoring the callee-saved
  5324. registers, so it is good that the argument passing registers are all
  5325. caller-saved registers.
  5326. One last note regarding which instruction to use to make the tail
  5327. call. When the callee is finished, it should not return to the current
  5328. function, but it should return to the function that called the current
  5329. one. Thus, the return address that is already on the stack is the
  5330. right one, and we should not use \key{callq} to make the tail call, as
  5331. that would unnecessarily overwrite the return address. Instead we can
  5332. simply use the \key{jmp} instruction. Like the indirect function call,
  5333. we write an indirect jump with a register prefixed with an asterisk.
  5334. We recommend using \code{rax} to hold the jump target because the
  5335. preceding ``conclusion'' overwrites just about everything else.
  5336. \begin{lstlisting}
  5337. jmp *%rax
  5338. \end{lstlisting}
  5339. %% Now that we have a good understanding of functions as they appear in
  5340. %% $R_4$ and the support for functions in x86, we need to plan the
  5341. %% changes to our compiler, that is, do we need any new passes and/or do
  5342. %% we need to change any existing passes? Also, do we need to add new
  5343. %% kinds of AST nodes to any of the intermediate languages?
  5344. \section{Shrink $R_4$}
  5345. \label{sec:shrink-r4}
  5346. The \code{shrink} pass performs a couple minor modifications to the
  5347. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5348. field to each function definition:
  5349. \begin{lstlisting}
  5350. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5351. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5352. \end{lstlisting}
  5353. and introduces an explicit \code{main} function.\\
  5354. \begin{tabular}{lll}
  5355. \begin{minipage}{0.45\textwidth}
  5356. \begin{lstlisting}
  5357. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5358. \end{lstlisting}
  5359. \end{minipage}
  5360. &
  5361. $\Rightarrow$
  5362. &
  5363. \begin{minipage}{0.45\textwidth}
  5364. \begin{lstlisting}
  5365. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5366. \end{lstlisting}
  5367. \end{minipage}
  5368. \end{tabular} \\
  5369. where $\itm{mainDef}$ is
  5370. \begin{lstlisting}
  5371. (define (main) : Integer () |$\Exp'$|)
  5372. \end{lstlisting}
  5373. \section{Reveal Functions}
  5374. \label{sec:reveal-functions-r4}
  5375. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5376. compilation because it conflates the use of function names and local
  5377. variables. This is a problem because we need to compile the use of a
  5378. function name differently than the use of a local variable; we need to
  5379. use \code{leaq} to convert the function name (a label in x86) to an
  5380. address in a register. Thus, it is a good idea to create a new pass
  5381. that changes function references from just a symbol $f$ to
  5382. \code{(fun-ref $f$)}. A good name for this pass is
  5383. \code{reveal-functions} and the output language, $F_1$, is defined in
  5384. Figure~\ref{fig:f1-syntax}.
  5385. \begin{figure}[tp]
  5386. \centering
  5387. \fbox{
  5388. \begin{minipage}{0.96\textwidth}
  5389. \[
  5390. \begin{array}{lcl}
  5391. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5392. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5393. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5394. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5395. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5396. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5397. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5398. (\key{vector-ref}\;\Exp\;\Int)} \\
  5399. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5400. (\key{app}\; \Exp \; \Exp^{*})} \\
  5401. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5402. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5403. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5404. \end{array}
  5405. \]
  5406. \end{minipage}
  5407. }
  5408. \caption{The $F_1$ language, an extension of $R_4$
  5409. (Figure~\ref{fig:r4-syntax}).}
  5410. \label{fig:f1-syntax}
  5411. \end{figure}
  5412. %% Distinguishing between calls in tail position and non-tail position
  5413. %% requires the pass to have some notion of context. We recommend using
  5414. %% two mutually recursive functions, one for processing expressions in
  5415. %% tail position and another for the rest.
  5416. Placing this pass after \code{uniquify} is a good idea, because it
  5417. will make sure that there are no local variables and functions that
  5418. share the same name. On the other hand, \code{reveal-functions} needs
  5419. to come before the \code{explicate-control} pass because that pass
  5420. will help us compile \code{fun-ref} into assignment statements.
  5421. \section{Limit Functions}
  5422. \label{sec:limit-functions-r4}
  5423. This pass transforms functions so that they have at most six
  5424. parameters and transforms all function calls so that they pass at most
  5425. six arguments. A simple strategy for imposing an argument limit of
  5426. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5427. into a vector, making that subsequent vector the $n$th argument.
  5428. \begin{tabular}{lll}
  5429. \begin{minipage}{0.2\textwidth}
  5430. \begin{lstlisting}
  5431. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5432. \end{lstlisting}
  5433. \end{minipage}
  5434. &
  5435. $\Rightarrow$
  5436. &
  5437. \begin{minipage}{0.4\textwidth}
  5438. \begin{lstlisting}
  5439. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5440. \end{lstlisting}
  5441. \end{minipage}
  5442. \end{tabular}
  5443. In the body of the function, all occurrences of the $i$th argument in
  5444. which $i>5$ must be replaced with a \code{vector-ref}.
  5445. \section{Remove Complex Operators and Operands}
  5446. \label{sec:rco-r4}
  5447. The primary decisions to make for this pass is whether to classify
  5448. \code{fun-ref} and \code{app} as either simple or complex
  5449. expressions. Recall that a simple expression will eventually end up as
  5450. just an ``immediate'' argument of an x86 instruction. Function
  5451. application will be translated to a sequence of instructions, so
  5452. \code{app} must be classified as complex expression. Regarding
  5453. \code{fun-ref}, as discussed above, the function label needs to
  5454. be converted to an address using the \code{leaq} instruction. Thus,
  5455. even though \code{fun-ref} seems rather simple, it needs to be
  5456. classified as a complex expression so that we generate an assignment
  5457. statement with a left-hand side that can serve as the target of the
  5458. \code{leaq}.
  5459. \section{Explicate Control and the $C_3$ language}
  5460. \label{sec:explicate-control-r4}
  5461. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5462. \key{explicate-control}. The three mutually recursive functions for
  5463. this pass, for assignment, tail, and predicate contexts, must all be
  5464. updated with cases for \code{fun-ref} and \code{app}. In
  5465. assignment and predicate contexts, \code{app} becomes \code{call},
  5466. whereas in tail position \code{app} becomes \code{tailcall}. We
  5467. recommend defining a new function for processing function definitions.
  5468. This code is similar to the case for \code{program} in $R_3$. The
  5469. top-level \code{explicate-control} function that handles the
  5470. \code{program} form of $R_4$ can then apply this new function to all
  5471. the function definitions.
  5472. \begin{figure}[tp]
  5473. \fbox{
  5474. \begin{minipage}{0.96\textwidth}
  5475. \[
  5476. \begin{array}{lcl}
  5477. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5478. \\
  5479. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5480. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5481. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5482. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5483. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5484. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5485. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5486. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5487. \mid (\key{collect} \,\itm{int}) }\\
  5488. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5489. &\mid& \gray{(\key{goto}\,\itm{label})
  5490. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5491. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5492. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5493. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5494. \end{array}
  5495. \]
  5496. \end{minipage}
  5497. }
  5498. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5499. \label{fig:c3-syntax}
  5500. \end{figure}
  5501. \section{Uncover Locals}
  5502. \label{sec:uncover-locals-r4}
  5503. The function for processing $\Tail$ should be updated with a case for
  5504. \code{tailcall}. We also recommend creating a new function for
  5505. processing function definitions. Each function definition in $C_3$ has
  5506. its own set of local variables, so the code for function definitions
  5507. should be similar to the case for the \code{program} form in $C_2$.
  5508. \section{Select Instructions}
  5509. \label{sec:select-r4}
  5510. The output of select instructions is a program in the x86$_3$
  5511. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5512. \begin{figure}[tp]
  5513. \fbox{
  5514. \begin{minipage}{0.96\textwidth}
  5515. \[
  5516. \begin{array}{lcl}
  5517. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  5518. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  5519. &\mid& \gray{ (\key{byte-reg}\; \itm{register})
  5520. \mid (\key{global-value}\; \itm{name}) } \\
  5521. &\mid& (\key{fun-ref}\; \itm{label})\\
  5522. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5523. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5524. (\key{subq} \; \Arg\; \Arg) \mid
  5525. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5526. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5527. (\key{pushq}\;\Arg) \mid
  5528. (\key{popq}\;\Arg) \mid
  5529. (\key{retq}) } \\
  5530. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5531. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5532. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5533. \mid (\key{jmp} \; \itm{label})
  5534. \mid (\key{j}\itm{cc} \; \itm{label})
  5535. \mid (\key{label} \; \itm{label}) } \\
  5536. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5537. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5538. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5539. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5540. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5541. \end{array}
  5542. \]
  5543. \end{minipage}
  5544. }
  5545. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5546. \label{fig:x86-3}
  5547. \end{figure}
  5548. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5549. as follows: \\
  5550. \begin{tabular}{lll}
  5551. \begin{minipage}{0.45\textwidth}
  5552. \begin{lstlisting}
  5553. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5554. \end{lstlisting}
  5555. \end{minipage}
  5556. &
  5557. $\Rightarrow$
  5558. &
  5559. \begin{minipage}{0.4\textwidth}
  5560. \begin{lstlisting}
  5561. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5562. \end{lstlisting}
  5563. \end{minipage}
  5564. \end{tabular} \\
  5565. Regarding function definitions, we need to remove their parameters and
  5566. instead perform parameter passing in terms of the conventions
  5567. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5568. in the argument passing registers, and inside the function we should
  5569. generate a \code{movq} instruction for each parameter, to move the
  5570. argument value from the appropriate register to a new local variable
  5571. with the same name as the old parameter.
  5572. Next, consider the compilation of function calls, which have the
  5573. following form upon input to \code{select-instructions}.
  5574. \begin{lstlisting}
  5575. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5576. \end{lstlisting}
  5577. In the mirror image of handling the parameters of function
  5578. definitions, the arguments \itm{args} need to be moved to the argument
  5579. passing registers.
  5580. %
  5581. Once the instructions for parameter passing have been generated, the
  5582. function call itself can be performed with an indirect function call,
  5583. for which I recommend creating the new instruction
  5584. \code{indirect-callq}. Of course, the return value from the function
  5585. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5586. \begin{lstlisting}
  5587. (indirect-callq |\itm{fun}|)
  5588. (movq (reg rax) |\itm{lhs}|)
  5589. \end{lstlisting}
  5590. Regarding tail calls, the parameter passing is the same as non-tail
  5591. calls: generate instructions to move the arguments into to the
  5592. argument passing registers. After that we need to pop the frame from
  5593. the procedure call stack. However, we do not yet know how big the
  5594. frame is; that gets determined during register allocation. So instead
  5595. of generating those instructions here, we invent a new instruction
  5596. that means ``pop the frame and then do an indirect jump'', which we
  5597. name \code{tail-jmp}.
  5598. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5599. using the label \code{start} for the initial block of a program, and
  5600. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5601. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5602. can be compiled to an assignment to \code{rax} followed by a jump to
  5603. \code{conclusion}. With the addition of function definitions, we will
  5604. have a starting block and conclusion for each function, but their
  5605. labels need to be unique. We recommend prepending the function's name
  5606. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5607. labels. (Alternatively, one could \code{gensym} labels for the start
  5608. and conclusion and store them in the $\itm{info}$ field of the
  5609. function definition.)
  5610. \section{Uncover Live}
  5611. %% The rest of the passes need only minor modifications to handle the new
  5612. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5613. %% \code{leaq}.
  5614. Inside \code{uncover-live}, when computing the $W$ set (written
  5615. variables) for an \code{indirect-callq} instruction, we recommend
  5616. including all the caller-saved registers, which will have the affect
  5617. of making sure that no caller-saved register actually needs to be
  5618. saved.
  5619. \section{Build Interference Graph}
  5620. With the addition of function definitions, we compute an interference
  5621. graph for each function (not just one for the whole program).
  5622. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5623. spill vector-typed variables that are live during a call to the
  5624. \code{collect}. With the addition of functions to our language, we
  5625. need to revisit this issue. Many functions will perform allocation and
  5626. therefore have calls to the collector inside of them. Thus, we should
  5627. not only spill a vector-typed variable when it is live during a call
  5628. to \code{collect}, but we should spill the variable if it is live
  5629. during any function call. Thus, in the \code{build-interference} pass,
  5630. we recommend adding interference edges between call-live vector-typed
  5631. variables and the callee-saved registers (in addition to the usual
  5632. addition of edges between call-live variables and the caller-saved
  5633. registers).
  5634. \section{Patch Instructions}
  5635. In \code{patch-instructions}, you should deal with the x86
  5636. idiosyncrasy that the destination argument of \code{leaq} must be a
  5637. register. Additionally, you should ensure that the argument of
  5638. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5639. code generation more convenient, because we will be trampling many
  5640. registers before the tail call (as explained below).
  5641. \section{Print x86}
  5642. For the \code{print-x86} pass, we recommend the following translations:
  5643. \begin{lstlisting}
  5644. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5645. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5646. \end{lstlisting}
  5647. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5648. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5649. is what we will want to do, but before the jump we need to pop the
  5650. current frame. So we need to restore the state of the registers to the
  5651. point they were at when the current function was called. This
  5652. sequence of instructions is the same as the code for the conclusion of
  5653. a function.
  5654. Note that your \code{print-x86} pass needs to add the code for saving
  5655. and restoring callee-saved registers, if you have not already
  5656. implemented that. This is necessary when generating code for function
  5657. definitions.
  5658. \section{An Example Translation}
  5659. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5660. function in $R_4$ to x86. The figure also includes the results of the
  5661. \code{explicate-control} and \code{select-instructions} passes. We
  5662. have omitted the \code{has-type} AST nodes for readability. Can you
  5663. see any ways to improve the translation?
  5664. \begin{figure}[tbp]
  5665. \begin{tabular}{ll}
  5666. \begin{minipage}{0.45\textwidth}
  5667. % s3_2.rkt
  5668. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5669. (program
  5670. (define (add [x : Integer]
  5671. [y : Integer])
  5672. : Integer (+ x y))
  5673. (add 40 2))
  5674. \end{lstlisting}
  5675. $\Downarrow$
  5676. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5677. (program ()
  5678. (define (add86 [x87 : Integer]
  5679. [y88 : Integer]) : Integer ()
  5680. ((add86start . (return (+ x87 y88)))))
  5681. (define (main) : Integer ()
  5682. ((mainstart .
  5683. (seq (assign tmp89 (fun-ref add86))
  5684. (tailcall tmp89 40 2))))))
  5685. \end{lstlisting}
  5686. \end{minipage}
  5687. &
  5688. $\Rightarrow$
  5689. \begin{minipage}{0.5\textwidth}
  5690. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5691. (program ()
  5692. (define (add86)
  5693. ((locals (x87 . Integer) (y88 . Integer))
  5694. (num-params . 2))
  5695. ((add86start .
  5696. (block ()
  5697. (movq (reg rcx) (var x87))
  5698. (movq (reg rdx) (var y88))
  5699. (movq (var x87) (reg rax))
  5700. (addq (var y88) (reg rax))
  5701. (jmp add86conclusion)))))
  5702. (define (main)
  5703. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5704. (num-params . 0))
  5705. ((mainstart .
  5706. (block ()
  5707. (leaq (fun-ref add86) (var tmp89))
  5708. (movq (int 40) (reg rcx))
  5709. (movq (int 2) (reg rdx))
  5710. (tail-jmp (var tmp89))))))
  5711. \end{lstlisting}
  5712. $\Downarrow$
  5713. \end{minipage}
  5714. \end{tabular}
  5715. \begin{tabular}{lll}
  5716. \begin{minipage}{0.3\textwidth}
  5717. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5718. _add90start:
  5719. movq %rcx, %rsi
  5720. movq %rdx, %rcx
  5721. movq %rsi, %rax
  5722. addq %rcx, %rax
  5723. jmp _add90conclusion
  5724. .globl _add90
  5725. .align 16
  5726. _add90:
  5727. pushq %rbp
  5728. movq %rsp, %rbp
  5729. pushq %r12
  5730. pushq %rbx
  5731. pushq %r13
  5732. pushq %r14
  5733. subq $0, %rsp
  5734. jmp _add90start
  5735. _add90conclusion:
  5736. addq $0, %rsp
  5737. popq %r14
  5738. popq %r13
  5739. popq %rbx
  5740. popq %r12
  5741. subq $0, %r15
  5742. popq %rbp
  5743. retq
  5744. \end{lstlisting}
  5745. \end{minipage}
  5746. &
  5747. \begin{minipage}{0.3\textwidth}
  5748. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5749. _mainstart:
  5750. leaq _add90(%rip), %rsi
  5751. movq $40, %rcx
  5752. movq $2, %rdx
  5753. movq %rsi, %rax
  5754. addq $0, %rsp
  5755. popq %r14
  5756. popq %r13
  5757. popq %rbx
  5758. popq %r12
  5759. subq $0, %r15
  5760. popq %rbp
  5761. jmp *%rax
  5762. .globl _main
  5763. .align 16
  5764. _main:
  5765. pushq %rbp
  5766. movq %rsp, %rbp
  5767. pushq %r12
  5768. pushq %rbx
  5769. pushq %r13
  5770. pushq %r14
  5771. subq $0, %rsp
  5772. movq $16384, %rdi
  5773. movq $16, %rsi
  5774. callq _initialize
  5775. movq _rootstack_begin(%rip), %r15
  5776. jmp _mainstart
  5777. \end{lstlisting}
  5778. \end{minipage}
  5779. &
  5780. \begin{minipage}{0.3\textwidth}
  5781. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5782. _mainconclusion:
  5783. addq $0, %rsp
  5784. popq %r14
  5785. popq %r13
  5786. popq %rbx
  5787. popq %r12
  5788. subq $0, %r15
  5789. popq %rbp
  5790. retq
  5791. \end{lstlisting}
  5792. \end{minipage}
  5793. \end{tabular}
  5794. \caption{Example compilation of a simple function to x86.}
  5795. \label{fig:add-fun}
  5796. \end{figure}
  5797. \begin{exercise}\normalfont
  5798. Expand your compiler to handle $R_4$ as outlined in this section.
  5799. Create 5 new programs that use functions, including examples that pass
  5800. functions and return functions from other functions and including
  5801. recursive functions. Test your compiler on these new programs and all
  5802. of your previously created test programs.
  5803. \end{exercise}
  5804. \begin{figure}[p]
  5805. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5806. \node (R4) at (0,2) {\large $R_4$};
  5807. \node (R4-2) at (3,2) {\large $R_4$};
  5808. \node (R4-3) at (6,2) {\large $R_4$};
  5809. \node (F1-1) at (12,0) {\large $F_1$};
  5810. \node (F1-2) at (9,0) {\large $F_1$};
  5811. \node (F1-3) at (6,0) {\large $F_1$};
  5812. \node (F1-4) at (3,0) {\large $F_1$};
  5813. \node (C3-1) at (6,-2) {\large $C_3$};
  5814. \node (C3-2) at (3,-2) {\large $C_3$};
  5815. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5816. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5817. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5818. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  5819. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5820. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5821. \path[->,bend left=15] (R4) edge [above] node
  5822. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  5823. \path[->,bend left=15] (R4-2) edge [above] node
  5824. {\ttfamily\footnotesize uniquify} (R4-3);
  5825. \path[->,bend left=15] (R4-3) edge [right] node
  5826. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  5827. \path[->,bend left=15] (F1-1) edge [below] node
  5828. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  5829. \path[->,bend right=15] (F1-2) edge [above] node
  5830. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  5831. \path[->,bend right=15] (F1-3) edge [above] node
  5832. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  5833. \path[->,bend left=15] (F1-4) edge [right] node
  5834. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  5835. \path[->,bend left=15] (C3-1) edge [below] node
  5836. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  5837. \path[->,bend right=15] (C3-2) edge [left] node
  5838. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5839. \path[->,bend left=15] (x86-2) edge [left] node
  5840. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5841. \path[->,bend right=15] (x86-2-1) edge [below] node
  5842. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5843. \path[->,bend right=15] (x86-2-2) edge [left] node
  5844. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5845. \path[->,bend left=15] (x86-3) edge [above] node
  5846. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  5847. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5848. \end{tikzpicture}
  5849. \caption{Diagram of the passes for $R_4$, a language with functions.}
  5850. \label{fig:R4-passes}
  5851. \end{figure}
  5852. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  5853. the compilation of $R_4$.
  5854. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5855. \chapter{Lexically Scoped Functions}
  5856. \label{ch:lambdas}
  5857. This chapter studies lexically scoped functions as they appear in
  5858. functional languages such as Racket. By lexical scoping we mean that a
  5859. function's body may refer to variables whose binding site is outside
  5860. of the function, in an enclosing scope.
  5861. %
  5862. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5863. anonymous function defined using the \key{lambda} form. The body of
  5864. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5865. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5866. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5867. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5868. returned from the function \code{f}. Below the definition of \code{f},
  5869. we have two calls to \code{f} with different arguments for \code{x},
  5870. first \code{5} then \code{3}. The functions returned from \code{f} are
  5871. bound to variables \code{g} and \code{h}. Even though these two
  5872. functions were created by the same \code{lambda}, they are really
  5873. different functions because they use different values for
  5874. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5875. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5876. the result of this program is \code{42}.
  5877. \begin{figure}[btp]
  5878. % s4_6.rkt
  5879. \begin{lstlisting}
  5880. (define (f [x : Integer]) : (Integer -> Integer)
  5881. (let ([y 4])
  5882. (lambda: ([z : Integer]) : Integer
  5883. (+ x (+ y z)))))
  5884. (let ([g (f 5)])
  5885. (let ([h (f 3)])
  5886. (+ (g 11) (h 15))))
  5887. \end{lstlisting}
  5888. \caption{Example of a lexically scoped function.}
  5889. \label{fig:lexical-scoping}
  5890. \end{figure}
  5891. \section{The $R_5$ Language}
  5892. The syntax for this language with anonymous functions and lexical
  5893. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5894. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5895. for function application. In this chapter we shall describe how to
  5896. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5897. into a combination of functions (as in $R_4$) and tuples (as in
  5898. $R_3$).
  5899. \begin{figure}[tp]
  5900. \centering
  5901. \fbox{
  5902. \begin{minipage}{0.96\textwidth}
  5903. \[
  5904. \begin{array}{lcl}
  5905. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5906. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5907. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5908. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5909. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  5910. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  5911. &\mid& \gray{\key{\#t} \mid \key{\#f}
  5912. \mid (\key{and}\;\Exp\;\Exp)
  5913. \mid (\key{or}\;\Exp\;\Exp)
  5914. \mid (\key{not}\;\Exp) } \\
  5915. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5916. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5917. (\key{vector-ref}\;\Exp\;\Int)} \\
  5918. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5919. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5920. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5921. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5922. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5923. \end{array}
  5924. \]
  5925. \end{minipage}
  5926. }
  5927. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  5928. with \key{lambda}.}
  5929. \label{fig:r5-syntax}
  5930. \end{figure}
  5931. To compile lexically-scoped functions to top-level function
  5932. definitions, the compiler will need to provide special treatment to
  5933. variable occurrences such as \code{x} and \code{y} in the body of the
  5934. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  5935. of $R_4$ may not refer to variables defined outside the function. To
  5936. identify such variable occurrences, we review the standard notion of
  5937. free variable.
  5938. \begin{definition}
  5939. A variable is \emph{free with respect to an expression} $e$ if the
  5940. variable occurs inside $e$ but does not have an enclosing binding in
  5941. $e$.
  5942. \end{definition}
  5943. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5944. free with respect to the expression \code{(+ x (+ y z))}. On the
  5945. other hand, only \code{x} and \code{y} are free with respect to the
  5946. following expression because \code{z} is bound by the \code{lambda}.
  5947. \begin{lstlisting}
  5948. (lambda: ([z : Integer]) : Integer
  5949. (+ x (+ y z)))
  5950. \end{lstlisting}
  5951. Once we have identified the free variables of a \code{lambda}, we need
  5952. to arrange for some way to transport, at runtime, the values of those
  5953. variables from the point where the \code{lambda} was created to the
  5954. point where the \code{lambda} is applied. Referring again to
  5955. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5956. needs to be used in the application of \code{g} to \code{11}, but the
  5957. binding of \code{x} to \code{3} needs to be used in the application of
  5958. \code{h} to \code{15}. An efficient solution to the problem, due to
  5959. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  5960. free variables together with the function pointer for the lambda's
  5961. code, an arrangement called a \emph{flat closure} (which we shorten to
  5962. just ``closure'') . Fortunately, we have all the ingredients to make
  5963. closures, Chapter~\ref{ch:tuples} gave us vectors and
  5964. Chapter~\ref{ch:functions} gave us function pointers. The function
  5965. pointer shall reside at index $0$ and the values for free variables
  5966. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  5967. the two closures created by the two calls to \code{f} in
  5968. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  5969. the same \key{lambda}, they share the same function pointer but differ
  5970. in the values for the free variable \code{x}.
  5971. \begin{figure}[tbp]
  5972. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  5973. \caption{Example closure representation for the \key{lambda}'s
  5974. in Figure~\ref{fig:lexical-scoping}.}
  5975. \label{fig:closures}
  5976. \end{figure}
  5977. \section{Interpreting $R_5$}
  5978. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5979. $R_5$. The clause for \key{lambda} saves the current environment
  5980. inside the returned \key{lambda}. Then the clause for \key{app} uses
  5981. the environment from the \key{lambda}, the \code{lam-env}, when
  5982. interpreting the body of the \key{lambda}. The \code{lam-env}
  5983. environment is extended with the mapping of parameters to argument
  5984. values.
  5985. \begin{figure}[tbp]
  5986. \begin{lstlisting}
  5987. (define (interp-exp env)
  5988. (lambda (e)
  5989. (define recur (interp-exp env))
  5990. (match e
  5991. ...
  5992. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5993. `(lambda ,xs ,body ,env)]
  5994. [`(app ,fun ,args ...)
  5995. (define fun-val ((interp-exp env) fun))
  5996. (define arg-vals (map (interp-exp env) args))
  5997. (match fun-val
  5998. [`(lambda (,xs ...) ,body ,lam-env)
  5999. (define new-env (append (map cons xs arg-vals) lam-env))
  6000. ((interp-exp new-env) body)]
  6001. [else (error "interp-exp, expected function, not" fun-val)])]
  6002. [else (error 'interp-exp "unrecognized expression")]
  6003. )))
  6004. \end{lstlisting}
  6005. \caption{Interpreter for $R_5$.}
  6006. \label{fig:interp-R5}
  6007. \end{figure}
  6008. \section{Type Checking $R_5$}
  6009. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6010. \key{lambda} form. The body of the \key{lambda} is checked in an
  6011. environment that includes the current environment (because it is
  6012. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6013. require the body's type to match the declared return type.
  6014. \begin{figure}[tbp]
  6015. \begin{lstlisting}
  6016. (define (typecheck-R5 env)
  6017. (lambda (e)
  6018. (match e
  6019. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6020. (define new-env (append (map cons xs Ts) env))
  6021. (define bodyT ((typecheck-R5 new-env) body))
  6022. (cond [(equal? rT bodyT)
  6023. `(,@Ts -> ,rT)]
  6024. [else
  6025. (error "mismatch in return type" bodyT rT)])]
  6026. ...
  6027. )))
  6028. \end{lstlisting}
  6029. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6030. \label{fig:typecheck-R5}
  6031. \end{figure}
  6032. \section{Closure Conversion}
  6033. The compiling of lexically-scoped functions into top-level function
  6034. definitions is accomplished in the pass \code{convert-to-closures}
  6035. that comes after \code{reveal-functions} and before
  6036. \code{limit-functions}.
  6037. As usual, we shall implement the pass as a recursive function over the
  6038. AST. All of the action is in the clauses for \key{lambda} and
  6039. \key{app}. We transform a \key{lambda} expression into an expression
  6040. that creates a closure, that is, creates a vector whose first element
  6041. is a function pointer and the rest of the elements are the free
  6042. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6043. generated to identify the function.
  6044. \begin{tabular}{lll}
  6045. \begin{minipage}{0.4\textwidth}
  6046. \begin{lstlisting}
  6047. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6048. \end{lstlisting}
  6049. \end{minipage}
  6050. &
  6051. $\Rightarrow$
  6052. &
  6053. \begin{minipage}{0.4\textwidth}
  6054. \begin{lstlisting}
  6055. (vector |\itm{name}| |\itm{fvs}| ...)
  6056. \end{lstlisting}
  6057. \end{minipage}
  6058. \end{tabular} \\
  6059. %
  6060. In addition to transforming each \key{lambda} into a \key{vector}, we
  6061. must create a top-level function definition for each \key{lambda}, as
  6062. shown below.\\
  6063. \begin{minipage}{0.8\textwidth}
  6064. \begin{lstlisting}
  6065. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6066. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6067. ...
  6068. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6069. |\itm{body'}|)...))
  6070. \end{lstlisting}
  6071. \end{minipage}\\
  6072. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6073. parameters are the normal parameters of the \key{lambda}. The types
  6074. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6075. underscore is a dummy type because it is rather difficult to give a
  6076. type to the function in the closure's type, and it does not matter.
  6077. The sequence of \key{let} forms bind the free variables to their
  6078. values obtained from the closure.
  6079. We transform function application into code that retrieves the
  6080. function pointer from the closure and then calls the function, passing
  6081. in the closure as the first argument. We bind $e'$ to a temporary
  6082. variable to avoid code duplication.
  6083. \begin{tabular}{lll}
  6084. \begin{minipage}{0.3\textwidth}
  6085. \begin{lstlisting}
  6086. (app |$e$| |\itm{es}| ...)
  6087. \end{lstlisting}
  6088. \end{minipage}
  6089. &
  6090. $\Rightarrow$
  6091. &
  6092. \begin{minipage}{0.5\textwidth}
  6093. \begin{lstlisting}
  6094. (let ([|\itm{tmp}| |$e'$|])
  6095. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6096. \end{lstlisting}
  6097. \end{minipage}
  6098. \end{tabular} \\
  6099. There is also the question of what to do with top-level function
  6100. definitions. To maintain a uniform translation of function
  6101. application, we turn function references into closures.
  6102. \begin{tabular}{lll}
  6103. \begin{minipage}{0.3\textwidth}
  6104. \begin{lstlisting}
  6105. (fun-ref |$f$|)
  6106. \end{lstlisting}
  6107. \end{minipage}
  6108. &
  6109. $\Rightarrow$
  6110. &
  6111. \begin{minipage}{0.5\textwidth}
  6112. \begin{lstlisting}
  6113. (vector (fun-ref |$f$|))
  6114. \end{lstlisting}
  6115. \end{minipage}
  6116. \end{tabular} \\
  6117. %
  6118. The top-level function definitions need to be updated as well to take
  6119. an extra closure parameter.
  6120. \section{An Example Translation}
  6121. \label{sec:example-lambda}
  6122. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6123. conversion for the example program demonstrating lexical scoping that
  6124. we discussed at the beginning of this chapter.
  6125. \begin{figure}[h]
  6126. \begin{minipage}{0.8\textwidth}
  6127. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6128. (program
  6129. (define (f [x : Integer]) : (Integer -> Integer)
  6130. (let ([y 4])
  6131. (lambda: ([z : Integer]) : Integer
  6132. (+ x (+ y z)))))
  6133. (let ([g (f 5)])
  6134. (let ([h (f 3)])
  6135. (+ (g 11) (h 15)))))
  6136. \end{lstlisting}
  6137. $\Downarrow$
  6138. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6139. (program (type Integer)
  6140. (define (f (x : Integer)) : (Integer -> Integer)
  6141. (let ((y 4))
  6142. (lambda: ((z : Integer)) : Integer
  6143. (+ x (+ y z)))))
  6144. (let ((g (app (fun-ref f) 5)))
  6145. (let ((h (app (fun-ref f) 3)))
  6146. (+ (app g 11) (app h 15)))))
  6147. \end{lstlisting}
  6148. $\Downarrow$
  6149. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6150. (program (type Integer)
  6151. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6152. (let ((y 4))
  6153. (vector (fun-ref lam.1) x y)))
  6154. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6155. (let ((x (vector-ref clos.2 1)))
  6156. (let ((y (vector-ref clos.2 2)))
  6157. (+ x (+ y z)))))
  6158. (let ((g (let ((t.1 (vector (fun-ref f))))
  6159. (app (vector-ref t.1 0) t.1 5))))
  6160. (let ((h (let ((t.2 (vector (fun-ref f))))
  6161. (app (vector-ref t.2 0) t.2 3))))
  6162. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6163. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6164. \end{lstlisting}
  6165. \end{minipage}
  6166. \caption{Example of closure conversion.}
  6167. \label{fig:lexical-functions-example}
  6168. \end{figure}
  6169. \begin{figure}[p]
  6170. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6171. \node (R4) at (0,2) {\large $R_4$};
  6172. \node (R4-2) at (3,2) {\large $R_4$};
  6173. \node (R4-3) at (6,2) {\large $R_4$};
  6174. \node (F1-1) at (12,0) {\large $F_1$};
  6175. \node (F1-2) at (9,0) {\large $F_1$};
  6176. \node (F1-3) at (6,0) {\large $F_1$};
  6177. \node (F1-4) at (3,0) {\large $F_1$};
  6178. \node (F1-5) at (0,0) {\large $F_1$};
  6179. \node (C3-1) at (6,-2) {\large $C_3$};
  6180. \node (C3-2) at (3,-2) {\large $C_3$};
  6181. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6182. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6183. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6184. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6185. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6186. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6187. \path[->,bend left=15] (R4) edge [above] node
  6188. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6189. \path[->,bend left=15] (R4-2) edge [above] node
  6190. {\ttfamily\footnotesize uniquify} (R4-3);
  6191. \path[->] (R4-3) edge [right] node
  6192. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6193. \path[->,bend left=15] (F1-1) edge [below] node
  6194. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6195. \path[->,bend right=15] (F1-2) edge [above] node
  6196. {\ttfamily\footnotesize limit-functions} (F1-3);
  6197. \path[->,bend right=15] (F1-3) edge [above] node
  6198. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6199. \path[->,bend right=15] (F1-4) edge [above] node
  6200. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6201. \path[->] (F1-5) edge [left] node
  6202. {\ttfamily\footnotesize explicate-control} (C3-1);
  6203. \path[->,bend left=15] (C3-1) edge [below] node
  6204. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6205. \path[->,bend right=15] (C3-2) edge [left] node
  6206. {\ttfamily\footnotesize select-instr.} (x86-2);
  6207. \path[->,bend left=15] (x86-2) edge [left] node
  6208. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6209. \path[->,bend right=15] (x86-2-1) edge [below] node
  6210. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6211. \path[->,bend right=15] (x86-2-2) edge [left] node
  6212. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6213. \path[->,bend left=15] (x86-3) edge [above] node
  6214. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6215. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6216. \end{tikzpicture}
  6217. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6218. functions.}
  6219. \label{fig:R5-passes}
  6220. \end{figure}
  6221. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6222. for the compilation of $R_5$.
  6223. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6224. \chapter{Dynamic Typing}
  6225. \label{ch:type-dynamic}
  6226. In this chapter we discuss the compilation of a dynamically typed
  6227. language, named $R_7$, that is a subset of the Racket
  6228. language. (Recall that in the previous chapters we have studied
  6229. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6230. languages, an expression may produce values of differing
  6231. type. Consider the following example with a conditional expression
  6232. that may return a Boolean or an integer depending on the input to the
  6233. program.
  6234. \begin{lstlisting}
  6235. (not (if (eq? (read) 1) #f 0))
  6236. \end{lstlisting}
  6237. Languages that allow expressions to produce different kinds of values
  6238. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6239. such as subtype polymorphism and parametric
  6240. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6241. talking about here does not have a special name, but it is the usual
  6242. kind that arises in dynamically typed languages.
  6243. Another characteristic of dynamically typed languages is that
  6244. primitive operations, such as \code{not}, are often defined to operate
  6245. on many different types of values. In fact, in Racket, the \code{not}
  6246. operator produces a result for any kind of value: given \code{\#f} it
  6247. returns \code{\#t} and given anything else it returns \code{\#f}.
  6248. Furthermore, even when primitive operations restrict their inputs to
  6249. values of a certain type, this restriction is enforced at runtime
  6250. instead of during compilation. For example, the following vector
  6251. reference results in a run-time contract violation.
  6252. \begin{lstlisting}
  6253. (vector-ref (vector 42) #t)
  6254. \end{lstlisting}
  6255. \begin{figure}[tp]
  6256. \centering
  6257. \fbox{
  6258. \begin{minipage}{0.97\textwidth}
  6259. \[
  6260. \begin{array}{rcl}
  6261. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6262. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6263. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6264. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6265. &\mid& \key{\#t} \mid \key{\#f}
  6266. \mid (\key{and}\;\Exp\;\Exp)
  6267. \mid (\key{or}\;\Exp\;\Exp)
  6268. \mid (\key{not}\;\Exp) \\
  6269. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6270. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6271. (\key{vector-ref}\;\Exp\;\Exp) \\
  6272. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6273. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6274. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6275. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6276. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6277. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6278. \end{array}
  6279. \]
  6280. \end{minipage}
  6281. }
  6282. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6283. \label{fig:r7-syntax}
  6284. \end{figure}
  6285. The syntax of $R_7$, our subset of Racket, is defined in
  6286. Figure~\ref{fig:r7-syntax}.
  6287. %
  6288. The definitional interpreter for $R_7$ is given in
  6289. Figure~\ref{fig:interp-R7}.
  6290. \begin{figure}[tbp]
  6291. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6292. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6293. (define (valid-op? op) (member op '(+ - and or not)))
  6294. (define (interp-r7 env)
  6295. (lambda (ast)
  6296. (define recur (interp-r7 env))
  6297. (match ast
  6298. [(? symbol?) (lookup ast env)]
  6299. [(? integer?) `(inject ,ast Integer)]
  6300. [#t `(inject #t Boolean)]
  6301. [#f `(inject #f Boolean)]
  6302. [`(read) `(inject ,(read-fixnum) Integer)]
  6303. [`(lambda (,xs ...) ,body)
  6304. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6305. [`(define (,f ,xs ...) ,body)
  6306. (mcons f `(lambda ,xs ,body))]
  6307. [`(program ,ds ... ,body)
  6308. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6309. (for/list ([b top-level])
  6310. (set-mcdr! b (match (mcdr b)
  6311. [`(lambda ,xs ,body)
  6312. `(inject (lambda ,xs ,body ,top-level)
  6313. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6314. ((interp-r7 top-level) body))]
  6315. [`(vector ,(app recur elts) ...)
  6316. (define tys (map get-tagged-type elts))
  6317. `(inject ,(apply vector elts) (Vector ,@tys))]
  6318. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6319. (match v1
  6320. [`(inject ,vec ,ty)
  6321. (vector-set! vec n v2)
  6322. `(inject (void) Void)])]
  6323. [`(vector-ref ,(app recur v) ,n)
  6324. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6325. [`(let ([,x ,(app recur v)]) ,body)
  6326. ((interp-r7 (cons (cons x v) env)) body)]
  6327. [`(,op ,es ...) #:when (valid-op? op)
  6328. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6329. [`(eq? ,(app recur l) ,(app recur r))
  6330. `(inject ,(equal? l r) Boolean)]
  6331. [`(if ,(app recur q) ,t ,f)
  6332. (match q
  6333. [`(inject #f Boolean) (recur f)]
  6334. [else (recur t)])]
  6335. [`(,(app recur f-val) ,(app recur vs) ...)
  6336. (match f-val
  6337. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6338. (define new-env (append (map cons xs vs) lam-env))
  6339. ((interp-r7 new-env) body)]
  6340. [else (error "interp-r7, expected function, not" f-val)])])))
  6341. \end{lstlisting}
  6342. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6343. \label{fig:interp-R7}
  6344. \end{figure}
  6345. Let us consider how we might compile $R_7$ to x86, thinking about the
  6346. first example above. Our bit-level representation of the Boolean
  6347. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6348. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6349. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6350. general, cannot be determined at compile time, but depends on the
  6351. runtime type of its input, as in the example above that depends on the
  6352. result of \code{(read)}.
  6353. The way around this problem is to include information about a value's
  6354. runtime type in the value itself, so that this information can be
  6355. inspected by operators such as \code{not}. In particular, we shall
  6356. steal the 3 right-most bits from our 64-bit values to encode the
  6357. runtime type. We shall use $001$ to identify integers, $100$ for
  6358. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6359. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6360. define the following auxiliary function.
  6361. \begin{align*}
  6362. \itm{tagof}(\key{Integer}) &= 001 \\
  6363. \itm{tagof}(\key{Boolean}) &= 100 \\
  6364. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6365. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6366. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6367. \itm{tagof}(\key{Void}) &= 101
  6368. \end{align*}
  6369. (We shall say more about the new \key{Vectorof} type shortly.)
  6370. This stealing of 3 bits comes at some
  6371. price: our integers are reduced to ranging from $-2^{60}$ to
  6372. $2^{60}$. The stealing does not adversely affect vectors and
  6373. procedures because those values are addresses, and our addresses are
  6374. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6375. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6376. bits with the tag and we can simply zero-out the tag to recover the
  6377. original address.
  6378. In some sense, these tagged values are a new kind of value. Indeed,
  6379. we can extend our \emph{typed} language with tagged values by adding a
  6380. new type to classify them, called \key{Any}, and with operations for
  6381. creating and using tagged values, yielding the $R_6$ language that we
  6382. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6383. fundamental support for polymorphism and runtime types that we need to
  6384. support dynamic typing.
  6385. There is an interesting interaction between tagged values and garbage
  6386. collection. A variable of type \code{Any} might refer to a vector and
  6387. therefore it might be a root that needs to be inspected and copied
  6388. during garbage collection. Thus, we need to treat variables of type
  6389. \code{Any} in a similar way to variables of type \code{Vector} for
  6390. purposes of register allocation, which we discuss in
  6391. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6392. variable of type \code{Any} is spilled, it must be spilled to the root
  6393. stack. But this means that the garbage collector needs to be able to
  6394. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6395. value that points to a tuple, and (3) a tagged value that is not a
  6396. tuple. We enable this differentiation by choosing not to use the tag
  6397. $000$. Instead, that bit pattern is reserved for identifying plain old
  6398. pointers to tuples. On the other hand, if one of the first three bits
  6399. is set, then we have a tagged value, and inspecting the tag can
  6400. differentiation between vectors ($010$) and the other kinds of values.
  6401. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6402. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6403. extend our compiler to handle the new features of $R_6$
  6404. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6405. \ref{sec:register-allocation-r6}).
  6406. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6407. \label{sec:r6-lang}
  6408. \begin{figure}[tp]
  6409. \centering
  6410. \fbox{
  6411. \begin{minipage}{0.97\textwidth}
  6412. \[
  6413. \begin{array}{lcl}
  6414. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6415. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6416. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6417. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6418. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6419. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6420. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6421. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6422. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6423. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6424. \mid (\key{and}\;\Exp\;\Exp)
  6425. \mid (\key{or}\;\Exp\;\Exp)
  6426. \mid (\key{not}\;\Exp)} \\
  6427. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6428. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6429. (\key{vector-ref}\;\Exp\;\Int)} \\
  6430. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6431. &\mid& \gray{(\Exp \; \Exp^{*})
  6432. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6433. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6434. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6435. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6436. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6437. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6438. \end{array}
  6439. \]
  6440. \end{minipage}
  6441. }
  6442. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6443. with \key{Any}.}
  6444. \label{fig:r6-syntax}
  6445. \end{figure}
  6446. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6447. $(\key{inject}\; e\; T)$ form converts the value produced by
  6448. expression $e$ of type $T$ into a tagged value. The
  6449. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6450. expression $e$ into a value of type $T$ or else halts the program if
  6451. the type tag is equivalent to $T$. We treat
  6452. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6453. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6454. Note that in both \key{inject} and
  6455. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6456. which simplifies the implementation and corresponds with what is
  6457. needed for compiling untyped Racket. The type predicates,
  6458. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6459. if the tag corresponds to the predicate, and return \key{\#t}
  6460. otherwise.
  6461. %
  6462. Selections from the type checker for $R_6$ are shown in
  6463. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6464. Figure~\ref{fig:interp-R6}.
  6465. \begin{figure}[btp]
  6466. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6467. (define (flat-ty? ty) ...)
  6468. (define (typecheck-R6 env)
  6469. (lambda (e)
  6470. (define recur (typecheck-R6 env))
  6471. (match e
  6472. [`(inject ,e ,ty)
  6473. (unless (flat-ty? ty)
  6474. (error "may only inject a value of flat type, not ~a" ty))
  6475. (define-values (new-e e-ty) (recur e))
  6476. (cond
  6477. [(equal? e-ty ty)
  6478. (values `(inject ,new-e ,ty) 'Any)]
  6479. [else
  6480. (error "inject expected ~a to have type ~a" e ty)])]
  6481. [`(project ,e ,ty)
  6482. (unless (flat-ty? ty)
  6483. (error "may only project to a flat type, not ~a" ty))
  6484. (define-values (new-e e-ty) (recur e))
  6485. (cond
  6486. [(equal? e-ty 'Any)
  6487. (values `(project ,new-e ,ty) ty)]
  6488. [else
  6489. (error "project expected ~a to have type Any" e)])]
  6490. [`(vector-ref ,e ,i)
  6491. (define-values (new-e e-ty) (recur e))
  6492. (match e-ty
  6493. [`(Vector ,ts ...) ...]
  6494. [`(Vectorof ,ty)
  6495. (unless (exact-nonnegative-integer? i)
  6496. (error 'type-check "invalid index ~a" i))
  6497. (values `(vector-ref ,new-e ,i) ty)]
  6498. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6499. ...
  6500. )))
  6501. \end{lstlisting}
  6502. \caption{Type checker for parts of the $R_6$ language.}
  6503. \label{fig:typecheck-R6}
  6504. \end{figure}
  6505. % to do: add rules for vector-ref, etc. for Vectorof
  6506. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6507. \begin{figure}[btp]
  6508. \begin{lstlisting}
  6509. (define primitives (set 'boolean? ...))
  6510. (define (interp-op op)
  6511. (match op
  6512. ['boolean? (lambda (v)
  6513. (match v
  6514. [`(tagged ,v1 Boolean) #t]
  6515. [else #f]))]
  6516. ...))
  6517. ;; Equivalence of flat types
  6518. (define (tyeq? t1 t2)
  6519. (match `(,t1 ,t2)
  6520. [`((Vectorof Any) (Vector ,t2s ...))
  6521. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6522. [`((Vector ,t1s ...) (Vectorof Any))
  6523. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6524. [else (equal? t1 t2)]))
  6525. (define (interp-R6 env)
  6526. (lambda (ast)
  6527. (match ast
  6528. [`(inject ,e ,t)
  6529. `(tagged ,((interp-R6 env) e) ,t)]
  6530. [`(project ,e ,t2)
  6531. (define v ((interp-R6 env) e))
  6532. (match v
  6533. [`(tagged ,v1 ,t1)
  6534. (cond [(tyeq? t1 t2)
  6535. v1]
  6536. [else
  6537. (error "in project, type mismatch" t1 t2)])]
  6538. [else
  6539. (error "in project, expected tagged value" v)])]
  6540. ...)))
  6541. \end{lstlisting}
  6542. \caption{Interpreter for $R_6$.}
  6543. \label{fig:interp-R6}
  6544. \end{figure}
  6545. %\clearpage
  6546. \section{Shrinking $R_6$}
  6547. \label{sec:shrink-r6}
  6548. In the \code{shrink} pass we recommend compiling \code{project} into
  6549. an explicit \code{if} expression that uses three new operations:
  6550. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6551. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6552. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6553. value from a tagged value. Finally, the \code{exit} operation ends the
  6554. execution of the program by invoking the operating system's
  6555. \code{exit} function. So the translation for \code{project} is as
  6556. follows. (We have omitted the \code{has-type} AST nodes to make this
  6557. output more readable.)
  6558. \begin{tabular}{lll}
  6559. \begin{minipage}{0.3\textwidth}
  6560. \begin{lstlisting}
  6561. (project |$e$| |$\Type$|)
  6562. \end{lstlisting}
  6563. \end{minipage}
  6564. &
  6565. $\Rightarrow$
  6566. &
  6567. \begin{minipage}{0.5\textwidth}
  6568. \begin{lstlisting}
  6569. (let ([|$\itm{tmp}$| |$e'$|])
  6570. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6571. (value-of-any |$\itm{tmp}$|)
  6572. (exit)))
  6573. \end{lstlisting}
  6574. \end{minipage}
  6575. \end{tabular} \\
  6576. Similarly, we recommend translating the type predicates
  6577. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6578. \section{Instruction Selection for $R_6$}
  6579. \label{sec:select-r6}
  6580. \paragraph{Inject}
  6581. We recommend compiling an \key{inject} as follows if the type is
  6582. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6583. destination to the left by the number of bits specified its source
  6584. argument (in this case $3$, the length of the tag) and it preserves
  6585. the sign of the integer. We use the \key{orq} instruction to combine
  6586. the tag and the value to form the tagged value. \\
  6587. \begin{tabular}{lll}
  6588. \begin{minipage}{0.4\textwidth}
  6589. \begin{lstlisting}
  6590. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6591. \end{lstlisting}
  6592. \end{minipage}
  6593. &
  6594. $\Rightarrow$
  6595. &
  6596. \begin{minipage}{0.5\textwidth}
  6597. \begin{lstlisting}
  6598. (movq |$e'$| |\itm{lhs}'|)
  6599. (salq (int 3) |\itm{lhs}'|)
  6600. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6601. \end{lstlisting}
  6602. \end{minipage}
  6603. \end{tabular} \\
  6604. The instruction selection for vectors and procedures is different
  6605. because their is no need to shift them to the left. The rightmost 3
  6606. bits are already zeros as described above. So we just combine the
  6607. value and the tag using \key{orq}. \\
  6608. \begin{tabular}{lll}
  6609. \begin{minipage}{0.4\textwidth}
  6610. \begin{lstlisting}
  6611. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6612. \end{lstlisting}
  6613. \end{minipage}
  6614. &
  6615. $\Rightarrow$
  6616. &
  6617. \begin{minipage}{0.5\textwidth}
  6618. \begin{lstlisting}
  6619. (movq |$e'$| |\itm{lhs}'|)
  6620. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6621. \end{lstlisting}
  6622. \end{minipage}
  6623. \end{tabular}
  6624. \paragraph{Tag of Any}
  6625. Recall that the \code{tag-of-any} operation extracts the type tag from
  6626. a value of type \code{Any}. The type tag is the bottom three bits, so
  6627. we obtain the tag by taking the bitwise-and of the value with $111$
  6628. ($7$ in decimal).
  6629. \begin{tabular}{lll}
  6630. \begin{minipage}{0.4\textwidth}
  6631. \begin{lstlisting}
  6632. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6633. \end{lstlisting}
  6634. \end{minipage}
  6635. &
  6636. $\Rightarrow$
  6637. &
  6638. \begin{minipage}{0.5\textwidth}
  6639. \begin{lstlisting}
  6640. (movq |$e'$| |\itm{lhs}'|)
  6641. (andq (int 7) |\itm{lhs}'|)
  6642. \end{lstlisting}
  6643. \end{minipage}
  6644. \end{tabular}
  6645. \paragraph{Value of Any}
  6646. Like \key{inject}, the instructions for \key{value-of-any} are
  6647. different depending on whether the type $T$ is a pointer (vector or
  6648. procedure) or not (Integer or Boolean). The following shows the
  6649. instruction selection for Integer and Boolean. We produce an untagged
  6650. value by shifting it to the right by 3 bits.
  6651. %
  6652. \\
  6653. \begin{tabular}{lll}
  6654. \begin{minipage}{0.4\textwidth}
  6655. \begin{lstlisting}
  6656. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6657. \end{lstlisting}
  6658. \end{minipage}
  6659. &
  6660. $\Rightarrow$
  6661. &
  6662. \begin{minipage}{0.5\textwidth}
  6663. \begin{lstlisting}
  6664. (movq |$e'$| |\itm{lhs}'|)
  6665. (sarq (int 3) |\itm{lhs}'|)
  6666. \end{lstlisting}
  6667. \end{minipage}
  6668. \end{tabular} \\
  6669. %
  6670. In the case for vectors and procedures, there is no need to
  6671. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6672. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6673. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6674. \code{movq} into the destination $\itm{lhs}$. We then generate
  6675. \code{andq} with the tagged value to get the desired result. \\
  6676. %
  6677. \begin{tabular}{lll}
  6678. \begin{minipage}{0.4\textwidth}
  6679. \begin{lstlisting}
  6680. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6681. \end{lstlisting}
  6682. \end{minipage}
  6683. &
  6684. $\Rightarrow$
  6685. &
  6686. \begin{minipage}{0.5\textwidth}
  6687. \begin{lstlisting}
  6688. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6689. (andq |$e'$| |\itm{lhs}'|)
  6690. \end{lstlisting}
  6691. \end{minipage}
  6692. \end{tabular}
  6693. %% \paragraph{Type Predicates} We leave it to the reader to
  6694. %% devise a sequence of instructions to implement the type predicates
  6695. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6696. \section{Register Allocation for $R_6$}
  6697. \label{sec:register-allocation-r6}
  6698. As mentioned above, a variable of type \code{Any} might refer to a
  6699. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6700. of type \code{Any} in the same way that it treats variables of type
  6701. \code{Vector} for purposes of garbage collection. In particular,
  6702. \begin{itemize}
  6703. \item If a variable of type \code{Any} is live during a function call,
  6704. then it must be spilled. One way to accomplish this is to augment
  6705. the pass \code{build-interference} to mark all variables that are
  6706. live after a \code{callq} as interfering with all the registers.
  6707. \item If a variable of type \code{Any} is spilled, it must be spilled
  6708. to the root stack instead of the normal procedure call stack.
  6709. \end{itemize}
  6710. \section{Compiling $R_7$ to $R_6$}
  6711. \label{sec:compile-r7}
  6712. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6713. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6714. given a subexpression $e$ of $R_7$, the pass will produce an
  6715. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6716. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6717. the Boolean \code{\#t}, which must be injected to produce an
  6718. expression of type \key{Any}.
  6719. %
  6720. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6721. addition, is representative of compilation for many operations: the
  6722. arguments have type \key{Any} and must be projected to \key{Integer}
  6723. before the addition can be performed.
  6724. The compilation of \key{lambda} (third row of
  6725. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6726. produce type annotations: we simply use \key{Any}.
  6727. %
  6728. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  6729. has to account for some differences in behavior between $R_7$ and
  6730. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  6731. kind of values can be used in various places. For example, the
  6732. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  6733. the arguments need not be of the same type (but in that case, the
  6734. result will be \code{\#f}).
  6735. \begin{figure}[btp]
  6736. \centering
  6737. \begin{tabular}{|lll|} \hline
  6738. \begin{minipage}{0.25\textwidth}
  6739. \begin{lstlisting}
  6740. #t
  6741. \end{lstlisting}
  6742. \end{minipage}
  6743. &
  6744. $\Rightarrow$
  6745. &
  6746. \begin{minipage}{0.6\textwidth}
  6747. \begin{lstlisting}
  6748. (inject #t Boolean)
  6749. \end{lstlisting}
  6750. \end{minipage}
  6751. \\[2ex]\hline
  6752. \begin{minipage}{0.25\textwidth}
  6753. \begin{lstlisting}
  6754. (+ |$e_1$| |$e_2$|)
  6755. \end{lstlisting}
  6756. \end{minipage}
  6757. &
  6758. $\Rightarrow$
  6759. &
  6760. \begin{minipage}{0.6\textwidth}
  6761. \begin{lstlisting}
  6762. (inject
  6763. (+ (project |$e'_1$| Integer)
  6764. (project |$e'_2$| Integer))
  6765. Integer)
  6766. \end{lstlisting}
  6767. \end{minipage}
  6768. \\[2ex]\hline
  6769. \begin{minipage}{0.25\textwidth}
  6770. \begin{lstlisting}
  6771. (lambda (|$x_1 \ldots$|) |$e$|)
  6772. \end{lstlisting}
  6773. \end{minipage}
  6774. &
  6775. $\Rightarrow$
  6776. &
  6777. \begin{minipage}{0.6\textwidth}
  6778. \begin{lstlisting}
  6779. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  6780. (Any|$\ldots$|Any -> Any))
  6781. \end{lstlisting}
  6782. \end{minipage}
  6783. \\[2ex]\hline
  6784. \begin{minipage}{0.25\textwidth}
  6785. \begin{lstlisting}
  6786. (app |$e_0$| |$e_1 \ldots e_n$|)
  6787. \end{lstlisting}
  6788. \end{minipage}
  6789. &
  6790. $\Rightarrow$
  6791. &
  6792. \begin{minipage}{0.6\textwidth}
  6793. \begin{lstlisting}
  6794. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6795. |$e'_1 \ldots e'_n$|)
  6796. \end{lstlisting}
  6797. \end{minipage}
  6798. \\[2ex]\hline
  6799. \begin{minipage}{0.25\textwidth}
  6800. \begin{lstlisting}
  6801. (vector-ref |$e_1$| |$e_2$|)
  6802. \end{lstlisting}
  6803. \end{minipage}
  6804. &
  6805. $\Rightarrow$
  6806. &
  6807. \begin{minipage}{0.6\textwidth}
  6808. \begin{lstlisting}
  6809. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6810. (let ([tmp2 (project |$e'_2$| Integer)])
  6811. (vector-ref tmp1 tmp2)))
  6812. \end{lstlisting}
  6813. \end{minipage}
  6814. \\[2ex]\hline
  6815. \begin{minipage}{0.25\textwidth}
  6816. \begin{lstlisting}
  6817. (if |$e_1$| |$e_2$| |$e_3$|)
  6818. \end{lstlisting}
  6819. \end{minipage}
  6820. &
  6821. $\Rightarrow$
  6822. &
  6823. \begin{minipage}{0.6\textwidth}
  6824. \begin{lstlisting}
  6825. (if (eq? |$e'_1$| (inject #f Boolean))
  6826. |$e'_3$|
  6827. |$e'_2$|)
  6828. \end{lstlisting}
  6829. \end{minipage}
  6830. \\[2ex]\hline
  6831. \begin{minipage}{0.25\textwidth}
  6832. \begin{lstlisting}
  6833. (eq? |$e_1$| |$e_2$|)
  6834. \end{lstlisting}
  6835. \end{minipage}
  6836. &
  6837. $\Rightarrow$
  6838. &
  6839. \begin{minipage}{0.6\textwidth}
  6840. \begin{lstlisting}
  6841. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6842. \end{lstlisting}
  6843. \end{minipage}
  6844. \\[2ex]\hline
  6845. \end{tabular}
  6846. \caption{Compiling $R_7$ to $R_6$.}
  6847. \label{fig:compile-r7-r6}
  6848. \end{figure}
  6849. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6850. \chapter{Gradual Typing}
  6851. \label{ch:gradual-typing}
  6852. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  6853. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6854. \chapter{Parametric Polymorphism}
  6855. \label{ch:parametric-polymorphism}
  6856. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  6857. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  6858. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6859. \chapter{High-level Optimization}
  6860. \label{ch:high-level-optimization}
  6861. This chapter will present a procedure inlining pass based on the
  6862. algorithm of \citet{Waddell:1997fk}.
  6863. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6864. \chapter{Appendix}
  6865. \section{Interpreters}
  6866. \label{appendix:interp}
  6867. We provide several interpreters in the \key{interp.rkt} file. The
  6868. \key{interp-scheme} function takes an AST in one of the Racket-like
  6869. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  6870. the program, returning the result value. The \key{interp-C} function
  6871. interprets an AST for a program in one of the C-like languages ($C_0,
  6872. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  6873. for an x86 program.
  6874. \section{Utility Functions}
  6875. \label{appendix:utilities}
  6876. The utility function described in this section can be found in the
  6877. \key{utilities.rkt} file.
  6878. The \key{read-program} function takes a file path and parses that file
  6879. (it must be a Racket program) into an abstract syntax tree (as an
  6880. S-expression) with a \key{program} AST at the top.
  6881. The \key{assert} function displays the error message \key{msg} if the
  6882. Boolean \key{bool} is false.
  6883. \begin{lstlisting}
  6884. (define (assert msg bool) ...)
  6885. \end{lstlisting}
  6886. The \key{lookup} function takes a key and an association list (a list
  6887. of key-value pairs), and returns the first value that is associated
  6888. with the given key, if there is one. If not, an error is triggered.
  6889. The association list may contain both immutable pairs (built with
  6890. \key{cons}) and mutable pairs (built with \key{mcons}).
  6891. The \key{map2} function ...
  6892. %% \subsection{Graphs}
  6893. %% \begin{itemize}
  6894. %% \item The \code{make-graph} function takes a list of vertices
  6895. %% (symbols) and returns a graph.
  6896. %% \item The \code{add-edge} function takes a graph and two vertices and
  6897. %% adds an edge to the graph that connects the two vertices. The graph
  6898. %% is updated in-place. There is no return value for this function.
  6899. %% \item The \code{adjacent} function takes a graph and a vertex and
  6900. %% returns the set of vertices that are adjacent to the given
  6901. %% vertex. The return value is a Racket \code{hash-set} so it can be
  6902. %% used with functions from the \code{racket/set} module.
  6903. %% \item The \code{vertices} function takes a graph and returns the list
  6904. %% of vertices in the graph.
  6905. %% \end{itemize}
  6906. \subsection{Testing}
  6907. The \key{interp-tests} function takes a compiler name (a string), a
  6908. description of the passes, an interpreter for the source language, a
  6909. test family name (a string), and a list of test numbers, and runs the
  6910. compiler passes and the interpreters to check whether the passes
  6911. correct. The description of the passes is a list with one entry per
  6912. pass. An entry is a list with three things: a string giving the name
  6913. of the pass, the function that implements the pass (a translator from
  6914. AST to AST), and a function that implements the interpreter (a
  6915. function from AST to result value) for the language of the output of
  6916. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  6917. good choice. The \key{interp-tests} function assumes that the
  6918. subdirectory \key{tests} has a collection of Scheme programs whose names
  6919. all start with the family name, followed by an underscore and then the
  6920. test number, ending in \key{.scm}. Also, for each Scheme program there
  6921. is a file with the same number except that it ends with \key{.in} that
  6922. provides the input for the Scheme program.
  6923. \begin{lstlisting}
  6924. (define (interp-tests name passes test-family test-nums) ...)
  6925. \end{lstlisting}
  6926. The compiler-tests function takes a compiler name (a string) a
  6927. description of the passes (as described above for
  6928. \code{interp-tests}), a test family name (a string), and a list of
  6929. test numbers (see the comment for interp-tests), and runs the compiler
  6930. to generate x86 (a \key{.s} file) and then runs gcc to generate
  6931. machine code. It runs the machine code and checks that the output is
  6932. 42.
  6933. \begin{lstlisting}
  6934. (define (compiler-tests name passes test-family test-nums) ...)
  6935. \end{lstlisting}
  6936. The compile-file function takes a description of the compiler passes
  6937. (see the comment for \key{interp-tests}) and returns a function that,
  6938. given a program file name (a string ending in \key{.scm}), applies all
  6939. of the passes and writes the output to a file whose name is the same
  6940. as the program file name but with \key{.scm} replaced with \key{.s}.
  6941. \begin{lstlisting}
  6942. (define (compile-file passes)
  6943. (lambda (prog-file-name) ...))
  6944. \end{lstlisting}
  6945. \section{x86 Instruction Set Quick-Reference}
  6946. \label{sec:x86-quick-reference}
  6947. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  6948. do. We write $A \to B$ to mean that the value of $A$ is written into
  6949. location $B$. Address offsets are given in bytes. The instruction
  6950. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  6951. registers (such as $\%rax$), or memory references (such as
  6952. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  6953. reference per instruction. Other operands must be immediates or
  6954. registers.
  6955. \begin{table}[tbp]
  6956. \centering
  6957. \begin{tabular}{l|l}
  6958. \textbf{Instruction} & \textbf{Operation} \\ \hline
  6959. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  6960. \texttt{negq} $A$ & $- A \to A$ \\
  6961. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  6962. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  6963. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  6964. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  6965. \texttt{retq} & Pops the return address and jumps to it \\
  6966. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  6967. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  6968. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  6969. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  6970. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  6971. matches the condition code of the instruction, otherwise go to the
  6972. next instructions. The condition codes are \key{e} for ``equal'',
  6973. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6974. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6975. \texttt{jl} $L$ & \\
  6976. \texttt{jle} $L$ & \\
  6977. \texttt{jg} $L$ & \\
  6978. \texttt{jge} $L$ & \\
  6979. \texttt{jmp} $L$ & Jump to label $L$ \\
  6980. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6981. \texttt{movzbq} $A$, $B$ &
  6982. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6983. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6984. and the extra bytes of $B$ are set to zero.} \\
  6985. & \\
  6986. & \\
  6987. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6988. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6989. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6990. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6991. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6992. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6993. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6994. description of the condition codes. $A$ must be a single byte register
  6995. (e.g., \texttt{al} or \texttt{cl}).} \\
  6996. \texttt{setl} $A$ & \\
  6997. \texttt{setle} $A$ & \\
  6998. \texttt{setg} $A$ & \\
  6999. \texttt{setge} $A$ &
  7000. \end{tabular}
  7001. \vspace{5pt}
  7002. \caption{Quick-reference for the x86 instructions used in this book.}
  7003. \label{tab:x86-instr}
  7004. \end{table}
  7005. \bibliographystyle{plainnat}
  7006. \bibliography{all}
  7007. \end{document}
  7008. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7009. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7010. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7011. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7012. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  7013. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7014. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7015. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7016. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7017. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7018. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7019. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7020. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7021. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7022. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7023. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7024. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7025. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7026. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7027. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7028. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7029. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7030. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7031. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7032. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7033. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7034. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7035. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7036. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7037. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7038. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge