book.tex 303 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107
  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. \usepackage{upquote}
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. %% For pictures
  55. \usepackage{tikz}
  56. \usetikzlibrary{arrows.meta}
  57. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  58. % Computer Modern is already the default. -Jeremy
  59. %\renewcommand{\ttdefault}{cmtt}
  60. \definecolor{comment-red}{rgb}{0.8,0,0}
  61. \if{0}
  62. % Peanut gallery comments:
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{#1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then},
  73. deletekeywords={read},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~}
  77. }
  78. \newtheorem{theorem}{Theorem}
  79. \newtheorem{lemma}[theorem]{Lemma}
  80. \newtheorem{corollary}[theorem]{Corollary}
  81. \newtheorem{proposition}[theorem]{Proposition}
  82. \newtheorem{constraint}[theorem]{Constraint}
  83. \newtheorem{definition}[theorem]{Definition}
  84. \newtheorem{exercise}[theorem]{Exercise}
  85. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  86. % 'dedication' environment: To add a dedication paragraph at the start of book %
  87. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  88. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  89. \newenvironment{dedication}
  90. {
  91. \cleardoublepage
  92. \thispagestyle{empty}
  93. \vspace*{\stretch{1}}
  94. \hfill\begin{minipage}[t]{0.66\textwidth}
  95. \raggedright
  96. }
  97. {
  98. \end{minipage}
  99. \vspace*{\stretch{3}}
  100. \clearpage
  101. }
  102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  103. % Chapter quote at the start of chapter %
  104. % Source: http://tex.stackexchange.com/a/53380 %
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \makeatletter
  107. \renewcommand{\@chapapp}{}% Not necessary...
  108. \newenvironment{chapquote}[2][2em]
  109. {\setlength{\@tempdima}{#1}%
  110. \def\chapquote@author{#2}%
  111. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  112. \itshape}
  113. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  114. \makeatother
  115. \input{defs}
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \title{\Huge \textbf{Essentials of Compilation} \\
  118. \huge An Incremental Approach}
  119. \author{\textsc{Jeremy G. Siek} \\
  120. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  121. Indiana University \\
  122. \\
  123. with contributions from: \\
  124. Carl Factora \\
  125. Andre Kuhlenschmidt \\
  126. Ryan R. Newton \\
  127. Ryan Scott \\
  128. Cameron Swords \\
  129. Michael M. Vitousek \\
  130. Michael Vollmer
  131. }
  132. \begin{document}
  133. \frontmatter
  134. \maketitle
  135. \begin{dedication}
  136. This book is dedicated to the programming language wonks at Indiana
  137. University.
  138. \end{dedication}
  139. \tableofcontents
  140. \listoffigures
  141. %\listoftables
  142. \mainmatter
  143. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  144. \chapter*{Preface}
  145. The tradition of compiler writing at Indiana University goes back to
  146. research and courses about programming languages by Daniel Friedman in
  147. the 1970's and 1980's. Dan conducted research on lazy
  148. evaluation~\citep{Friedman:1976aa} in the context of
  149. Lisp~\citep{McCarthy:1960dz} and then studied
  150. continuations~\citep{Felleisen:kx} and
  151. macros~\citep{Kohlbecker:1986dk} in the context of the
  152. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  153. of those courses, Kent Dybvig, went on to build Chez
  154. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  155. compiler for Scheme. After completing his Ph.D. at the University of
  156. North Carolina, Kent returned to teach at Indiana University.
  157. Throughout the 1990's and 2000's, Kent continued development of Chez
  158. Scheme and taught the compiler course.
  159. The compiler course evolved to incorporate novel pedagogical ideas
  160. while also including elements of effective real-world compilers. One
  161. of Dan's ideas was to split the compiler into many small ``passes'' so
  162. that the code for each pass would be easy to understood in isolation.
  163. (In contrast, most compilers of the time were organized into only a
  164. few monolithic passes for reasons of compile-time efficiency.) Kent,
  165. with later help from his students Dipanwita Sarkar and Andrew Keep,
  166. developed infrastructure to support this approach and evolved the
  167. course, first to use micro-sized passes and then into even smaller
  168. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  169. student in this compiler course in the early 2000's, as part of his
  170. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  171. the course immensely!
  172. During that time, another student named Abdulaziz Ghuloum observed
  173. that the front-to-back organization of the course made it difficult
  174. for students to understand the rationale for the compiler
  175. design. Abdulaziz proposed an incremental approach in which the
  176. students build the compiler in stages; they start by implementing a
  177. complete compiler for a very small subset of the input language and in
  178. each subsequent stage they add a language feature and add or modify
  179. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  180. the students see how the language features motivate aspects of the
  181. compiler design.
  182. After graduating from Indiana University in 2005, Jeremy went on to
  183. teach at the University of Colorado. He adapted the nano pass and
  184. incremental approaches to compiling a subset of the Python
  185. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  186. on the surface but there is a large overlap in the compiler techniques
  187. required for the two languages. Thus, Jeremy was able to teach much of
  188. the same content from the Indiana compiler course. He very much
  189. enjoyed teaching the course organized in this way, and even better,
  190. many of the students learned a lot and got excited about compilers.
  191. Jeremy returned to teach at Indiana University in 2013. In his
  192. absence the compiler course had switched from the front-to-back
  193. organization to a back-to-front organization. Seeing how well the
  194. incremental approach worked at Colorado, he started porting and
  195. adapting the structure of the Colorado course back into the land of
  196. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  197. the course is now about compiling a subset of Racket (and Typed
  198. Racket) to the x86 assembly language. The compiler is implemented in
  199. Racket 7.1~\citep{plt-tr}.
  200. This is the textbook for the incremental version of the compiler
  201. course at Indiana University (Spring 2016 - present) and it is the
  202. first open textbook for an Indiana compiler course. With this book we
  203. hope to make the Indiana compiler course available to people that have
  204. not had the chance to study in Bloomington in person. Many of the
  205. compiler design decisions in this book are drawn from the assignment
  206. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  207. are the most important topics from \cite{Dybvig:2010aa} but we have
  208. omitted topics that we think are less interesting conceptually and we
  209. have made simplifications to reduce complexity. In this way, this
  210. book leans more towards pedagogy than towards the efficiency of the
  211. generated code. Also, the book differs in places where we saw the
  212. opportunity to make the topics more fun, such as in relating register
  213. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  214. \section*{Prerequisites}
  215. The material in this book is challenging but rewarding. It is meant to
  216. prepare students for a lifelong career in programming languages.
  217. The book uses the Racket language both for the implementation of the
  218. compiler and for the language that is compiled, so a student should be
  219. proficient with Racket (or Scheme) prior to reading this book. There
  220. are many excellent resources for learning Scheme and
  221. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  222. is helpful but not necessary for the student to have prior exposure to
  223. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  224. obtain from a computer systems
  225. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  226. parts of x86-64 assembly language that are needed.
  227. %\section*{Structure of book}
  228. % You might want to add short description about each chapter in this book.
  229. %\section*{About the companion website}
  230. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  231. %\begin{itemize}
  232. % \item A link to (freely downlodable) latest version of this document.
  233. % \item Link to download LaTeX source for this document.
  234. % \item Miscellaneous material (e.g. suggested readings etc).
  235. %\end{itemize}
  236. \section*{Acknowledgments}
  237. Many people have contributed to the ideas, techniques, organization,
  238. and teaching of the materials in this book. We especially thank the
  239. following people.
  240. \begin{itemize}
  241. \item Bor-Yuh Evan Chang
  242. \item Kent Dybvig
  243. \item Daniel P. Friedman
  244. \item Ronald Garcia
  245. \item Abdulaziz Ghuloum
  246. \item Jay McCarthy
  247. \item Dipanwita Sarkar
  248. \item Andrew Keep
  249. \item Oscar Waddell
  250. \item Michael Wollowski
  251. \end{itemize}
  252. \mbox{}\\
  253. \noindent Jeremy G. Siek \\
  254. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  255. %\noindent Spring 2016
  256. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  257. \chapter{Preliminaries}
  258. \label{ch:trees-recur}
  259. In this chapter we review the basic tools that are needed to implement
  260. a compiler. Programs are typically input by a programmer as text,
  261. i.e., a sequence of characters. The program-as-text representation is
  262. called \emph{concrete syntax}. We use concrete syntax to concisely
  263. write down and talk about programs. Inside the compiler, we use
  264. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  265. that efficiently supports the operations that the compiler needs to
  266. perform.
  267. %
  268. The translation from concrete syntax to abstract syntax is a process
  269. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  270. and implementation of parsing in this book. A parser is provided in
  271. the supporting materials for translating from concrete syntax to
  272. abstract syntax for the languages used in this book.
  273. ASTs can be represented in many different ways inside the compiler,
  274. depending on the programming language used to write the compiler.
  275. %
  276. We use Racket's \code{struct} feature to represent ASTs
  277. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  278. of programming languages (Section~\ref{sec:grammar}) and pattern
  279. matching to inspect individual nodes in an AST
  280. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  281. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  282. chapter provides an brief introduction to these ideas.
  283. \section{Abstract Syntax Trees and Racket Structures}
  284. \label{sec:ast}
  285. Compilers use abstract syntax trees to represent programs because
  286. compilers often need to ask questions like: for a given part of a
  287. program, what kind of language feature is it? What are the sub-parts
  288. of this part of the program? Consider the program on the left and its
  289. AST on the right. This program is an addition and it has two
  290. sub-parts, a read operation and a negation. The negation has another
  291. sub-part, the integer constant \code{8}. By using a tree to represent
  292. the program, we can easily follow the links to go from one part of a
  293. program to its sub-parts.
  294. \begin{center}
  295. \begin{minipage}{0.4\textwidth}
  296. \begin{lstlisting}
  297. (+ (read) (- 8))
  298. \end{lstlisting}
  299. \end{minipage}
  300. \begin{minipage}{0.4\textwidth}
  301. \begin{equation}
  302. \begin{tikzpicture}
  303. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  304. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  305. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  306. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  307. \draw[->] (plus) to (read);
  308. \draw[->] (plus) to (minus);
  309. \draw[->] (minus) to (8);
  310. \end{tikzpicture}
  311. \label{eq:arith-prog}
  312. \end{equation}
  313. \end{minipage}
  314. \end{center}
  315. We use the standard terminology for trees to describe ASTs: each
  316. circle above is called a \emph{node}. The arrows connect a node to its
  317. \emph{children} (which are also nodes). The top-most node is the
  318. \emph{root}. Every node except for the root has a \emph{parent} (the
  319. node it is the child of). If a node has no children, it is a
  320. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  321. %% Recall that an \emph{symbolic expression} (S-expression) is either
  322. %% \begin{enumerate}
  323. %% \item an atom, or
  324. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  325. %% where $e_1$ and $e_2$ are each an S-expression.
  326. %% \end{enumerate}
  327. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  328. %% null value \code{'()}, etc. We can create an S-expression in Racket
  329. %% simply by writing a backquote (called a quasi-quote in Racket)
  330. %% followed by the textual representation of the S-expression. It is
  331. %% quite common to use S-expressions to represent a list, such as $a, b
  332. %% ,c$ in the following way:
  333. %% \begin{lstlisting}
  334. %% `(a . (b . (c . ())))
  335. %% \end{lstlisting}
  336. %% Each element of the list is in the first slot of a pair, and the
  337. %% second slot is either the rest of the list or the null value, to mark
  338. %% the end of the list. Such lists are so common that Racket provides
  339. %% special notation for them that removes the need for the periods
  340. %% and so many parenthesis:
  341. %% \begin{lstlisting}
  342. %% `(a b c)
  343. %% \end{lstlisting}
  344. %% The following expression creates an S-expression that represents AST
  345. %% \eqref{eq:arith-prog}.
  346. %% \begin{lstlisting}
  347. %% `(+ (read) (- 8))
  348. %% \end{lstlisting}
  349. %% When using S-expressions to represent ASTs, the convention is to
  350. %% represent each AST node as a list and to put the operation symbol at
  351. %% the front of the list. The rest of the list contains the children. So
  352. %% in the above case, the root AST node has operation \code{`+} and its
  353. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  354. %% diagram \eqref{eq:arith-prog}.
  355. %% To build larger S-expressions one often needs to splice together
  356. %% several smaller S-expressions. Racket provides the comma operator to
  357. %% splice an S-expression into a larger one. For example, instead of
  358. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  359. %% we could have first created an S-expression for AST
  360. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  361. %% S-expression.
  362. %% \begin{lstlisting}
  363. %% (define ast1.4 `(- 8))
  364. %% (define ast1.1 `(+ (read) ,ast1.4))
  365. %% \end{lstlisting}
  366. %% In general, the Racket expression that follows the comma (splice)
  367. %% can be any expression that produces an S-expression.
  368. We define a Racket \code{struct} for each kind of node. For this
  369. chapter we require just two kinds of nodes: one for integer constants
  370. and one for primitive operations. The following is the \code{struct}
  371. definition for integer constants.
  372. \begin{lstlisting}
  373. (struct Int (value))
  374. \end{lstlisting}
  375. An integer node includes just one thing: the integer value.
  376. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  377. \begin{lstlisting}
  378. (define eight (Int 8))
  379. \end{lstlisting}
  380. We say that the value created by \code{(Int 8)} is an
  381. \emph{instance} of the \code{Int} structure.
  382. The following is the \code{struct} definition for primitives operations.
  383. \begin{lstlisting}
  384. (struct Prim (op arg*))
  385. \end{lstlisting}
  386. A primitive operation node includes an operator symbol \code{op}
  387. and a list of children \code{arg*}. For example, to create
  388. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  389. \begin{lstlisting}
  390. (define neg-eight (Prim '- (list eight)))
  391. \end{lstlisting}
  392. Primitive operations may have zero or more children. The \code{read}
  393. operator has zero children:
  394. \begin{lstlisting}
  395. (define rd (Prim 'read '()))
  396. \end{lstlisting}
  397. whereas the addition operator has two children:
  398. \begin{lstlisting}
  399. (define ast1.1 (Prim '+ (list rd neg-eight)))
  400. \end{lstlisting}
  401. We have made a design choice regarding the \code{Prim} structure.
  402. Instead of using one structure for many different operations
  403. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  404. structure for each operation, as follows.
  405. \begin{lstlisting}
  406. (struct Read ())
  407. (struct Add (left right))
  408. (struct Neg (value))
  409. \end{lstlisting}
  410. The reason we choose to use just one structure is that in many parts
  411. of the compiler the code for the different primitive operators is the
  412. same, so we might as well just write that code once, which is enabled
  413. by using a single structure.
  414. When compiling a program such as \eqref{eq:arith-prog}, we need to
  415. know that the operation associated with the root node is addition and
  416. we need to be able to access its two children. Racket provides pattern
  417. matching over structures to support these kinds of queries, as we
  418. shall see in Section~\ref{sec:pattern-matching}.
  419. In this book, we often write down the concrete syntax of a program
  420. even when we really have in mind the AST because the concrete syntax
  421. is more concise. We recommend that, in your mind, you always think of
  422. programs as abstract syntax trees.
  423. \section{Grammars}
  424. \label{sec:grammar}
  425. A programming language can be thought of as a \emph{set} of programs.
  426. The set is typically infinite (one can always create larger and larger
  427. programs), so one cannot simply describe a language by listing all of
  428. the programs in the language. Instead we write down a set of rules, a
  429. \emph{grammar}, for building programs. Grammars are often used to
  430. define the concrete syntax of a language, but they can also be used to
  431. describe the abstract syntax. We shall write our rules in a variant of
  432. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  433. example, we describe a small language, named $R_0$, that consists of
  434. integers and arithmetic operations.
  435. The first grammar rule for the abstract syntax of $R_0$ says that an
  436. instance of the \code{Int} structure is an expression:
  437. \begin{equation}
  438. \Exp ::= \INT{\Int} \label{eq:arith-int}
  439. \end{equation}
  440. %
  441. Each rule has a left-hand-side and a right-hand-side. The way to read
  442. a rule is that if you have all the program parts on the
  443. right-hand-side, then you can create an AST node and categorize it
  444. according to the left-hand-side.
  445. %
  446. A name such as $\Exp$ that is
  447. defined by the grammar rules is a \emph{non-terminal}.
  448. %
  449. The name $\Int$ is a also a non-terminal, but instead of defining it
  450. with a grammar rule, we define it with the following explanation. We
  451. make the simplifying design decision that all of the languages in this
  452. book only handle machine-representable integers. On most modern
  453. machines this corresponds to integers represented with 64-bits, i.e.,
  454. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  455. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  456. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  457. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  458. that the sequence of decimals represent an integer in range $-2^{62}$
  459. to $2^{62}-1$.
  460. The second grammar rule is the \texttt{read} operation that receives
  461. an input integer from the user of the program.
  462. \begin{equation}
  463. \Exp ::= \READ{} \label{eq:arith-read}
  464. \end{equation}
  465. The third rule says that, given an $\Exp$ node, you can build another
  466. $\Exp$ node by negating it.
  467. \begin{equation}
  468. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  469. \end{equation}
  470. Symbols in typewriter font such as \key{-} and \key{read} are
  471. \emph{terminal} symbols and must literally appear in the program for
  472. the rule to be applicable.
  473. We can apply the rules to build ASTs in the $R_0$
  474. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  475. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  476. an $\Exp$.
  477. \begin{center}
  478. \begin{minipage}{0.4\textwidth}
  479. \begin{lstlisting}
  480. (Prim '- (list (Int 8)))
  481. \end{lstlisting}
  482. \end{minipage}
  483. \begin{minipage}{0.25\textwidth}
  484. \begin{equation}
  485. \begin{tikzpicture}
  486. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  487. \node[draw, circle] (8) at (0, -1.2) {$8$};
  488. \draw[->] (minus) to (8);
  489. \end{tikzpicture}
  490. \label{eq:arith-neg8}
  491. \end{equation}
  492. \end{minipage}
  493. \end{center}
  494. The next grammar rule defines addition expressions:
  495. \begin{equation}
  496. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  497. \end{equation}
  498. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  499. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  500. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  501. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  502. to show that
  503. \begin{lstlisting}
  504. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  505. \end{lstlisting}
  506. is an $\Exp$ in the $R_0$ language.
  507. If you have an AST for which the above rules do not apply, then the
  508. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  509. is not in $R_0$ because there are no rules for \code{+} with only one
  510. argument, nor for \key{-} with two arguments. Whenever we define a
  511. language with a grammar, the language only includes those programs
  512. that are justified by the rules.
  513. The last grammar rule for $R_0$ states that there is a \code{Program}
  514. node to mark the top of the whole program:
  515. \[
  516. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  517. \]
  518. The \code{Program} structure is defined as follows
  519. \begin{lstlisting}
  520. (struct Program (info body))
  521. \end{lstlisting}
  522. where \code{body} is an expression. In later chapters, the \code{info}
  523. part will be used to store auxiliary information but for now it is
  524. just the empty list.
  525. It is common to have many grammar rules with the same left-hand side
  526. but different right-hand sides, such as the rules for $\Exp$ in the
  527. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  528. combine several right-hand-sides into a single rule.
  529. We collect all of the grammar rules for the abstract syntax of $R_0$
  530. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  531. defined in Figure~\ref{fig:r0-concrete-syntax}.
  532. The \code{read-program} function provided in \code{utilities.rkt} of
  533. the support materials reads a program in from a file (the sequence of
  534. characters in the concrete syntax of Racket) and parses it into an
  535. abstract syntax tree. See the description of \code{read-program} in
  536. Appendix~\ref{appendix:utilities} for more details.
  537. \begin{figure}[tp]
  538. \fbox{
  539. \begin{minipage}{0.96\textwidth}
  540. \[
  541. \begin{array}{rcl}
  542. \begin{array}{rcl}
  543. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)
  544. \mid (\key{-}\;\Exp\;\Exp) \\
  545. R_0 &::=& \Exp
  546. \end{array}
  547. \end{array}
  548. \]
  549. \end{minipage}
  550. }
  551. \caption{The concrete syntax of $R_0$.}
  552. \label{fig:r0-concrete-syntax}
  553. \end{figure}
  554. \begin{figure}[tp]
  555. \fbox{
  556. \begin{minipage}{0.96\textwidth}
  557. \[
  558. \begin{array}{rcl}
  559. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  560. &\mid& \ADD{\Exp}{\Exp} \\
  561. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  562. \end{array}
  563. \]
  564. \end{minipage}
  565. }
  566. \caption{The abstract syntax of $R_0$.}
  567. \label{fig:r0-syntax}
  568. \end{figure}
  569. \section{Pattern Matching}
  570. \label{sec:pattern-matching}
  571. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  572. the parts of an AST node. Racket provides the \texttt{match} form to
  573. access the parts of a structure. Consider the following example and
  574. the output on the right.
  575. \begin{center}
  576. \begin{minipage}{0.5\textwidth}
  577. \begin{lstlisting}
  578. (match ast1.1
  579. [(Prim op (list child1 child2))
  580. (print op)])
  581. \end{lstlisting}
  582. \end{minipage}
  583. \vrule
  584. \begin{minipage}{0.25\textwidth}
  585. \begin{lstlisting}
  586. '+
  587. \end{lstlisting}
  588. \end{minipage}
  589. \end{center}
  590. In the above example, the \texttt{match} form takes the AST
  591. \eqref{eq:arith-prog} and binds its parts to the three pattern
  592. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  593. general, a match clause consists of a \emph{pattern} and a
  594. \emph{body}. Patterns are recursively defined to be either a pattern
  595. variable, a structure name followed by a pattern for each of the
  596. structure's arguments, or an S-expression (symbols, lists, etc.).
  597. (See Chapter 12 of The Racket
  598. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  599. and Chapter 9 of The Racket
  600. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  601. for a complete description of \code{match}.)
  602. %
  603. The body of a match clause may contain arbitrary Racket code. The
  604. pattern variables can be used in the scope of the body.
  605. A \code{match} form may contain several clauses, as in the following
  606. function \code{leaf?} that recognizes when an $R_0$ node is
  607. a leaf. The \code{match} proceeds through the clauses in order,
  608. checking whether the pattern can match the input AST. The
  609. body of the first clause that matches is executed. The output of
  610. \code{leaf?} for several ASTs is shown on the right.
  611. \begin{center}
  612. \begin{minipage}{0.6\textwidth}
  613. \begin{lstlisting}
  614. (define (leaf? arith)
  615. (match arith
  616. [(Int n) #t]
  617. [(Prim 'read '()) #t]
  618. [(Prim '- (list c1)) #f]
  619. [(Prim '+ (list c1 c2)) #f]))
  620. (leaf? (Prim 'read '()))
  621. (leaf? (Prim '- (list (Int 8))))
  622. (leaf? (Int 8))
  623. \end{lstlisting}
  624. \end{minipage}
  625. \vrule
  626. \begin{minipage}{0.25\textwidth}
  627. \begin{lstlisting}
  628. #t
  629. #f
  630. #t
  631. \end{lstlisting}
  632. \end{minipage}
  633. \end{center}
  634. When writing a \code{match}, we refer to the grammar definition to
  635. identify which non-terminal we are expecting to match against, then we
  636. make sure that 1) we have one clause for each alternative of that
  637. non-terminal and 2) that the pattern in each clause corresponds to the
  638. corresponding right-hand side of a grammar rule. For the \code{match}
  639. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  640. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  641. alternatives, so the \code{match} has 4 clauses. The pattern in each
  642. clause corresponds to the right-hand side of a grammar rule. For
  643. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  644. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  645. patterns, replace non-terminals such as $\Exp$ with pattern variables
  646. of your choice (e.g. \code{c1} and \code{c2}).
  647. \section{Recursion}
  648. \label{sec:recursion}
  649. Programs are inherently recursive. For example, an $R_0$ expression is
  650. often made of smaller expressions. Thus, the natural way to process an
  651. entire program is with a recursive function. As a first example of
  652. such a recursive function, we define \texttt{exp?} below, which takes
  653. an arbitrary value and determines whether or not it is an $R_0$
  654. expression.
  655. %
  656. When a recursive function is defined using a sequence of match clauses
  657. that correspond to a grammar, and the body of each clause makes a
  658. recursive call on each child node, then we say the function is defined
  659. by \emph{structural recursion}\footnote{This principle of structuring
  660. code according to the data definition is advocated in the book
  661. \emph{How to Design Programs}
  662. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  663. define a second function, named \code{R0?}, that determines whether a
  664. value is an $R_0$ program. In general we can expect to write one
  665. recursive function to handle each non-terminal in a grammar.
  666. %
  667. \begin{center}
  668. \begin{minipage}{0.7\textwidth}
  669. \begin{lstlisting}
  670. (define (exp? ast)
  671. (match ast
  672. [(Int n) #t]
  673. [(Prim 'read '()) #t]
  674. [(Prim '- (list e)) (exp? e)]
  675. [(Prim '+ (list e1 e2))
  676. (and (exp? e1) (exp? e2))]
  677. [else #f]))
  678. (define (R0? ast)
  679. (match ast
  680. [(Program '() e) (exp? e)]
  681. [else #f]))
  682. (R0? (Program '() ast1.1)
  683. (R0? (Program '()
  684. (Prim '- (list (Prim 'read '())
  685. (Prim '+ (list (Num 8)))))))
  686. \end{lstlisting}
  687. \end{minipage}
  688. \vrule
  689. \begin{minipage}{0.25\textwidth}
  690. \begin{lstlisting}
  691. #t
  692. #f
  693. \end{lstlisting}
  694. \end{minipage}
  695. \end{center}
  696. You may be tempted to merge the two functions into one, like this:
  697. \begin{center}
  698. \begin{minipage}{0.5\textwidth}
  699. \begin{lstlisting}
  700. (define (R0? ast)
  701. (match ast
  702. [(Int n) #t]
  703. [(Prim 'read '()) #t]
  704. [(Prim '- (list e)) (R0? e)]
  705. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  706. [(Program '() e) (R0? e)]
  707. [else #f]))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \end{center}
  711. %
  712. Sometimes such a trick will save a few lines of code, especially when
  713. it comes to the \code{Program} wrapper. Yet this style is generally
  714. \emph{not} recommended because it can get you into trouble.
  715. %
  716. For example, the above function is subtly wrong:
  717. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  718. will return true, when it should return false.
  719. %% NOTE FIXME - must check for consistency on this issue throughout.
  720. \section{Interpreters}
  721. \label{sec:interp-R0}
  722. The meaning, or semantics, of a program is typically defined in the
  723. specification of the language. For example, the Scheme language is
  724. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  725. defined in its reference manual~\citep{plt-tr}. In this book we use an
  726. interpreter to define the meaning of each language that we consider,
  727. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  728. interpreter that is designated (by some people) as the definition of a
  729. language is called a \emph{definitional interpreter}. We warm up by
  730. creating a definitional interpreter for the $R_0$ language, which
  731. serves as a second example of structural recursion. The
  732. \texttt{interp-R0} function is defined in
  733. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  734. input program followed by a call to the \lstinline{interp-exp} helper
  735. function, which in turn has one match clause per grammar rule for
  736. $R_0$ expressions.
  737. \begin{figure}[tbp]
  738. \begin{lstlisting}
  739. (define (interp-exp e)
  740. (match e
  741. [(Int n) n]
  742. [(Prim 'read '())
  743. (define r (read))
  744. (cond [(fixnum? r) r]
  745. [else (error 'interp-R1 "expected an integer" r)])]
  746. [(Prim '- (list e))
  747. (define v (interp-exp e))
  748. (fx- 0 v)]
  749. [(Prim '+ (list e1 e2))
  750. (define v1 (interp-exp e1))
  751. (define v2 (interp-exp e2))
  752. (fx+ v1 v2)]
  753. )))
  754. (define (interp-R0 p)
  755. (match p
  756. [(Program '() e) (interp-exp e)]
  757. ))
  758. \end{lstlisting}
  759. \caption{Interpreter for the $R_0$ language.}
  760. \label{fig:interp-R0}
  761. \end{figure}
  762. Let us consider the result of interpreting a few $R_0$ programs. The
  763. following program adds two integers.
  764. \begin{lstlisting}
  765. (+ 10 32)
  766. \end{lstlisting}
  767. The result is \key{42}. We wrote the above program in concrete syntax,
  768. whereas the parsed abstract syntax is:
  769. \begin{lstlisting}
  770. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  771. \end{lstlisting}
  772. The next example demonstrates that expressions may be nested within
  773. each other, in this case nesting several additions and negations.
  774. \begin{lstlisting}
  775. (+ 10 (- (+ 12 20)))
  776. \end{lstlisting}
  777. What is the result of the above program?
  778. As mentioned previously, the $R_0$ language does not support
  779. arbitrarily-large integers, but only $63$-bit integers, so we
  780. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  781. in Racket.
  782. Suppose
  783. \[
  784. n = 999999999999999999
  785. \]
  786. which indeed fits in $63$-bits. What happens when we run the
  787. following program in our interpreter?
  788. \begin{lstlisting}
  789. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  790. \end{lstlisting}
  791. It produces an error:
  792. \begin{lstlisting}
  793. fx+: result is not a fixnum
  794. \end{lstlisting}
  795. We establish the convention that if running the definitional
  796. interpreter on a program produces an error, then the meaning of that
  797. program is \emph{unspecified}. That means a compiler for the language
  798. is under no obligations regarding that program; it may or may not
  799. produce an executable, and if it does, that executable can do
  800. anything. This convention applies to the languages defined in this
  801. book, as a way to simplify the student's task of implementing them,
  802. but this convention is not applicable to all programming languages.
  803. Moving on to the last feature of the $R_0$ language, the \key{read}
  804. operation prompts the user of the program for an integer. Recall that
  805. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  806. \code{8}. So if we run
  807. \begin{lstlisting}
  808. (interp-R0 ast1.1)
  809. \end{lstlisting}
  810. and if the input is \code{50}, then we get the answer to life, the
  811. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  812. Guide to the Galaxy} by Douglas Adams.}
  813. We include the \key{read} operation in $R_0$ so a clever student
  814. cannot implement a compiler for $R_0$ that simply runs the interpreter
  815. during compilation to obtain the output and then generates the trivial
  816. code to produce the output. (Yes, a clever student did this in the
  817. first instance of this course.)
  818. The job of a compiler is to translate a program in one language into a
  819. program in another language so that the output program behaves the
  820. same way as the input program does according to its definitional
  821. interpreter. This idea is depicted in the following diagram. Suppose
  822. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  823. interpreter for each language. Suppose that the compiler translates
  824. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  825. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  826. respective interpreters with input $i$ should yield the same output
  827. $o$.
  828. \begin{equation} \label{eq:compile-correct}
  829. \begin{tikzpicture}[baseline=(current bounding box.center)]
  830. \node (p1) at (0, 0) {$P_1$};
  831. \node (p2) at (3, 0) {$P_2$};
  832. \node (o) at (3, -2.5) {$o$};
  833. \path[->] (p1) edge [above] node {compile} (p2);
  834. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  835. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  836. \end{tikzpicture}
  837. \end{equation}
  838. In the next section we see our first example of a compiler.
  839. \section{Example Compiler: a Partial Evaluator}
  840. \label{sec:partial-evaluation}
  841. In this section we consider a compiler that translates $R_0$ programs
  842. into $R_0$ programs that may be more efficient, that is, this compiler
  843. is an optimizer. This optimizer eagerly computes the parts of the
  844. program that do not depend on any inputs, a process known as
  845. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  846. following program
  847. \begin{lstlisting}
  848. (+ (read) (- (+ 5 3)))
  849. \end{lstlisting}
  850. our compiler will translate it into the program
  851. \begin{lstlisting}
  852. (+ (read) -8)
  853. \end{lstlisting}
  854. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  855. evaluator for the $R_0$ language. The output of the partial evaluator
  856. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  857. recursion over $\Exp$ is captured in the \code{pe-exp} function
  858. whereas the code for partially evaluating the negation and addition
  859. operations is factored into two separate helper functions:
  860. \code{pe-neg} and \code{pe-add}. The input to these helper
  861. functions is the output of partially evaluating the children.
  862. \begin{figure}[tbp]
  863. \begin{lstlisting}
  864. (define (pe-neg r)
  865. (match r
  866. [(Int n) (Int (fx- 0 n))]
  867. [else (Prim '- (list r))]))
  868. (define (pe-add r1 r2)
  869. (match* (r1 r2)
  870. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  871. [(_ _) (Prim '+ (list r1 r2))]))
  872. (define (pe-exp e)
  873. (match e
  874. [(Int n) (Int n)]
  875. [(Prim 'read '()) (Prim 'read '())]
  876. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  877. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  878. ))
  879. (define (pe-R0 p)
  880. (match p
  881. [(Program info e) (Program info (pe-exp e))]
  882. ))
  883. \end{lstlisting}
  884. \caption{A partial evaluator for $R_0$ expressions.}
  885. \label{fig:pe-arith}
  886. \end{figure}
  887. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  888. arguments are integers and if they are, perform the appropriate
  889. arithmetic. Otherwise, they create an AST node for the operation
  890. (either negation or addition).
  891. To gain some confidence that the partial evaluator is correct, we can
  892. test whether it produces programs that get the same result as the
  893. input programs. That is, we can test whether it satisfies Diagram
  894. \eqref{eq:compile-correct}. The following code runs the partial
  895. evaluator on several examples and tests the output program. The
  896. \texttt{parse-program} and \texttt{assert} functions are defined in
  897. Appendix~\ref{appendix:utilities}.\\
  898. \begin{minipage}{1.0\textwidth}
  899. \begin{lstlisting}
  900. (define (test-pe p)
  901. (assert "testing pe-R0"
  902. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  903. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  904. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  905. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  906. \end{lstlisting}
  907. \end{minipage}
  908. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  909. \chapter{Integers and Variables}
  910. \label{ch:int-exp}
  911. This chapter is about compiling the subset of Racket that includes
  912. integer arithmetic and local variable binding, which we name $R_1$, to
  913. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  914. to x86-64 simply as x86. The chapter begins with a description of the
  915. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  916. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  917. discuss only what is needed for compiling $R_1$. We introduce more of
  918. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  919. reflect on their differences and come up with a plan to break down the
  920. translation from $R_1$ to x86 into a handful of steps
  921. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  922. chapter give detailed hints regarding each step
  923. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  924. to give enough hints that the well-prepared reader, together with a
  925. few friends, can implement a compiler from $R_1$ to x86 in a couple
  926. weeks while at the same time leaving room for some fun and creativity.
  927. To give the reader a feeling for the scale of this first compiler, the
  928. instructor solution for the $R_1$ compiler is less than 500 lines of
  929. code.
  930. \section{The $R_1$ Language}
  931. \label{sec:s0}
  932. The $R_1$ language extends the $R_0$ language with variable
  933. definitions. The concrete syntax of the $R_1$ language is defined by
  934. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  935. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  936. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  937. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  938. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  939. \key{Program} struct to mark the top of the program.
  940. %% The $\itm{info}$
  941. %% field of the \key{Program} structure contains an \emph{association
  942. %% list} (a list of key-value pairs) that is used to communicate
  943. %% auxiliary data from one compiler pass the next.
  944. Despite the simplicity of the $R_1$ language, it is rich enough to
  945. exhibit several compilation techniques.
  946. \begin{figure}[btp]
  947. \centering
  948. \fbox{
  949. \begin{minipage}{0.96\textwidth}
  950. \[
  951. \begin{array}{rcl}
  952. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)
  953. \mid (\key{-}\;\Exp\;\Exp) \\
  954. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  955. R_1 &::=& \Exp
  956. \end{array}
  957. \]
  958. \end{minipage}
  959. }
  960. \caption{The concrete syntax of $R_1$.}
  961. \label{fig:r1-concrete-syntax}
  962. \end{figure}
  963. \begin{figure}[btp]
  964. \centering
  965. \fbox{
  966. \begin{minipage}{0.96\textwidth}
  967. \[
  968. \begin{array}{rcl}
  969. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  970. &\mid& \ADD{\Exp}{\Exp}
  971. \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  972. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  973. \end{array}
  974. \]
  975. \end{minipage}
  976. }
  977. \caption{The abstract syntax of $R_1$.}
  978. \label{fig:r1-syntax}
  979. \end{figure}
  980. Let us dive further into the syntax and semantics of the $R_1$
  981. language. The \key{Let} feature defines a variable for use within its
  982. body and initializes the variable with the value of an expression.
  983. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  984. The concrete syntax for \key{Let} is
  985. \begin{lstlisting}
  986. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  987. \end{lstlisting}
  988. For example, the following program initializes \code{x} to $32$ and then
  989. evaluates the body \code{(+ 10 x)}, producing $42$.
  990. \begin{lstlisting}
  991. (let ([x (+ 12 20)]) (+ 10 x))
  992. \end{lstlisting}
  993. When there are multiple \key{let}'s for the same variable, the closest
  994. enclosing \key{let} is used. That is, variable definitions overshadow
  995. prior definitions. Consider the following program with two \key{let}'s
  996. that define variables named \code{x}. Can you figure out the result?
  997. \begin{lstlisting}
  998. (let ([x 32]) (+ (let ([x 10]) x) x))
  999. \end{lstlisting}
  1000. For the purposes of depicting which variable uses correspond to which
  1001. definitions, the following shows the \code{x}'s annotated with
  1002. subscripts to distinguish them. Double check that your answer for the
  1003. above is the same as your answer for this annotated version of the
  1004. program.
  1005. \begin{lstlisting}
  1006. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1007. \end{lstlisting}
  1008. The initializing expression is always evaluated before the body of the
  1009. \key{let}, so in the following, the \key{read} for \code{x} is
  1010. performed before the \key{read} for \code{y}. Given the input
  1011. $52$ then $10$, the following produces $42$ (not $-42$).
  1012. \begin{lstlisting}
  1013. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1014. \end{lstlisting}
  1015. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1016. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1017. \key{match} clauses for variables and for \key{let}. For \key{let},
  1018. we need a way to communicate the value of a variable to all the uses
  1019. of a variable. To accomplish this, we maintain a mapping from
  1020. variables to values, which is called an \emph{environment}. For
  1021. simplicity, here we use an association list to represent the
  1022. environment. The \code{interp-R1} function takes the current
  1023. environment, \code{env}, as an extra parameter. When the interpreter
  1024. encounters a variable, it finds the corresponding value using the
  1025. \code{dict-ref} function from the \code{racket/dict} package. When
  1026. the interpreter encounters a \key{Let}, it evaluates the initializing
  1027. expression, extends the environment with the result value bound to the
  1028. variable (using \code{dict-set}), then evaluates the body of the
  1029. \key{Let}.
  1030. \begin{figure}[tbp]
  1031. \begin{lstlisting}
  1032. (define (interp-exp env)
  1033. (lambda (e)
  1034. (match e
  1035. [(Int n) n]
  1036. [(Prim 'read '())
  1037. (define r (read))
  1038. (cond [(fixnum? r) r]
  1039. [else (error 'interp-R1 "expected an integer" r)])]
  1040. [(Prim '- (list e))
  1041. (define v ((interp-exp env) e))
  1042. (fx- 0 v)]
  1043. [(Prim '+ (list e1 e2))
  1044. (define v1 ((interp-exp env) e1))
  1045. (define v2 ((interp-exp env) e2))
  1046. (fx+ v1 v2)]
  1047. [(Var x) (dict-ref env x)]
  1048. [(Let x e body)
  1049. (define new-env (dict-set env x ((interp-exp env) e)))
  1050. ((interp-exp new-env) body)]
  1051. )))
  1052. (define (interp-R1 p)
  1053. (match p
  1054. [(Program info e) ((interp-exp '()) e)]
  1055. ))
  1056. \end{lstlisting}
  1057. \caption{Interpreter for the $R_1$ language.}
  1058. \label{fig:interp-R1}
  1059. \end{figure}
  1060. The goal for this chapter is to implement a compiler that translates
  1061. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1062. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1063. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1064. is, they both output the same integer $n$. We depict this correctness
  1065. criteria in the following diagram.
  1066. \[
  1067. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1068. \node (p1) at (0, 0) {$P_1$};
  1069. \node (p2) at (4, 0) {$P_2$};
  1070. \node (o) at (4, -2) {$n$};
  1071. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1072. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1073. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1074. \end{tikzpicture}
  1075. \]
  1076. In the next section we introduce enough of the x86 assembly
  1077. language to compile $R_1$.
  1078. \section{The x86 Assembly Language}
  1079. \label{sec:x86}
  1080. Figure~\ref{fig:x86-a} defines the concrete syntax for the subset of
  1081. the x86 assembly language needed for this chapter.
  1082. %
  1083. An x86 program is a sequence of instructions. The program is stored in
  1084. the computer's memory and the computer has a \emph{program counter}
  1085. that points to the address of the next instruction to be executed. For
  1086. most instructions, once the instruction is executed, the program
  1087. counter is incremented to point to the immediately following
  1088. instruction in memory. Most x86 instructions take two operands, where
  1089. each operand is either an integer constant (called \emph{immediate
  1090. value}), a \emph{register}, or a \emph{memory} location. A register
  1091. is a special kind of variable. Each one holds a 64-bit value; there
  1092. are 16 registers in the computer and their names are given in
  1093. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  1094. addresses to 64-bit values%
  1095. \footnote{This simple story suffices for describing how sequential
  1096. programs access memory but is not sufficient for multi-threaded
  1097. programs. However, multi-threaded execution is beyond the scope of
  1098. this book.}.
  1099. %
  1100. We use the AT\&T syntax expected by the GNU assembler, which comes
  1101. with the \key{gcc} compiler that we use for compiling assembly code to
  1102. machine code.
  1103. %
  1104. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1105. the x86 instructions used in this book.
  1106. % to do: finish treatment of imulq
  1107. % it's needed for vector's in R6/R7
  1108. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1109. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1110. && \key{r8} \mid \key{r9} \mid \key{r10}
  1111. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1112. \mid \key{r14} \mid \key{r15}}
  1113. \begin{figure}[tp]
  1114. \fbox{
  1115. \begin{minipage}{0.96\textwidth}
  1116. \[
  1117. \begin{array}{lcl}
  1118. \Reg &::=& \allregisters{} \\
  1119. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1120. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1121. \key{subq} \; \Arg\key{,} \Arg \mid
  1122. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1123. && \key{callq} \; \mathit{label} \mid
  1124. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1125. \Prog &::= & \key{.globl main}\\
  1126. & & \key{main:} \; \Instr^{+}
  1127. \end{array}
  1128. \]
  1129. \end{minipage}
  1130. }
  1131. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1132. \label{fig:x86-a}
  1133. \end{figure}
  1134. An immediate value is written using the notation \key{\$}$n$ where $n$
  1135. is an integer.
  1136. %
  1137. A register is written with a \key{\%} followed by the register name,
  1138. such as \key{\%rax}.
  1139. %
  1140. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1141. which obtains the address stored in register $r$ and then adds $n$
  1142. bytes to the address. The resulting address is used to either load or
  1143. store to memory depending on whether it occurs as a source or
  1144. destination argument of an instruction.
  1145. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1146. source $s$ and destination $d$, applies the arithmetic operation, then
  1147. writes the result back to the destination $d$.
  1148. %
  1149. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1150. stores the result in $d$.
  1151. %
  1152. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1153. specified by the label. We discuss procedure calls in more detail
  1154. later in this chapter and in Chapter~\ref{ch:functions}.
  1155. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1156. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1157. \key{main} procedure is externally visible, which is necessary so
  1158. that the operating system can call it. The label \key{main:}
  1159. indicates the beginning of the \key{main} procedure which is where
  1160. the operating system starts executing this program. The instruction
  1161. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1162. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1163. $10$ in \key{rax} and puts the result, $42$, back into
  1164. \key{rax}.
  1165. %
  1166. The last instruction, \key{retq}, finishes the \key{main} function by
  1167. returning the integer in \key{rax} to the operating system. The
  1168. operating system interprets this integer as the program's exit
  1169. code. By convention, an exit code of 0 indicates that a program
  1170. completed successfully, and all other exit codes indicate various
  1171. errors. Nevertheless, we return the result of the program as the exit
  1172. code.
  1173. %\begin{wrapfigure}{r}{2.25in}
  1174. \begin{figure}[tbp]
  1175. \begin{lstlisting}
  1176. .globl main
  1177. main:
  1178. movq $10, %rax
  1179. addq $32, %rax
  1180. retq
  1181. \end{lstlisting}
  1182. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1183. \label{fig:p0-x86}
  1184. %\end{wrapfigure}
  1185. \end{figure}
  1186. Unfortunately, x86 varies in a couple ways depending on what operating
  1187. system it is assembled in. The code examples shown here are correct on
  1188. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1189. labels like \key{main} must be prefixed with an underscore, as in
  1190. \key{\_main}.
  1191. We exhibit the use of memory for storing intermediate results in the
  1192. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1193. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1194. region of memory called the \emph{procedure call stack} (or
  1195. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1196. for each procedure call. The memory layout for an individual frame is
  1197. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1198. \emph{stack pointer} and points to the item at the top of the
  1199. stack. The stack grows downward in memory, so we increase the size of
  1200. the stack by subtracting from the stack pointer. Some operating
  1201. systems require the frame size to be a multiple of 16 bytes. In the
  1202. context of a procedure call, the \emph{return address} is the next
  1203. instruction after the call instruction on the caller side. During a
  1204. function call, the return address is pushed onto the stack. The
  1205. register \key{rbp} is the \emph{base pointer} which serves two
  1206. purposes: 1) it saves the location of the stack pointer for the
  1207. calling procedure and 2) it is used to access variables associated
  1208. with the current procedure. The base pointer of the calling procedure
  1209. is pushed onto the stack after the return address. We number the
  1210. variables from $1$ to $n$. Variable $1$ is stored at address
  1211. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1212. \begin{figure}[tbp]
  1213. \begin{lstlisting}
  1214. start:
  1215. movq $10, -8(%rbp)
  1216. negq -8(%rbp)
  1217. movq -8(%rbp), %rax
  1218. addq $52, %rax
  1219. jmp conclusion
  1220. .globl main
  1221. main:
  1222. pushq %rbp
  1223. movq %rsp, %rbp
  1224. subq $16, %rsp
  1225. jmp start
  1226. conclusion:
  1227. addq $16, %rsp
  1228. popq %rbp
  1229. retq
  1230. \end{lstlisting}
  1231. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1232. \label{fig:p1-x86}
  1233. \end{figure}
  1234. \begin{figure}[tbp]
  1235. \centering
  1236. \begin{tabular}{|r|l|} \hline
  1237. Position & Contents \\ \hline
  1238. 8(\key{\%rbp}) & return address \\
  1239. 0(\key{\%rbp}) & old \key{rbp} \\
  1240. -8(\key{\%rbp}) & variable $1$ \\
  1241. -16(\key{\%rbp}) & variable $2$ \\
  1242. \ldots & \ldots \\
  1243. 0(\key{\%rsp}) & variable $n$\\ \hline
  1244. \end{tabular}
  1245. \caption{Memory layout of a frame.}
  1246. \label{fig:frame}
  1247. \end{figure}
  1248. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1249. three instructions are the typical \emph{prelude} for a procedure.
  1250. The instruction \key{pushq \%rbp} saves the base pointer for the
  1251. caller onto the stack and subtracts $8$ from the stack pointer. The
  1252. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1253. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1254. stack pointer down to make enough room for storing variables. This
  1255. program needs one variable ($8$ bytes) but because the frame size is
  1256. required to be a multiple of 16 bytes, the space for variables is
  1257. rounded to 16 bytes.
  1258. The four instructions under the label \code{start} carry out the work
  1259. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1260. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1261. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1262. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1263. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1264. \key{rax}, at which point \key{rax} contains $42$.
  1265. The three instructions under the label \code{conclusion} are the
  1266. typical \emph{finale} of a procedure. The first two instructions are
  1267. necessary to get the state of the machine back to where it was at the
  1268. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1269. moves the stack pointer back to point at the old base pointer. The
  1270. amount added here needs to match the amount that was subtracted in the
  1271. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1272. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1273. instruction, \key{retq}, jumps back to the procedure that called this
  1274. one and adds 8 to the stack pointer, which returns the stack pointer
  1275. to where it was prior to the procedure call.
  1276. The compiler will need a convenient representation for manipulating
  1277. x86 programs, so we define an abstract syntax for x86 in
  1278. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1279. a subscript $0$ because later we introduce extended versions of this
  1280. assembly language. The main difference compared to the concrete syntax
  1281. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1282. instructions to appear anywhere, but instead organizes instructions
  1283. into groups called \emph{blocks} and associates a label with every
  1284. block, which is why the \key{CFG} struct (for control-flow graph)
  1285. includes an association list mapping labels to blocks. The reason for
  1286. this organization becomes apparent in Chapter~\ref{ch:bool-types} when
  1287. we introduce conditional branching.
  1288. \begin{figure}[tp]
  1289. \fbox{
  1290. \begin{minipage}{0.96\textwidth}
  1291. \small
  1292. \[
  1293. \begin{array}{lcl}
  1294. \Reg &::=& \allregisters{} \\
  1295. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1296. \mid \DEREF{\Reg}{\Int} \\
  1297. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1298. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1299. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1300. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1301. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1302. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \\
  1303. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1304. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1305. \end{array}
  1306. \]
  1307. \end{minipage}
  1308. }
  1309. \caption{Abstract syntax of $x86_0$ assembly.}
  1310. \label{fig:x86-ast-a}
  1311. \end{figure}
  1312. \section{Planning the trip to x86 via the $C_0$ language}
  1313. \label{sec:plan-s0-x86}
  1314. To compile one language to another it helps to focus on the
  1315. differences between the two languages because the compiler will need
  1316. to bridge those differences. What are the differences between $R_1$
  1317. and x86 assembly? Here are some of the most important ones:
  1318. \begin{enumerate}
  1319. \item[(a)] x86 arithmetic instructions typically have two arguments
  1320. and update the second argument in place. In contrast, $R_1$
  1321. arithmetic operations take two arguments and produce a new value.
  1322. An x86 instruction may have at most one memory-accessing argument.
  1323. Furthermore, some instructions place special restrictions on their
  1324. arguments.
  1325. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1326. whereas x86 instructions restrict their arguments to be integers
  1327. constants, registers, and memory locations.
  1328. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1329. sequence of instructions and jumps to labeled positions, whereas in
  1330. $R_1$ the order of evaluation is a left-to-right depth-first
  1331. traversal of the abstract syntax tree.
  1332. \item[(d)] An $R_1$ program can have any number of variables whereas
  1333. x86 has 16 registers and the procedure calls stack.
  1334. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1335. same name. The registers and memory locations of x86 all have unique
  1336. names or addresses.
  1337. \end{enumerate}
  1338. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1339. the problem into several steps, dealing with the above differences one
  1340. at a time. Each of these steps is called a \emph{pass} of the
  1341. compiler.
  1342. %
  1343. This terminology comes from each step traverses (i.e. passes over) the
  1344. AST of the program.
  1345. %
  1346. We begin by sketching how we might implement each pass, and give them
  1347. names. We then figure out an ordering of the passes and the
  1348. input/output language for each pass. The very first pass has $R_1$ as
  1349. its input language and the last pass has x86 as its output
  1350. language. In between we can choose whichever language is most
  1351. convenient for expressing the output of each pass, whether that be
  1352. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1353. Finally, to implement each pass we write one recursive function per
  1354. non-terminal in the grammar of the input language of the pass.
  1355. \begin{description}
  1356. \item[Pass \key{select-instructions}] To handle the difference between
  1357. $R_1$ operations and x86 instructions we convert each $R_1$
  1358. operation to a short sequence of instructions that accomplishes the
  1359. same task.
  1360. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1361. subexpression (i.e. operator and operand, and hence the name
  1362. \key{opera*}) is an \emph{atomic} expression (a variable or
  1363. integer), we introduce temporary variables to hold the results
  1364. of subexpressions.
  1365. \item[Pass \key{explicate-control}] To make the execution order of the
  1366. program explicit, we convert from the abstract syntax tree
  1367. representation into a \emph{control-flow graph} in which each node
  1368. contains a sequence of statements and the edges between nodes say
  1369. where to go at the end of the sequence.
  1370. \item[Pass \key{assign-homes}] To handle the difference between the
  1371. variables in $R_1$ versus the registers and stack locations in x86,
  1372. we assignment of each variable to a register or stack location.
  1373. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1374. by renaming every variable to a unique name, so that shadowing no
  1375. longer occurs.
  1376. \end{description}
  1377. The next question is: in what order should we apply these passes? This
  1378. question can be challenging because it is difficult to know ahead of
  1379. time which orders will be better (easier to implement, produce more
  1380. efficient code, etc.) so oftentimes trial-and-error is
  1381. involved. Nevertheless, we can try to plan ahead and make educated
  1382. choices regarding the ordering.
  1383. Let us consider the ordering of \key{uniquify} and
  1384. \key{remove-complex-opera*}. The assignment of subexpressions to
  1385. temporary variables involves introducing new variables and moving
  1386. subexpressions, which might change the shadowing of variables and
  1387. inadvertently change the behavior of the program. But if we apply
  1388. \key{uniquify} first, this will not be an issue. Of course, this means
  1389. that in \key{remove-complex-opera*}, we need to ensure that the
  1390. temporary variables that it creates are unique.
  1391. What should be the ordering of \key{explicate-control} with respect to
  1392. \key{uniquify}? The \key{uniquify} pass should come first because
  1393. \key{explicate-control} changes all the \key{let}-bound variables to
  1394. become local variables whose scope is the entire program, which would
  1395. confuse variables with the same name.
  1396. %
  1397. Likewise, we place \key{explicate-control} after
  1398. \key{remove-complex-opera*} because \key{explicate-control} removes
  1399. the \key{let} form, but it is convenient to use \key{let} in the
  1400. output of \key{remove-complex-opera*}.
  1401. %
  1402. Regarding \key{assign-homes}, it is helpful to place
  1403. \key{explicate-control} first because \key{explicate-control} changes
  1404. \key{let}-bound variables into program-scope variables. This means
  1405. that the \key{assign-homes} pass can read off the variables from the
  1406. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1407. entire program in search of \key{let}-bound variables.
  1408. Last, we need to decide on the ordering of \key{select-instructions}
  1409. and \key{assign-homes}. These two passes are intertwined, creating a
  1410. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1411. have already determined which instructions will be used, because x86
  1412. instructions have restrictions about which of their arguments can be
  1413. registers versus stack locations. One might want to give preferential
  1414. treatment to variables that occur in register-argument positions. On
  1415. the other hand, it may turn out to be impossible to make sure that all
  1416. such variables are assigned to registers, and then one must redo the
  1417. selection of instructions. Some compilers handle this problem by
  1418. iteratively repeating these two passes until a good solution is found.
  1419. We shall use a simpler approach in which \key{select-instructions}
  1420. comes first, followed by the \key{assign-homes}, then a third
  1421. pass named \key{patch-instructions} that uses a reserved register to
  1422. patch-up outstanding problems regarding instructions with too many
  1423. memory accesses. The disadvantage of this approach is some programs
  1424. may not execute as efficiently as they would if we used the iterative
  1425. approach and used all of the registers for variables.
  1426. \begin{figure}[tbp]
  1427. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1428. \node (R1) at (0,2) {\large $R_1$};
  1429. \node (R1-2) at (3,2) {\large $R_1$};
  1430. \node (R1-3) at (6,2) {\large $R_1$};
  1431. %\node (C0-1) at (6,0) {\large $C_0$};
  1432. \node (C0-2) at (3,0) {\large $C_0$};
  1433. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1434. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1435. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1436. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1437. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1438. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1439. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1440. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1441. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1442. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1443. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1444. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1445. \end{tikzpicture}
  1446. \caption{Overview of the passes for compiling $R_1$. }
  1447. \label{fig:R1-passes}
  1448. \end{figure}
  1449. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1450. passes in the form of a graph. Each pass is an edge and the
  1451. input/output language of each pass is a node in the graph. The output
  1452. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1453. are still in the $R_1$ language, but the output of the pass
  1454. \key{explicate-control} is in a different language $C_0$ that is
  1455. designed to make the order of evaluation explicit in its syntax, which
  1456. we introduce in the next section. The \key{select-instruction} pass
  1457. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1458. \key{patch-instructions} passes input and output variants of x86
  1459. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1460. \key{print-x86}, which converts from the abstract syntax of
  1461. $\text{x86}_0$ to the concrete syntax of x86.
  1462. In the next sections we discuss the $C_0$ language and the
  1463. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1464. remainder of this chapter gives hints regarding the implementation of
  1465. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1466. \subsection{The $C_0$ Intermediate Language}
  1467. The output of \key{explicate-control} is similar to the $C$
  1468. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1469. categories for expressions and statements, so we name it $C_0$. The
  1470. concrete syntax for $C_0$ is defined in
  1471. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1472. is defined in Figure~\ref{fig:c0-syntax}.
  1473. %
  1474. The $C_0$ language supports the same operators as $R_1$ but the
  1475. arguments of operators are restricted to atomic expressions (variables
  1476. and integers), thanks to the \key{remove-complex-opera*} pass. In the
  1477. literature this style of intermediate language is called
  1478. administrative normal form, or ANF for
  1479. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{Let}
  1480. expressions, $C_0$ has assignment statements which can be executed in
  1481. sequence using the \key{Seq} form. A sequence of statements always
  1482. ends with \key{Return}, a guarantee that is baked into the grammar
  1483. rules for the \itm{tail} non-terminal. The naming of this non-terminal
  1484. comes from the term \emph{tail position}, which refers to an
  1485. expression that is the last one to execute within a function. (A
  1486. expression in tail position may contain subexpressions, and those may
  1487. or may not be in tail position depending on the kind of expression.)
  1488. A $C_0$ program consists of a control-flow graph (represented as an
  1489. association list mapping labels to tails). This is more general than
  1490. necessary for the present chapter, as we do not yet need to introduce
  1491. \key{goto} for jumping to labels, but it saves us from having to
  1492. change the syntax of the program construct in
  1493. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1494. \key{start}, and the whole program is its tail.
  1495. %
  1496. The $\itm{info}$ field of the \key{Program} form, after the
  1497. \key{explicate-control} pass, contains a mapping from the symbol
  1498. \key{locals} to a list of variables, that is, a list of all the
  1499. variables used in the program. At the start of the program, these
  1500. variables are uninitialized; they become initialized on their first
  1501. assignment.
  1502. \begin{figure}[tbp]
  1503. \fbox{
  1504. \begin{minipage}{0.96\textwidth}
  1505. \[
  1506. \begin{array}{lcl}
  1507. \Atm &::=& \Int \mid \Var \\
  1508. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1509. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1510. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1511. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1512. \end{array}
  1513. \]
  1514. \end{minipage}
  1515. }
  1516. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1517. \label{fig:c0-concrete-syntax}
  1518. \end{figure}
  1519. \begin{figure}[tbp]
  1520. \fbox{
  1521. \begin{minipage}{0.96\textwidth}
  1522. \[
  1523. \begin{array}{lcl}
  1524. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1525. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1526. &\mid& \ADD{\Atm}{\Atm}\\
  1527. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1528. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1529. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1530. \end{array}
  1531. \]
  1532. \end{minipage}
  1533. }
  1534. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1535. \label{fig:c0-syntax}
  1536. \end{figure}
  1537. %% The \key{select-instructions} pass is optimistic in the sense that it
  1538. %% treats variables as if they were all mapped to registers. The
  1539. %% \key{select-instructions} pass generates a program that consists of
  1540. %% x86 instructions but that still uses variables, so it is an
  1541. %% intermediate language that is technically different than x86, which
  1542. %% explains the asterisks in the diagram above.
  1543. %% In this Chapter we shall take the easy road to implementing
  1544. %% \key{assign-homes} and simply map all variables to stack locations.
  1545. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1546. %% smarter approach in which we make a best-effort to map variables to
  1547. %% registers, resorting to the stack only when necessary.
  1548. %% Once variables have been assigned to their homes, we can finalize the
  1549. %% instruction selection by dealing with an idiosyncrasy of x86
  1550. %% assembly. Many x86 instructions have two arguments but only one of the
  1551. %% arguments may be a memory reference (and the stack is a part of
  1552. %% memory). Because some variables may get mapped to stack locations,
  1553. %% some of our generated instructions may violate this restriction. The
  1554. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1555. %% replacing every violating instruction with a short sequence of
  1556. %% instructions that use the \key{rax} register. Once we have implemented
  1557. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1558. %% need to patch instructions will be relatively rare.
  1559. \subsection{The dialects of x86}
  1560. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1561. the pass \key{select-instructions}. It extends $x86_0$ with an
  1562. unbounded number of program-scope variables and has looser rules
  1563. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1564. output of \key{print-x86}, is the concrete syntax for x86.
  1565. \section{Uniquify Variables}
  1566. \label{sec:uniquify-s0}
  1567. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1568. programs in which every \key{let} uses a unique variable name. For
  1569. example, the \code{uniquify} pass should translate the program on the
  1570. left into the program on the right. \\
  1571. \begin{tabular}{lll}
  1572. \begin{minipage}{0.4\textwidth}
  1573. \begin{lstlisting}
  1574. (let ([x 32])
  1575. (+ (let ([x 10]) x) x))
  1576. \end{lstlisting}
  1577. \end{minipage}
  1578. &
  1579. $\Rightarrow$
  1580. &
  1581. \begin{minipage}{0.4\textwidth}
  1582. \begin{lstlisting}
  1583. (let ([x.1 32])
  1584. (+ (let ([x.2 10]) x.2) x.1))
  1585. \end{lstlisting}
  1586. \end{minipage}
  1587. \end{tabular} \\
  1588. %
  1589. The following is another example translation, this time of a program
  1590. with a \key{let} nested inside the initializing expression of another
  1591. \key{let}.\\
  1592. \begin{tabular}{lll}
  1593. \begin{minipage}{0.4\textwidth}
  1594. \begin{lstlisting}
  1595. (let ([x (let ([x 4])
  1596. (+ x 1))])
  1597. (+ x 2))
  1598. \end{lstlisting}
  1599. \end{minipage}
  1600. &
  1601. $\Rightarrow$
  1602. &
  1603. \begin{minipage}{0.4\textwidth}
  1604. \begin{lstlisting}
  1605. (let ([x.2 (let ([x.1 4])
  1606. (+ x.1 1))])
  1607. (+ x.2 2))
  1608. \end{lstlisting}
  1609. \end{minipage}
  1610. \end{tabular}
  1611. We recommend implementing \code{uniquify} by creating a function named
  1612. \code{uniquify-exp} that is structurally recursive function and mostly
  1613. just copies the input program. However, when encountering a \key{let},
  1614. it should generate a unique name for the variable (the Racket function
  1615. \code{gensym} is handy for this) and associate the old name with the
  1616. new unique name in an association list. The \code{uniquify-exp}
  1617. function will need to access this association list when it gets to a
  1618. variable reference, so we add another parameter to \code{uniquify-exp}
  1619. for the association list. It is quite common for a compiler pass to
  1620. need a map to store extra information about variables. Such maps are
  1621. traditionally called \emph{symbol tables}.
  1622. The skeleton of the \code{uniquify-exp} function is shown in
  1623. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1624. convenient to partially apply it to a symbol table and then apply it
  1625. to different expressions, as in the last clause for primitive
  1626. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1627. is useful for applying a function to each element of a list to produce
  1628. a new list.
  1629. \begin{exercise}
  1630. \normalfont % I don't like the italics for exercises. -Jeremy
  1631. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1632. implement the clauses for variables and for the \key{let} form.
  1633. \end{exercise}
  1634. \begin{figure}[tbp]
  1635. \begin{lstlisting}
  1636. (define (uniquify-exp symtab)
  1637. (lambda (e)
  1638. (match e
  1639. [(Var x) ___]
  1640. [(Int n) (Int n)]
  1641. [(Let x e body) ___]
  1642. [(Prim op es)
  1643. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1644. )))
  1645. (define (uniquify p)
  1646. (match p
  1647. [(Program info e)
  1648. (Program info ((uniquify-exp '()) e))]
  1649. )))
  1650. \end{lstlisting}
  1651. \caption{Skeleton for the \key{uniquify} pass.}
  1652. \label{fig:uniquify-s0}
  1653. \end{figure}
  1654. \begin{exercise}
  1655. \normalfont % I don't like the italics for exercises. -Jeremy
  1656. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1657. and checking whether the output programs produce the same result as
  1658. the input programs. The $R_1$ programs should be designed to test the
  1659. most interesting parts of the \key{uniquify} pass, that is, the
  1660. programs should include \key{let} forms, variables, and variables
  1661. that overshadow each other. The five programs should be in a
  1662. subdirectory named \key{tests} and they should have the same file name
  1663. except for a different integer at the end of the name, followed by the
  1664. ending \key{.rkt}. Use the \key{interp-tests} function
  1665. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1666. your \key{uniquify} pass on the example programs. See the
  1667. \key{run-tests.rkt} script in the student support code for an example
  1668. of how to use \key{interp-tests}.
  1669. \end{exercise}
  1670. \section{Remove Complex Operands}
  1671. \label{sec:remove-complex-opera-r1}
  1672. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1673. $R_1$ programs in which the arguments of operations are atomic
  1674. expressions. Put another way, this pass removes complex operands,
  1675. such as the expression \code{(- 10)} in the program below. This is
  1676. accomplished by introducing a new \key{let}-bound variable, binding
  1677. the complex operand to the new variable, and then using the new
  1678. variable in place of the complex operand, as shown in the output of
  1679. \code{remove-complex-opera*} on the right.\\
  1680. \begin{tabular}{lll}
  1681. \begin{minipage}{0.4\textwidth}
  1682. % s0_19.rkt
  1683. \begin{lstlisting}
  1684. (+ 52 (- 10))
  1685. \end{lstlisting}
  1686. \end{minipage}
  1687. &
  1688. $\Rightarrow$
  1689. &
  1690. \begin{minipage}{0.4\textwidth}
  1691. \begin{lstlisting}
  1692. (let ([tmp.1 (- 10)])
  1693. (+ 52 tmp.1))
  1694. \end{lstlisting}
  1695. \end{minipage}
  1696. \end{tabular}
  1697. We recommend implementing this pass with two mutually recursive
  1698. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1699. \code{rco-atom} to subexpressions that need to become atomic and to
  1700. apply \code{rco-exp} to subexpressions that can be atomic or complex.
  1701. Both functions take an $R_1$ expression as input. The \code{rco-exp}
  1702. function returns an expression. The \code{rco-atom} function returns
  1703. two things: an atomic expression and association list mapping
  1704. temporary variables to complex subexpressions. You can return multiple
  1705. things from a function using Racket's \key{values} form and you can
  1706. receive multiple things from a function call using the
  1707. \key{define-values} form. If you are not familiar with these features,
  1708. review the Racket documentation. Also, the \key{for/lists} form is
  1709. useful for applying a function to each element of a list, in the case
  1710. where the function returns multiple values.
  1711. The following shows the output of \code{rco-atom} on the expression
  1712. \code{(- 10)} (using concrete syntax to be concise).
  1713. \begin{tabular}{lll}
  1714. \begin{minipage}{0.4\textwidth}
  1715. \begin{lstlisting}
  1716. (- 10)
  1717. \end{lstlisting}
  1718. \end{minipage}
  1719. &
  1720. $\Rightarrow$
  1721. &
  1722. \begin{minipage}{0.4\textwidth}
  1723. \begin{lstlisting}
  1724. tmp.1
  1725. ((tmp.1 . (- 10)))
  1726. \end{lstlisting}
  1727. \end{minipage}
  1728. \end{tabular}
  1729. Take special care of programs such as the next one that \key{let}-bind
  1730. variables with integers or other variables. You should leave them
  1731. unchanged, as shown in to the program on the right \\
  1732. \begin{tabular}{lll}
  1733. \begin{minipage}{0.4\textwidth}
  1734. % s0_20.rkt
  1735. \begin{lstlisting}
  1736. (let ([a 42])
  1737. (let ([b a])
  1738. b))
  1739. \end{lstlisting}
  1740. \end{minipage}
  1741. &
  1742. $\Rightarrow$
  1743. &
  1744. \begin{minipage}{0.4\textwidth}
  1745. \begin{lstlisting}
  1746. (let ([a 42])
  1747. (let ([b a])
  1748. b))
  1749. \end{lstlisting}
  1750. \end{minipage}
  1751. \end{tabular} \\
  1752. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1753. produce the following output.\\
  1754. \begin{minipage}{0.4\textwidth}
  1755. \begin{lstlisting}
  1756. (let ([tmp.1 42])
  1757. (let ([a tmp.1])
  1758. (let ([tmp.2 a])
  1759. (let ([b tmp.2])
  1760. b))))
  1761. \end{lstlisting}
  1762. \end{minipage}
  1763. \begin{exercise}
  1764. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1765. it on all of the example programs that you created to test the
  1766. \key{uniquify} pass and create three new example programs that are
  1767. designed to exercise the interesting code in the
  1768. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1769. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1770. your passes on the example programs.
  1771. \end{exercise}
  1772. \section{Explicate Control}
  1773. \label{sec:explicate-control-r1}
  1774. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1775. programs that make the order of execution explicit in their
  1776. syntax. For now this amounts to flattening \key{let} constructs into a
  1777. sequence of assignment statements. For example, consider the following
  1778. $R_1$ program.\\
  1779. % s0_11.rkt
  1780. \begin{minipage}{0.96\textwidth}
  1781. \begin{lstlisting}
  1782. (let ([y (let ([x 20])
  1783. (+ x (let ([x 22]) x)))])
  1784. y)
  1785. \end{lstlisting}
  1786. \end{minipage}\\
  1787. %
  1788. The output of the previous pass and of \code{explicate-control} is
  1789. shown below. Recall that the right-hand-side of a \key{let} executes
  1790. before its body, so the order of evaluation for this program is to
  1791. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1792. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1793. output of \code{explicate-control} makes this ordering explicit.\\
  1794. \begin{tabular}{lll}
  1795. \begin{minipage}{0.4\textwidth}
  1796. \begin{lstlisting}
  1797. (let ([y (let ([x.1 20])
  1798. (let ([x.2 22])
  1799. (+ x.1 x.2)))])
  1800. y)
  1801. \end{lstlisting}
  1802. \end{minipage}
  1803. &
  1804. $\Rightarrow$
  1805. &
  1806. \begin{minipage}{0.4\textwidth}
  1807. \begin{lstlisting}
  1808. locals: y x.1 x.2
  1809. start:
  1810. x.1 = 20;
  1811. x.2 = 22;
  1812. y = (+ x.1 x.2);
  1813. return y;
  1814. \end{lstlisting}
  1815. \end{minipage}
  1816. \end{tabular}
  1817. We recommend implementing \code{explicate-control} using two mutually
  1818. recursive functions: \code{explicate-tail} and
  1819. \code{explicate-assign}. The first function should be applied to
  1820. expressions in tail position whereas the second should be applied to
  1821. expressions that occur on the right-hand-side of a \key{let}. The
  1822. \code{explicate-tail} function takes an $R_1$ expression as input and
  1823. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1824. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1825. function takes an $R_1$ expression, the variable that it is to be
  1826. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1827. assignment (e.g., the code generated for the body of the \key{let}).
  1828. It returns a $\Tail$ and a list of variables. The top-level
  1829. \code{explicate-control} function should invoke \code{explicate-tail}
  1830. on the body of the \key{program} and then associate the \code{locals}
  1831. symbol with the resulting list of variables in the $\itm{info}$ field,
  1832. as in the above example.
  1833. \section{Select Instructions}
  1834. \label{sec:select-r1}
  1835. In the \code{select-instructions} pass we begin the work of
  1836. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1837. this pass is a variable of x86 that still uses variables, so we add an
  1838. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1839. syntax of Figure~\ref{fig:x86-ast-a}. We recommend implementing the
  1840. \code{select-instructions} in terms of three auxiliary functions, one
  1841. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1842. The cases for $\Atm$ are straightforward, variables stay
  1843. the same and integer constants are changed to immediates:
  1844. $\INT{n}$ changes to $\IMM{n}$.
  1845. Next we consider the cases for $\Stmt$, starting with arithmetic
  1846. operations. For example, in $C_0$ an addition operation can take the
  1847. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1848. need to use the \key{addq} instruction which does an in-place
  1849. update. So we must first move \code{10} to \code{x}. \\
  1850. \begin{tabular}{lll}
  1851. \begin{minipage}{0.4\textwidth}
  1852. \begin{lstlisting}
  1853. x = (+ 10 32);
  1854. \end{lstlisting}
  1855. \end{minipage}
  1856. &
  1857. $\Rightarrow$
  1858. &
  1859. \begin{minipage}{0.4\textwidth}
  1860. \begin{lstlisting}
  1861. movq $10, x
  1862. addq $32, x
  1863. \end{lstlisting}
  1864. \end{minipage}
  1865. \end{tabular} \\
  1866. %
  1867. There are cases that require special care to avoid generating
  1868. needlessly complicated code. If one of the arguments of the addition
  1869. is the same as the left-hand side of the assignment, then there is no
  1870. need for the extra move instruction. For example, the following
  1871. assignment statement can be translated into a single \key{addq}
  1872. instruction.\\
  1873. \begin{tabular}{lll}
  1874. \begin{minipage}{0.4\textwidth}
  1875. \begin{lstlisting}
  1876. x = (+ 10 x);
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. &
  1880. $\Rightarrow$
  1881. &
  1882. \begin{minipage}{0.4\textwidth}
  1883. \begin{lstlisting}
  1884. addq $10, x
  1885. \end{lstlisting}
  1886. \end{minipage}
  1887. \end{tabular} \\
  1888. The \key{read} operation does not have a direct counterpart in x86
  1889. assembly, so we have instead implemented this functionality in the C
  1890. language, with the function \code{read\_int} in the file
  1891. \code{runtime.c}. In general, we refer to all of the functionality in
  1892. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1893. for short. When compiling your generated x86 assembly code, you need
  1894. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1895. using \code{gcc} option \code{-c}) and link it into the
  1896. executable. For our purposes of code generation, all you need to do is
  1897. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1898. (for left-hand side) into a call to the \code{read\_int} function
  1899. followed by a move from \code{rax} to the left-hand side. The move
  1900. from \code{rax} is needed because the return value from
  1901. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1902. \begin{tabular}{lll}
  1903. \begin{minipage}{0.4\textwidth}
  1904. \begin{lstlisting}
  1905. |$\itm{lhs}$| = (read);
  1906. \end{lstlisting}
  1907. \end{minipage}
  1908. &
  1909. $\Rightarrow$
  1910. &
  1911. \begin{minipage}{0.4\textwidth}
  1912. \begin{lstlisting}
  1913. callq read_int
  1914. movq %rax, |$\itm{lhs}$|
  1915. \end{lstlisting}
  1916. \end{minipage}
  1917. \end{tabular} \\
  1918. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1919. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1920. assignment to the \key{rax} register followed by a jump to the
  1921. conclusion of the program (so the conclusion needs to be labeled).
  1922. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1923. recursively and append the resulting instructions.
  1924. \begin{exercise}
  1925. \normalfont
  1926. Implement the \key{select-instructions} pass and test it on all of the
  1927. example programs that you created for the previous passes and create
  1928. three new example programs that are designed to exercise all of the
  1929. interesting code in this pass. Use the \key{interp-tests} function
  1930. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1931. your passes on the example programs.
  1932. \end{exercise}
  1933. \section{Assign Homes}
  1934. \label{sec:assign-r1}
  1935. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1936. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1937. Thus, the \key{assign-homes} pass is responsible for placing all of
  1938. the program variables in registers or on the stack. For runtime
  1939. efficiency, it is better to place variables in registers, but as there
  1940. are only 16 registers, some programs must necessarily resort to
  1941. placing some variables on the stack. In this chapter we focus on the
  1942. mechanics of placing variables on the stack. We study an algorithm for
  1943. placing variables in registers in
  1944. Chapter~\ref{ch:register-allocation-r1}.
  1945. Consider again the following $R_1$ program.
  1946. % s0_20.rkt
  1947. \begin{lstlisting}
  1948. (let ([a 42])
  1949. (let ([b a])
  1950. b))
  1951. \end{lstlisting}
  1952. For reference, we repeat the output of \code{select-instructions} on
  1953. the left and show the output of \code{assign-homes} on the right.
  1954. Recall that \key{explicate-control} associated the list of
  1955. variables with the \code{locals} symbol in the program's $\itm{info}$
  1956. field, so \code{assign-homes} has convenient access to the them. In
  1957. this example, we assign variable \code{a} to stack location
  1958. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1959. \begin{tabular}{l}
  1960. \begin{minipage}{0.4\textwidth}
  1961. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1962. locals: a b
  1963. start:
  1964. movq $42, a
  1965. movq a, b
  1966. movq b, %rax
  1967. jmp conclusion
  1968. \end{lstlisting}
  1969. \end{minipage}
  1970. {$\Rightarrow$}
  1971. \begin{minipage}{0.4\textwidth}
  1972. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1973. stack-space: 16
  1974. start:
  1975. movq $42, -8(%rbp)
  1976. movq -8(%rbp), -16(%rbp)
  1977. movq -16(%rbp), %rax
  1978. jmp conclusion
  1979. \end{lstlisting}
  1980. \end{minipage}
  1981. \end{tabular} \\
  1982. In the process of assigning variables to stack locations, it is
  1983. convenient to compute and store the size of the frame (in bytes) in
  1984. the $\itm{info}$ field of the \key{Program} node, with the key
  1985. \code{stack-space}, which will be needed later to generate the
  1986. procedure conclusion. Some operating systems place restrictions on
  1987. the frame size. For example, Mac OS X requires the frame size to be a
  1988. multiple of 16 bytes.
  1989. \begin{exercise}
  1990. \normalfont Implement the \key{assign-homes} pass and test it on all
  1991. of the example programs that you created for the previous passes pass.
  1992. We recommend that \key{assign-homes} take an extra parameter that is a
  1993. mapping of variable names to homes (stack locations for now). Use the
  1994. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1995. \key{utilities.rkt} to test your passes on the example programs.
  1996. \end{exercise}
  1997. \section{Patch Instructions}
  1998. \label{sec:patch-s0}
  1999. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2000. programs to $\text{x86}_0$ programs by making sure that each
  2001. instruction adheres to the restrictions of the x86 assembly language.
  2002. In particular, at most one argument of an instruction may be a memory
  2003. reference.
  2004. We return to the following running example.
  2005. % s0_20.rkt
  2006. \begin{lstlisting}
  2007. (let ([a 42])
  2008. (let ([b a])
  2009. b))
  2010. \end{lstlisting}
  2011. After the \key{assign-homes} pass, the above program has been translated to
  2012. the following. \\
  2013. \begin{minipage}{0.5\textwidth}
  2014. \begin{lstlisting}
  2015. stack-space: 16
  2016. start:
  2017. movq $42, -8(%rbp)
  2018. movq -8(%rbp), -16(%rbp)
  2019. movq -16(%rbp), %rax
  2020. jmp conclusion
  2021. \end{lstlisting}
  2022. \end{minipage}\\
  2023. The second \key{movq} instruction is problematic because both
  2024. arguments are stack locations. We suggest fixing this problem by
  2025. moving from the source location to the register \key{rax} and then
  2026. from \key{rax} to the destination location, as follows.
  2027. \begin{lstlisting}
  2028. movq -8(%rbp), %rax
  2029. movq %rax, -16(%rbp)
  2030. \end{lstlisting}
  2031. \begin{exercise}
  2032. \normalfont
  2033. Implement the \key{patch-instructions} pass and test it on all of the
  2034. example programs that you created for the previous passes and create
  2035. three new example programs that are designed to exercise all of the
  2036. interesting code in this pass. Use the \key{interp-tests} function
  2037. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2038. your passes on the example programs.
  2039. \end{exercise}
  2040. \section{Print x86}
  2041. \label{sec:print-x86}
  2042. The last step of the compiler from $R_1$ to x86 is to convert the
  2043. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  2044. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  2045. \key{format} and \key{string-append} functions are useful in this
  2046. regard. The main work that this step needs to perform is to create the
  2047. \key{main} function and the standard instructions for its prelude and
  2048. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2049. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2050. variables, so we suggest computing it in the \key{assign-homes} pass
  2051. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2052. of the \key{program} node.
  2053. %% Your compiled code should print the result of the program's execution
  2054. %% by using the \code{print\_int} function provided in
  2055. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2056. %% far, this final result should be stored in the \key{rax} register.
  2057. %% We'll talk more about how to perform function calls with arguments in
  2058. %% general later on, but for now, place the following after the compiled
  2059. %% code for the $R_1$ program but before the conclusion:
  2060. %% \begin{lstlisting}
  2061. %% movq %rax, %rdi
  2062. %% callq print_int
  2063. %% \end{lstlisting}
  2064. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2065. %% stores the first argument to be passed into \key{print\_int}.
  2066. If you want your program to run on Mac OS X, your code needs to
  2067. determine whether or not it is running on a Mac, and prefix
  2068. underscores to labels like \key{main}. You can determine the platform
  2069. with the Racket call \code{(system-type 'os)}, which returns
  2070. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2071. %% In addition to
  2072. %% placing underscores on \key{main}, you need to put them in front of
  2073. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2074. %% \_print\_int}).
  2075. \begin{exercise}
  2076. \normalfont Implement the \key{print-x86} pass and test it on all of
  2077. the example programs that you created for the previous passes. Use the
  2078. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2079. \key{utilities.rkt} to test your complete compiler on the example
  2080. programs. See the \key{run-tests.rkt} script in the student support
  2081. code for an example of how to use \key{compiler-tests}. Also, remember
  2082. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2083. \key{gcc}.
  2084. \end{exercise}
  2085. \section{Challenge: Partial Evaluator for $R_1$}
  2086. \label{sec:pe-R1}
  2087. This section describes optional challenge exercises that involve
  2088. adapting and improving the partial evaluator for $R_0$ that was
  2089. introduced in Section~\ref{sec:partial-evaluation}.
  2090. \begin{exercise}\label{ex:pe-R1}
  2091. \normalfont
  2092. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2093. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2094. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2095. and variables to the $R_0$ language, so you will need to add cases for
  2096. them in the \code{pe-exp} function. Also, note that the \key{program}
  2097. form changes slightly to include an $\itm{info}$ field. Once
  2098. complete, add the partial evaluation pass to the front of your
  2099. compiler and make sure that your compiler still passes all of the
  2100. tests.
  2101. \end{exercise}
  2102. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2103. \begin{exercise}
  2104. \normalfont
  2105. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2106. \code{pe-add} auxiliary functions with functions that know more about
  2107. arithmetic. For example, your partial evaluator should translate
  2108. \begin{lstlisting}
  2109. (+ 1 (+ (read) 1))
  2110. \end{lstlisting}
  2111. into
  2112. \begin{lstlisting}
  2113. (+ 2 (read))
  2114. \end{lstlisting}
  2115. To accomplish this, the \code{pe-exp} function should produce output
  2116. in the form of the $\itm{residual}$ non-terminal of the following
  2117. grammar.
  2118. \[
  2119. \begin{array}{lcl}
  2120. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2121. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2122. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2123. \end{array}
  2124. \]
  2125. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2126. that their inputs are $\itm{residual}$ expressions and they should
  2127. return $\itm{residual}$ expressions. Once the improvements are
  2128. complete, make sure that your compiler still passes all of the tests.
  2129. After all, fast code is useless if it produces incorrect results!
  2130. \end{exercise}
  2131. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2132. \chapter{Register Allocation}
  2133. \label{ch:register-allocation-r1}
  2134. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2135. make our life easier. However, we can improve the performance of the
  2136. generated code if we instead place some variables into registers. The
  2137. CPU can access a register in a single cycle, whereas accessing the
  2138. stack takes many cycles if the relevant data is in cache or many more
  2139. to access main memory if the data is not in cache.
  2140. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2141. serves as a running example. We show the source program and also the
  2142. output of instruction selection. At that point the program is almost
  2143. x86 assembly but not quite; it still contains variables instead of
  2144. stack locations or registers.
  2145. \begin{figure}
  2146. \begin{minipage}{0.45\textwidth}
  2147. Example $R_1$ program:
  2148. % s0_22.rkt
  2149. \begin{lstlisting}
  2150. (let ([v 1])
  2151. (let ([w 46])
  2152. (let ([x (+ v 7)])
  2153. (let ([y (+ 4 x)])
  2154. (let ([z (+ x w)])
  2155. (+ z (- y)))))))
  2156. \end{lstlisting}
  2157. \end{minipage}
  2158. \begin{minipage}{0.45\textwidth}
  2159. After instruction selection:
  2160. \begin{lstlisting}
  2161. locals: v w x y z t.1
  2162. start:
  2163. movq $1, v
  2164. movq $46, w
  2165. movq v, x
  2166. addq $7, x
  2167. movq x, y
  2168. addq $4, y
  2169. movq x, z
  2170. addq w, z
  2171. movq y, t.1
  2172. negq t.1
  2173. movq z, %rax
  2174. addq t.1, %rax
  2175. jmp conclusion
  2176. \end{lstlisting}
  2177. \end{minipage}
  2178. \caption{An example program for register allocation.}
  2179. \label{fig:reg-eg}
  2180. \end{figure}
  2181. The goal of register allocation is to fit as many variables into
  2182. registers as possible. A program sometimes has more variables than
  2183. registers, so we cannot map each variable to a different
  2184. register. Fortunately, it is common for different variables to be
  2185. needed during different periods of time during program execution, and
  2186. in such cases several variables can be mapped to the same register.
  2187. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2188. After the variable \code{x} is moved to \code{z} it is no longer
  2189. needed. Variable \code{y}, on the other hand, is used only after this
  2190. point, so \code{x} and \code{y} could share the same register. The
  2191. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2192. where a variable is needed. Once we have that information, we compute
  2193. which variables are needed at the same time, i.e., which ones
  2194. \emph{interfere}, and represent this relation as an undirected graph
  2195. whose vertices are variables and edges indicate when two variables
  2196. interfere with each other (Section~\ref{sec:build-interference}). We
  2197. then model register allocation as a graph coloring problem, which we
  2198. discuss in Section~\ref{sec:graph-coloring}.
  2199. In the event that we run out of registers despite these efforts, we
  2200. place the remaining variables on the stack, similar to what we did in
  2201. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2202. for assigning a variable to a stack location. The process of spilling
  2203. variables is handled as part of the graph coloring process described
  2204. in \ref{sec:graph-coloring}.
  2205. \section{Registers and Calling Conventions}
  2206. \label{sec:calling-conventions}
  2207. As we perform register allocation, we need to be aware of the
  2208. conventions that govern the way in which registers interact with
  2209. function calls, such as calls to the \code{read\_int} function. The
  2210. convention for x86 is that the caller is responsible for freeing up
  2211. some registers, the \emph{caller-saved registers}, prior to the
  2212. function call, and the callee is responsible for saving and restoring
  2213. some other registers, the \emph{callee-saved registers}, before and
  2214. after using them. The caller-saved registers are
  2215. \begin{lstlisting}
  2216. rax rdx rcx rsi rdi r8 r9 r10 r11
  2217. \end{lstlisting}
  2218. while the callee-saved registers are
  2219. \begin{lstlisting}
  2220. rsp rbp rbx r12 r13 r14 r15
  2221. \end{lstlisting}
  2222. Another way to think about this caller/callee convention is the
  2223. following. The caller should assume that all the caller-saved registers
  2224. get overwritten with arbitrary values by the callee. On the other
  2225. hand, the caller can safely assume that all the callee-saved registers
  2226. contain the same values after the call that they did before the call.
  2227. The callee can freely use any of the caller-saved registers. However,
  2228. if the callee wants to use a callee-saved register, the callee must
  2229. arrange to put the original value back in the register prior to
  2230. returning to the caller, which is usually accomplished by saving and
  2231. restoring the value from the stack.
  2232. \section{Liveness Analysis}
  2233. \label{sec:liveness-analysis-r1}
  2234. A variable is \emph{live} if the variable is used at some later point
  2235. in the program and there is not an intervening assignment to the
  2236. variable.
  2237. %
  2238. To understand the latter condition, consider the following code
  2239. fragment in which there are two writes to \code{b}. Are \code{a} and
  2240. \code{b} both live at the same time?
  2241. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2242. movq $5, a
  2243. movq $30, b
  2244. movq a, c
  2245. movq $10, b
  2246. addq b, c
  2247. \end{lstlisting}
  2248. The answer is no because the integer \code{30} written to \code{b} on
  2249. line 2 is never used. The variable \code{b} is read on line 5 and
  2250. there is an intervening write to \code{b} on line 4, so the read on
  2251. line 5 receives the value written on line 4, not line 2.
  2252. The live variables can be computed by traversing the instruction
  2253. sequence back to front (i.e., backwards in execution order). Let
  2254. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2255. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2256. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2257. variables before instruction $I_k$. The live variables after an
  2258. instruction are always the same as the live variables before the next
  2259. instruction.
  2260. \begin{equation} \label{eq:live-after-before-next}
  2261. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2262. \end{equation}
  2263. To start things off, there are no live variables after the last
  2264. instruction, so
  2265. \begin{equation}\label{eq:live-last-empty}
  2266. L_{\mathsf{after}}(n) = \emptyset
  2267. \end{equation}
  2268. We then apply the following rule repeatedly, traversing the
  2269. instruction sequence back to front.
  2270. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2271. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2272. \end{equation}
  2273. where $W(k)$ are the variables written to by instruction $I_k$ and
  2274. $R(k)$ are the variables read by instruction $I_k$.
  2275. Let us walk through the above example, applying these formulas
  2276. starting with the instruction on line 5. We collect the answers in the
  2277. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2278. instruction is $\emptyset$ because it is the last instruction
  2279. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2280. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2281. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2282. is
  2283. \[
  2284. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2285. \]
  2286. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2287. the live-before set from line 5 to be the live-after set for this
  2288. instruction (formula~\ref{eq:live-after-before-next}).
  2289. \[
  2290. L_{\mathsf{after}}(4) = \{ b, c \}
  2291. \]
  2292. This move instruction writes to $b$ and does not read from any
  2293. variables, so we have the following live-before set
  2294. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2295. \[
  2296. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2297. \]
  2298. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2299. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2300. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2301. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2302. variable that is not live and does not read from a variable.
  2303. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2304. because it writes to variable $a$.
  2305. \begin{center}
  2306. \begin{minipage}{0.45\textwidth}
  2307. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2308. movq $5, a
  2309. movq $30, b
  2310. movq a, c
  2311. movq $10, b
  2312. addq b, c
  2313. \end{lstlisting}
  2314. \end{minipage}
  2315. \vrule\hspace{10pt}
  2316. \begin{minipage}{0.45\textwidth}
  2317. \begin{align*}
  2318. L_{\mathsf{before}}(1)= \emptyset,
  2319. L_{\mathsf{after}}(1)= \{a\}\\
  2320. L_{\mathsf{before}}(2)= \{a\},
  2321. L_{\mathsf{after}}(2)= \{a\}\\
  2322. L_{\mathsf{before}}(3)= \{a\},
  2323. L_{\mathsf{after}}(2)= \{c\}\\
  2324. L_{\mathsf{before}}(4)= \{c\},
  2325. L_{\mathsf{after}}(4)= \{b,c\}\\
  2326. L_{\mathsf{before}}(5)= \{b,c\},
  2327. L_{\mathsf{after}}(5)= \emptyset
  2328. \end{align*}
  2329. \end{minipage}
  2330. \end{center}
  2331. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2332. for the running example program, with each instruction aligned with
  2333. its $L_{\mathtt{after}}$ set to make the figure easy to read.
  2334. \begin{figure}[tbp]
  2335. \hspace{20pt}
  2336. \begin{minipage}{0.45\textwidth}
  2337. \begin{lstlisting}[numbers=left]
  2338. movq $1, v
  2339. movq $46, w
  2340. movq v, x
  2341. addq $7, x
  2342. movq x, y
  2343. addq $4, y
  2344. movq x, z
  2345. addq w, z
  2346. movq y, t.1
  2347. negq t.1)
  2348. movq z, %rax
  2349. addq t.1, %rax
  2350. jmp conclusion
  2351. \end{lstlisting}
  2352. \end{minipage}
  2353. \vrule\hspace{10pt}
  2354. \begin{minipage}{0.45\textwidth}
  2355. \begin{lstlisting}
  2356. |$\{\}$|
  2357. |$\{v \}$|
  2358. |$\{v,w\}$|
  2359. |$\{w,x\}$|
  2360. |$\{w,x\}$|
  2361. |$\{w,x,y\}$|
  2362. |$\{w,x,y\}$|
  2363. |$\{w,y,z\}$|
  2364. |$\{y,z\}$|
  2365. |$\{z,t.1\}$|
  2366. |$\{z,t.1\}$|
  2367. |$\{t.1\}$|
  2368. |$\{\}$|
  2369. |$\{\}$|
  2370. \end{lstlisting}
  2371. \end{minipage}
  2372. \caption{The running example annotated with live-after sets.}
  2373. \label{fig:live-eg}
  2374. \end{figure}
  2375. \begin{exercise}\normalfont
  2376. Implement the compiler pass named \code{uncover-live} that computes
  2377. the live-after sets. We recommend storing the live-after sets (a list
  2378. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2379. structure.
  2380. %
  2381. We recommend organizing your code to use a helper function that takes
  2382. a list of instructions and an initial live-after set (typically empty)
  2383. and returns the list of live-after sets.
  2384. %
  2385. We recommend creating helper functions to 1) compute the set of
  2386. variables that appear in an argument (of an instruction), 2) compute
  2387. the variables read by an instruction which corresponds to the $R$
  2388. function discussed above, and 3) the variables written by an
  2389. instruction which corresponds to $W$.
  2390. \end{exercise}
  2391. \section{Building the Interference Graph}
  2392. \label{sec:build-interference}
  2393. Based on the liveness analysis, we know where each variable is needed.
  2394. However, during register allocation, we need to answer questions of
  2395. the specific form: are variables $u$ and $v$ live at the same time?
  2396. (And therefore cannot be assigned to the same register.) To make this
  2397. question easier to answer, we create an explicit data structure, an
  2398. \emph{interference graph}. An interference graph is an undirected
  2399. graph that has an edge between two variables if they are live at the
  2400. same time, that is, if they interfere with each other.
  2401. The most obvious way to compute the interference graph is to look at
  2402. the set of live variables between each statement in the program and
  2403. add an edge to the graph for every pair of variables in the same set.
  2404. This approach is less than ideal for two reasons. First, it can be
  2405. expensive because it takes $O(n^2)$ time to look at every pair in a
  2406. set of $n$ live variables. Second, there is a special case in which
  2407. two variables that are live at the same time do not actually interfere
  2408. with each other: when they both contain the same value because we have
  2409. assigned one to the other.
  2410. A better way to compute the interference graph is to focus on the
  2411. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2412. instruction to overwrite something in a live variable. So for each
  2413. instruction, we create an edge between the variable being written to
  2414. and all the \emph{other} live variables. (One should not create self
  2415. edges.) For a \key{callq} instruction, think of all caller-saved
  2416. registers as being written to, so an edge must be added between every
  2417. live variable and every caller-saved register. For \key{movq}, we deal
  2418. with the above-mentioned special case by not adding an edge between a
  2419. live variable $v$ and destination $d$ if $v$ matches the source of the
  2420. move. So we have the following three rules.
  2421. \begin{enumerate}
  2422. \item If instruction $I_k$ is an arithmetic instruction such as
  2423. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2424. L_{\mathsf{after}}(k)$ unless $v = d$.
  2425. \item If instruction $I_k$ is of the form \key{callq}
  2426. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2427. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2428. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2429. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2430. d$ or $v = s$.
  2431. \end{enumerate}
  2432. \margincomment{JM: I think you could give examples of each one of these
  2433. using the example program and use those to help explain why these
  2434. rules are correct.\\
  2435. JS: Agreed.}
  2436. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2437. the following interference for the instruction at the specified line
  2438. number.
  2439. \begin{quote}
  2440. Line 2: no interference,\\
  2441. Line 3: $w$ interferes with $v$,\\
  2442. Line 4: $x$ interferes with $w$,\\
  2443. Line 5: $x$ interferes with $w$,\\
  2444. Line 6: $y$ interferes with $w$,\\
  2445. Line 7: $y$ interferes with $w$ and $x$,\\
  2446. Line 8: $z$ interferes with $w$ and $y$,\\
  2447. Line 9: $z$ interferes with $y$, \\
  2448. Line 10: $t.1$ interferes with $z$, \\
  2449. Line 11: $t.1$ interferes with $z$, \\
  2450. Line 12: no interference, \\
  2451. Line 13: no interference. \\
  2452. Line 14: no interference.
  2453. \end{quote}
  2454. The resulting interference graph is shown in
  2455. Figure~\ref{fig:interfere}.
  2456. \begin{figure}[tbp]
  2457. \large
  2458. \[
  2459. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2460. \node (v) at (0,0) {$v$};
  2461. \node (w) at (2,0) {$w$};
  2462. \node (x) at (4,0) {$x$};
  2463. \node (t1) at (6,-2) {$t.1$};
  2464. \node (y) at (2,-2) {$y$};
  2465. \node (z) at (4,-2) {$z$};
  2466. \draw (v) to (w);
  2467. \foreach \i in {w,x,y}
  2468. {
  2469. \foreach \j in {w,x,y}
  2470. {
  2471. \draw (\i) to (\j);
  2472. }
  2473. }
  2474. \draw (z) to (w);
  2475. \draw (z) to (y);
  2476. \draw (t1) to (z);
  2477. \end{tikzpicture}
  2478. \]
  2479. \caption{The interference graph of the example program.}
  2480. \label{fig:interfere}
  2481. \end{figure}
  2482. %% Our next concern is to choose a data structure for representing the
  2483. %% interference graph. There are many choices for how to represent a
  2484. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2485. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2486. %% data structure is to study the algorithm that uses the data structure,
  2487. %% determine what operations need to be performed, and then choose the
  2488. %% data structure that provide the most efficient implementations of
  2489. %% those operations. Often times the choice of data structure can have an
  2490. %% effect on the time complexity of the algorithm, as it does here. If
  2491. %% you skim the next section, you will see that the register allocation
  2492. %% algorithm needs to ask the graph for all of its vertices and, given a
  2493. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2494. %% correct choice of graph representation is that of an adjacency
  2495. %% list. There are helper functions in \code{utilities.rkt} for
  2496. %% representing graphs using the adjacency list representation:
  2497. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2498. %% (Appendix~\ref{appendix:utilities}).
  2499. %% %
  2500. %% \margincomment{\footnotesize To do: change to use the
  2501. %% Racket graph library. \\ --Jeremy}
  2502. %% %
  2503. %% In particular, those functions use a hash table to map each vertex to
  2504. %% the set of adjacent vertices, and the sets are represented using
  2505. %% Racket's \key{set}, which is also a hash table.
  2506. \begin{exercise}\normalfont
  2507. Implement the compiler pass named \code{build-interference} according
  2508. to the algorithm suggested above. We recommend using the Racket
  2509. \code{graph} package to create and inspect the interference graph.
  2510. The output graph of this pass should be stored in the $\itm{info}$
  2511. field of the program, under the key \code{conflicts}.
  2512. \end{exercise}
  2513. \section{Graph Coloring via Sudoku}
  2514. \label{sec:graph-coloring}
  2515. We come to the main event, mapping variables to registers (or to stack
  2516. locations in the event that we run out of registers). We need to make
  2517. sure that two variables do not get mapped to the same register if the
  2518. two variables interfere with each other. Thinking about the
  2519. interference graph, this means that adjacent vertices must be mapped
  2520. to different registers. If we think of registers as colors, the
  2521. register allocation problem becomes the widely-studied graph coloring
  2522. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2523. The reader may be more familiar with the graph coloring problem than he
  2524. or she realizes; the popular game of Sudoku is an instance of the
  2525. graph coloring problem. The following describes how to build a graph
  2526. out of an initial Sudoku board.
  2527. \begin{itemize}
  2528. \item There is one vertex in the graph for each Sudoku square.
  2529. \item There is an edge between two vertices if the corresponding squares
  2530. are in the same row, in the same column, or if the squares are in
  2531. the same $3\times 3$ region.
  2532. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2533. \item Based on the initial assignment of numbers to squares in the
  2534. Sudoku board, assign the corresponding colors to the corresponding
  2535. vertices in the graph.
  2536. \end{itemize}
  2537. If you can color the remaining vertices in the graph with the nine
  2538. colors, then you have also solved the corresponding game of Sudoku.
  2539. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2540. the corresponding graph with colored vertices. We map the Sudoku
  2541. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2542. sampling of the vertices (the colored ones) because showing edges for
  2543. all of the vertices would make the graph unreadable.
  2544. \begin{figure}[tbp]
  2545. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2546. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2547. \caption{A Sudoku game board and the corresponding colored graph.}
  2548. \label{fig:sudoku-graph}
  2549. \end{figure}
  2550. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2551. strategies to come up with an algorithm for allocating registers. For
  2552. example, one of the basic techniques for Sudoku is called Pencil
  2553. Marks. The idea is to use a process of elimination to determine what
  2554. numbers no longer make sense for a square and write down those
  2555. numbers in the square (writing very small). For example, if the number
  2556. $1$ is assigned to a square, then by process of elimination, you can
  2557. write the pencil mark $1$ in all the squares in the same row, column,
  2558. and region. Many Sudoku computer games provide automatic support for
  2559. Pencil Marks.
  2560. %
  2561. The Pencil Marks technique corresponds to the notion of
  2562. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2563. vertex, in Sudoku terms, is the set of numbers that are no longer
  2564. available. In graph terminology, we have the following definition:
  2565. \begin{equation*}
  2566. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2567. \text{ and } \mathrm{color}(v) = c \}
  2568. \end{equation*}
  2569. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2570. edge with $u$.
  2571. Using the Pencil Marks technique leads to a simple strategy for
  2572. filling in numbers: if there is a square with only one possible number
  2573. left, then choose that number! But what if there are no squares with
  2574. only one possibility left? One brute-force approach is to try them
  2575. all: choose the first and if it ultimately leads to a solution,
  2576. great. If not, backtrack and choose the next possibility. One good
  2577. thing about Pencil Marks is that it reduces the degree of branching in
  2578. the search tree. Nevertheless, backtracking can be horribly time
  2579. consuming. One way to reduce the amount of backtracking is to use the
  2580. most-constrained-first heuristic. That is, when choosing a square,
  2581. always choose one with the fewest possibilities left (the vertex with
  2582. the highest saturation). The idea is that choosing highly constrained
  2583. squares earlier rather than later is better because later on there may
  2584. not be any possibilities left for those squares.
  2585. In some sense, register allocation is easier than Sudoku because the
  2586. register allocator can choose to map variables to stack locations when
  2587. the registers run out. Thus, it makes sense to drop backtracking in
  2588. favor of greedy search, that is, make the best choice at the time and
  2589. keep going. We still wish to minimize the number of colors needed, so
  2590. keeping the most-constrained-first heuristic is a good idea.
  2591. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2592. algorithm for register allocation based on saturation and the
  2593. most-constrained-first heuristic. It is roughly equivalent to the
  2594. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2595. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2596. Sudoku, the algorithm represents colors with integers. The first $k$
  2597. colors corresponding to the $k$ registers in a given machine and the
  2598. rest of the integers corresponding to stack locations.
  2599. \begin{figure}[btp]
  2600. \centering
  2601. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2602. Algorithm: DSATUR
  2603. Input: a graph |$G$|
  2604. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2605. |$W \gets \mathit{vertices}(G)$|
  2606. while |$W \neq \emptyset$| do
  2607. pick a vertex |$u$| from |$W$| with the highest saturation,
  2608. breaking ties randomly
  2609. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2610. |$\mathrm{color}[u] \gets c$|
  2611. |$W \gets W - \{u\}$|
  2612. \end{lstlisting}
  2613. \caption{The saturation-based greedy graph coloring algorithm.}
  2614. \label{fig:satur-algo}
  2615. \end{figure}
  2616. With this algorithm in hand, let us return to the running example and
  2617. consider how to color the interference graph in
  2618. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2619. colored and they are unsaturated, so we annotate each of them with a
  2620. dash for their color and an empty set for the saturation.
  2621. \[
  2622. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2623. \node (v) at (0,0) {$v:-,\{\}$};
  2624. \node (w) at (3,0) {$w:-,\{\}$};
  2625. \node (x) at (6,0) {$x:-,\{\}$};
  2626. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2627. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2628. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2629. \draw (v) to (w);
  2630. \foreach \i in {w,x,y}
  2631. {
  2632. \foreach \j in {w,x,y}
  2633. {
  2634. \draw (\i) to (\j);
  2635. }
  2636. }
  2637. \draw (z) to (w);
  2638. \draw (z) to (y);
  2639. \draw (t1) to (z);
  2640. \end{tikzpicture}
  2641. \]
  2642. The algorithm says to select a maximally saturated vertex and color it
  2643. $0$. In this case we have a 7-way tie, so we arbitrarily pick
  2644. $t.1$. We then mark color $0$ as no longer available for $z$ because
  2645. it interferes with $t.1$.
  2646. \[
  2647. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2648. \node (v) at (0,0) {$v:-,\{\}$};
  2649. \node (w) at (3,0) {$w:-,\{\}$};
  2650. \node (x) at (6,0) {$x:-,\{\}$};
  2651. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2652. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2653. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2654. \draw (v) to (w);
  2655. \foreach \i in {w,x,y}
  2656. {
  2657. \foreach \j in {w,x,y}
  2658. {
  2659. \draw (\i) to (\j);
  2660. }
  2661. }
  2662. \draw (z) to (w);
  2663. \draw (z) to (y);
  2664. \draw (t1) to (z);
  2665. \end{tikzpicture}
  2666. \]
  2667. Next we repeat the process, selecting another maximally saturated
  2668. vertex, which is $z$, and color it with the first available number,
  2669. which is $1$.
  2670. \[
  2671. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2672. \node (v) at (0,0) {$v:-,\{\}$};
  2673. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2674. \node (x) at (6,0) {$x:-,\{\}$};
  2675. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2676. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2677. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2678. \draw (t1) to (z);
  2679. \draw (v) to (w);
  2680. \foreach \i in {w,x,y}
  2681. {
  2682. \foreach \j in {w,x,y}
  2683. {
  2684. \draw (\i) to (\j);
  2685. }
  2686. }
  2687. \draw (z) to (w);
  2688. \draw (z) to (y);
  2689. \end{tikzpicture}
  2690. \]
  2691. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2692. first available color, which is $0$.
  2693. \[
  2694. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2695. \node (v) at (0,0) {$v:-,\{\}$};
  2696. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2697. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2698. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2699. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2700. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2701. \draw (t1) to (z);
  2702. \draw (v) to (w);
  2703. \foreach \i in {w,x,y}
  2704. {
  2705. \foreach \j in {w,x,y}
  2706. {
  2707. \draw (\i) to (\j);
  2708. }
  2709. }
  2710. \draw (z) to (w);
  2711. \draw (z) to (y);
  2712. \end{tikzpicture}
  2713. \]
  2714. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2715. We cannot choose $0$ or $1$ because those numbers are in $w$'s
  2716. saturation set. Indeed, $w$ interferes with $y$ and $z$, whose colors
  2717. are $0$ and $1$ respectively.
  2718. \[
  2719. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2720. \node (v) at (0,0) {$v:-,\{2\}$};
  2721. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2722. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2723. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2724. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2725. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2726. \draw (t1) to (z);
  2727. \draw (v) to (w);
  2728. \foreach \i in {w,x,y}
  2729. {
  2730. \foreach \j in {w,x,y}
  2731. {
  2732. \draw (\i) to (\j);
  2733. }
  2734. }
  2735. \draw (z) to (w);
  2736. \draw (z) to (y);
  2737. \end{tikzpicture}
  2738. \]
  2739. Now $x$ has the highest saturation, so we color it $1$.
  2740. \[
  2741. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2742. \node (v) at (0,0) {$v:-,\{2\}$};
  2743. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2744. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2745. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2746. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2747. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2748. \draw (t1) to (z);
  2749. \draw (v) to (w);
  2750. \foreach \i in {w,x,y}
  2751. {
  2752. \foreach \j in {w,x,y}
  2753. {
  2754. \draw (\i) to (\j);
  2755. }
  2756. }
  2757. \draw (z) to (w);
  2758. \draw (z) to (y);
  2759. \end{tikzpicture}
  2760. \]
  2761. In the last step of the algorithm, we color $v$ with $0$.
  2762. \[
  2763. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2764. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2765. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2766. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2767. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2768. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2769. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2770. \draw (t1) to (z);
  2771. \draw (v) to (w);
  2772. \foreach \i in {w,x,y}
  2773. {
  2774. \foreach \j in {w,x,y}
  2775. {
  2776. \draw (\i) to (\j);
  2777. }
  2778. }
  2779. \draw (z) to (w);
  2780. \draw (z) to (y);
  2781. \end{tikzpicture}
  2782. \]
  2783. With the coloring complete, we finalize the assignment of variables to
  2784. registers and stack locations. Recall that if we have $k$ registers,
  2785. we map the first $k$ colors to registers and the rest to stack
  2786. locations. Suppose for the moment that we have just one register to
  2787. use for register allocation, \key{rcx}. Then the following is the
  2788. mapping of colors to registers and stack allocations.
  2789. \[
  2790. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2791. \]
  2792. Putting this mapping together with the above coloring of the
  2793. variables, we arrive at the following assignment of variables to
  2794. registers and stack locations.
  2795. \begin{gather*}
  2796. \{ v \mapsto \key{\%rcx}, \,
  2797. w \mapsto \key{-16(\%rbp)}, \,
  2798. x \mapsto \key{-8(\%rbp)}, \\
  2799. y \mapsto \key{\%rcx}, \,
  2800. z\mapsto \key{-8(\%rbp)},
  2801. t.1\mapsto \key{\%rcx} \}
  2802. \end{gather*}
  2803. Applying this assignment to our running example, on the left, yields
  2804. the program on the right.
  2805. % why frame size of 32? -JGS
  2806. \begin{center}
  2807. \begin{minipage}{0.3\textwidth}
  2808. \begin{lstlisting}
  2809. movq $1, v
  2810. movq $46, w
  2811. movq v, x
  2812. addq $7, x
  2813. movq x, y
  2814. addq $4, y
  2815. movq x, z
  2816. addq w, z
  2817. movq y, t.1
  2818. negq t.1
  2819. movq z, %rax
  2820. addq t.1, %rax
  2821. jmp conclusion
  2822. \end{lstlisting}
  2823. \end{minipage}
  2824. $\Rightarrow\qquad$
  2825. \begin{minipage}{0.45\textwidth}
  2826. \begin{lstlisting}
  2827. movq $1, %rcx
  2828. movq $46, -16(%rbp)
  2829. movq %rcx, -8(%rbp)
  2830. addq $7, -8(%rbp)
  2831. movq -8(%rbp), %rcx
  2832. addq $4, %rcx
  2833. movq -8(%rbp), -8(%rbp)
  2834. addq -16(%rbp), -8(%rbp)
  2835. movq %rcx, %rcx
  2836. negq %rcx
  2837. movq -8(%rbp), %rax
  2838. addq %rcx, %rax
  2839. jmp conclusion
  2840. \end{lstlisting}
  2841. \end{minipage}
  2842. \end{center}
  2843. The resulting program is almost an x86 program. The remaining step is
  2844. the patch instructions pass. In this example, the trivial move of
  2845. \code{-8(\%rbp)} to itself is deleted and the addition of
  2846. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2847. \code{rax} as follows.
  2848. \begin{lstlisting}
  2849. movq -16(%rbp), %rax
  2850. addq %rax, -8(%rbp)
  2851. \end{lstlisting}
  2852. An overview of all of the passes involved in register allocation is
  2853. shown in Figure~\ref{fig:reg-alloc-passes}.
  2854. \begin{figure}[tbp]
  2855. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2856. \node (R1) at (0,2) {\large $R_1$};
  2857. \node (R1-2) at (3,2) {\large $R_1$};
  2858. \node (R1-3) at (6,2) {\large $R_1$};
  2859. \node (C0-1) at (6,0) {\large $C_0$};
  2860. \node (C0-2) at (3,0) {\large $C_0$};
  2861. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2862. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2863. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2864. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2865. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2866. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2867. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2868. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2869. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2870. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2871. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2872. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2873. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2874. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2875. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2876. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2877. \end{tikzpicture}
  2878. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2879. \label{fig:reg-alloc-passes}
  2880. \end{figure}
  2881. \begin{exercise}\normalfont
  2882. Implement the pass \code{allocate-registers}, which should come
  2883. after the \code{build-interference} pass. The three new passes,
  2884. \code{uncover-live}, \code{build-interference}, and
  2885. \code{allocate-registers} replace the \code{assign-homes} pass of
  2886. Section~\ref{sec:assign-r1}.
  2887. We recommend that you create a helper function named
  2888. \code{color-graph} that takes an interference graph and a list of
  2889. all the variables in the program. This function should return a
  2890. mapping of variables to their colors (represented as natural
  2891. numbers). By creating this helper function, you will be able to
  2892. reuse it in Chapter~\ref{ch:functions} when you add support for
  2893. functions.
  2894. Once you have obtained the coloring from \code{color-graph}, you can
  2895. assign the variables to registers or stack locations and then reuse
  2896. code from the \code{assign-homes} pass from
  2897. Section~\ref{sec:assign-r1} to replace the variables with their
  2898. assigned location.
  2899. Test your updated compiler by creating new example programs that
  2900. exercise all of the register allocation algorithm, such as forcing
  2901. variables to be spilled to the stack.
  2902. \end{exercise}
  2903. \section{Print x86 and Conventions for Registers}
  2904. \label{sec:print-x86-reg-alloc}
  2905. Recall that the \code{print-x86} pass generates the prelude and
  2906. conclusion instructions for the \code{main} function.
  2907. %
  2908. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2909. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2910. reason for this is that our \code{main} function must adhere to the
  2911. x86 calling conventions that we described in
  2912. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2913. function needs to restore (in the conclusion) any callee-saved
  2914. registers that get used during register allocation. The simplest
  2915. approach is to save and restore all of the callee-saved registers. The
  2916. more efficient approach is to keep track of which callee-saved
  2917. registers were used and only save and restore them. Either way, make
  2918. sure to take this use of stack space into account when you are
  2919. calculating the size of the frame. Also, don't forget that the size of
  2920. the frame needs to be a multiple of 16 bytes.
  2921. \section{Challenge: Move Biasing}
  2922. \label{sec:move-biasing}
  2923. This section describes an optional enhancement to register allocation
  2924. for those students who are looking for an extra challenge or who have
  2925. a deeper interest in register allocation.
  2926. We return to the running example, but we remove the supposition that
  2927. we only have one register to use. So we have the following mapping of
  2928. color numbers to registers.
  2929. \[
  2930. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  2931. \]
  2932. Using the same assignment of variables to color numbers that was
  2933. produced by the register allocator described in the last section, we
  2934. get the following program.
  2935. \begin{minipage}{0.3\textwidth}
  2936. \begin{lstlisting}
  2937. movq $1, v
  2938. movq $46, w
  2939. movq v, x
  2940. addq $7, x
  2941. movq x, y
  2942. addq $4, y
  2943. movq x, z
  2944. addq w, z
  2945. movq y, t.1
  2946. negq t.1
  2947. movq z, %rax
  2948. addq t.1, %rax
  2949. jmp conclusion
  2950. \end{lstlisting}
  2951. \end{minipage}
  2952. $\Rightarrow\qquad$
  2953. \begin{minipage}{0.45\textwidth}
  2954. \begin{lstlisting}
  2955. movq $1, %rbx
  2956. movq $46, %rdx
  2957. movq %rbx, %rcx
  2958. addq $7, %rcx
  2959. movq %rcx, %rbx
  2960. addq $4, %rbx
  2961. movq %rcx, %rcx
  2962. addq %rdx, %rcx
  2963. movq %rbx, %rbx
  2964. negq %rbx
  2965. movq %rcx, %rax
  2966. addq %rbx, %rax
  2967. jmp conclusion
  2968. \end{lstlisting}
  2969. \end{minipage}
  2970. While this allocation is quite good, we could do better. For example,
  2971. the variables \key{v} and \key{x} ended up in different registers, but
  2972. if they had been placed in the same register, then the move from
  2973. \key{v} to \key{x} could be removed.
  2974. We say that two variables $p$ and $q$ are \emph{move related} if they
  2975. participate together in a \key{movq} instruction, that is, \key{movq}
  2976. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  2977. allocator chooses a color for a variable, it should prefer a color
  2978. that has already been used for a move-related variable (assuming that
  2979. they do not interfere). Of course, this preference should not override
  2980. the preference for registers over stack locations. This preference
  2981. should be used as a tie breaker when choosing between registers or
  2982. when choosing between stack locations.
  2983. We recommend representing the move relationships in a graph, similar
  2984. to how we represented interference. The following is the \emph{move
  2985. graph} for our running example.
  2986. \[
  2987. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2988. \node (v) at (0,0) {$v$};
  2989. \node (w) at (3,0) {$w$};
  2990. \node (x) at (6,0) {$x$};
  2991. \node (y) at (3,-1.5) {$y$};
  2992. \node (z) at (6,-1.5) {$z$};
  2993. \node (t1) at (9,-1.5) {$t.1$};
  2994. \draw[bend left=15] (t1) to (y);
  2995. \draw[bend left=15] (v) to (x);
  2996. \draw (x) to (y);
  2997. \draw (x) to (z);
  2998. \end{tikzpicture}
  2999. \]
  3000. Now we replay the graph coloring, pausing to see the coloring of $x$
  3001. and $v$. So we have the following coloring and the most saturated
  3002. vertex is $x$.
  3003. \[
  3004. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3005. \node (v) at (0,0) {$v:-,\{2\}$};
  3006. \node (w) at (3,0) {$w:2,\{0,1\}$};
  3007. \node (x) at (6,0) {$x:-,\{0,2\}$};
  3008. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3009. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3010. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3011. \draw (t1) to (z);
  3012. \draw (v) to (w);
  3013. \foreach \i in {w,x,y}
  3014. {
  3015. \foreach \j in {w,x,y}
  3016. {
  3017. \draw (\i) to (\j);
  3018. }
  3019. }
  3020. \draw (z) to (w);
  3021. \draw (z) to (y);
  3022. \end{tikzpicture}
  3023. \]
  3024. Last time we chose to color $x$ with $1$,
  3025. %
  3026. which so happens to be the color of $z$, and $x$ is move related to
  3027. $z$. This was lucky, and if the program had been a little different,
  3028. and say $z$ had been already assigned to $2$, then $x$ would still get
  3029. $1$ and our luck would have run out. With move biasing, we use the
  3030. fact that $x$ and $z$ are move related to influence the choice of
  3031. color for $x$, in this case choosing $1$ because that is the color of
  3032. $z$.
  3033. \[
  3034. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3035. \node (v) at (0,0) {$v:-,\{2\}$};
  3036. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3037. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  3038. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  3039. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3040. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3041. \draw (t1) to (z);
  3042. \draw (v) to (w);
  3043. \foreach \i in {w,x,y}
  3044. {
  3045. \foreach \j in {w,x,y}
  3046. {
  3047. \draw (\i) to (\j);
  3048. }
  3049. }
  3050. \draw (z) to (w);
  3051. \draw (z) to (y);
  3052. \end{tikzpicture}
  3053. \]
  3054. Next we consider coloring the variable $v$. We need to avoid choosing
  3055. $2$ because of the interference with $w$. Last time we chose the color
  3056. $0$ because it was the lowest, but this time we know that $v$ is move
  3057. related to $x$, so we choose the color $1$.
  3058. \[
  3059. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3060. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  3061. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3062. \node (x) at (6,0) {$x:1,\{0,2\}$};
  3063. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3064. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3065. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3066. \draw (t1) to (z);
  3067. \draw (v) to (w);
  3068. \foreach \i in {w,x,y}
  3069. {
  3070. \foreach \j in {w,x,y}
  3071. {
  3072. \draw (\i) to (\j);
  3073. }
  3074. }
  3075. \draw (z) to (w);
  3076. \draw (z) to (y);
  3077. \end{tikzpicture}
  3078. \]
  3079. We apply this register assignment to the running example, on the left,
  3080. to obtain the code on right.
  3081. \begin{minipage}{0.3\textwidth}
  3082. \begin{lstlisting}
  3083. movq $1, v
  3084. movq $46, w
  3085. movq v, x
  3086. addq $7, x
  3087. movq x, y
  3088. addq $4, y
  3089. movq x, z
  3090. addq w, z
  3091. movq y, t.1
  3092. negq t.1
  3093. movq z, %rax
  3094. addq t.1, %rax
  3095. jmp conclusion
  3096. \end{lstlisting}
  3097. \end{minipage}
  3098. $\Rightarrow\qquad$
  3099. \begin{minipage}{0.45\textwidth}
  3100. \begin{lstlisting}
  3101. movq $1, %rcx
  3102. movq $46, %rbx
  3103. movq %rcx, %rcx
  3104. addq $7, %rcx
  3105. movq %rcx, %rdx
  3106. addq $4, %rdx
  3107. movq %rcx, %rcx
  3108. addq %rbx, %rcx
  3109. movq %rdx, %rbx
  3110. negq %rbx
  3111. movq %rcx, %rax
  3112. addq %rbx, %rax
  3113. jmp conclusion
  3114. \end{lstlisting}
  3115. \end{minipage}
  3116. The \code{patch-instructions} then removes the trivial moves from
  3117. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3118. result.
  3119. \begin{minipage}{0.45\textwidth}
  3120. \begin{lstlisting}
  3121. movq $1 %rcx
  3122. movq $46 %rbx
  3123. addq $7 %rcx
  3124. movq %rcx %rdx
  3125. addq $4 %rdx
  3126. addq %rbx %rcx
  3127. movq %rdx %rbx
  3128. negq %rbx
  3129. movq %rcx %rax
  3130. addq %rbx %rax
  3131. jmp conclusion
  3132. \end{lstlisting}
  3133. \end{minipage}
  3134. \begin{exercise}\normalfont
  3135. Change your implementation of \code{allocate-registers} to take move
  3136. biasing into account. Make sure that your compiler still passes all of
  3137. the previous tests. Create two new tests that include at least one
  3138. opportunity for move biasing and visually inspect the output x86
  3139. programs to make sure that your move biasing is working properly.
  3140. \end{exercise}
  3141. \margincomment{\footnotesize To do: another neat challenge would be to do
  3142. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3143. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3144. \chapter{Booleans and Control Flow}
  3145. \label{ch:bool-types}
  3146. The $R_0$ and $R_1$ languages only had a single kind of value, the
  3147. integers. In this chapter we add a second kind of value, the Booleans,
  3148. to create the $R_2$ language. The Boolean values \emph{true} and
  3149. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3150. Racket. The $R_2$ language includes several operations that involve
  3151. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3152. conditional \key{if} expression. With the addition of \key{if}
  3153. expressions, programs can have non-trivial control flow which has an
  3154. impact on several parts of the compiler. Also, because we now have two
  3155. kinds of values, we need to worry about programs that apply an
  3156. operation to the wrong kind of value, such as \code{(not 1)}.
  3157. There are two language design options for such situations. One option
  3158. is to signal an error and the other is to provide a wider
  3159. interpretation of the operation. The Racket language uses a mixture of
  3160. these two options, depending on the operation and the kind of
  3161. value. For example, the result of \code{(not 1)} in Racket is
  3162. \code{\#f} because Racket treats non-zero integers as if they were
  3163. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3164. error in Racket stating that \code{car} expects a pair.
  3165. The Typed Racket language makes similar design choices as Racket,
  3166. except much of the error detection happens at compile time instead of
  3167. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3168. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3169. reports a compile-time error because Typed Racket expects the type of
  3170. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3171. For the $R_2$ language we choose to be more like Typed Racket in that
  3172. we shall perform type checking during compilation. In
  3173. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3174. is, how to compile a dynamically typed language like Racket. The
  3175. $R_2$ language is a subset of Typed Racket but by no means includes
  3176. all of Typed Racket. Furthermore, for many of the operations we shall
  3177. take a narrower interpretation than Typed Racket, for example,
  3178. rejecting \code{(not 1)}.
  3179. This chapter is organized as follows. We begin by defining the syntax
  3180. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3181. then introduce the idea of type checking and build a type checker for
  3182. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3183. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3184. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  3185. how our compiler passes need to change to accommodate Booleans and
  3186. conditional control flow.
  3187. \section{The $R_2$ Language}
  3188. \label{sec:r2-lang}
  3189. The concrete syntax of the $R_2$ language is defined in
  3190. Figure~\ref{fig:r2-concretesyntax} and the abstract syntax is defined
  3191. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3192. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3193. and the conditional \code{if} expression. Also, we expand the
  3194. operators to include subtraction, \key{and}, \key{or} and \key{not},
  3195. the \key{eq?} operations for comparing two integers or two Booleans,
  3196. and the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3197. comparing integers.
  3198. \begin{figure}[tp]
  3199. \centering
  3200. \fbox{
  3201. \begin{minipage}{0.96\textwidth}
  3202. \[
  3203. \begin{array}{lcl}
  3204. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3205. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3206. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3207. &\mid& \key{\#t} \mid \key{\#f}
  3208. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3209. \mid (\key{not}\;\Exp) \\
  3210. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3211. R_2 &::=& \Exp
  3212. \end{array}
  3213. \]
  3214. \end{minipage}
  3215. }
  3216. \caption{The concrete syntax of $R_2$, extending $R_1$
  3217. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3218. \label{fig:r2-concrete-syntax}
  3219. \end{figure}
  3220. \begin{figure}[tp]
  3221. \centering
  3222. \fbox{
  3223. \begin{minipage}{0.96\textwidth}
  3224. \[
  3225. \begin{array}{lcl}
  3226. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3227. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3228. \Exp &::=& \gray{\INT{\Int} \mid \READ{} \mid \NEG{\Exp}} \\
  3229. &\mid& \gray{\ADD{\Exp}{\Exp}}
  3230. \mid \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3231. &\mid& \gray{\VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp}} \\
  3232. &\mid& \BOOL{\itm{bool}}
  3233. \mid \AND{\Exp}{\Exp}\\
  3234. &\mid& \OR{\Exp}{\Exp}
  3235. \mid \NOT{\Exp} \\
  3236. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3237. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3238. \end{array}
  3239. \]
  3240. \end{minipage}
  3241. }
  3242. \caption{The abstract syntax of $R_2$.}
  3243. \label{fig:r2-syntax}
  3244. \end{figure}
  3245. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3246. the parts that are the same as the interpreter for $R_1$
  3247. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3248. simply evaluate to themselves. The conditional expression $(\key{if}\,
  3249. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  3250. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3251. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3252. operations \code{not} and \code{and} behave as you might expect, but
  3253. note that the \code{and} operation is short-circuiting. That is, given
  3254. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3255. evaluated if $e_1$ evaluates to \code{\#f}.
  3256. With the addition of the comparison operations, there are quite a few
  3257. primitive operations and the interpreter code for them is somewhat
  3258. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  3259. parts into the \code{interp-op} function and the similar parts into
  3260. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  3261. use \code{interp-op} for the \code{and} operation because of the
  3262. short-circuiting behavior in the order of evaluation of its arguments.
  3263. \begin{figure}[tbp]
  3264. \begin{lstlisting}
  3265. (define (interp-op op)
  3266. (match op
  3267. ...
  3268. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3269. ['eq? (lambda (v1 v2)
  3270. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3271. (and (boolean? v1) (boolean? v2)))
  3272. (eq? v1 v2)]))]
  3273. ['< (lambda (v1 v2)
  3274. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3275. ['<= (lambda (v1 v2)
  3276. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3277. ['> (lambda (v1 v2)
  3278. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3279. ['>= (lambda (v1 v2)
  3280. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3281. [else (error 'interp-op "unknown operator")]))
  3282. (define (interp-exp env)
  3283. (lambda (e)
  3284. (define recur (interp-exp env))
  3285. (match e
  3286. ...
  3287. [(Bool b) b]
  3288. [(If cnd thn els)
  3289. (define b (recur cnd))
  3290. (match b
  3291. [#t (recur thn)]
  3292. [#f (recur els)])]
  3293. [(Prim 'and (list e1 e2))
  3294. (define v1 (recur e1))
  3295. (match v1
  3296. [#t (match (recur e2) [#t #t] [#f #f])]
  3297. [#f #f])]
  3298. [(Prim op args)
  3299. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3300. )))
  3301. (define (interp-R2 p)
  3302. (match p
  3303. [(Program info e)
  3304. ((interp-exp '()) e)]
  3305. ))
  3306. \end{lstlisting}
  3307. \caption{Interpreter for the $R_2$ language.}
  3308. \label{fig:interp-R2}
  3309. \end{figure}
  3310. \section{Type Checking $R_2$ Programs}
  3311. \label{sec:type-check-r2}
  3312. It is helpful to think about type checking in two complementary
  3313. ways. A type checker predicts the \emph{type} of value that will be
  3314. produced by each expression in the program. For $R_2$, we have just
  3315. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3316. predict that
  3317. \begin{lstlisting}
  3318. (+ 10 (- (+ 12 20)))
  3319. \end{lstlisting}
  3320. produces an \key{Integer} while
  3321. \begin{lstlisting}
  3322. (and (not #f) #t)
  3323. \end{lstlisting}
  3324. produces a \key{Boolean}.
  3325. As mentioned at the beginning of this chapter, a type checker also
  3326. rejects programs that apply operators to the wrong type of value. Our
  3327. type checker for $R_2$ will signal an error for the below expression
  3328. because, as we have seen above, the expression \code{(+ 10 ...)} has
  3329. type \key{Integer}, and we require the argument of a \code{not} to
  3330. have type \key{Boolean}.
  3331. \begin{lstlisting}
  3332. (not (+ 10 (- (+ 12 20))))
  3333. \end{lstlisting}
  3334. The type checker for $R_2$ is best implemented as a structurally
  3335. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3336. many of the clauses for the \code{type-check-exp} function. Given an
  3337. input expression \code{e}, the type checker either returns the type
  3338. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3339. the type of an integer literal is \code{Integer} and the type of a
  3340. Boolean literal is \code{Boolean}. To handle variables, the type
  3341. checker, like the interpreter, uses an association list. However, in
  3342. this case the association list maps variables to types instead of
  3343. values. Consider the clause for \key{let}. We type check the
  3344. initializing expression to obtain its type \key{T} and then associate
  3345. type \code{T} with the variable \code{x}. When the type checker
  3346. encounters the use of a variable, it can find its type in the
  3347. association list.
  3348. \begin{figure}[tbp]
  3349. \begin{lstlisting}
  3350. (definepublic (type-check-exp env)
  3351. (lambda (e)
  3352. (match e
  3353. [(Var x) (dict-ref env x)]
  3354. [(Int n) 'Integer]
  3355. [(Bool b) 'Boolean]
  3356. [(Let x e body)
  3357. (define Te ((type-check-exp env) e))
  3358. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3359. Tb]
  3360. ...
  3361. [else
  3362. (error "type-check-exp couldn't match" e)])))
  3363. (define (type-check env)
  3364. (lambda (e)
  3365. (match e
  3366. [(Program info body)
  3367. (define Tb ((type-check-exp '()) body))
  3368. (unless (equal? Tb 'Integer)
  3369. (error "result of the program must be an integer, not " Tb))
  3370. (Program info body)]
  3371. )))
  3372. \end{lstlisting}
  3373. \caption{Skeleton of a type checker for the $R_2$ language.}
  3374. \label{fig:type-check-R2}
  3375. \end{figure}
  3376. \begin{exercise}\normalfont
  3377. Complete the implementation of \code{type-check-R2} and test it on 10
  3378. new example programs in $R_2$ that you choose based on how thoroughly
  3379. they test the type checking algorithm. Half of the example programs
  3380. should have a type error, to make sure that your type checker properly
  3381. rejects them. The other half of the example programs should not have
  3382. type errors. Your testing should check that the result of the type
  3383. checker agrees with the value returned by the interpreter, that is, if
  3384. the type checker returns \key{Integer}, then the interpreter should
  3385. return an integer. Likewise, if the type checker returns
  3386. \key{Boolean}, then the interpreter should return \code{\#t} or
  3387. \code{\#f}. Note that if your type checker does not signal an error
  3388. for a program, then interpreting that program should not encounter an
  3389. error. If it does, there is something wrong with your type checker.
  3390. \end{exercise}
  3391. \section{Shrink the $R_2$ Language}
  3392. \label{sec:shrink-r2}
  3393. The $R_2$ language includes several operators that are easily
  3394. expressible in terms of other operators. For example, subtraction is
  3395. expressible in terms of addition and negation.
  3396. \[
  3397. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3398. \]
  3399. Several of the comparison operations are expressible in terms of
  3400. less-than and logical negation.
  3401. \[
  3402. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad
  3403. \LET{t_1}{e_1}{(\key{not}\;(\key{<}\;e_2\;t_1))}
  3404. \]
  3405. By performing these translations near the front-end of the compiler,
  3406. the later passes of the compiler do not need to deal with these
  3407. constructs, making those passes shorter. On the other hand, sometimes
  3408. these translations make it more difficult to generate the most
  3409. efficient code with respect to the number of instructions. However,
  3410. these differences typically do not affect the number of accesses to
  3411. memory, which is the primary factor that determines execution time on
  3412. modern computer architectures.
  3413. \begin{exercise}\normalfont
  3414. Implement the pass \code{shrink} that removes subtraction,
  3415. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3416. by translating them to other constructs in $R_2$. Create tests to
  3417. make sure that the behavior of all of these constructs stays the
  3418. same after translation.
  3419. \end{exercise}
  3420. \section{XOR, Comparisons, and Control Flow in x86}
  3421. \label{sec:x86-1}
  3422. To implement the new logical operations, the comparison operations,
  3423. and the \key{if} expression, we need to delve further into the x86
  3424. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3425. larger subset of x86 that includes instructions for logical
  3426. operations, comparisons, and jumps.
  3427. One small challenge is that x86 does not provide an instruction that
  3428. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3429. However, the \code{xorq} instruction can be used to encode \code{not}.
  3430. The \key{xorq} instruction takes two arguments, performs a pairwise
  3431. exclusive-or operation on each bit of its arguments, and writes the
  3432. results into its second argument. Recall the truth table for
  3433. exclusive-or:
  3434. \begin{center}
  3435. \begin{tabular}{l|cc}
  3436. & 0 & 1 \\ \hline
  3437. 0 & 0 & 1 \\
  3438. 1 & 1 & 0
  3439. \end{tabular}
  3440. \end{center}
  3441. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3442. in the row of the table for the bit $1$, the result is the opposite of the
  3443. second bit. Thus, the \code{not} operation can be implemented by
  3444. \code{xorq} with $1$ as the first argument:
  3445. \begin{align*}
  3446. 0001 \mathrel{\mathrm{XOR}} 0000 &= 0001\\
  3447. 0001 \mathrel{\mathrm{XOR}} 0001 &= 0000
  3448. \end{align*}
  3449. \begin{figure}[tp]
  3450. \fbox{
  3451. \begin{minipage}{0.96\textwidth}
  3452. \small
  3453. \[
  3454. \begin{array}{lcl}
  3455. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3456. \mid \BYTEREG{\code{'}\Reg} \\
  3457. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3458. \Instr &::=& \gray{\BININSTR{\code{'addq}}{\Arg}{\Arg}}
  3459. \mid \gray{\BININSTR{\code{'subq}}{\Arg}{\Arg}} \\
  3460. &\mid& \gray{\BININSTR{\code{'movq}}{\Arg}{\Arg}}
  3461. \mid \gray{\UNIINSTR{\code{'negq}}{\Arg}} \\
  3462. &\mid& \gray{\CALLQ{\itm{label}} \mid \RETQ{}}
  3463. \mid \gray{\PUSHQ{\Arg} \mid \POPQ{\Arg}} \\
  3464. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3465. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3466. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3467. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3468. &\mid& \JMP{\itm{label}}
  3469. \mid \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3470. % &\mid& (\key{label} \; \itm{label}) \\
  3471. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3472. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3473. \end{array}
  3474. \]
  3475. \end{minipage}
  3476. }
  3477. \caption{The abstract syntax of $x86_1$ (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3478. \label{fig:x86-1}
  3479. \end{figure}
  3480. Next we consider the x86 instructions that are relevant for compiling
  3481. the comparison operations. The \key{cmpq} instruction compares its two
  3482. arguments to determine whether one argument is less than, equal, or
  3483. greater than the other argument. The \key{cmpq} instruction is unusual
  3484. regarding the order of its arguments and where the result is
  3485. placed. The argument order is backwards: if you want to test whether
  3486. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3487. \key{cmpq} is placed in the special EFLAGS register. This register
  3488. cannot be accessed directly but it can be queried by a number of
  3489. instructions, including the \key{set} instruction. The \key{set}
  3490. instruction puts a \key{1} or \key{0} into its destination depending
  3491. on whether the comparison came out according to the condition code
  3492. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3493. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3494. The \key{set} instruction has an annoying quirk in that its
  3495. destination argument must be single byte register, such as \code{al},
  3496. which is part of the \code{rax} register. Thankfully, the
  3497. \key{movzbq} instruction can then be used to move from a single byte
  3498. register to a normal 64-bit register.
  3499. For compiling the \key{if} expression, the x86 instructions for
  3500. jumping are relevant. The \key{Jmp} instruction updates the program
  3501. counter to point to the instruction after the indicated label. The
  3502. \key{JmpIf} instruction updates the program counter to point to the
  3503. instruction after the indicated label depending on whether the result
  3504. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3505. the \key{JmpIf} instruction falls through to the next
  3506. instruction. Because the \key{JmpIf} instruction relies on the EFLAGS
  3507. register, it is quite common for the \key{JmpIf} to be immediately
  3508. preceded by a \key{cmpq} instruction, to set the EFLAGS register.
  3509. Our abstract syntax for \key{JmpIf} differs from the concrete syntax
  3510. for x86 to separate the instruction name from the condition code. For
  3511. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}.
  3512. \section{The $C_1$ Intermediate Language}
  3513. \label{sec:c1}
  3514. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3515. language, but we need to grow that intermediate language to handle the
  3516. new features in $R_2$: Booleans and conditional expressions.
  3517. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3518. logic and comparison operators to the $\Exp$ non-terminal, the
  3519. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3520. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3521. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3522. goto's in the grammar for $\Tail$. This means that a sequence of
  3523. statements may now end with a \code{goto} or a conditional
  3524. \code{goto}, which jumps to one of two labeled pieces of code
  3525. depending on the outcome of the comparison. In
  3526. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3527. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3528. and \key{goto}'s.
  3529. \begin{figure}[tp]
  3530. \fbox{
  3531. \begin{minipage}{0.96\textwidth}
  3532. \small
  3533. \[
  3534. \begin{array}{lcl}
  3535. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3536. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3537. \Exp &::= & \gray{\Atm \mid \READ{} \mid \NEG{\Atm} }\\
  3538. &\mid& \gray{ \ADD{\Atm}{\Atm} }
  3539. \mid \UNIOP{\key{not}}{\Atm} \\
  3540. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \\
  3541. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3542. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} } \\
  3543. &\mid& \GOTO{\itm{label}} \mid \IFSTMT{\key{(}\itm{cmp}\,\Atm\,\Atm\key{)}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3544. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3545. \end{array}
  3546. \]
  3547. \end{minipage}
  3548. }
  3549. \caption{The abstract syntax of $C_1$, extending $C_0$ with Booleans and conditionals.}
  3550. \label{fig:c1-syntax}
  3551. \end{figure}
  3552. \section{Explicate Control}
  3553. \label{sec:explicate-control-r2}
  3554. Recall that the purpose of \code{explicate-control} is to make the
  3555. order of evaluation explicit in the syntax of the program. With the
  3556. addition of \key{if} in $R_2$, things get more interesting.
  3557. As a motivating example, consider the following program that has an
  3558. \key{if} expression nested in the predicate of another \key{if}.
  3559. % s1_38.rkt
  3560. \begin{center}
  3561. \begin{minipage}{0.96\textwidth}
  3562. \begin{lstlisting}
  3563. (if (if (eq? (read) 1)
  3564. (eq? (read) 0)
  3565. (eq? (read) 2))
  3566. (+ 10 32)
  3567. (+ 700 77))
  3568. \end{lstlisting}
  3569. \end{minipage}
  3570. \end{center}
  3571. %
  3572. The naive way to compile \key{if} and \key{eq?} would be to handle
  3573. each of them in isolation, regardless of their context. Each
  3574. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3575. by a couple instructions to move the result from the EFLAGS register
  3576. into a general purpose register or stack location. Each \key{if} would
  3577. be translated into the combination of a \key{cmpq} and \key{JmpIf}.
  3578. However, if we take context into account we can do better and reduce
  3579. the use of \key{cmpq} and EFLAG-accessing instructions.
  3580. One idea is to try and reorganize the code at the level of $R_2$,
  3581. pushing the outer \key{if} inside the inner one. This would yield the
  3582. following code.
  3583. \begin{center}
  3584. \begin{minipage}{0.96\textwidth}
  3585. \begin{lstlisting}
  3586. (if (eq? (read) 1)
  3587. (if (eq? (read) 0)
  3588. (+ 10 32)
  3589. (+ 700 77))
  3590. (if (eq? (read) 2))
  3591. (+ 10 32)
  3592. (+ 700 77))
  3593. \end{lstlisting}
  3594. \end{minipage}
  3595. \end{center}
  3596. Unfortunately, this approach duplicates the two branches, and a
  3597. compiler must never duplicate code!
  3598. We need a way to perform the above transformation, but without
  3599. duplicating code. The solution is straightforward if we think at the
  3600. level of x86 assembly: we can label the code for each of the branches
  3601. and insert jumps in all the places that need to execute the
  3602. branches. Put another way, we need to move away from abstract syntax
  3603. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3604. use a standard program representation called a \emph{control flow
  3605. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3606. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3607. each edge represents a jump to another block. The \key{Program}
  3608. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3609. as an association list mapping labels to basic blocks. Each block is
  3610. represented by the $\Tail$ non-terminal.
  3611. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3612. \code{remove-complex-opera*} pass and then the
  3613. \code{explicate-control} pass on the example program. We walk through
  3614. the output program and then discuss the algorithm.
  3615. %
  3616. Following the order of evaluation in the output of
  3617. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3618. comparison to \code{1} from the predicate of the inner \key{if}. In
  3619. the output of \code{explicate-control}, in the \code{start} block,
  3620. this becomes a \code{(read)} followed by a conditional goto to either
  3621. \code{block61} or \code{block62}. Each of these contains the
  3622. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3623. 1)}, respectively. Regarding \code{block61}, we start with the
  3624. \code{(read)} and comparison to \code{0} and then have a conditional
  3625. goto, either to \code{block59} or \code{block60}, which indirectly
  3626. take us to \code{block55} and \code{block56}, the two branches of the
  3627. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3628. story for \code{block62} is similar.
  3629. \begin{figure}[tbp]
  3630. \begin{tabular}{lll}
  3631. \begin{minipage}{0.4\textwidth}
  3632. \begin{lstlisting}
  3633. (if (if (eq? (read) 1)
  3634. (eq? (read) 0)
  3635. (eq? (read) 2))
  3636. (+ 10 32)
  3637. (+ 700 77))
  3638. \end{lstlisting}
  3639. \hspace{40pt}$\Downarrow$
  3640. \begin{lstlisting}
  3641. (if (if (let ([tmp52 (read)])
  3642. (eq? tmp52 1))
  3643. (let ([tmp53 (read)])
  3644. (eq? tmp53 0))
  3645. (let ([tmp54 (read)])
  3646. (eq? tmp54 2)))
  3647. (+ 10 32)
  3648. (+ 700 77))
  3649. \end{lstlisting}
  3650. \end{minipage}
  3651. &
  3652. $\Rightarrow$
  3653. &
  3654. \begin{minipage}{0.55\textwidth}
  3655. \begin{lstlisting}
  3656. block62:
  3657. tmp54 = (read);
  3658. if (eq? tmp54 2) then
  3659. goto block59;
  3660. else
  3661. goto block60;
  3662. block61:
  3663. tmp53 = (read);
  3664. if (eq? tmp53 0) then
  3665. goto block57;
  3666. else
  3667. goto block58;
  3668. block60:
  3669. goto block56;
  3670. block59:
  3671. goto block55;
  3672. block58:
  3673. goto block56;
  3674. block57:
  3675. goto block55;
  3676. block56:
  3677. return (+ 700 77);
  3678. block55:
  3679. return (+ 10 32);
  3680. start:
  3681. tmp52 = (read);
  3682. if (eq? tmp52 1) then
  3683. goto block61;
  3684. else
  3685. goto block62;
  3686. \end{lstlisting}
  3687. \end{minipage}
  3688. \end{tabular}
  3689. \caption{Example translation from $R_2$ to $C_1$
  3690. via the \code{explicate-control}.}
  3691. \label{fig:explicate-control-s1-38}
  3692. \end{figure}
  3693. The nice thing about the output of \code{explicate-control} is that
  3694. there are no unnecessary uses of \code{eq?} and every use of
  3695. \code{eq?} is part of a conditional jump. The down-side of this output
  3696. is that it includes trivial blocks, such as \code{block57} through
  3697. \code{block60}, that only jump to another block. We discuss a solution
  3698. to this problem in Section~\ref{sec:opt-jumps}.
  3699. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3700. \code{explicate-control} for $R_1$ using two mutually recursive
  3701. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3702. former function translates expressions in tail position whereas the
  3703. later function translates expressions on the right-hand-side of a
  3704. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3705. new kind of context to deal with: the predicate position of the
  3706. \key{if}. We need another function, \code{explicate-pred}, that takes
  3707. an $R_2$ expression and two pieces of $C_1$ code (two $\Tail$'s) for
  3708. the then-branch and else-branch. The output of \code{explicate-pred}
  3709. is a $C_1$ $\Tail$ and a list of formerly \key{let}-bound variables.
  3710. However, these three functions also need to
  3711. construct the control-flow graph, which we recommend they do via
  3712. updates to a global variable (be careful!). Next we consider the
  3713. specific additions to the tail and assign functions, and some of cases
  3714. for the pred function.
  3715. The \code{explicate-tail} function needs an additional case for
  3716. \key{if}. The branches of the \key{if} inherit the current context, so
  3717. they are in tail position. Let $B_1$ be the result of
  3718. \code{explicate-tail} on the ``then'' branch of the \key{if} and $B_2$
  3719. be the result of apply \code{explicate-tail} to the ``else''
  3720. branch. Then the \key{if} as a whole translates to the block $B_3$
  3721. which is the result of applying \code{explicate-pred} to the predicate
  3722. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3723. \[
  3724. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3725. \]
  3726. Next we consider the case for \key{if} in the \code{explicate-assign}
  3727. function. The context of the \key{if} is an assignment to some
  3728. variable $x$ and then the control continues to some block $B_1$. The
  3729. code that we generate for the $\itm{thn}$ and $\itm{els}$ branches
  3730. needs to continue to $B_1$, so we add $B_1$ to the control flow graph
  3731. with a fresh label $\ell_1$. Again, the branches of the \key{if}
  3732. inherit the current context, so that are in assignment positions. Let
  3733. $B_2$ be the result of applying \code{explicate-assign} to the
  3734. $\itm{thn}$ branch, variable $x$, and the block \GOTO{$\ell_1$}. Let
  3735. $B_3$ be the result of applying \code{explicate-assign} to the
  3736. $\itm{else}$ branch, variable $x$, and the block \GOTO{$\ell_1$}. The
  3737. \key{if} translates to the block $B_4$ which is the result of applying
  3738. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  3739. $B_2$ and $B_3$.
  3740. \[
  3741. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3742. \]
  3743. The function \code{explicate-pred} will need a case for every
  3744. expression that can have type \code{Boolean}. We detail a few cases
  3745. here and leave the rest for the reader. The input to this function is
  3746. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3747. enclosing \key{if}. Suppose the expression is the Boolean \code{\#t}.
  3748. Then we can perform a kind of partial evaluation and translate it to the
  3749. ``then'' branch $B_1$. Likewise, we translate
  3750. \code{\#f} to the ``else`` branch $B_2$.
  3751. \[
  3752. \key{\#t} \quad\Rightarrow\quad B_1,
  3753. \qquad\qquad\qquad
  3754. \key{\#f} \quad\Rightarrow\quad B_2
  3755. \]
  3756. Next, suppose the
  3757. expression is a less-than comparison. We translate it to a conditional
  3758. goto. We need labels for the two branches $B_1$ and $B_2$, so we add
  3759. those blocks to the control flow graph and obtain some labels $\ell_1$
  3760. and $\ell_2$. The translation of the less-than comparison is as
  3761. follows.
  3762. \[
  3763. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  3764. \begin{array}{l}
  3765. \key{if}~(\key{<}~e_1~e_2)~\key{then} \\
  3766. \qquad\key{goto}~\ell_1\key{;}\\
  3767. \key{else}\\
  3768. \qquad\key{goto}~\ell_2\key{;}
  3769. \end{array}
  3770. \]
  3771. The case for \key{if} in \code{explicate-pred} is particularly
  3772. illuminating, as it deals with the challenges that we discussed above
  3773. regarding the example of the nested \key{if} expressions. Again, we
  3774. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3775. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3776. and $\itm{els}$ of the current \key{if} inherit their context from the
  3777. current one, i.e., predicate context. So we apply
  3778. \code{explicate-pred} to $\itm{thn}$ with the two blocks
  3779. \GOTO{$\ell_1$} and \GOTO{$\ell_2$}, to obtain $B_3$.
  3780. Proceed in a similar way with the $\itm{els}$ branch, to obtain $B_4$.
  3781. Finally, we apply \code{explicate-pred} to
  3782. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3783. to obtain the result $B_5$.
  3784. \[
  3785. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3786. \quad\Rightarrow\quad
  3787. B_5
  3788. \]
  3789. \begin{exercise}\normalfont
  3790. Implement the pass \code{explicate-control} by adding the cases for
  3791. \key{if} to the functions for tail and assignment contexts, and
  3792. implement \code{explicate-pred} for predicate contexts. Create test
  3793. cases that exercise all of the new cases in the code for this pass.
  3794. \end{exercise}
  3795. \section{Select Instructions}
  3796. \label{sec:select-r2}
  3797. Recall that the \code{select-instructions} pass lowers from our
  3798. $C$-like intermediate representation to the pseudo-x86 language, which
  3799. is suitable for conducting register allocation. The pass is
  3800. implemented using three auxiliary functions, one for each of the
  3801. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  3802. For $\Atm$, we have new cases for the Booleans. We take the usual
  3803. approach of encoding them as integers, with true as 1 and false as 0.
  3804. \[
  3805. \key{\#t} \Rightarrow \key{1}
  3806. \qquad
  3807. \key{\#f} \Rightarrow \key{0}
  3808. \]
  3809. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3810. be implemented in terms of \code{xorq} as we discussed at the
  3811. beginning of this section. Given an assignment
  3812. $\itm{lhs}$ \key{=} \key{(not} $\Arg$\key{);},
  3813. if the left-hand side $\itm{lhs}$ is
  3814. the same as $\Arg$, then just the \code{xorq} suffices.
  3815. \[
  3816. x~\key{=}~ \key{(not}\; x\key{);}
  3817. \quad\Rightarrow\quad
  3818. \key{xorq}~\key{\$}1\key{,}~x
  3819. \]
  3820. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3821. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3822. $\Arg$. Then we have
  3823. \[
  3824. \itm{lhs}~\key{=}~ \key{(not}\; \Arg\key{);}
  3825. \quad\Rightarrow\quad
  3826. \begin{array}{l}
  3827. \key{movq}~\Arg'\key{,}~\itm{lhs}\\
  3828. \key{xorq}~\key{\$}1\key{,}~\itm{lhs}
  3829. \end{array}
  3830. \]
  3831. Next consider the cases for \code{eq?} and less-than comparison.
  3832. Translating these operations to x86 is slightly involved due to the
  3833. unusual nature of the \key{cmpq} instruction discussed above. We
  3834. recommend translating an assignment from \code{eq?} into the following
  3835. sequence of three instructions. \\
  3836. \begin{tabular}{lll}
  3837. \begin{minipage}{0.4\textwidth}
  3838. \begin{lstlisting}
  3839. |$\itm{lhs}$| = (eq? |$\Arg_1$| |$\Arg_2$|);
  3840. \end{lstlisting}
  3841. \end{minipage}
  3842. &
  3843. $\Rightarrow$
  3844. &
  3845. \begin{minipage}{0.4\textwidth}
  3846. \begin{lstlisting}
  3847. cmpq |$\Arg'_2$|, |$\Arg'_1$|
  3848. sete %al
  3849. movzbq %al, |$\itm{lhs}'$|
  3850. \end{lstlisting}
  3851. \end{minipage}
  3852. \end{tabular} \\
  3853. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3854. \key{goto} and conditional \key{goto}. Both are straightforward
  3855. to handle. A \key{goto} becomes a jump instruction.
  3856. \[
  3857. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  3858. \]
  3859. A conditional \key{goto} becomes a compare instruction followed
  3860. by a conditional jump (for ``then'') and the fall-through is
  3861. to a regular jump (for ``else'').\\
  3862. \begin{tabular}{lll}
  3863. \begin{minipage}{0.4\textwidth}
  3864. \begin{lstlisting}
  3865. if (eq? |$\Arg_1$| |$\Arg_2$|) then
  3866. goto |$\ell_1$|;
  3867. else
  3868. goto |$\ell_2$|;
  3869. \end{lstlisting}
  3870. \end{minipage}
  3871. &
  3872. $\Rightarrow$
  3873. &
  3874. \begin{minipage}{0.4\textwidth}
  3875. \begin{lstlisting}
  3876. cmpq |$\Arg'_2$| |$\Arg'_1$|
  3877. je |$\ell_1$|
  3878. jmp |$\ell_2$|
  3879. \end{lstlisting}
  3880. \end{minipage}
  3881. \end{tabular} \\
  3882. \begin{exercise}\normalfont
  3883. Expand your \code{select-instructions} pass to handle the new features
  3884. of the $R_2$ language. Test the pass on all the examples you have
  3885. created and make sure that you have some test programs that use the
  3886. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3887. the output using the \code{interp-x86} interpreter
  3888. (Appendix~\ref{appendix:interp}).
  3889. \end{exercise}
  3890. \section{Register Allocation}
  3891. \label{sec:register-allocation-r2}
  3892. The changes required for $R_2$ affect liveness analysis, building the
  3893. interference graph, and assigning homes, but the graph coloring
  3894. algorithm itself does not change.
  3895. \subsection{Liveness Analysis}
  3896. \label{sec:liveness-analysis-r2}
  3897. Recall that for $R_1$ we implemented liveness analysis for a single
  3898. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3899. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3900. now produces many basic blocks arranged in a control-flow graph. The
  3901. first question we need to consider is: what order should we process
  3902. the basic blocks? Recall that to perform liveness analysis, we need to
  3903. know the live-after set. If a basic block has no successor blocks
  3904. (i.e. no out-edges in the control flow graph), then it has an empty
  3905. live-after set and we can immediately apply liveness analysis to
  3906. it. If a basic block has some successors, then we need to complete
  3907. liveness analysis on those blocks first. Furthermore, we know that
  3908. the control flow graph does not contain any cycles (it is a DAG, that
  3909. is, a directed acyclic graph)\footnote{If we were to add loops to the
  3910. language, then the CFG could contain cycles and we would instead
  3911. need to use the classic worklist algorithm for computing the fixed
  3912. point of the liveness analysis~\citep{Aho:1986qf}.}. Returning to
  3913. the question of what order should we process the basic blocks: the
  3914. answer is reverse topological order. We recommend using the
  3915. \code{tsort} (topological sort) and \code{transpose} functions of the
  3916. Racket \code{graph} package to obtain this ordering.
  3917. The next question is how to compute the live-after set of a block
  3918. given the live-before sets of all its successor blocks. During
  3919. compilation we do not know which way the branch will go, so we do not
  3920. know which of the successor's live-before set to use. The solution
  3921. comes from the observation that there is no harm to the correctness of
  3922. the compiler if we classify more variables as live than the ones that
  3923. are truly live during program execution. Thus, we can take the union
  3924. of the live-before sets from all the successors to be the live-after
  3925. set for the block. Once we have computed the live-after set, we can
  3926. proceed to perform liveness analysis on the block just as we did in
  3927. Section~\ref{sec:liveness-analysis-r1}.
  3928. The helper functions for computing the variables in an instruction's
  3929. argument and for computing the variables read-from ($R$) or written-to
  3930. ($W$) by an instruction need to be updated to handle the new kinds of
  3931. arguments and instructions in x86$_1$.
  3932. \subsection{Build Interference}
  3933. \label{sec:build-interference-r2}
  3934. Many of the new instructions in x86$_1$ can be handled in the same way
  3935. as the instructions in x86$_0$. Thus, if your code was already quite
  3936. general, it will not need to be changed to handle the new
  3937. instructions. If not, I recommend that you change your code to be more
  3938. general. The \key{movzbq} instruction should be handled like the
  3939. \key{movq} instruction.
  3940. %% \subsection{Assign Homes}
  3941. %% \label{sec:assign-homes-r2}
  3942. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3943. %% to be updated to handle the \key{if} statement, simply by recursively
  3944. %% processing the child nodes. Hopefully your code already handles the
  3945. %% other new instructions, but if not, you can generalize your code.
  3946. \begin{exercise}\normalfont
  3947. Update the \code{register-allocation} pass so that it works for $R_2$
  3948. and test your compiler using your previously created programs on the
  3949. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3950. \end{exercise}
  3951. \section{Patch Instructions}
  3952. The second argument of the \key{cmpq} instruction must not be an
  3953. immediate value (such as an integer). So if you are comparing two
  3954. immediates, we recommend inserting a \key{movq} instruction to put the
  3955. second argument in \key{rax}.
  3956. %
  3957. The second argument of the \key{movzbq} must be a register.
  3958. %
  3959. There are no special restrictions on the x86 instructions \key{JmpIf}
  3960. and \key{Jmp}.
  3961. \begin{exercise}\normalfont
  3962. Update \code{patch-instructions} to handle the new x86 instructions.
  3963. Test your compiler using your previously created programs on the
  3964. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3965. \end{exercise}
  3966. \section{An Example Translation}
  3967. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3968. $R_2$ translated to x86, showing the results of
  3969. \code{explicate-control}, \code{select-instructions}, and the final
  3970. x86 assembly code.
  3971. \begin{figure}[tbp]
  3972. \begin{tabular}{lll}
  3973. \begin{minipage}{0.5\textwidth}
  3974. % s1_20.rkt
  3975. \begin{lstlisting}
  3976. (if (eq? (read) 1) 42 0)
  3977. \end{lstlisting}
  3978. $\Downarrow$
  3979. \begin{lstlisting}
  3980. start:
  3981. tmp7951 = (read);
  3982. if (eq? tmp7951 1) then
  3983. goto block7952;
  3984. else
  3985. goto block7953;
  3986. block7952:
  3987. return 42;
  3988. block7953:
  3989. return 0;
  3990. \end{lstlisting}
  3991. $\Downarrow$
  3992. \begin{lstlisting}
  3993. start:
  3994. callq read_int
  3995. movq %rax, tmp7951
  3996. cmpq $1, tmp7951
  3997. je block7952
  3998. jmp block7953
  3999. block7953:
  4000. movq $0, %rax
  4001. jmp conclusion
  4002. block7952:
  4003. movq $42, %rax
  4004. jmp conclusion
  4005. \end{lstlisting}
  4006. \end{minipage}
  4007. &
  4008. $\Rightarrow\qquad$
  4009. \begin{minipage}{0.4\textwidth}
  4010. \begin{lstlisting}
  4011. start:
  4012. callq read_int
  4013. movq %rax, %rcx
  4014. cmpq $1, %rcx
  4015. je block7952
  4016. jmp block7953
  4017. block7953:
  4018. movq $0, %rax
  4019. jmp conclusion
  4020. block7952:
  4021. movq $42, %rax
  4022. jmp conclusion
  4023. .globl main
  4024. main:
  4025. pushq %rbp
  4026. movq %rsp, %rbp
  4027. pushq %r13
  4028. pushq %r12
  4029. pushq %rbx
  4030. pushq %r14
  4031. subq $0, %rsp
  4032. jmp start
  4033. conclusion:
  4034. addq $0, %rsp
  4035. popq %r14
  4036. popq %rbx
  4037. popq %r12
  4038. popq %r13
  4039. popq %rbp
  4040. retq
  4041. \end{lstlisting}
  4042. \end{minipage}
  4043. \end{tabular}
  4044. \caption{Example compilation of an \key{if} expression to x86.}
  4045. \label{fig:if-example-x86}
  4046. \end{figure}
  4047. \begin{figure}[p]
  4048. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4049. \node (R2) at (0,2) {\large $R_2$};
  4050. \node (R2-2) at (3,2) {\large $R_2$};
  4051. \node (R2-3) at (6,2) {\large $R_2$};
  4052. \node (R2-4) at (9,2) {\large $R_2$};
  4053. \node (R2-5) at (12,2) {\large $R_2$};
  4054. \node (C1-1) at (6,0) {\large $C_1$};
  4055. %\node (C1-2) at (3,0) {\large $C_1$};
  4056. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4057. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4058. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4059. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4060. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4061. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4062. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4063. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4064. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4065. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4066. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4067. %\path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4068. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4069. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4070. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4071. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4072. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4073. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4074. \end{tikzpicture}
  4075. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4076. \label{fig:R2-passes}
  4077. \end{figure}
  4078. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4079. compilation of $R_2$.
  4080. \section{Challenge: Optimize Jumps}
  4081. \label{sec:opt-jumps}
  4082. Recall that in the example output of \code{explicate-control} in
  4083. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4084. \code{block60} are trivial blocks, they do nothing but jump to another
  4085. block. The first goal of this challenge assignment is to remove those
  4086. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4087. \code{explicate-control} on the left and shows the result of bypassing
  4088. the trivial blocks on the right. Let us focus on \code{block61}. The
  4089. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4090. \code{block55}. The optimized code on the right of
  4091. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4092. \code{then} branch jumping directly to \code{block55}. The story is
  4093. similar for the \code{else} branch, as well as for the two branchs in
  4094. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4095. have been optimized in this way, there are no longer any jumps to
  4096. blocks \code{block57} through \code{block60}, so they can be removed.
  4097. \begin{figure}[tbp]
  4098. \begin{tabular}{lll}
  4099. \begin{minipage}{0.4\textwidth}
  4100. \begin{lstlisting}
  4101. block62:
  4102. tmp54 = (read);
  4103. if (eq? tmp54 2) then
  4104. goto block59;
  4105. else
  4106. goto block60;
  4107. block61:
  4108. tmp53 = (read);
  4109. if (eq? tmp53 0) then
  4110. goto block57;
  4111. else
  4112. goto block58;
  4113. block60:
  4114. goto block56;
  4115. block59:
  4116. goto block55;
  4117. block58:
  4118. goto block56;
  4119. block57:
  4120. goto block55;
  4121. block56:
  4122. return (+ 700 77);
  4123. block55:
  4124. return (+ 10 32);
  4125. start:
  4126. tmp52 = (read);
  4127. if (eq? tmp52 1) then
  4128. goto block61;
  4129. else
  4130. goto block62;
  4131. \end{lstlisting}
  4132. \end{minipage}
  4133. &
  4134. $\Rightarrow$
  4135. &
  4136. \begin{minipage}{0.55\textwidth}
  4137. \begin{lstlisting}
  4138. block62:
  4139. tmp54 = (read);
  4140. if (eq? tmp54 2) then
  4141. goto block55;
  4142. else
  4143. goto block56;
  4144. block61:
  4145. tmp53 = (read);
  4146. if (eq? tmp53 0) then
  4147. goto block55;
  4148. else
  4149. goto block56;
  4150. block56:
  4151. return (+ 700 77);
  4152. block55:
  4153. return (+ 10 32);
  4154. start:
  4155. tmp52 = (read);
  4156. if (eq? tmp52 1) then
  4157. goto block61;
  4158. else
  4159. goto block62;
  4160. \end{lstlisting}
  4161. \end{minipage}
  4162. \end{tabular}
  4163. \caption{Optimize jumps by removing trivial blocks.}
  4164. \label{fig:optimize-jumps}
  4165. \end{figure}
  4166. The name of this pass is \code{optimize-jumps}. We recommend
  4167. implementing this pass in two phases. The first phrase builds a hash
  4168. table that maps labels to possibly improved labels. The second phase
  4169. changes the target of each \code{goto} to use the improved label. If
  4170. the label is for a trivial block, then the hash table should map the
  4171. label to the first non-trivial block that can be reached from this
  4172. label by jumping through trivial blocks. If the label is for a
  4173. non-trivial block, then the hash table should map the label to itself;
  4174. we do not want to change jumps to non-trivial blocks.
  4175. The first phase can be accomplished by constructing an empty hash
  4176. table, call it \code{short-cut}, and then iterating over the control
  4177. flow graph. Each time you encouter a block that is just a \code{goto},
  4178. then update the hash table, mapping the block's source to the target
  4179. of the \code{goto}. Also, the hash table may already have mapped some
  4180. labels to the block's source, to you must iterate through the hash
  4181. table and update all of those so that they instead map to the target
  4182. of the \code{goto}.
  4183. For the second phase, we recommend iterating through the $\Tail$ of
  4184. each block in the program, updating the target of every \code{goto}
  4185. according to the mapping in \code{short-cut}.
  4186. \begin{exercise}\normalfont
  4187. Implement the \code{optimize-jumps} pass and check that it remove
  4188. trivial blocks in a few example programs. Then check that your
  4189. compiler still passes all of your tests.
  4190. \end{exercise}
  4191. There is another opportunity for optimizing jumps that is apparent in
  4192. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4193. end with a jump to \code{block7953} and there are no other jumps to
  4194. \code{block7953} in the rest of the program. In this situation we can
  4195. avoid the runtime overhead of this jump by merging \code{block7953}
  4196. into the preceeding block, in this case the \code{start} block.
  4197. Figure~\ref{fig:remove-jumps} shows the output of
  4198. \code{select-instructions} on the left and the result of this
  4199. optimization on the right.
  4200. \begin{figure}[tbp]
  4201. \begin{tabular}{lll}
  4202. \begin{minipage}{0.5\textwidth}
  4203. % s1_20.rkt
  4204. \begin{lstlisting}
  4205. start:
  4206. callq read_int
  4207. movq %rax, tmp7951
  4208. cmpq $1, tmp7951
  4209. je block7952
  4210. jmp block7953
  4211. block7953:
  4212. movq $0, %rax
  4213. jmp conclusion
  4214. block7952:
  4215. movq $42, %rax
  4216. jmp conclusion
  4217. \end{lstlisting}
  4218. \end{minipage}
  4219. &
  4220. $\Rightarrow\qquad$
  4221. \begin{minipage}{0.4\textwidth}
  4222. \begin{lstlisting}
  4223. start:
  4224. callq read_int
  4225. movq %rax, tmp7951
  4226. cmpq $1, tmp7951
  4227. je block7952
  4228. movq $0, %rax
  4229. jmp conclusion
  4230. block7952:
  4231. movq $42, %rax
  4232. jmp conclusion
  4233. \end{lstlisting}
  4234. \end{minipage}
  4235. \end{tabular}
  4236. \caption{Merging basic blocks by removing unnecessary jumps.}
  4237. \label{fig:remove-jumps}
  4238. \end{figure}
  4239. \begin{exercise}\normalfont
  4240. Implement a pass named \code{remove-jumps} that merges basic blocks
  4241. into their preceeding basic block, when there is only one preceeding
  4242. block. Check that your pass accomplishes this goal on several test
  4243. programs and check that your compiler passes all of your tests.
  4244. \end{exercise}
  4245. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4246. \chapter{Tuples and Garbage Collection}
  4247. \label{ch:tuples}
  4248. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4249. things to discuss in this chapter. \\ --Jeremy}
  4250. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4251. all the IR grammars are spelled out! \\ --Jeremy}
  4252. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4253. but keep type annotations on vector creation and local variables, function
  4254. parameters, etc. \\ --Jeremy}
  4255. \margincomment{\scriptsize Be more explicit about how to deal with
  4256. the root stack. \\ --Jeremy}
  4257. In this chapter we study the implementation of mutable tuples (called
  4258. ``vectors'' in Racket). This language feature is the first to use the
  4259. computer's \emph{heap} because the lifetime of a Racket tuple is
  4260. indefinite, that is, a tuple lives forever from the programmer's
  4261. viewpoint. Of course, from an implementer's viewpoint, it is important
  4262. to reclaim the space associated with a tuple when it is no longer
  4263. needed, which is why we also study \emph{garbage collection}
  4264. techniques in this chapter.
  4265. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4266. interpreter and type checker. The $R_3$ language extends the $R_2$
  4267. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4268. \code{void} value. The reason for including the later is that the
  4269. \code{vector-set!} operation returns a value of type
  4270. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4271. called the \code{Unit} type in the programming languages
  4272. literature. Racket's \code{Void} type is inhabited by a single value
  4273. \code{void} which corresponds to \code{unit} or \code{()} in the
  4274. literature~\citep{Pierce:2002hj}.}.
  4275. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4276. copying live objects back and forth between two halves of the
  4277. heap. The garbage collector requires coordination with the compiler so
  4278. that it can see all of the \emph{root} pointers, that is, pointers in
  4279. registers or on the procedure call stack.
  4280. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4281. discuss all the necessary changes and additions to the compiler
  4282. passes, including a new compiler pass named \code{expose-allocation}.
  4283. \section{The $R_3$ Language}
  4284. \label{sec:r3}
  4285. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4286. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4287. $R_3$ language includes three new forms for creating a tuple, reading
  4288. an element of a tuple, and writing to an element of a tuple. The
  4289. program in Figure~\ref{fig:vector-eg} shows the usage of tuples in
  4290. Racket. We create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is
  4291. stored at index $2$ of the 3-tuple, demonstrating that tuples are
  4292. first-class values. The element at index $1$ of \code{t} is
  4293. \code{\#t}, so the ``then'' branch of the \key{if} is taken. The
  4294. element at index $0$ of \code{t} is $40$, to which we add $2$, the
  4295. element at index $0$ of the 1-tuple. So the result of the program is
  4296. $42$.
  4297. \begin{figure}[tbp]
  4298. \begin{lstlisting}
  4299. (let ([t (vector 40 #t (vector 2))])
  4300. (if (vector-ref t 1)
  4301. (+ (vector-ref t 0)
  4302. (vector-ref (vector-ref t 2) 0))
  4303. 44))
  4304. \end{lstlisting}
  4305. \caption{Example program that creates tuples and reads from them.}
  4306. \label{fig:vector-eg}
  4307. \end{figure}
  4308. \begin{figure}[tbp]
  4309. \centering
  4310. \fbox{
  4311. \begin{minipage}{0.96\textwidth}
  4312. \[
  4313. \begin{array}{lcl}
  4314. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4315. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4316. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4317. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4318. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4319. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4320. \mid (\key{and}\;\Exp\;\Exp)
  4321. \mid (\key{or}\;\Exp\;\Exp)
  4322. \mid (\key{not}\;\Exp) } \\
  4323. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4324. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4325. &\mid& (\key{vector}\;\Exp^{+})
  4326. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4327. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4328. &\mid& (\key{void}) \\
  4329. R_3 &::=& \Exp
  4330. \end{array}
  4331. \]
  4332. \end{minipage}
  4333. }
  4334. \caption{The concrete syntax of $R_3$, extending $R_2$
  4335. (Figure~\ref{fig:r2-concrete-syntax}).}
  4336. \label{fig:r3-concrete-syntax}
  4337. \end{figure}
  4338. \begin{figure}[tp]
  4339. \centering
  4340. \fbox{
  4341. \begin{minipage}{0.96\textwidth}
  4342. \[
  4343. \begin{array}{lcl}
  4344. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4345. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4346. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4347. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4348. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4349. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4350. &\mid& \gray{ \BOOL{\itm{bool}}
  4351. \mid \AND{\Exp}{\Exp} }\\
  4352. &\mid& \gray{ \OR{\Exp}{\Exp}
  4353. \mid \NOT{\Exp} } \\
  4354. &\mid& \gray{ \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp}
  4355. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4356. &\mid& \VECTOR{\Exp} \\
  4357. &\mid& \VECREF{\Exp}{\Int}\\
  4358. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4359. &\mid& \VOID{} \\
  4360. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4361. \end{array}
  4362. \]
  4363. \end{minipage}
  4364. }
  4365. \caption{The abstract syntax of $R_3$.}
  4366. \label{fig:r3-syntax}
  4367. \end{figure}
  4368. Tuples are our first encounter with heap-allocated data, which raises
  4369. several interesting issues. First, variable binding performs a
  4370. shallow-copy when dealing with tuples, which means that different
  4371. variables can refer to the same tuple, i.e., different variables can
  4372. be \emph{aliases} for the same thing. Consider the following example
  4373. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4374. the mutation through \code{t2} is visible when referencing the tuple
  4375. from \code{t1}, so the result of this program is \code{42}.
  4376. \begin{center}
  4377. \begin{minipage}{0.96\textwidth}
  4378. \begin{lstlisting}
  4379. (let ([t1 (vector 3 7)])
  4380. (let ([t2 t1])
  4381. (let ([_ (vector-set! t2 0 42)])
  4382. (vector-ref t1 0))))
  4383. \end{lstlisting}
  4384. \end{minipage}
  4385. \end{center}
  4386. The next issue concerns the lifetime of tuples. Of course, they are
  4387. created by the \code{vector} form, but when does their lifetime end?
  4388. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4389. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4390. is not tied to any notion of static scoping. For example, the
  4391. following program returns \code{3} even though the variable \code{t}
  4392. goes out of scope prior to accessing the vector.
  4393. \begin{center}
  4394. \begin{minipage}{0.96\textwidth}
  4395. \begin{lstlisting}
  4396. (vector-ref
  4397. (let ([t (vector 3 7)])
  4398. t)
  4399. 0)
  4400. \end{lstlisting}
  4401. \end{minipage}
  4402. \end{center}
  4403. From the perspective of programmer-observable behavior, tuples live
  4404. forever. Of course, if they really lived forever, then many programs
  4405. would run out of memory.\footnote{The $R_3$ language does not have
  4406. looping or recursive function, so it is nigh impossible to write a
  4407. program in $R_3$ that will run out of memory. However, we add
  4408. recursive functions in the next Chapter!} A Racket implementation
  4409. must therefore perform automatic garbage collection.
  4410. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4411. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4412. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4413. operations in Racket. One subtle point is that the \code{vector-set!}
  4414. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4415. can be passed around just like other values inside an $R_3$ program,
  4416. but there are no operations specific to the the \code{\#<void>} value
  4417. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4418. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4419. otherwise.
  4420. \begin{figure}[tbp]
  4421. \begin{lstlisting}
  4422. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4423. (define (interp-op op)
  4424. (match op
  4425. ...
  4426. ['vector vector]
  4427. ['vector-ref vector-ref]
  4428. ['vector-set! vector-set!]
  4429. [else (error 'interp-op "unknown operator")]))
  4430. (define (interp-R3 env)
  4431. (lambda (e)
  4432. (match e
  4433. ...
  4434. [else (error 'interp-R3 "unrecognized expression")]
  4435. )))
  4436. \end{lstlisting}
  4437. \caption{Interpreter for the $R_3$ language.}
  4438. \label{fig:interp-R3}
  4439. \end{figure}
  4440. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4441. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4442. need to know which variables are pointers into the heap, that is,
  4443. which variables are vectors. Also, when allocating a vector, we need
  4444. to know which elements of the vector are pointers. We can obtain this
  4445. information during type checking. The type checker in
  4446. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4447. expression, it also wraps every sub-expression $e$ with the form
  4448. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4449. % TODO: UPDATE? -Jeremy
  4450. Subsequently, in the \code{uncover-locals} pass
  4451. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4452. propagated to all variables (including the temporaries generated by
  4453. \code{remove-complex-opera*}).
  4454. \begin{figure}[tbp]
  4455. \begin{lstlisting}
  4456. (define (type-check-exp env)
  4457. (lambda (e)
  4458. (define recur (type-check-exp env))
  4459. (match e
  4460. ...
  4461. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4462. [(Prim 'vector es)
  4463. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4464. (recur e)))
  4465. (let ([t `(Vector ,@t*)])
  4466. (values (HasType (Prim 'vector e*) t) t))]
  4467. [(Prim 'vector-ref (list e (Int i)))
  4468. (define-values (e^ t) (recur e))
  4469. (match t
  4470. [`(Vector ,ts ...)
  4471. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4472. (error 'type-check-exp "invalid index ~a" i))
  4473. (let ([t (list-ref ts i)])
  4474. (values
  4475. (HasType (Prim 'vector-ref (list e^ (HasType (Int i) 'Integer))) t)
  4476. t))]
  4477. [else (error "expected a vector in vector-ref, not" t)])]
  4478. [(Prim 'eq? (list e1 e2))
  4479. (define-values (e1^ T1) (recur e1))
  4480. (define-values (e2^ T2) (recur e2))
  4481. (unless (equal? T1 T2)
  4482. (error "arguments of eq? must have the same type, but are not"
  4483. (list T1 T2)))
  4484. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4485. ...
  4486. )))
  4487. \end{lstlisting}
  4488. \caption{Type checker for the $R_3$ language.}
  4489. \label{fig:typecheck-R3}
  4490. \end{figure}
  4491. \section{Garbage Collection}
  4492. \label{sec:GC}
  4493. Here we study a relatively simple algorithm for garbage collection
  4494. that is the basis of state-of-the-art garbage
  4495. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4496. particular, we describe a two-space copying
  4497. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4498. perform the
  4499. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4500. coarse-grained depiction of what happens in a two-space collector,
  4501. showing two time steps, prior to garbage collection on the top and
  4502. after garbage collection on the bottom. In a two-space collector, the
  4503. heap is divided into two parts, the FromSpace and the
  4504. ToSpace. Initially, all allocations go to the FromSpace until there is
  4505. not enough room for the next allocation request. At that point, the
  4506. garbage collector goes to work to make more room.
  4507. The garbage collector must be careful not to reclaim tuples that will
  4508. be used by the program in the future. Of course, it is impossible in
  4509. general to predict what a program will do, but we can over approximate
  4510. the will-be-used tuples by preserving all tuples that could be
  4511. accessed by \emph{any} program given the current computer state. A
  4512. program could access any tuple whose address is in a register or on
  4513. the procedure call stack. These addresses are called the \emph{root
  4514. set}. In addition, a program could access any tuple that is
  4515. transitively reachable from the root set. Thus, it is safe for the
  4516. garbage collector to reclaim the tuples that are not reachable in this
  4517. way.
  4518. So the goal of the garbage collector is twofold:
  4519. \begin{enumerate}
  4520. \item preserve all tuple that are reachable from the root set via a
  4521. path of pointers, that is, the \emph{live} tuples, and
  4522. \item reclaim the memory of everything else, that is, the
  4523. \emph{garbage}.
  4524. \end{enumerate}
  4525. A copying collector accomplishes this by copying all of the live
  4526. objects from the FromSpace into the ToSpace and then performs a slight
  4527. of hand, treating the ToSpace as the new FromSpace and the old
  4528. FromSpace as the new ToSpace. In the example of
  4529. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4530. root set, one in a register and two on the stack. All of the live
  4531. objects have been copied to the ToSpace (the right-hand side of
  4532. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4533. pointer relationships. For example, the pointer in the register still
  4534. points to a 2-tuple whose first element is a 3-tuple and second
  4535. element is a 2-tuple. There are four tuples that are not reachable
  4536. from the root set and therefore do not get copied into the ToSpace.
  4537. (The situation in Figure~\ref{fig:copying-collector}, with a
  4538. cycle, cannot be created by a well-typed program in $R_3$. However,
  4539. creating cycles will be possible once we get to $R_6$. We design
  4540. the garbage collector to deal with cycles to begin with, so we will
  4541. not need to revisit this issue.)
  4542. \begin{figure}[tbp]
  4543. \centering
  4544. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4545. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4546. \caption{A copying collector in action.}
  4547. \label{fig:copying-collector}
  4548. \end{figure}
  4549. There are many alternatives to copying collectors (and their older
  4550. siblings, the generational collectors) when its comes to garbage
  4551. collection, such as mark-and-sweep and reference counting. The
  4552. strengths of copying collectors are that allocation is fast (just a
  4553. test and pointer increment), there is no fragmentation, cyclic garbage
  4554. is collected, and the time complexity of collection only depends on
  4555. the amount of live data, and not on the amount of
  4556. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4557. copying collectors is that they use a lot of space, though that
  4558. problem is ameliorated in generational collectors. Racket and Scheme
  4559. programs tend to allocate many small objects and generate a lot of
  4560. garbage, so copying and generational collectors are a good fit. Of
  4561. course, garbage collection is an active research topic, especially
  4562. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4563. continuously developing new techniques and revisiting old
  4564. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4565. \subsection{Graph Copying via Cheney's Algorithm}
  4566. \label{sec:cheney}
  4567. Let us take a closer look at how the copy works. The allocated objects
  4568. and pointers can be viewed as a graph and we need to copy the part of
  4569. the graph that is reachable from the root set. To make sure we copy
  4570. all of the reachable vertices in the graph, we need an exhaustive
  4571. graph traversal algorithm, such as depth-first search or breadth-first
  4572. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4573. take into account the possibility of cycles by marking which vertices
  4574. have already been visited, so as to ensure termination of the
  4575. algorithm. These search algorithms also use a data structure such as a
  4576. stack or queue as a to-do list to keep track of the vertices that need
  4577. to be visited. We shall use breadth-first search and a trick due to
  4578. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4579. copying tuples into the ToSpace.
  4580. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4581. copy progresses. The queue is represented by a chunk of contiguous
  4582. memory at the beginning of the ToSpace, using two pointers to track
  4583. the front and the back of the queue. The algorithm starts by copying
  4584. all tuples that are immediately reachable from the root set into the
  4585. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4586. old tuple to indicate that it has been visited. (We discuss the
  4587. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4588. inside the copied tuples in the queue still point back to the
  4589. FromSpace. Once the initial queue has been created, the algorithm
  4590. enters a loop in which it repeatedly processes the tuple at the front
  4591. of the queue and pops it off the queue. To process a tuple, the
  4592. algorithm copies all the tuple that are directly reachable from it to
  4593. the ToSpace, placing them at the back of the queue. The algorithm then
  4594. updates the pointers in the popped tuple so they point to the newly
  4595. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4596. step we copy the tuple whose second element is $42$ to the back of the
  4597. queue. The other pointer goes to a tuple that has already been copied,
  4598. so we do not need to copy it again, but we do need to update the
  4599. pointer to the new location. This can be accomplished by storing a
  4600. \emph{forwarding} pointer to the new location in the old tuple, back
  4601. when we initially copied the tuple into the ToSpace. This completes
  4602. one step of the algorithm. The algorithm continues in this way until
  4603. the front of the queue is empty, that is, until the front catches up
  4604. with the back.
  4605. \begin{figure}[tbp]
  4606. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4607. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4608. \label{fig:cheney}
  4609. \end{figure}
  4610. \subsection{Data Representation}
  4611. \label{sec:data-rep-gc}
  4612. The garbage collector places some requirements on the data
  4613. representations used by our compiler. First, the garbage collector
  4614. needs to distinguish between pointers and other kinds of data. There
  4615. are several ways to accomplish this.
  4616. \begin{enumerate}
  4617. \item Attached a tag to each object that identifies what type of
  4618. object it is~\citep{McCarthy:1960dz}.
  4619. \item Store different types of objects in different
  4620. regions~\citep{Steele:1977ab}.
  4621. \item Use type information from the program to either generate
  4622. type-specific code for collecting or to generate tables that can
  4623. guide the
  4624. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4625. \end{enumerate}
  4626. Dynamically typed languages, such as Lisp, need to tag objects
  4627. anyways, so option 1 is a natural choice for those languages.
  4628. However, $R_3$ is a statically typed language, so it would be
  4629. unfortunate to require tags on every object, especially small and
  4630. pervasive objects like integers and Booleans. Option 3 is the
  4631. best-performing choice for statically typed languages, but comes with
  4632. a relatively high implementation complexity. To keep this chapter to a
  4633. 2-week time budget, we recommend a combination of options 1 and 2,
  4634. with separate strategies used for the stack and the heap.
  4635. Regarding the stack, we recommend using a separate stack for
  4636. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4637. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4638. local variable needs to be spilled and is of type \code{(Vector
  4639. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4640. of the normal procedure call stack. Furthermore, we always spill
  4641. vector-typed variables if they are live during a call to the
  4642. collector, thereby ensuring that no pointers are in registers during a
  4643. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4644. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4645. layout using a root stack. The root stack contains the two pointers
  4646. from the regular stack and also the pointer in the second
  4647. register.
  4648. \begin{figure}[tbp]
  4649. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4650. \caption{Maintaining a root stack to facilitate garbage collection.}
  4651. \label{fig:shadow-stack}
  4652. \end{figure}
  4653. The problem of distinguishing between pointers and other kinds of data
  4654. also arises inside of each tuple. We solve this problem by attaching a
  4655. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4656. in on the tags for two of the tuples in the example from
  4657. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4658. in a big-endian way, from right-to-left, with bit location 0 (the
  4659. least significant bit) on the far right, which corresponds to the
  4660. directional of the x86 shifting instructions \key{salq} (shift
  4661. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4662. specifying which elements of the tuple are pointers, the part labeled
  4663. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4664. a pointer and a 0 bit indicates some other kind of data. The pointer
  4665. mask starts at bit location 7. We have limited tuples to a maximum
  4666. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4667. tag also contains two other pieces of information. The length of the
  4668. tuple (number of elements) is stored in bits location 1 through
  4669. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4670. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4671. has not yet been copied. If the bit has value 0 then the entire tag
  4672. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4673. always zero anyways because our tuples are 8-byte aligned.)
  4674. \begin{figure}[tbp]
  4675. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4676. \caption{Representation for tuples in the heap.}
  4677. \label{fig:tuple-rep}
  4678. \end{figure}
  4679. \subsection{Implementation of the Garbage Collector}
  4680. \label{sec:organize-gz}
  4681. The implementation of the garbage collector needs to do a lot of
  4682. bit-level data manipulation and we need to link it with our
  4683. compiler-generated x86 code. Thus, we recommend implementing the
  4684. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4685. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4686. interface to the garbage collector. The \code{initialize} function
  4687. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4688. function is meant to be called near the beginning of \code{main},
  4689. before the rest of the program executes. The \code{initialize}
  4690. function puts the address of the beginning of the FromSpace into the
  4691. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4692. points to the address that is 1-past the last element of the
  4693. FromSpace. (We use half-open intervals to represent chunks of
  4694. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4695. points to the first element of the root stack.
  4696. As long as there is room left in the FromSpace, your generated code
  4697. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4698. %
  4699. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4700. --Jeremy}
  4701. %
  4702. The amount of room left in FromSpace is the difference between the
  4703. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4704. function should be called when there is not enough room left in the
  4705. FromSpace for the next allocation. The \code{collect} function takes
  4706. a pointer to the current top of the root stack (one past the last item
  4707. that was pushed) and the number of bytes that need to be
  4708. allocated. The \code{collect} function performs the copying collection
  4709. and leaves the heap in a state such that the next allocation will
  4710. succeed.
  4711. \begin{figure}[tbp]
  4712. \begin{lstlisting}
  4713. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4714. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4715. int64_t* free_ptr;
  4716. int64_t* fromspace_begin;
  4717. int64_t* fromspace_end;
  4718. int64_t** rootstack_begin;
  4719. \end{lstlisting}
  4720. \caption{The compiler's interface to the garbage collector.}
  4721. \label{fig:gc-header}
  4722. \end{figure}
  4723. \begin{exercise}
  4724. In the file \code{runtime.c} you will find the implementation of
  4725. \code{initialize} and a partial implementation of \code{collect}.
  4726. The \code{collect} function calls another function, \code{cheney},
  4727. to perform the actual copy, and that function is left to the reader
  4728. to implement. The following is the prototype for \code{cheney}.
  4729. \begin{lstlisting}
  4730. static void cheney(int64_t** rootstack_ptr);
  4731. \end{lstlisting}
  4732. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4733. rootstack (which is an array of pointers). The \code{cheney} function
  4734. also communicates with \code{collect} through the global
  4735. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4736. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4737. the ToSpace:
  4738. \begin{lstlisting}
  4739. static int64_t* tospace_begin;
  4740. static int64_t* tospace_end;
  4741. \end{lstlisting}
  4742. The job of the \code{cheney} function is to copy all the live
  4743. objects (reachable from the root stack) into the ToSpace, update
  4744. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4745. update the root stack so that it points to the objects in the
  4746. ToSpace, and finally to swap the global pointers for the FromSpace
  4747. and ToSpace.
  4748. \end{exercise}
  4749. %% \section{Compiler Passes}
  4750. %% \label{sec:code-generation-gc}
  4751. The introduction of garbage collection has a non-trivial impact on our
  4752. compiler passes. We introduce one new compiler pass called
  4753. \code{expose-allocation} and make non-trivial changes to
  4754. \code{type-check}, \code{flatten}, \code{select-instructions},
  4755. \code{allocate-registers}, and \code{print-x86}. The following
  4756. program will serve as our running example. It creates two tuples, one
  4757. nested inside the other. Both tuples have length one. The example then
  4758. accesses the element in the inner tuple tuple via two vector
  4759. references.
  4760. % tests/s2_17.rkt
  4761. \begin{lstlisting}
  4762. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4763. \end{lstlisting}
  4764. Next we proceed to discuss the new \code{expose-allocation} pass.
  4765. \section{Expose Allocation}
  4766. \label{sec:expose-allocation}
  4767. The pass \code{expose-allocation} lowers the \code{vector} creation
  4768. form into a conditional call to the collector followed by the
  4769. allocation. We choose to place the \code{expose-allocation} pass
  4770. before \code{flatten} because \code{expose-allocation} introduces new
  4771. variables, which can be done locally with \code{let}, but \code{let}
  4772. is gone after \code{flatten}. In the following, we show the
  4773. transformation for the \code{vector} form into let-bindings for the
  4774. initializing expressions, by a conditional \code{collect}, an
  4775. \code{allocate}, and the initialization of the vector.
  4776. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4777. total bytes need to be allocated for the vector, which is 8 for the
  4778. tag plus \itm{len} times 8.)
  4779. \begin{lstlisting}
  4780. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4781. |$\Longrightarrow$|
  4782. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4783. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4784. (global-value fromspace_end))
  4785. (void)
  4786. (collect |\itm{bytes}|))])
  4787. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4788. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4789. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4790. |$v$|) ... )))) ...)
  4791. \end{lstlisting}
  4792. (In the above, we suppressed all of the \code{has-type} forms in the
  4793. output for the sake of readability.) The placement of the initializing
  4794. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4795. the sequence of \code{vector-set!}'s is important, as those expressions
  4796. may trigger garbage collection and we do not want an allocated but
  4797. uninitialized tuple to be present during a garbage collection.
  4798. The output of \code{expose-allocation} is a language that extends
  4799. $R_3$ with the three new forms that we use above in the translation of
  4800. \code{vector}.
  4801. \[
  4802. \begin{array}{lcl}
  4803. \Exp &::=& \cdots
  4804. \mid (\key{collect} \,\itm{int})
  4805. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4806. \mid (\key{global-value} \,\itm{name})
  4807. \end{array}
  4808. \]
  4809. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4810. %% the beginning of the program which will instruct the garbage collector
  4811. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4812. %% two arguments of \code{initialize} specify the initial allocated space
  4813. %% for the root stack and for the heap.
  4814. %
  4815. %% The \code{expose-allocation} pass annotates all of the local variables
  4816. %% in the \code{program} form with their type.
  4817. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4818. \code{expose-allocation} pass on our running example.
  4819. \begin{figure}[tbp]
  4820. % tests/s2_17.rkt
  4821. \begin{lstlisting}
  4822. (vector-ref
  4823. (vector-ref
  4824. (let ([vecinit7976
  4825. (let ([vecinit7972 42])
  4826. (let ([collectret7974
  4827. (if (< (+ free_ptr 16) fromspace_end)
  4828. (void)
  4829. (collect 16);
  4830. )])
  4831. (let ([alloc7971 (allocate 1 (Vector Integer))])
  4832. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  4833. alloc7971)
  4834. )
  4835. )
  4836. )
  4837. ])
  4838. (let ([collectret7978
  4839. (if (< (+ free_ptr 16) fromspace_end)
  4840. (void)
  4841. (collect 16);
  4842. )])
  4843. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  4844. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  4845. alloc7975)
  4846. )
  4847. )
  4848. )
  4849. 0)
  4850. 0)
  4851. \end{lstlisting}
  4852. \caption{Output of the \code{expose-allocation} pass, minus
  4853. all of the \code{HasType} forms.}
  4854. \label{fig:expose-alloc-output}
  4855. \end{figure}
  4856. %\clearpage
  4857. \section{Explicate Control and the $C_2$ language}
  4858. \label{sec:explicate-control-r3}
  4859. \begin{figure}[tp]
  4860. \fbox{
  4861. \begin{minipage}{0.96\textwidth}
  4862. \[
  4863. \begin{array}{lcl}
  4864. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4865. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4866. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4867. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4868. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4869. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4870. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4871. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4872. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4873. \mid (\key{collect} \,\itm{int}) \\
  4874. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4875. &\mid& \gray{(\key{goto}\,\itm{label})
  4876. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4877. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4878. \end{array}
  4879. \]
  4880. \end{minipage}
  4881. }
  4882. \caption{The $C_2$ language, extending $C_1$
  4883. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4884. \label{fig:c2-syntax}
  4885. \end{figure}
  4886. The output of \code{explicate-control} is a program in the
  4887. intermediate language $C_2$, whose syntax is defined in
  4888. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4889. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4890. \key{global-value} expressions and the \code{collect} statement. The
  4891. \code{explicate-control} pass can treat these new forms much like the
  4892. other forms.
  4893. \section{Uncover Locals}
  4894. \label{sec:uncover-locals-r3}
  4895. Recall that the \code{explicate-control} function collects all of the
  4896. local variables so that it can store them in the $\itm{info}$ field of
  4897. the \code{Program} structure. Also recall that we need to know the
  4898. types of all the local variables for purposes of identifying the root
  4899. set for the garbage collector. Thus, we create a pass named
  4900. \code{uncover-locals} to collect not just the variables but the
  4901. variables and their types in the form of an association list. Thanks
  4902. to the \code{HasType} nodes, the types are readily available in the
  4903. AST. Figure~\ref{fig:uncover-locals-r3} lists the output of the
  4904. \code{uncover-locals} pass on the running example.
  4905. \begin{figure}[tbp]
  4906. % tests/s2_17.rkt
  4907. \begin{lstlisting}
  4908. program:
  4909. locals:
  4910. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  4911. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  4912. collectret7974 : 'Void, initret7977 : 'Void,
  4913. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  4914. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  4915. alloc7971 : '(Vector Integer), tmp7981 : 'Integer, vecinit7972 : 'Integer,
  4916. initret7973 : 'Void,
  4917. block7991:
  4918. (collect 16);
  4919. goto block7989;
  4920. block7990:
  4921. collectret7974 = (void);
  4922. goto block7989;
  4923. block7989:
  4924. alloc7971 = (allocate 1 (Vector Integer));
  4925. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  4926. vecinit7976 = alloc7971;
  4927. tmp7982 = free_ptr;
  4928. tmp7983 = (+ tmp7982 16);
  4929. tmp7984 = fromspace_end;
  4930. if (< tmp7983 tmp7984) then
  4931. goto block7987;
  4932. else
  4933. goto block7988;
  4934. block7988:
  4935. (collect 16);
  4936. goto block7986;
  4937. block7987:
  4938. collectret7978 = (void);
  4939. goto block7986;
  4940. block7986:
  4941. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  4942. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  4943. tmp7985 = (vector-ref alloc7975 0);
  4944. return (vector-ref tmp7985 0);
  4945. start:
  4946. vecinit7972 = 42;
  4947. tmp7979 = free_ptr;
  4948. tmp7980 = (+ tmp7979 16);
  4949. tmp7981 = fromspace_end;
  4950. if (< tmp7980 tmp7981) then
  4951. goto block7990;
  4952. else
  4953. goto block7991;
  4954. \end{lstlisting}
  4955. \caption{Output of \code{uncover-locals} for the running example.}
  4956. \label{fig:uncover-locals-r3}
  4957. \end{figure}
  4958. \clearpage
  4959. \section{Select Instructions}
  4960. \label{sec:select-instructions-gc}
  4961. %% void (rep as zero)
  4962. %% allocate
  4963. %% collect (callq collect)
  4964. %% vector-ref
  4965. %% vector-set!
  4966. %% global-value (postpone)
  4967. In this pass we generate x86 code for most of the new operations that
  4968. were needed to compile tuples, including \code{allocate},
  4969. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4970. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4971. The \code{vector-ref} and \code{vector-set!} forms translate into
  4972. \code{movq} instructions with the appropriate \key{deref}. (The
  4973. plus one is to get past the tag at the beginning of the tuple
  4974. representation.)
  4975. \begin{lstlisting}
  4976. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4977. |$\Longrightarrow$|
  4978. (movq |$\itm{vec}'$| (reg r11))
  4979. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4980. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4981. |$\Longrightarrow$|
  4982. (movq |$\itm{vec}'$| (reg r11))
  4983. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4984. (movq (int 0) |$\itm{lhs}$|)
  4985. \end{lstlisting}
  4986. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4987. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4988. register \code{r11} ensures that offsets are only performed with
  4989. register operands. This requires removing \code{r11} from
  4990. consideration by the register allocating.
  4991. We compile the \code{allocate} form to operations on the
  4992. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4993. is the next free address in the FromSpace, so we move it into the
  4994. \itm{lhs} and then move it forward by enough space for the tuple being
  4995. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4996. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4997. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4998. how the tag is organized. We recommend using the Racket operations
  4999. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  5000. The type annotation in the \code{vector} form is used to determine the
  5001. pointer mask region of the tag.
  5002. \begin{lstlisting}
  5003. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  5004. |$\Longrightarrow$|
  5005. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  5006. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  5007. (movq |$\itm{lhs}'$| (reg r11))
  5008. (movq (int |$\itm{tag}$|) (deref r11 0))
  5009. \end{lstlisting}
  5010. The \code{collect} form is compiled to a call to the \code{collect}
  5011. function in the runtime. The arguments to \code{collect} are the top
  5012. of the root stack and the number of bytes that need to be allocated.
  5013. We shall use a dedicated register, \code{r15}, to store the pointer to
  5014. the top of the root stack. So \code{r15} is not available for use by
  5015. the register allocator.
  5016. \begin{lstlisting}
  5017. (collect |$\itm{bytes}$|)
  5018. |$\Longrightarrow$|
  5019. (movq (reg r15) (reg rdi))
  5020. (movq |\itm{bytes}| (reg rsi))
  5021. (callq collect)
  5022. \end{lstlisting}
  5023. \begin{figure}[tp]
  5024. \fbox{
  5025. \begin{minipage}{0.96\textwidth}
  5026. \[
  5027. \begin{array}{lcl}
  5028. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5029. \mid (\key{deref}\,\Reg\,\Int) } \\
  5030. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  5031. \mid (\key{global-value}\; \itm{name}) \\
  5032. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5033. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  5034. (\key{subq} \; \Arg\; \Arg) \mid
  5035. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  5036. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  5037. (\key{pushq}\;\Arg) \mid
  5038. (\key{popq}\;\Arg) \mid
  5039. (\key{retq})} \\
  5040. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5041. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5042. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5043. \mid (\key{jmp} \; \itm{label})
  5044. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  5045. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  5046. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  5047. \end{array}
  5048. \]
  5049. \end{minipage}
  5050. }
  5051. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5052. \label{fig:x86-2}
  5053. \end{figure}
  5054. The syntax of the $x86_2$ language is defined in
  5055. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  5056. of the form for global variables.
  5057. %
  5058. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5059. \code{select-instructions} pass on the running example.
  5060. \begin{figure}[tbp]
  5061. \centering
  5062. \begin{minipage}{0.75\textwidth}
  5063. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5064. (program
  5065. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5066. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5067. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5068. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5069. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5070. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5071. ((block63 . (block ()
  5072. (movq (reg r15) (reg rdi))
  5073. (movq (int 16) (reg rsi))
  5074. (callq collect)
  5075. (jmp block61)))
  5076. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5077. (block61 . (block ()
  5078. (movq (global-value free_ptr) (var alloc43))
  5079. (addq (int 16) (global-value free_ptr))
  5080. (movq (var alloc43) (reg r11))
  5081. (movq (int 3) (deref r11 0))
  5082. (movq (var alloc43) (reg r11))
  5083. (movq (var vecinit44) (deref r11 8))
  5084. (movq (int 0) (var initret45))
  5085. (movq (var alloc43) (var vecinit48))
  5086. (movq (global-value free_ptr) (var tmp54))
  5087. (movq (var tmp54) (var tmp55))
  5088. (addq (int 16) (var tmp55))
  5089. (movq (global-value fromspace_end) (var tmp56))
  5090. (cmpq (var tmp56) (var tmp55))
  5091. (jmp-if l block59)
  5092. (jmp block60)))
  5093. (block60 . (block ()
  5094. (movq (reg r15) (reg rdi))
  5095. (movq (int 16) (reg rsi))
  5096. (callq collect)
  5097. (jmp block58))
  5098. (block59 . (block ()
  5099. (movq (int 0) (var collectret50))
  5100. (jmp block58)))
  5101. (block58 . (block ()
  5102. (movq (global-value free_ptr) (var alloc47))
  5103. (addq (int 16) (global-value free_ptr))
  5104. (movq (var alloc47) (reg r11))
  5105. (movq (int 131) (deref r11 0))
  5106. (movq (var alloc47) (reg r11))
  5107. (movq (var vecinit48) (deref r11 8))
  5108. (movq (int 0) (var initret49))
  5109. (movq (var alloc47) (reg r11))
  5110. (movq (deref r11 8) (var tmp57))
  5111. (movq (var tmp57) (reg r11))
  5112. (movq (deref r11 8) (reg rax))
  5113. (jmp conclusion)))
  5114. (start . (block ()
  5115. (movq (int 42) (var vecinit44))
  5116. (movq (global-value free_ptr) (var tmp51))
  5117. (movq (var tmp51) (var tmp52))
  5118. (addq (int 16) (var tmp52))
  5119. (movq (global-value fromspace_end) (var tmp53))
  5120. (cmpq (var tmp53) (var tmp52))
  5121. (jmp-if l block62)
  5122. (jmp block63))))))
  5123. \end{lstlisting}
  5124. \end{minipage}
  5125. \caption{Output of the \code{select-instructions} pass.}
  5126. \label{fig:select-instr-output-gc}
  5127. \end{figure}
  5128. \clearpage
  5129. \section{Register Allocation}
  5130. \label{sec:reg-alloc-gc}
  5131. As discussed earlier in this chapter, the garbage collector needs to
  5132. access all the pointers in the root set, that is, all variables that
  5133. are vectors. It will be the responsibility of the register allocator
  5134. to make sure that:
  5135. \begin{enumerate}
  5136. \item the root stack is used for spilling vector-typed variables, and
  5137. \item if a vector-typed variable is live during a call to the
  5138. collector, it must be spilled to ensure it is visible to the
  5139. collector.
  5140. \end{enumerate}
  5141. The later responsibility can be handled during construction of the
  5142. inference graph, by adding interference edges between the call-live
  5143. vector-typed variables and all the callee-saved registers. (They
  5144. already interfere with the caller-saved registers.) The type
  5145. information for variables is in the \code{program} form, so we
  5146. recommend adding another parameter to the \code{build-interference}
  5147. function to communicate this association list.
  5148. The spilling of vector-typed variables to the root stack can be
  5149. handled after graph coloring, when choosing how to assign the colors
  5150. (integers) to registers and stack locations. The \code{program} output
  5151. of this pass changes to also record the number of spills to the root
  5152. stack.
  5153. % build-interference
  5154. %
  5155. % callq
  5156. % extra parameter for var->type assoc. list
  5157. % update 'program' and 'if'
  5158. % allocate-registers
  5159. % allocate spilled vectors to the rootstack
  5160. % don't change color-graph
  5161. \section{Print x86}
  5162. \label{sec:print-x86-gc}
  5163. \margincomment{\scriptsize We need to show the translation to x86 and what
  5164. to do about global-value. \\ --Jeremy}
  5165. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5166. \code{print-x86} pass on the running example. In the prelude and
  5167. conclusion of the \code{main} function, we treat the root stack very
  5168. much like the regular stack in that we move the root stack pointer
  5169. (\code{r15}) to make room for all of the spills to the root stack,
  5170. except that the root stack grows up instead of down. For the running
  5171. example, there was just one spill so we increment \code{r15} by 8
  5172. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5173. One issue that deserves special care is that there may be a call to
  5174. \code{collect} prior to the initializing assignments for all the
  5175. variables in the root stack. We do not want the garbage collector to
  5176. accidentally think that some uninitialized variable is a pointer that
  5177. needs to be followed. Thus, we zero-out all locations on the root
  5178. stack in the prelude of \code{main}. In
  5179. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5180. %
  5181. \lstinline{movq $0, (%r15)}
  5182. %
  5183. accomplishes this task. The garbage collector tests each root to see
  5184. if it is null prior to dereferencing it.
  5185. \begin{figure}[htbp]
  5186. \begin{minipage}[t]{0.5\textwidth}
  5187. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5188. _block58:
  5189. movq _free_ptr(%rip), %rcx
  5190. addq $16, _free_ptr(%rip)
  5191. movq %rcx, %r11
  5192. movq $131, 0(%r11)
  5193. movq %rcx, %r11
  5194. movq -8(%r15), %rax
  5195. movq %rax, 8(%r11)
  5196. movq $0, %rdx
  5197. movq %rcx, %r11
  5198. movq 8(%r11), %rcx
  5199. movq %rcx, %r11
  5200. movq 8(%r11), %rax
  5201. jmp _conclusion
  5202. _block59:
  5203. movq $0, %rcx
  5204. jmp _block58
  5205. _block62:
  5206. movq $0, %rcx
  5207. jmp _block61
  5208. _block60:
  5209. movq %r15, %rdi
  5210. movq $16, %rsi
  5211. callq _collect
  5212. jmp _block58
  5213. _block63:
  5214. movq %r15, %rdi
  5215. movq $16, %rsi
  5216. callq _collect
  5217. jmp _block61
  5218. _start:
  5219. movq $42, %rbx
  5220. movq _free_ptr(%rip), %rdx
  5221. addq $16, %rdx
  5222. movq _fromspace_end(%rip), %rcx
  5223. cmpq %rcx, %rdx
  5224. jl _block62
  5225. jmp _block63
  5226. \end{lstlisting}
  5227. \end{minipage}
  5228. \begin{minipage}[t]{0.45\textwidth}
  5229. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5230. _block61:
  5231. movq _free_ptr(%rip), %rcx
  5232. addq $16, _free_ptr(%rip)
  5233. movq %rcx, %r11
  5234. movq $3, 0(%r11)
  5235. movq %rcx, %r11
  5236. movq %rbx, 8(%r11)
  5237. movq $0, %rdx
  5238. movq %rcx, -8(%r15)
  5239. movq _free_ptr(%rip), %rcx
  5240. addq $16, %rcx
  5241. movq _fromspace_end(%rip), %rdx
  5242. cmpq %rdx, %rcx
  5243. jl _block59
  5244. jmp _block60
  5245. .globl _main
  5246. _main:
  5247. pushq %rbp
  5248. movq %rsp, %rbp
  5249. pushq %r12
  5250. pushq %rbx
  5251. pushq %r13
  5252. pushq %r14
  5253. subq $0, %rsp
  5254. movq $16384, %rdi
  5255. movq $16, %rsi
  5256. callq _initialize
  5257. movq _rootstack_begin(%rip), %r15
  5258. movq $0, (%r15)
  5259. addq $8, %r15
  5260. jmp _start
  5261. _conclusion:
  5262. subq $8, %r15
  5263. addq $0, %rsp
  5264. popq %r14
  5265. popq %r13
  5266. popq %rbx
  5267. popq %r12
  5268. popq %rbp
  5269. retq
  5270. \end{lstlisting}
  5271. \end{minipage}
  5272. \caption{Output of the \code{print-x86} pass.}
  5273. \label{fig:print-x86-output-gc}
  5274. \end{figure}
  5275. \margincomment{\scriptsize Suggest an implementation strategy
  5276. in which the students first do the code gen and test that
  5277. without GC (just use a big heap), then after that is debugged,
  5278. implement the GC. \\ --Jeremy}
  5279. \begin{figure}[p]
  5280. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5281. \node (R3) at (0,2) {\large $R_3$};
  5282. \node (R3-2) at (3,2) {\large $R_3$};
  5283. \node (R3-3) at (6,2) {\large $R_3$};
  5284. \node (R3-4) at (9,2) {\large $R_3$};
  5285. \node (R3-5) at (12,2) {\large $R_3$};
  5286. \node (C2-4) at (3,0) {\large $C_2$};
  5287. \node (C2-3) at (6,0) {\large $C_2$};
  5288. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5289. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5290. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5291. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5292. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5293. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5294. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5295. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5296. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5297. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5298. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5299. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5300. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5301. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5302. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5303. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5304. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5305. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5306. \end{tikzpicture}
  5307. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5308. \label{fig:R3-passes}
  5309. \end{figure}
  5310. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5311. for the compilation of $R_3$.
  5312. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5313. \chapter{Functions}
  5314. \label{ch:functions}
  5315. This chapter studies the compilation of functions at the level of
  5316. abstraction of the C language. This corresponds to a subset of Typed
  5317. Racket in which only top-level function definitions are allowed. These
  5318. kind of functions are an important stepping stone to implementing
  5319. lexically-scoped functions in the form of \key{lambda} abstractions,
  5320. which is the topic of Chapter~\ref{ch:lambdas}.
  5321. \section{The $R_4$ Language}
  5322. The syntax for function definitions and function application is shown
  5323. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5324. Programs in $R_4$ start with zero or more function definitions. The
  5325. function names from these definitions are in-scope for the entire
  5326. program, including all other function definitions (so the ordering of
  5327. function definitions does not matter). The syntax for function
  5328. application does not include an explicit keyword, which is error prone
  5329. when using \code{match}. To alleviate this problem, we change the
  5330. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5331. during type checking.
  5332. Functions are first-class in the sense that a function pointer is data
  5333. and can be stored in memory or passed as a parameter to another
  5334. function. Thus, we introduce a function type, written
  5335. \begin{lstlisting}
  5336. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5337. \end{lstlisting}
  5338. for a function whose $n$ parameters have the types $\Type_1$ through
  5339. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5340. these functions (with respect to Racket functions) is that they are
  5341. not lexically scoped. That is, the only external entities that can be
  5342. referenced from inside a function body are other globally-defined
  5343. functions. The syntax of $R_4$ prevents functions from being nested
  5344. inside each other.
  5345. \begin{figure}[tp]
  5346. \centering
  5347. \fbox{
  5348. \begin{minipage}{0.96\textwidth}
  5349. \[
  5350. \begin{array}{lcl}
  5351. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5352. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5353. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5354. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5355. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5356. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5357. \mid (\key{and}\;\Exp\;\Exp)
  5358. \mid (\key{or}\;\Exp\;\Exp)
  5359. \mid (\key{not}\;\Exp)} \\
  5360. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5361. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5362. (\key{vector-ref}\;\Exp\;\Int)} \\
  5363. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5364. &\mid& (\Exp \; \Exp^{*}) \\
  5365. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5366. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5367. \end{array}
  5368. \]
  5369. \end{minipage}
  5370. }
  5371. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5372. with functions.}
  5373. \label{fig:r4-syntax}
  5374. \end{figure}
  5375. The program in Figure~\ref{fig:r4-function-example} is a
  5376. representative example of defining and using functions in $R_4$. We
  5377. define a function \code{map-vec} that applies some other function
  5378. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5379. vector containing the results. We also define a function \code{add1}
  5380. that does what its name suggests. The program then applies
  5381. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5382. \code{(vector 1 42)}, from which we return the \code{42}.
  5383. \begin{figure}[tbp]
  5384. \begin{lstlisting}
  5385. (program ()
  5386. (define (map-vec [f : (Integer -> Integer)]
  5387. [v : (Vector Integer Integer)])
  5388. : (Vector Integer Integer)
  5389. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5390. (define (add1 [x : Integer]) : Integer
  5391. (+ x 1))
  5392. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5393. )
  5394. \end{lstlisting}
  5395. \caption{Example of using functions in $R_4$.}
  5396. \label{fig:r4-function-example}
  5397. \end{figure}
  5398. The definitional interpreter for $R_4$ is in
  5399. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5400. responsible for setting up the mutual recursion between the top-level
  5401. function definitions. We use the classic back-patching approach that
  5402. uses mutable variables and makes two passes over the function
  5403. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5404. top-level environment using a mutable cons cell for each function
  5405. definition. Note that the \code{lambda} value for each function is
  5406. incomplete; it does not yet include the environment. Once the
  5407. top-level environment is constructed, we then iterate over it and
  5408. update the \code{lambda} value's to use the top-level environment.
  5409. \begin{figure}[tp]
  5410. \begin{lstlisting}
  5411. (define (interp-exp env)
  5412. (lambda (e)
  5413. (define recur (interp-exp env))
  5414. (match e
  5415. ...
  5416. [`(,fun ,args ...)
  5417. (define arg-vals (for/list ([e args]) (recur e)))
  5418. (define fun-val (recur fun))
  5419. (match fun-val
  5420. [`(lambda (,xs ...) ,body ,fun-env)
  5421. (define new-env (append (map cons xs arg-vals) fun-env))
  5422. ((interp-exp new-env) body)]
  5423. [else (error "interp-exp, expected function, not" fun-val)])]
  5424. [else (error 'interp-exp "unrecognized expression")]
  5425. )))
  5426. (define (interp-def d)
  5427. (match d
  5428. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5429. (mcons f `(lambda ,xs ,body ()))]
  5430. ))
  5431. (define (interp-R4 p)
  5432. (match p
  5433. [`(program ,ds ... ,body)
  5434. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5435. (for/list ([b top-level])
  5436. (set-mcdr! b (match (mcdr b)
  5437. [`(lambda ,xs ,body ())
  5438. `(lambda ,xs ,body ,top-level)])))
  5439. ((interp-exp top-level) body))]
  5440. ))
  5441. \end{lstlisting}
  5442. \caption{Interpreter for the $R_4$ language.}
  5443. \label{fig:interp-R4}
  5444. \end{figure}
  5445. \section{Functions in x86}
  5446. \label{sec:fun-x86}
  5447. \margincomment{\tiny Make sure callee-saved registers are discussed
  5448. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5449. \margincomment{\tiny Talk about the return address on the
  5450. stack and what callq and retq does.\\ --Jeremy }
  5451. The x86 architecture provides a few features to support the
  5452. implementation of functions. We have already seen that x86 provides
  5453. labels so that one can refer to the location of an instruction, as is
  5454. needed for jump instructions. Labels can also be used to mark the
  5455. beginning of the instructions for a function. Going further, we can
  5456. obtain the address of a label by using the \key{leaq} instruction and
  5457. \key{rip}-relative addressing. For example, the following puts the
  5458. address of the \code{add1} label into the \code{rbx} register.
  5459. \begin{lstlisting}
  5460. leaq add1(%rip), %rbx
  5461. \end{lstlisting}
  5462. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5463. instruction for jumping to a function whose location is given by a
  5464. label. Here we instead will be jumping to a function whose location is
  5465. given by an address, that is, we need to make an \emph{indirect
  5466. function call}. The x86 syntax is to give the register name prefixed
  5467. with an asterisk.
  5468. \begin{lstlisting}
  5469. callq *%rbx
  5470. \end{lstlisting}
  5471. \subsection{Calling Conventions}
  5472. The \code{callq} instruction provides partial support for implementing
  5473. functions, but it does not handle (1) parameter passing, (2) saving
  5474. and restoring frames on the procedure call stack, or (3) determining
  5475. how registers are shared by different functions. These issues require
  5476. coordination between the caller and the callee, which is often
  5477. assembly code written by different programmers or generated by
  5478. different compilers. As a result, people have developed
  5479. \emph{conventions} that govern how functions calls are performed.
  5480. Here we shall use the same conventions used by the \code{gcc}
  5481. compiler~\citep{Matz:2013aa}.
  5482. Regarding (1) parameter passing, the convention is to use the
  5483. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5484. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5485. than six arguments, then the convention is to use space on the frame
  5486. of the caller for the rest of the arguments. However, to ease the
  5487. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5488. we shall arrange to never have more than six arguments.
  5489. %
  5490. The register \code{rax} is for the return value of the function.
  5491. Regarding (2) frames and the procedure call stack, the convention is
  5492. that the stack grows down, with each function call using a chunk of
  5493. space called a frame. The caller sets the stack pointer, register
  5494. \code{rsp}, to the last data item in its frame. The callee must not
  5495. change anything in the caller's frame, that is, anything that is at or
  5496. above the stack pointer. The callee is free to use locations that are
  5497. below the stack pointer.
  5498. Regarding (3) the sharing of registers between different functions,
  5499. recall from Section~\ref{sec:calling-conventions} that the registers
  5500. are divided into two groups, the caller-saved registers and the
  5501. callee-saved registers. The caller should assume that all the
  5502. caller-saved registers get overwritten with arbitrary values by the
  5503. callee. Thus, the caller should either 1) not put values that are live
  5504. across a call in caller-saved registers, or 2) save and restore values
  5505. that are live across calls. We shall recommend option 1). On the flip
  5506. side, if the callee wants to use a callee-saved register, the callee
  5507. must save the contents of those registers on their stack frame and
  5508. then put them back prior to returning to the caller. The base
  5509. pointer, register \code{rbp}, is used as a point-of-reference within a
  5510. frame, so that each local variable can be accessed at a fixed offset
  5511. from the base pointer.
  5512. %
  5513. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5514. frames.
  5515. %% If we were to use stack arguments, they would be between the
  5516. %% caller locals and the callee return address.
  5517. \begin{figure}[tbp]
  5518. \centering
  5519. \begin{tabular}{r|r|l|l} \hline
  5520. Caller View & Callee View & Contents & Frame \\ \hline
  5521. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5522. 0(\key{\%rbp}) & & old \key{rbp} \\
  5523. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5524. \ldots & & \ldots \\
  5525. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5526. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5527. \ldots & & \ldots \\
  5528. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5529. %% & & \\
  5530. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5531. %% & \ldots & \ldots \\
  5532. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5533. \hline
  5534. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5535. & 0(\key{\%rbp}) & old \key{rbp} \\
  5536. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5537. & \ldots & \ldots \\
  5538. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5539. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5540. & \ldots & \ldots \\
  5541. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5542. \end{tabular}
  5543. \caption{Memory layout of caller and callee frames.}
  5544. \label{fig:call-frames}
  5545. \end{figure}
  5546. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5547. %% local variables and for storing the values of callee-saved registers
  5548. %% (we shall refer to all of these collectively as ``locals''), and that
  5549. %% at the beginning of a function we move the stack pointer \code{rsp}
  5550. %% down to make room for them.
  5551. %% We recommend storing the local variables
  5552. %% first and then the callee-saved registers, so that the local variables
  5553. %% can be accessed using \code{rbp} the same as before the addition of
  5554. %% functions.
  5555. %% To make additional room for passing arguments, we shall
  5556. %% move the stack pointer even further down. We count how many stack
  5557. %% arguments are needed for each function call that occurs inside the
  5558. %% body of the function and find their maximum. Adding this number to the
  5559. %% number of locals gives us how much the \code{rsp} should be moved at
  5560. %% the beginning of the function. In preparation for a function call, we
  5561. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5562. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5563. %% so on.
  5564. %% Upon calling the function, the stack arguments are retrieved by the
  5565. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5566. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5567. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5568. %% the layout of the caller and callee frames. Notice how important it is
  5569. %% that we correctly compute the maximum number of arguments needed for
  5570. %% function calls; if that number is too small then the arguments and
  5571. %% local variables will smash into each other!
  5572. \subsection{Efficient Tail Calls}
  5573. \label{sec:tail-call}
  5574. In general, the amount of stack space used by a program is determined
  5575. by the longest chain of nested function calls. That is, if function
  5576. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5577. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5578. $n$ can grow quite large in the case of recursive or mutually
  5579. recursive functions. However, in some cases we can arrange to use only
  5580. constant space, i.e. $O(1)$, instead of $O(n)$.
  5581. If a function call is the last action in a function body, then that
  5582. call is said to be a \emph{tail call}. In such situations, the frame
  5583. of the caller is no longer needed, so we can pop the caller's frame
  5584. before making the tail call. With this approach, a recursive function
  5585. that only makes tail calls will only use $O(1)$ stack space.
  5586. Functional languages like Racket typically rely heavily on recursive
  5587. functions, so they typically guarantee that all tail calls will be
  5588. optimized in this way.
  5589. However, some care is needed with regards to argument passing in tail
  5590. calls. As mentioned above, for arguments beyond the sixth, the
  5591. convention is to use space in the caller's frame for passing
  5592. arguments. But here we've popped the caller's frame and can no longer
  5593. use it. Another alternative is to use space in the callee's frame for
  5594. passing arguments. However, this option is also problematic because
  5595. the caller and callee's frame overlap in memory. As we begin to copy
  5596. the arguments from their sources in the caller's frame, the target
  5597. locations in the callee's frame might overlap with the sources for
  5598. later arguments! We solve this problem by not using the stack for
  5599. parameter passing but instead use the heap, as we describe in the
  5600. Section~\ref{sec:limit-functions-r4}.
  5601. As mentioned above, for a tail call we pop the caller's frame prior to
  5602. making the tail call. The instructions for popping a frame are the
  5603. instructions that we usually place in the conclusion of a
  5604. function. Thus, we also need to place such code immediately before
  5605. each tail call. These instructions include restoring the callee-saved
  5606. registers, so it is good that the argument passing registers are all
  5607. caller-saved registers.
  5608. One last note regarding which instruction to use to make the tail
  5609. call. When the callee is finished, it should not return to the current
  5610. function, but it should return to the function that called the current
  5611. one. Thus, the return address that is already on the stack is the
  5612. right one, and we should not use \key{callq} to make the tail call, as
  5613. that would unnecessarily overwrite the return address. Instead we can
  5614. simply use the \key{jmp} instruction. Like the indirect function call,
  5615. we write an indirect jump with a register prefixed with an asterisk.
  5616. We recommend using \code{rax} to hold the jump target because the
  5617. preceding ``conclusion'' overwrites just about everything else.
  5618. \begin{lstlisting}
  5619. jmp *%rax
  5620. \end{lstlisting}
  5621. %% Now that we have a good understanding of functions as they appear in
  5622. %% $R_4$ and the support for functions in x86, we need to plan the
  5623. %% changes to our compiler, that is, do we need any new passes and/or do
  5624. %% we need to change any existing passes? Also, do we need to add new
  5625. %% kinds of AST nodes to any of the intermediate languages?
  5626. \section{Shrink $R_4$}
  5627. \label{sec:shrink-r4}
  5628. The \code{shrink} pass performs a couple minor modifications to the
  5629. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5630. field to each function definition:
  5631. \begin{lstlisting}
  5632. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5633. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5634. \end{lstlisting}
  5635. and introduces an explicit \code{main} function.\\
  5636. \begin{tabular}{lll}
  5637. \begin{minipage}{0.45\textwidth}
  5638. \begin{lstlisting}
  5639. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5640. \end{lstlisting}
  5641. \end{minipage}
  5642. &
  5643. $\Rightarrow$
  5644. &
  5645. \begin{minipage}{0.45\textwidth}
  5646. \begin{lstlisting}
  5647. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5648. \end{lstlisting}
  5649. \end{minipage}
  5650. \end{tabular} \\
  5651. where $\itm{mainDef}$ is
  5652. \begin{lstlisting}
  5653. (define (main) : Integer () |$\Exp'$|)
  5654. \end{lstlisting}
  5655. \section{Reveal Functions}
  5656. \label{sec:reveal-functions-r4}
  5657. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5658. compilation because it conflates the use of function names and local
  5659. variables. This is a problem because we need to compile the use of a
  5660. function name differently than the use of a local variable; we need to
  5661. use \code{leaq} to convert the function name (a label in x86) to an
  5662. address in a register. Thus, it is a good idea to create a new pass
  5663. that changes function references from just a symbol $f$ to
  5664. \code{(fun-ref $f$)}. A good name for this pass is
  5665. \code{reveal-functions} and the output language, $F_1$, is defined in
  5666. Figure~\ref{fig:f1-syntax}.
  5667. \begin{figure}[tp]
  5668. \centering
  5669. \fbox{
  5670. \begin{minipage}{0.96\textwidth}
  5671. \[
  5672. \begin{array}{lcl}
  5673. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5674. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5675. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5676. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5677. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5678. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5679. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5680. (\key{vector-ref}\;\Exp\;\Int)} \\
  5681. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5682. (\key{app}\; \Exp \; \Exp^{*})} \\
  5683. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5684. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5685. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5686. \end{array}
  5687. \]
  5688. \end{minipage}
  5689. }
  5690. \caption{The $F_1$ language, an extension of $R_4$
  5691. (Figure~\ref{fig:r4-syntax}).}
  5692. \label{fig:f1-syntax}
  5693. \end{figure}
  5694. %% Distinguishing between calls in tail position and non-tail position
  5695. %% requires the pass to have some notion of context. We recommend using
  5696. %% two mutually recursive functions, one for processing expressions in
  5697. %% tail position and another for the rest.
  5698. Placing this pass after \code{uniquify} is a good idea, because it
  5699. will make sure that there are no local variables and functions that
  5700. share the same name. On the other hand, \code{reveal-functions} needs
  5701. to come before the \code{explicate-control} pass because that pass
  5702. will help us compile \code{fun-ref} into assignment statements.
  5703. \section{Limit Functions}
  5704. \label{sec:limit-functions-r4}
  5705. This pass transforms functions so that they have at most six
  5706. parameters and transforms all function calls so that they pass at most
  5707. six arguments. A simple strategy for imposing an argument limit of
  5708. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5709. into a vector, making that subsequent vector the $n$th argument.
  5710. \begin{tabular}{lll}
  5711. \begin{minipage}{0.2\textwidth}
  5712. \begin{lstlisting}
  5713. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5714. \end{lstlisting}
  5715. \end{minipage}
  5716. &
  5717. $\Rightarrow$
  5718. &
  5719. \begin{minipage}{0.4\textwidth}
  5720. \begin{lstlisting}
  5721. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5722. \end{lstlisting}
  5723. \end{minipage}
  5724. \end{tabular}
  5725. In the body of the function, all occurrences of the $i$th argument in
  5726. which $i>5$ must be replaced with a \code{vector-ref}.
  5727. \section{Remove Complex Operators and Operands}
  5728. \label{sec:rco-r4}
  5729. The primary decisions to make for this pass is whether to classify
  5730. \code{fun-ref} and \code{app} as either simple or complex
  5731. expressions. Recall that a simple expression will eventually end up as
  5732. just an ``immediate'' argument of an x86 instruction. Function
  5733. application will be translated to a sequence of instructions, so
  5734. \code{app} must be classified as complex expression. Regarding
  5735. \code{fun-ref}, as discussed above, the function label needs to
  5736. be converted to an address using the \code{leaq} instruction. Thus,
  5737. even though \code{fun-ref} seems rather simple, it needs to be
  5738. classified as a complex expression so that we generate an assignment
  5739. statement with a left-hand side that can serve as the target of the
  5740. \code{leaq}.
  5741. \section{Explicate Control and the $C_3$ language}
  5742. \label{sec:explicate-control-r4}
  5743. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5744. \key{explicate-control}. The three mutually recursive functions for
  5745. this pass, for assignment, tail, and predicate contexts, must all be
  5746. updated with cases for \code{fun-ref} and \code{app}. In
  5747. assignment and predicate contexts, \code{app} becomes \code{call},
  5748. whereas in tail position \code{app} becomes \code{tailcall}. We
  5749. recommend defining a new function for processing function definitions.
  5750. This code is similar to the case for \code{program} in $R_3$. The
  5751. top-level \code{explicate-control} function that handles the
  5752. \code{program} form of $R_4$ can then apply this new function to all
  5753. the function definitions.
  5754. \begin{figure}[tp]
  5755. \fbox{
  5756. \begin{minipage}{0.96\textwidth}
  5757. \[
  5758. \begin{array}{lcl}
  5759. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5760. \\
  5761. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5762. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5763. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5764. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5765. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5766. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5767. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5768. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5769. \mid (\key{collect} \,\itm{int}) }\\
  5770. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5771. &\mid& \gray{(\key{goto}\,\itm{label})
  5772. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5773. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5774. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5775. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5776. \end{array}
  5777. \]
  5778. \end{minipage}
  5779. }
  5780. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5781. \label{fig:c3-syntax}
  5782. \end{figure}
  5783. \section{Uncover Locals}
  5784. \label{sec:uncover-locals-r4}
  5785. The function for processing $\Tail$ should be updated with a case for
  5786. \code{tailcall}. We also recommend creating a new function for
  5787. processing function definitions. Each function definition in $C_3$ has
  5788. its own set of local variables, so the code for function definitions
  5789. should be similar to the case for the \code{program} form in $C_2$.
  5790. \section{Select Instructions}
  5791. \label{sec:select-r4}
  5792. The output of select instructions is a program in the x86$_3$
  5793. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5794. \begin{figure}[tp]
  5795. \fbox{
  5796. \begin{minipage}{0.96\textwidth}
  5797. \[
  5798. \begin{array}{lcl}
  5799. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5800. \mid (\key{deref}\,\Reg\,\Int) } \\
  5801. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  5802. \mid (\key{global-value}\; \itm{name}) } \\
  5803. &\mid& (\key{fun-ref}\; \itm{label})\\
  5804. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5805. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5806. (\key{subq} \; \Arg\; \Arg) \mid
  5807. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5808. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5809. (\key{pushq}\;\Arg) \mid
  5810. (\key{popq}\;\Arg) \mid
  5811. (\key{retq}) } \\
  5812. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5813. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5814. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5815. \mid (\key{jmp} \; \itm{label})
  5816. \mid (\key{j}\itm{cc} \; \itm{label})
  5817. \mid (\key{label} \; \itm{label}) } \\
  5818. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5819. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5820. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5821. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5822. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5823. \end{array}
  5824. \]
  5825. \end{minipage}
  5826. }
  5827. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5828. \label{fig:x86-3}
  5829. \end{figure}
  5830. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5831. as follows: \\
  5832. \begin{tabular}{lll}
  5833. \begin{minipage}{0.45\textwidth}
  5834. \begin{lstlisting}
  5835. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5836. \end{lstlisting}
  5837. \end{minipage}
  5838. &
  5839. $\Rightarrow$
  5840. &
  5841. \begin{minipage}{0.4\textwidth}
  5842. \begin{lstlisting}
  5843. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5844. \end{lstlisting}
  5845. \end{minipage}
  5846. \end{tabular} \\
  5847. Regarding function definitions, we need to remove their parameters and
  5848. instead perform parameter passing in terms of the conventions
  5849. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5850. in the argument passing registers, and inside the function we should
  5851. generate a \code{movq} instruction for each parameter, to move the
  5852. argument value from the appropriate register to a new local variable
  5853. with the same name as the old parameter.
  5854. Next, consider the compilation of function calls, which have the
  5855. following form upon input to \code{select-instructions}.
  5856. \begin{lstlisting}
  5857. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5858. \end{lstlisting}
  5859. In the mirror image of handling the parameters of function
  5860. definitions, the arguments \itm{args} need to be moved to the argument
  5861. passing registers.
  5862. %
  5863. Once the instructions for parameter passing have been generated, the
  5864. function call itself can be performed with an indirect function call,
  5865. for which I recommend creating the new instruction
  5866. \code{indirect-callq}. Of course, the return value from the function
  5867. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5868. \begin{lstlisting}
  5869. (indirect-callq |\itm{fun}|)
  5870. (movq (reg rax) |\itm{lhs}|)
  5871. \end{lstlisting}
  5872. Regarding tail calls, the parameter passing is the same as non-tail
  5873. calls: generate instructions to move the arguments into to the
  5874. argument passing registers. After that we need to pop the frame from
  5875. the procedure call stack. However, we do not yet know how big the
  5876. frame is; that gets determined during register allocation. So instead
  5877. of generating those instructions here, we invent a new instruction
  5878. that means ``pop the frame and then do an indirect jump'', which we
  5879. name \code{tail-jmp}.
  5880. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5881. using the label \code{start} for the initial block of a program, and
  5882. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5883. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5884. can be compiled to an assignment to \code{rax} followed by a jump to
  5885. \code{conclusion}. With the addition of function definitions, we will
  5886. have a starting block and conclusion for each function, but their
  5887. labels need to be unique. We recommend prepending the function's name
  5888. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5889. labels. (Alternatively, one could \code{gensym} labels for the start
  5890. and conclusion and store them in the $\itm{info}$ field of the
  5891. function definition.)
  5892. \section{Uncover Live}
  5893. %% The rest of the passes need only minor modifications to handle the new
  5894. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5895. %% \code{leaq}.
  5896. Inside \code{uncover-live}, when computing the $W$ set (written
  5897. variables) for an \code{indirect-callq} instruction, we recommend
  5898. including all the caller-saved registers, which will have the affect
  5899. of making sure that no caller-saved register actually needs to be
  5900. saved.
  5901. \section{Build Interference Graph}
  5902. With the addition of function definitions, we compute an interference
  5903. graph for each function (not just one for the whole program).
  5904. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5905. spill vector-typed variables that are live during a call to the
  5906. \code{collect}. With the addition of functions to our language, we
  5907. need to revisit this issue. Many functions will perform allocation and
  5908. therefore have calls to the collector inside of them. Thus, we should
  5909. not only spill a vector-typed variable when it is live during a call
  5910. to \code{collect}, but we should spill the variable if it is live
  5911. during any function call. Thus, in the \code{build-interference} pass,
  5912. we recommend adding interference edges between call-live vector-typed
  5913. variables and the callee-saved registers (in addition to the usual
  5914. addition of edges between call-live variables and the caller-saved
  5915. registers).
  5916. \section{Patch Instructions}
  5917. In \code{patch-instructions}, you should deal with the x86
  5918. idiosyncrasy that the destination argument of \code{leaq} must be a
  5919. register. Additionally, you should ensure that the argument of
  5920. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5921. code generation more convenient, because we will be trampling many
  5922. registers before the tail call (as explained below).
  5923. \section{Print x86}
  5924. For the \code{print-x86} pass, we recommend the following translations:
  5925. \begin{lstlisting}
  5926. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5927. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5928. \end{lstlisting}
  5929. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5930. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5931. is what we will want to do, but before the jump we need to pop the
  5932. current frame. So we need to restore the state of the registers to the
  5933. point they were at when the current function was called. This
  5934. sequence of instructions is the same as the code for the conclusion of
  5935. a function.
  5936. Note that your \code{print-x86} pass needs to add the code for saving
  5937. and restoring callee-saved registers, if you have not already
  5938. implemented that. This is necessary when generating code for function
  5939. definitions.
  5940. \section{An Example Translation}
  5941. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5942. function in $R_4$ to x86. The figure also includes the results of the
  5943. \code{explicate-control} and \code{select-instructions} passes. We
  5944. have omitted the \code{has-type} AST nodes for readability. Can you
  5945. see any ways to improve the translation?
  5946. \begin{figure}[tbp]
  5947. \begin{tabular}{ll}
  5948. \begin{minipage}{0.45\textwidth}
  5949. % s3_2.rkt
  5950. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5951. (program
  5952. (define (add [x : Integer]
  5953. [y : Integer])
  5954. : Integer (+ x y))
  5955. (add 40 2))
  5956. \end{lstlisting}
  5957. $\Downarrow$
  5958. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5959. (program ()
  5960. (define (add86 [x87 : Integer]
  5961. [y88 : Integer]) : Integer ()
  5962. ((add86start . (return (+ x87 y88)))))
  5963. (define (main) : Integer ()
  5964. ((mainstart .
  5965. (seq (assign tmp89 (fun-ref add86))
  5966. (tailcall tmp89 40 2))))))
  5967. \end{lstlisting}
  5968. \end{minipage}
  5969. &
  5970. $\Rightarrow$
  5971. \begin{minipage}{0.5\textwidth}
  5972. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5973. (program ()
  5974. (define (add86)
  5975. ((locals (x87 . Integer) (y88 . Integer))
  5976. (num-params . 2))
  5977. ((add86start .
  5978. (block ()
  5979. (movq (reg rcx) (var x87))
  5980. (movq (reg rdx) (var y88))
  5981. (movq (var x87) (reg rax))
  5982. (addq (var y88) (reg rax))
  5983. (jmp add86conclusion)))))
  5984. (define (main)
  5985. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5986. (num-params . 0))
  5987. ((mainstart .
  5988. (block ()
  5989. (leaq (fun-ref add86) (var tmp89))
  5990. (movq (int 40) (reg rcx))
  5991. (movq (int 2) (reg rdx))
  5992. (tail-jmp (var tmp89))))))
  5993. \end{lstlisting}
  5994. $\Downarrow$
  5995. \end{minipage}
  5996. \end{tabular}
  5997. \begin{tabular}{lll}
  5998. \begin{minipage}{0.3\textwidth}
  5999. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6000. _add90start:
  6001. movq %rcx, %rsi
  6002. movq %rdx, %rcx
  6003. movq %rsi, %rax
  6004. addq %rcx, %rax
  6005. jmp _add90conclusion
  6006. .globl _add90
  6007. .align 16
  6008. _add90:
  6009. pushq %rbp
  6010. movq %rsp, %rbp
  6011. pushq %r12
  6012. pushq %rbx
  6013. pushq %r13
  6014. pushq %r14
  6015. subq $0, %rsp
  6016. jmp _add90start
  6017. _add90conclusion:
  6018. addq $0, %rsp
  6019. popq %r14
  6020. popq %r13
  6021. popq %rbx
  6022. popq %r12
  6023. subq $0, %r15
  6024. popq %rbp
  6025. retq
  6026. \end{lstlisting}
  6027. \end{minipage}
  6028. &
  6029. \begin{minipage}{0.3\textwidth}
  6030. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6031. _mainstart:
  6032. leaq _add90(%rip), %rsi
  6033. movq $40, %rcx
  6034. movq $2, %rdx
  6035. movq %rsi, %rax
  6036. addq $0, %rsp
  6037. popq %r14
  6038. popq %r13
  6039. popq %rbx
  6040. popq %r12
  6041. subq $0, %r15
  6042. popq %rbp
  6043. jmp *%rax
  6044. .globl _main
  6045. .align 16
  6046. _main:
  6047. pushq %rbp
  6048. movq %rsp, %rbp
  6049. pushq %r12
  6050. pushq %rbx
  6051. pushq %r13
  6052. pushq %r14
  6053. subq $0, %rsp
  6054. movq $16384, %rdi
  6055. movq $16, %rsi
  6056. callq _initialize
  6057. movq _rootstack_begin(%rip), %r15
  6058. jmp _mainstart
  6059. \end{lstlisting}
  6060. \end{minipage}
  6061. &
  6062. \begin{minipage}{0.3\textwidth}
  6063. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6064. _mainconclusion:
  6065. addq $0, %rsp
  6066. popq %r14
  6067. popq %r13
  6068. popq %rbx
  6069. popq %r12
  6070. subq $0, %r15
  6071. popq %rbp
  6072. retq
  6073. \end{lstlisting}
  6074. \end{minipage}
  6075. \end{tabular}
  6076. \caption{Example compilation of a simple function to x86.}
  6077. \label{fig:add-fun}
  6078. \end{figure}
  6079. \begin{exercise}\normalfont
  6080. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6081. Create 5 new programs that use functions, including examples that pass
  6082. functions and return functions from other functions and including
  6083. recursive functions. Test your compiler on these new programs and all
  6084. of your previously created test programs.
  6085. \end{exercise}
  6086. \begin{figure}[p]
  6087. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6088. \node (R4) at (0,2) {\large $R_4$};
  6089. \node (R4-2) at (3,2) {\large $R_4$};
  6090. \node (R4-3) at (6,2) {\large $R_4$};
  6091. \node (F1-1) at (12,0) {\large $F_1$};
  6092. \node (F1-2) at (9,0) {\large $F_1$};
  6093. \node (F1-3) at (6,0) {\large $F_1$};
  6094. \node (F1-4) at (3,0) {\large $F_1$};
  6095. \node (C3-1) at (6,-2) {\large $C_3$};
  6096. \node (C3-2) at (3,-2) {\large $C_3$};
  6097. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6098. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6099. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6100. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6101. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6102. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6103. \path[->,bend left=15] (R4) edge [above] node
  6104. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6105. \path[->,bend left=15] (R4-2) edge [above] node
  6106. {\ttfamily\footnotesize uniquify} (R4-3);
  6107. \path[->,bend left=15] (R4-3) edge [right] node
  6108. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6109. \path[->,bend left=15] (F1-1) edge [below] node
  6110. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6111. \path[->,bend right=15] (F1-2) edge [above] node
  6112. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6113. \path[->,bend right=15] (F1-3) edge [above] node
  6114. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6115. \path[->,bend left=15] (F1-4) edge [right] node
  6116. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6117. \path[->,bend left=15] (C3-1) edge [below] node
  6118. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6119. \path[->,bend right=15] (C3-2) edge [left] node
  6120. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6121. \path[->,bend left=15] (x86-2) edge [left] node
  6122. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6123. \path[->,bend right=15] (x86-2-1) edge [below] node
  6124. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6125. \path[->,bend right=15] (x86-2-2) edge [left] node
  6126. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6127. \path[->,bend left=15] (x86-3) edge [above] node
  6128. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6129. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6130. \end{tikzpicture}
  6131. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6132. \label{fig:R4-passes}
  6133. \end{figure}
  6134. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6135. the compilation of $R_4$.
  6136. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6137. \chapter{Lexically Scoped Functions}
  6138. \label{ch:lambdas}
  6139. This chapter studies lexically scoped functions as they appear in
  6140. functional languages such as Racket. By lexical scoping we mean that a
  6141. function's body may refer to variables whose binding site is outside
  6142. of the function, in an enclosing scope.
  6143. %
  6144. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6145. anonymous function defined using the \key{lambda} form. The body of
  6146. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6147. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6148. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6149. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6150. returned from the function \code{f}. Below the definition of \code{f},
  6151. we have two calls to \code{f} with different arguments for \code{x},
  6152. first \code{5} then \code{3}. The functions returned from \code{f} are
  6153. bound to variables \code{g} and \code{h}. Even though these two
  6154. functions were created by the same \code{lambda}, they are really
  6155. different functions because they use different values for
  6156. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6157. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6158. the result of this program is \code{42}.
  6159. \begin{figure}[btp]
  6160. % s4_6.rkt
  6161. \begin{lstlisting}
  6162. (define (f [x : Integer]) : (Integer -> Integer)
  6163. (let ([y 4])
  6164. (lambda: ([z : Integer]) : Integer
  6165. (+ x (+ y z)))))
  6166. (let ([g (f 5)])
  6167. (let ([h (f 3)])
  6168. (+ (g 11) (h 15))))
  6169. \end{lstlisting}
  6170. \caption{Example of a lexically scoped function.}
  6171. \label{fig:lexical-scoping}
  6172. \end{figure}
  6173. \section{The $R_5$ Language}
  6174. The syntax for this language with anonymous functions and lexical
  6175. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6176. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6177. for function application. In this chapter we shall describe how to
  6178. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6179. into a combination of functions (as in $R_4$) and tuples (as in
  6180. $R_3$).
  6181. \begin{figure}[tp]
  6182. \centering
  6183. \fbox{
  6184. \begin{minipage}{0.96\textwidth}
  6185. \[
  6186. \begin{array}{lcl}
  6187. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6188. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6189. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6190. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6191. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6192. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6193. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6194. \mid (\key{and}\;\Exp\;\Exp)
  6195. \mid (\key{or}\;\Exp\;\Exp)
  6196. \mid (\key{not}\;\Exp) } \\
  6197. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6198. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6199. (\key{vector-ref}\;\Exp\;\Int)} \\
  6200. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6201. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6202. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6203. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6204. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6205. \end{array}
  6206. \]
  6207. \end{minipage}
  6208. }
  6209. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6210. with \key{lambda}.}
  6211. \label{fig:r5-syntax}
  6212. \end{figure}
  6213. To compile lexically-scoped functions to top-level function
  6214. definitions, the compiler will need to provide special treatment to
  6215. variable occurrences such as \code{x} and \code{y} in the body of the
  6216. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6217. of $R_4$ may not refer to variables defined outside the function. To
  6218. identify such variable occurrences, we review the standard notion of
  6219. free variable.
  6220. \begin{definition}
  6221. A variable is \emph{free with respect to an expression} $e$ if the
  6222. variable occurs inside $e$ but does not have an enclosing binding in
  6223. $e$.
  6224. \end{definition}
  6225. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6226. free with respect to the expression \code{(+ x (+ y z))}. On the
  6227. other hand, only \code{x} and \code{y} are free with respect to the
  6228. following expression because \code{z} is bound by the \code{lambda}.
  6229. \begin{lstlisting}
  6230. (lambda: ([z : Integer]) : Integer
  6231. (+ x (+ y z)))
  6232. \end{lstlisting}
  6233. Once we have identified the free variables of a \code{lambda}, we need
  6234. to arrange for some way to transport, at runtime, the values of those
  6235. variables from the point where the \code{lambda} was created to the
  6236. point where the \code{lambda} is applied. Referring again to
  6237. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6238. needs to be used in the application of \code{g} to \code{11}, but the
  6239. binding of \code{x} to \code{3} needs to be used in the application of
  6240. \code{h} to \code{15}. An efficient solution to the problem, due to
  6241. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6242. free variables together with the function pointer for the lambda's
  6243. code, an arrangement called a \emph{flat closure} (which we shorten to
  6244. just ``closure'') . Fortunately, we have all the ingredients to make
  6245. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6246. Chapter~\ref{ch:functions} gave us function pointers. The function
  6247. pointer shall reside at index $0$ and the values for free variables
  6248. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6249. the two closures created by the two calls to \code{f} in
  6250. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6251. the same \key{lambda}, they share the same function pointer but differ
  6252. in the values for the free variable \code{x}.
  6253. \begin{figure}[tbp]
  6254. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6255. \caption{Example closure representation for the \key{lambda}'s
  6256. in Figure~\ref{fig:lexical-scoping}.}
  6257. \label{fig:closures}
  6258. \end{figure}
  6259. \section{Interpreting $R_5$}
  6260. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6261. $R_5$. The clause for \key{lambda} saves the current environment
  6262. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6263. the environment from the \key{lambda}, the \code{lam-env}, when
  6264. interpreting the body of the \key{lambda}. The \code{lam-env}
  6265. environment is extended with the mapping of parameters to argument
  6266. values.
  6267. \begin{figure}[tbp]
  6268. \begin{lstlisting}
  6269. (define (interp-exp env)
  6270. (lambda (e)
  6271. (define recur (interp-exp env))
  6272. (match e
  6273. ...
  6274. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6275. `(lambda ,xs ,body ,env)]
  6276. [`(app ,fun ,args ...)
  6277. (define fun-val ((interp-exp env) fun))
  6278. (define arg-vals (map (interp-exp env) args))
  6279. (match fun-val
  6280. [`(lambda (,xs ...) ,body ,lam-env)
  6281. (define new-env (append (map cons xs arg-vals) lam-env))
  6282. ((interp-exp new-env) body)]
  6283. [else (error "interp-exp, expected function, not" fun-val)])]
  6284. [else (error 'interp-exp "unrecognized expression")]
  6285. )))
  6286. \end{lstlisting}
  6287. \caption{Interpreter for $R_5$.}
  6288. \label{fig:interp-R5}
  6289. \end{figure}
  6290. \section{Type Checking $R_5$}
  6291. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6292. \key{lambda} form. The body of the \key{lambda} is checked in an
  6293. environment that includes the current environment (because it is
  6294. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6295. require the body's type to match the declared return type.
  6296. \begin{figure}[tbp]
  6297. \begin{lstlisting}
  6298. (define (typecheck-R5 env)
  6299. (lambda (e)
  6300. (match e
  6301. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6302. (define new-env (append (map cons xs Ts) env))
  6303. (define bodyT ((typecheck-R5 new-env) body))
  6304. (cond [(equal? rT bodyT)
  6305. `(,@Ts -> ,rT)]
  6306. [else
  6307. (error "mismatch in return type" bodyT rT)])]
  6308. ...
  6309. )))
  6310. \end{lstlisting}
  6311. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6312. \label{fig:typecheck-R5}
  6313. \end{figure}
  6314. \section{Closure Conversion}
  6315. The compiling of lexically-scoped functions into top-level function
  6316. definitions is accomplished in the pass \code{convert-to-closures}
  6317. that comes after \code{reveal-functions} and before
  6318. \code{limit-functions}.
  6319. As usual, we shall implement the pass as a recursive function over the
  6320. AST. All of the action is in the clauses for \key{lambda} and
  6321. \key{app}. We transform a \key{lambda} expression into an expression
  6322. that creates a closure, that is, creates a vector whose first element
  6323. is a function pointer and the rest of the elements are the free
  6324. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6325. generated to identify the function.
  6326. \begin{tabular}{lll}
  6327. \begin{minipage}{0.4\textwidth}
  6328. \begin{lstlisting}
  6329. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6330. \end{lstlisting}
  6331. \end{minipage}
  6332. &
  6333. $\Rightarrow$
  6334. &
  6335. \begin{minipage}{0.4\textwidth}
  6336. \begin{lstlisting}
  6337. (vector |\itm{name}| |\itm{fvs}| ...)
  6338. \end{lstlisting}
  6339. \end{minipage}
  6340. \end{tabular} \\
  6341. %
  6342. In addition to transforming each \key{lambda} into a \key{vector}, we
  6343. must create a top-level function definition for each \key{lambda}, as
  6344. shown below.\\
  6345. \begin{minipage}{0.8\textwidth}
  6346. \begin{lstlisting}
  6347. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6348. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6349. ...
  6350. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6351. |\itm{body'}|)...))
  6352. \end{lstlisting}
  6353. \end{minipage}\\
  6354. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6355. parameters are the normal parameters of the \key{lambda}. The types
  6356. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6357. underscore is a dummy type because it is rather difficult to give a
  6358. type to the function in the closure's type, and it does not matter.
  6359. The sequence of \key{let} forms bind the free variables to their
  6360. values obtained from the closure.
  6361. We transform function application into code that retrieves the
  6362. function pointer from the closure and then calls the function, passing
  6363. in the closure as the first argument. We bind $e'$ to a temporary
  6364. variable to avoid code duplication.
  6365. \begin{tabular}{lll}
  6366. \begin{minipage}{0.3\textwidth}
  6367. \begin{lstlisting}
  6368. (app |$e$| |\itm{es}| ...)
  6369. \end{lstlisting}
  6370. \end{minipage}
  6371. &
  6372. $\Rightarrow$
  6373. &
  6374. \begin{minipage}{0.5\textwidth}
  6375. \begin{lstlisting}
  6376. (let ([|\itm{tmp}| |$e'$|])
  6377. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6378. \end{lstlisting}
  6379. \end{minipage}
  6380. \end{tabular} \\
  6381. There is also the question of what to do with top-level function
  6382. definitions. To maintain a uniform translation of function
  6383. application, we turn function references into closures.
  6384. \begin{tabular}{lll}
  6385. \begin{minipage}{0.3\textwidth}
  6386. \begin{lstlisting}
  6387. (fun-ref |$f$|)
  6388. \end{lstlisting}
  6389. \end{minipage}
  6390. &
  6391. $\Rightarrow$
  6392. &
  6393. \begin{minipage}{0.5\textwidth}
  6394. \begin{lstlisting}
  6395. (vector (fun-ref |$f$|))
  6396. \end{lstlisting}
  6397. \end{minipage}
  6398. \end{tabular} \\
  6399. %
  6400. The top-level function definitions need to be updated as well to take
  6401. an extra closure parameter.
  6402. \section{An Example Translation}
  6403. \label{sec:example-lambda}
  6404. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6405. conversion for the example program demonstrating lexical scoping that
  6406. we discussed at the beginning of this chapter.
  6407. \begin{figure}[h]
  6408. \begin{minipage}{0.8\textwidth}
  6409. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6410. (program
  6411. (define (f [x : Integer]) : (Integer -> Integer)
  6412. (let ([y 4])
  6413. (lambda: ([z : Integer]) : Integer
  6414. (+ x (+ y z)))))
  6415. (let ([g (f 5)])
  6416. (let ([h (f 3)])
  6417. (+ (g 11) (h 15)))))
  6418. \end{lstlisting}
  6419. $\Downarrow$
  6420. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6421. (program (type Integer)
  6422. (define (f (x : Integer)) : (Integer -> Integer)
  6423. (let ((y 4))
  6424. (lambda: ((z : Integer)) : Integer
  6425. (+ x (+ y z)))))
  6426. (let ((g (app (fun-ref f) 5)))
  6427. (let ((h (app (fun-ref f) 3)))
  6428. (+ (app g 11) (app h 15)))))
  6429. \end{lstlisting}
  6430. $\Downarrow$
  6431. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6432. (program (type Integer)
  6433. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6434. (let ((y 4))
  6435. (vector (fun-ref lam.1) x y)))
  6436. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6437. (let ((x (vector-ref clos.2 1)))
  6438. (let ((y (vector-ref clos.2 2)))
  6439. (+ x (+ y z)))))
  6440. (let ((g (let ((t.1 (vector (fun-ref f))))
  6441. (app (vector-ref t.1 0) t.1 5))))
  6442. (let ((h (let ((t.2 (vector (fun-ref f))))
  6443. (app (vector-ref t.2 0) t.2 3))))
  6444. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6445. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6446. \end{lstlisting}
  6447. \end{minipage}
  6448. \caption{Example of closure conversion.}
  6449. \label{fig:lexical-functions-example}
  6450. \end{figure}
  6451. \begin{figure}[p]
  6452. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6453. \node (R4) at (0,2) {\large $R_4$};
  6454. \node (R4-2) at (3,2) {\large $R_4$};
  6455. \node (R4-3) at (6,2) {\large $R_4$};
  6456. \node (F1-1) at (12,0) {\large $F_1$};
  6457. \node (F1-2) at (9,0) {\large $F_1$};
  6458. \node (F1-3) at (6,0) {\large $F_1$};
  6459. \node (F1-4) at (3,0) {\large $F_1$};
  6460. \node (F1-5) at (0,0) {\large $F_1$};
  6461. \node (C3-1) at (6,-2) {\large $C_3$};
  6462. \node (C3-2) at (3,-2) {\large $C_3$};
  6463. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6464. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6465. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6466. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6467. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6468. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6469. \path[->,bend left=15] (R4) edge [above] node
  6470. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6471. \path[->,bend left=15] (R4-2) edge [above] node
  6472. {\ttfamily\footnotesize uniquify} (R4-3);
  6473. \path[->] (R4-3) edge [right] node
  6474. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6475. \path[->,bend left=15] (F1-1) edge [below] node
  6476. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6477. \path[->,bend right=15] (F1-2) edge [above] node
  6478. {\ttfamily\footnotesize limit-functions} (F1-3);
  6479. \path[->,bend right=15] (F1-3) edge [above] node
  6480. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6481. \path[->,bend right=15] (F1-4) edge [above] node
  6482. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6483. \path[->] (F1-5) edge [left] node
  6484. {\ttfamily\footnotesize explicate-control} (C3-1);
  6485. \path[->,bend left=15] (C3-1) edge [below] node
  6486. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6487. \path[->,bend right=15] (C3-2) edge [left] node
  6488. {\ttfamily\footnotesize select-instr.} (x86-2);
  6489. \path[->,bend left=15] (x86-2) edge [left] node
  6490. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6491. \path[->,bend right=15] (x86-2-1) edge [below] node
  6492. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6493. \path[->,bend right=15] (x86-2-2) edge [left] node
  6494. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6495. \path[->,bend left=15] (x86-3) edge [above] node
  6496. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6497. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6498. \end{tikzpicture}
  6499. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6500. functions.}
  6501. \label{fig:R5-passes}
  6502. \end{figure}
  6503. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6504. for the compilation of $R_5$.
  6505. \begin{exercise}\normalfont
  6506. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6507. Create 5 new programs that use \key{lambda} functions and make use of
  6508. lexical scoping. Test your compiler on these new programs and all of
  6509. your previously created test programs.
  6510. \end{exercise}
  6511. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6512. \chapter{Dynamic Typing}
  6513. \label{ch:type-dynamic}
  6514. In this chapter we discuss the compilation of a dynamically typed
  6515. language, named $R_7$, that is a subset of the Racket
  6516. language. (Recall that in the previous chapters we have studied
  6517. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6518. languages, an expression may produce values of differing
  6519. type. Consider the following example with a conditional expression
  6520. that may return a Boolean or an integer depending on the input to the
  6521. program.
  6522. \begin{lstlisting}
  6523. (not (if (eq? (read) 1) #f 0))
  6524. \end{lstlisting}
  6525. Languages that allow expressions to produce different kinds of values
  6526. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6527. such as subtype polymorphism and parametric
  6528. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6529. talking about here does not have a special name, but it is the usual
  6530. kind that arises in dynamically typed languages.
  6531. Another characteristic of dynamically typed languages is that
  6532. primitive operations, such as \code{not}, are often defined to operate
  6533. on many different types of values. In fact, in Racket, the \code{not}
  6534. operator produces a result for any kind of value: given \code{\#f} it
  6535. returns \code{\#t} and given anything else it returns \code{\#f}.
  6536. Furthermore, even when primitive operations restrict their inputs to
  6537. values of a certain type, this restriction is enforced at runtime
  6538. instead of during compilation. For example, the following vector
  6539. reference results in a run-time contract violation.
  6540. \begin{lstlisting}
  6541. (vector-ref (vector 42) #t)
  6542. \end{lstlisting}
  6543. \begin{figure}[tp]
  6544. \centering
  6545. \fbox{
  6546. \begin{minipage}{0.97\textwidth}
  6547. \[
  6548. \begin{array}{rcl}
  6549. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6550. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6551. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6552. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6553. &\mid& \key{\#t} \mid \key{\#f}
  6554. \mid (\key{and}\;\Exp\;\Exp)
  6555. \mid (\key{or}\;\Exp\;\Exp)
  6556. \mid (\key{not}\;\Exp) \\
  6557. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6558. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6559. (\key{vector-ref}\;\Exp\;\Exp) \\
  6560. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6561. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6562. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6563. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6564. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6565. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6566. \end{array}
  6567. \]
  6568. \end{minipage}
  6569. }
  6570. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6571. \label{fig:r7-syntax}
  6572. \end{figure}
  6573. The syntax of $R_7$, our subset of Racket, is defined in
  6574. Figure~\ref{fig:r7-syntax}.
  6575. %
  6576. The definitional interpreter for $R_7$ is given in
  6577. Figure~\ref{fig:interp-R7}.
  6578. \begin{figure}[tbp]
  6579. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6580. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6581. (define (valid-op? op) (member op '(+ - and or not)))
  6582. (define (interp-r7 env)
  6583. (lambda (ast)
  6584. (define recur (interp-r7 env))
  6585. (match ast
  6586. [(? symbol?) (lookup ast env)]
  6587. [(? integer?) `(inject ,ast Integer)]
  6588. [#t `(inject #t Boolean)]
  6589. [#f `(inject #f Boolean)]
  6590. [`(read) `(inject ,(read-fixnum) Integer)]
  6591. [`(lambda (,xs ...) ,body)
  6592. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6593. [`(define (,f ,xs ...) ,body)
  6594. (mcons f `(lambda ,xs ,body))]
  6595. [`(program ,ds ... ,body)
  6596. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6597. (for/list ([b top-level])
  6598. (set-mcdr! b (match (mcdr b)
  6599. [`(lambda ,xs ,body)
  6600. `(inject (lambda ,xs ,body ,top-level)
  6601. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6602. ((interp-r7 top-level) body))]
  6603. [`(vector ,(app recur elts) ...)
  6604. (define tys (map get-tagged-type elts))
  6605. `(inject ,(apply vector elts) (Vector ,@tys))]
  6606. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6607. (match v1
  6608. [`(inject ,vec ,ty)
  6609. (vector-set! vec n v2)
  6610. `(inject (void) Void)])]
  6611. [`(vector-ref ,(app recur v) ,n)
  6612. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6613. [`(let ([,x ,(app recur v)]) ,body)
  6614. ((interp-r7 (cons (cons x v) env)) body)]
  6615. [`(,op ,es ...) #:when (valid-op? op)
  6616. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6617. [`(eq? ,(app recur l) ,(app recur r))
  6618. `(inject ,(equal? l r) Boolean)]
  6619. [`(if ,(app recur q) ,t ,f)
  6620. (match q
  6621. [`(inject #f Boolean) (recur f)]
  6622. [else (recur t)])]
  6623. [`(,(app recur f-val) ,(app recur vs) ...)
  6624. (match f-val
  6625. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6626. (define new-env (append (map cons xs vs) lam-env))
  6627. ((interp-r7 new-env) body)]
  6628. [else (error "interp-r7, expected function, not" f-val)])])))
  6629. \end{lstlisting}
  6630. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6631. \label{fig:interp-R7}
  6632. \end{figure}
  6633. Let us consider how we might compile $R_7$ to x86, thinking about the
  6634. first example above. Our bit-level representation of the Boolean
  6635. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6636. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6637. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6638. general, cannot be determined at compile time, but depends on the
  6639. runtime type of its input, as in the example above that depends on the
  6640. result of \code{(read)}.
  6641. The way around this problem is to include information about a value's
  6642. runtime type in the value itself, so that this information can be
  6643. inspected by operators such as \code{not}. In particular, we shall
  6644. steal the 3 right-most bits from our 64-bit values to encode the
  6645. runtime type. We shall use $001$ to identify integers, $100$ for
  6646. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6647. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6648. define the following auxiliary function.
  6649. \begin{align*}
  6650. \itm{tagof}(\key{Integer}) &= 001 \\
  6651. \itm{tagof}(\key{Boolean}) &= 100 \\
  6652. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6653. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6654. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6655. \itm{tagof}(\key{Void}) &= 101
  6656. \end{align*}
  6657. (We shall say more about the new \key{Vectorof} type shortly.)
  6658. This stealing of 3 bits comes at some
  6659. price: our integers are reduced to ranging from $-2^{60}$ to
  6660. $2^{60}$. The stealing does not adversely affect vectors and
  6661. procedures because those values are addresses, and our addresses are
  6662. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6663. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6664. bits with the tag and we can simply zero-out the tag to recover the
  6665. original address.
  6666. In some sense, these tagged values are a new kind of value. Indeed,
  6667. we can extend our \emph{typed} language with tagged values by adding a
  6668. new type to classify them, called \key{Any}, and with operations for
  6669. creating and using tagged values, yielding the $R_6$ language that we
  6670. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6671. fundamental support for polymorphism and runtime types that we need to
  6672. support dynamic typing.
  6673. There is an interesting interaction between tagged values and garbage
  6674. collection. A variable of type \code{Any} might refer to a vector and
  6675. therefore it might be a root that needs to be inspected and copied
  6676. during garbage collection. Thus, we need to treat variables of type
  6677. \code{Any} in a similar way to variables of type \code{Vector} for
  6678. purposes of register allocation, which we discuss in
  6679. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6680. variable of type \code{Any} is spilled, it must be spilled to the root
  6681. stack. But this means that the garbage collector needs to be able to
  6682. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6683. value that points to a tuple, and (3) a tagged value that is not a
  6684. tuple. We enable this differentiation by choosing not to use the tag
  6685. $000$. Instead, that bit pattern is reserved for identifying plain old
  6686. pointers to tuples. On the other hand, if one of the first three bits
  6687. is set, then we have a tagged value, and inspecting the tag can
  6688. differentiation between vectors ($010$) and the other kinds of values.
  6689. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6690. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6691. extend our compiler to handle the new features of $R_6$
  6692. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6693. \ref{sec:register-allocation-r6}).
  6694. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6695. \label{sec:r6-lang}
  6696. \begin{figure}[tp]
  6697. \centering
  6698. \fbox{
  6699. \begin{minipage}{0.97\textwidth}
  6700. \[
  6701. \begin{array}{lcl}
  6702. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6703. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6704. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6705. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6706. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6707. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6708. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6709. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6710. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6711. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6712. \mid (\key{and}\;\Exp\;\Exp)
  6713. \mid (\key{or}\;\Exp\;\Exp)
  6714. \mid (\key{not}\;\Exp)} \\
  6715. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6716. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6717. (\key{vector-ref}\;\Exp\;\Int)} \\
  6718. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6719. &\mid& \gray{(\Exp \; \Exp^{*})
  6720. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6721. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6722. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6723. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6724. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6725. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6726. \end{array}
  6727. \]
  6728. \end{minipage}
  6729. }
  6730. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6731. with \key{Any}.}
  6732. \label{fig:r6-syntax}
  6733. \end{figure}
  6734. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6735. $(\key{inject}\; e\; T)$ form converts the value produced by
  6736. expression $e$ of type $T$ into a tagged value. The
  6737. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6738. expression $e$ into a value of type $T$ or else halts the program if
  6739. the type tag is equivalent to $T$. We treat
  6740. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6741. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6742. Note that in both \key{inject} and
  6743. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6744. which simplifies the implementation and corresponds with what is
  6745. needed for compiling untyped Racket. The type predicates,
  6746. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6747. if the tag corresponds to the predicate, and return \key{\#t}
  6748. otherwise.
  6749. %
  6750. Selections from the type checker for $R_6$ are shown in
  6751. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6752. Figure~\ref{fig:interp-R6}.
  6753. \begin{figure}[btp]
  6754. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6755. (define (flat-ty? ty) ...)
  6756. (define (typecheck-R6 env)
  6757. (lambda (e)
  6758. (define recur (typecheck-R6 env))
  6759. (match e
  6760. [`(inject ,e ,ty)
  6761. (unless (flat-ty? ty)
  6762. (error "may only inject a value of flat type, not ~a" ty))
  6763. (define-values (new-e e-ty) (recur e))
  6764. (cond
  6765. [(equal? e-ty ty)
  6766. (values `(inject ,new-e ,ty) 'Any)]
  6767. [else
  6768. (error "inject expected ~a to have type ~a" e ty)])]
  6769. [`(project ,e ,ty)
  6770. (unless (flat-ty? ty)
  6771. (error "may only project to a flat type, not ~a" ty))
  6772. (define-values (new-e e-ty) (recur e))
  6773. (cond
  6774. [(equal? e-ty 'Any)
  6775. (values `(project ,new-e ,ty) ty)]
  6776. [else
  6777. (error "project expected ~a to have type Any" e)])]
  6778. [`(vector-ref ,e ,i)
  6779. (define-values (new-e e-ty) (recur e))
  6780. (match e-ty
  6781. [`(Vector ,ts ...) ...]
  6782. [`(Vectorof ,ty)
  6783. (unless (exact-nonnegative-integer? i)
  6784. (error 'type-check "invalid index ~a" i))
  6785. (values `(vector-ref ,new-e ,i) ty)]
  6786. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6787. ...
  6788. )))
  6789. \end{lstlisting}
  6790. \caption{Type checker for parts of the $R_6$ language.}
  6791. \label{fig:typecheck-R6}
  6792. \end{figure}
  6793. % to do: add rules for vector-ref, etc. for Vectorof
  6794. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6795. \begin{figure}[btp]
  6796. \begin{lstlisting}
  6797. (define primitives (set 'boolean? ...))
  6798. (define (interp-op op)
  6799. (match op
  6800. ['boolean? (lambda (v)
  6801. (match v
  6802. [`(tagged ,v1 Boolean) #t]
  6803. [else #f]))]
  6804. ...))
  6805. ;; Equivalence of flat types
  6806. (define (tyeq? t1 t2)
  6807. (match `(,t1 ,t2)
  6808. [`((Vectorof Any) (Vector ,t2s ...))
  6809. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6810. [`((Vector ,t1s ...) (Vectorof Any))
  6811. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6812. [else (equal? t1 t2)]))
  6813. (define (interp-R6 env)
  6814. (lambda (ast)
  6815. (match ast
  6816. [`(inject ,e ,t)
  6817. `(tagged ,((interp-R6 env) e) ,t)]
  6818. [`(project ,e ,t2)
  6819. (define v ((interp-R6 env) e))
  6820. (match v
  6821. [`(tagged ,v1 ,t1)
  6822. (cond [(tyeq? t1 t2)
  6823. v1]
  6824. [else
  6825. (error "in project, type mismatch" t1 t2)])]
  6826. [else
  6827. (error "in project, expected tagged value" v)])]
  6828. ...)))
  6829. \end{lstlisting}
  6830. \caption{Interpreter for $R_6$.}
  6831. \label{fig:interp-R6}
  6832. \end{figure}
  6833. %\clearpage
  6834. \section{Shrinking $R_6$}
  6835. \label{sec:shrink-r6}
  6836. In the \code{shrink} pass we recommend compiling \code{project} into
  6837. an explicit \code{if} expression that uses three new operations:
  6838. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6839. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6840. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6841. value from a tagged value. Finally, the \code{exit} operation ends the
  6842. execution of the program by invoking the operating system's
  6843. \code{exit} function. So the translation for \code{project} is as
  6844. follows. (We have omitted the \code{has-type} AST nodes to make this
  6845. output more readable.)
  6846. \begin{tabular}{lll}
  6847. \begin{minipage}{0.3\textwidth}
  6848. \begin{lstlisting}
  6849. (project |$e$| |$\Type$|)
  6850. \end{lstlisting}
  6851. \end{minipage}
  6852. &
  6853. $\Rightarrow$
  6854. &
  6855. \begin{minipage}{0.5\textwidth}
  6856. \begin{lstlisting}
  6857. (let ([|$\itm{tmp}$| |$e'$|])
  6858. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6859. (value-of-any |$\itm{tmp}$|)
  6860. (exit)))
  6861. \end{lstlisting}
  6862. \end{minipage}
  6863. \end{tabular} \\
  6864. Similarly, we recommend translating the type predicates
  6865. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6866. \section{Instruction Selection for $R_6$}
  6867. \label{sec:select-r6}
  6868. \paragraph{Inject}
  6869. We recommend compiling an \key{inject} as follows if the type is
  6870. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6871. destination to the left by the number of bits specified its source
  6872. argument (in this case $3$, the length of the tag) and it preserves
  6873. the sign of the integer. We use the \key{orq} instruction to combine
  6874. the tag and the value to form the tagged value. \\
  6875. \begin{tabular}{lll}
  6876. \begin{minipage}{0.4\textwidth}
  6877. \begin{lstlisting}
  6878. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6879. \end{lstlisting}
  6880. \end{minipage}
  6881. &
  6882. $\Rightarrow$
  6883. &
  6884. \begin{minipage}{0.5\textwidth}
  6885. \begin{lstlisting}
  6886. (movq |$e'$| |\itm{lhs}'|)
  6887. (salq (int 3) |\itm{lhs}'|)
  6888. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6889. \end{lstlisting}
  6890. \end{minipage}
  6891. \end{tabular} \\
  6892. The instruction selection for vectors and procedures is different
  6893. because their is no need to shift them to the left. The rightmost 3
  6894. bits are already zeros as described above. So we just combine the
  6895. value and the tag using \key{orq}. \\
  6896. \begin{tabular}{lll}
  6897. \begin{minipage}{0.4\textwidth}
  6898. \begin{lstlisting}
  6899. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6900. \end{lstlisting}
  6901. \end{minipage}
  6902. &
  6903. $\Rightarrow$
  6904. &
  6905. \begin{minipage}{0.5\textwidth}
  6906. \begin{lstlisting}
  6907. (movq |$e'$| |\itm{lhs}'|)
  6908. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6909. \end{lstlisting}
  6910. \end{minipage}
  6911. \end{tabular}
  6912. \paragraph{Tag of Any}
  6913. Recall that the \code{tag-of-any} operation extracts the type tag from
  6914. a value of type \code{Any}. The type tag is the bottom three bits, so
  6915. we obtain the tag by taking the bitwise-and of the value with $111$
  6916. ($7$ in decimal).
  6917. \begin{tabular}{lll}
  6918. \begin{minipage}{0.4\textwidth}
  6919. \begin{lstlisting}
  6920. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6921. \end{lstlisting}
  6922. \end{minipage}
  6923. &
  6924. $\Rightarrow$
  6925. &
  6926. \begin{minipage}{0.5\textwidth}
  6927. \begin{lstlisting}
  6928. (movq |$e'$| |\itm{lhs}'|)
  6929. (andq (int 7) |\itm{lhs}'|)
  6930. \end{lstlisting}
  6931. \end{minipage}
  6932. \end{tabular}
  6933. \paragraph{Value of Any}
  6934. Like \key{inject}, the instructions for \key{value-of-any} are
  6935. different depending on whether the type $T$ is a pointer (vector or
  6936. procedure) or not (Integer or Boolean). The following shows the
  6937. instruction selection for Integer and Boolean. We produce an untagged
  6938. value by shifting it to the right by 3 bits.
  6939. %
  6940. \\
  6941. \begin{tabular}{lll}
  6942. \begin{minipage}{0.4\textwidth}
  6943. \begin{lstlisting}
  6944. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6945. \end{lstlisting}
  6946. \end{minipage}
  6947. &
  6948. $\Rightarrow$
  6949. &
  6950. \begin{minipage}{0.5\textwidth}
  6951. \begin{lstlisting}
  6952. (movq |$e'$| |\itm{lhs}'|)
  6953. (sarq (int 3) |\itm{lhs}'|)
  6954. \end{lstlisting}
  6955. \end{minipage}
  6956. \end{tabular} \\
  6957. %
  6958. In the case for vectors and procedures, there is no need to
  6959. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6960. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6961. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6962. \code{movq} into the destination $\itm{lhs}$. We then generate
  6963. \code{andq} with the tagged value to get the desired result. \\
  6964. %
  6965. \begin{tabular}{lll}
  6966. \begin{minipage}{0.4\textwidth}
  6967. \begin{lstlisting}
  6968. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6969. \end{lstlisting}
  6970. \end{minipage}
  6971. &
  6972. $\Rightarrow$
  6973. &
  6974. \begin{minipage}{0.5\textwidth}
  6975. \begin{lstlisting}
  6976. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6977. (andq |$e'$| |\itm{lhs}'|)
  6978. \end{lstlisting}
  6979. \end{minipage}
  6980. \end{tabular}
  6981. %% \paragraph{Type Predicates} We leave it to the reader to
  6982. %% devise a sequence of instructions to implement the type predicates
  6983. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6984. \section{Register Allocation for $R_6$}
  6985. \label{sec:register-allocation-r6}
  6986. As mentioned above, a variable of type \code{Any} might refer to a
  6987. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6988. of type \code{Any} in the same way that it treats variables of type
  6989. \code{Vector} for purposes of garbage collection. In particular,
  6990. \begin{itemize}
  6991. \item If a variable of type \code{Any} is live during a function call,
  6992. then it must be spilled. One way to accomplish this is to augment
  6993. the pass \code{build-interference} to mark all variables that are
  6994. live after a \code{callq} as interfering with all the registers.
  6995. \item If a variable of type \code{Any} is spilled, it must be spilled
  6996. to the root stack instead of the normal procedure call stack.
  6997. \end{itemize}
  6998. \begin{exercise}\normalfont
  6999. Expand your compiler to handle $R_6$ as discussed in the last few
  7000. sections. Create 5 new programs that use the \code{Any} type and the
  7001. new operations (\code{inject}, \code{project}, \code{boolean?},
  7002. etc.). Test your compiler on these new programs and all of your
  7003. previously created test programs.
  7004. \end{exercise}
  7005. \section{Compiling $R_7$ to $R_6$}
  7006. \label{sec:compile-r7}
  7007. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7008. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7009. given a subexpression $e$ of $R_7$, the pass will produce an
  7010. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7011. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7012. the Boolean \code{\#t}, which must be injected to produce an
  7013. expression of type \key{Any}.
  7014. %
  7015. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7016. addition, is representative of compilation for many operations: the
  7017. arguments have type \key{Any} and must be projected to \key{Integer}
  7018. before the addition can be performed.
  7019. The compilation of \key{lambda} (third row of
  7020. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7021. produce type annotations: we simply use \key{Any}.
  7022. %
  7023. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7024. has to account for some differences in behavior between $R_7$ and
  7025. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7026. kind of values can be used in various places. For example, the
  7027. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7028. the arguments need not be of the same type (but in that case, the
  7029. result will be \code{\#f}).
  7030. \begin{figure}[btp]
  7031. \centering
  7032. \begin{tabular}{|lll|} \hline
  7033. \begin{minipage}{0.25\textwidth}
  7034. \begin{lstlisting}
  7035. #t
  7036. \end{lstlisting}
  7037. \end{minipage}
  7038. &
  7039. $\Rightarrow$
  7040. &
  7041. \begin{minipage}{0.6\textwidth}
  7042. \begin{lstlisting}
  7043. (inject #t Boolean)
  7044. \end{lstlisting}
  7045. \end{minipage}
  7046. \\[2ex]\hline
  7047. \begin{minipage}{0.25\textwidth}
  7048. \begin{lstlisting}
  7049. (+ |$e_1$| |$e_2$|)
  7050. \end{lstlisting}
  7051. \end{minipage}
  7052. &
  7053. $\Rightarrow$
  7054. &
  7055. \begin{minipage}{0.6\textwidth}
  7056. \begin{lstlisting}
  7057. (inject
  7058. (+ (project |$e'_1$| Integer)
  7059. (project |$e'_2$| Integer))
  7060. Integer)
  7061. \end{lstlisting}
  7062. \end{minipage}
  7063. \\[2ex]\hline
  7064. \begin{minipage}{0.25\textwidth}
  7065. \begin{lstlisting}
  7066. (lambda (|$x_1 \ldots$|) |$e$|)
  7067. \end{lstlisting}
  7068. \end{minipage}
  7069. &
  7070. $\Rightarrow$
  7071. &
  7072. \begin{minipage}{0.6\textwidth}
  7073. \begin{lstlisting}
  7074. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7075. (Any|$\ldots$|Any -> Any))
  7076. \end{lstlisting}
  7077. \end{minipage}
  7078. \\[2ex]\hline
  7079. \begin{minipage}{0.25\textwidth}
  7080. \begin{lstlisting}
  7081. (app |$e_0$| |$e_1 \ldots e_n$|)
  7082. \end{lstlisting}
  7083. \end{minipage}
  7084. &
  7085. $\Rightarrow$
  7086. &
  7087. \begin{minipage}{0.6\textwidth}
  7088. \begin{lstlisting}
  7089. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7090. |$e'_1 \ldots e'_n$|)
  7091. \end{lstlisting}
  7092. \end{minipage}
  7093. \\[2ex]\hline
  7094. \begin{minipage}{0.25\textwidth}
  7095. \begin{lstlisting}
  7096. (vector-ref |$e_1$| |$e_2$|)
  7097. \end{lstlisting}
  7098. \end{minipage}
  7099. &
  7100. $\Rightarrow$
  7101. &
  7102. \begin{minipage}{0.6\textwidth}
  7103. \begin{lstlisting}
  7104. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7105. (let ([tmp2 (project |$e'_2$| Integer)])
  7106. (vector-ref tmp1 tmp2)))
  7107. \end{lstlisting}
  7108. \end{minipage}
  7109. \\[2ex]\hline
  7110. \begin{minipage}{0.25\textwidth}
  7111. \begin{lstlisting}
  7112. (if |$e_1$| |$e_2$| |$e_3$|)
  7113. \end{lstlisting}
  7114. \end{minipage}
  7115. &
  7116. $\Rightarrow$
  7117. &
  7118. \begin{minipage}{0.6\textwidth}
  7119. \begin{lstlisting}
  7120. (if (eq? |$e'_1$| (inject #f Boolean))
  7121. |$e'_3$|
  7122. |$e'_2$|)
  7123. \end{lstlisting}
  7124. \end{minipage}
  7125. \\[2ex]\hline
  7126. \begin{minipage}{0.25\textwidth}
  7127. \begin{lstlisting}
  7128. (eq? |$e_1$| |$e_2$|)
  7129. \end{lstlisting}
  7130. \end{minipage}
  7131. &
  7132. $\Rightarrow$
  7133. &
  7134. \begin{minipage}{0.6\textwidth}
  7135. \begin{lstlisting}
  7136. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7137. \end{lstlisting}
  7138. \end{minipage}
  7139. \\[2ex]\hline
  7140. \end{tabular}
  7141. \caption{Compiling $R_7$ to $R_6$.}
  7142. \label{fig:compile-r7-r6}
  7143. \end{figure}
  7144. \begin{exercise}\normalfont
  7145. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7146. Create tests for $R_7$ by adapting all of your previous test programs
  7147. by removing type annotations. Add 5 more tests programs that
  7148. specifically rely on the language being dynamically typed. That is,
  7149. they should not be legal programs in a statically typed language, but
  7150. nevertheless, they should be valid $R_7$ programs that run to
  7151. completion without error.
  7152. \end{exercise}
  7153. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7154. \chapter{Gradual Typing}
  7155. \label{ch:gradual-typing}
  7156. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7157. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7158. \chapter{Parametric Polymorphism}
  7159. \label{ch:parametric-polymorphism}
  7160. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7161. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7162. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7163. \chapter{High-level Optimization}
  7164. \label{ch:high-level-optimization}
  7165. This chapter will present a procedure inlining pass based on the
  7166. algorithm of \citet{Waddell:1997fk}.
  7167. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7168. \chapter{Appendix}
  7169. \section{Interpreters}
  7170. \label{appendix:interp}
  7171. We provide several interpreters in the \key{interp.rkt} file. The
  7172. \key{interp-scheme} function takes an AST in one of the Racket-like
  7173. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7174. the program, returning the result value. The \key{interp-C} function
  7175. interprets an AST for a program in one of the C-like languages ($C_0,
  7176. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7177. for an x86 program.
  7178. \section{Utility Functions}
  7179. \label{appendix:utilities}
  7180. The utility function described in this section can be found in the
  7181. \key{utilities.rkt} file.
  7182. The \key{read-program} function takes a file path and parses that file
  7183. (it must be a Racket program) into an abstract syntax tree with a
  7184. \key{Program} node at the top.
  7185. The \key{parse-program} function takes an S-expression representation
  7186. of an AST and converts it into the struct-based representation.
  7187. The \key{assert} function displays the error message \key{msg} if the
  7188. Boolean \key{bool} is false.
  7189. \begin{lstlisting}
  7190. (define (assert msg bool) ...)
  7191. \end{lstlisting}
  7192. The \key{lookup} function takes a key and an association list (a list
  7193. of key-value pairs), and returns the first value that is associated
  7194. with the given key, if there is one. If not, an error is triggered.
  7195. The association list may contain both immutable pairs (built with
  7196. \key{cons}) and mutable pairs (built with \key{mcons}).
  7197. The \key{map2} function ...
  7198. %% \subsection{Graphs}
  7199. %% \begin{itemize}
  7200. %% \item The \code{make-graph} function takes a list of vertices
  7201. %% (symbols) and returns a graph.
  7202. %% \item The \code{add-edge} function takes a graph and two vertices and
  7203. %% adds an edge to the graph that connects the two vertices. The graph
  7204. %% is updated in-place. There is no return value for this function.
  7205. %% \item The \code{adjacent} function takes a graph and a vertex and
  7206. %% returns the set of vertices that are adjacent to the given
  7207. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7208. %% used with functions from the \code{racket/set} module.
  7209. %% \item The \code{vertices} function takes a graph and returns the list
  7210. %% of vertices in the graph.
  7211. %% \end{itemize}
  7212. \subsection{Testing}
  7213. The \key{interp-tests} function takes a compiler name (a string), a
  7214. description of the passes, an interpreter for the source language, a
  7215. test family name (a string), and a list of test numbers, and runs the
  7216. compiler passes and the interpreters to check whether the passes
  7217. correct. The description of the passes is a list with one entry per
  7218. pass. An entry is a list with three things: a string giving the name
  7219. of the pass, the function that implements the pass (a translator from
  7220. AST to AST), and a function that implements the interpreter (a
  7221. function from AST to result value) for the language of the output of
  7222. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7223. good choice. The \key{interp-tests} function assumes that the
  7224. subdirectory \key{tests} has a collection of Scheme programs whose names
  7225. all start with the family name, followed by an underscore and then the
  7226. test number, ending in \key{.scm}. Also, for each Scheme program there
  7227. is a file with the same number except that it ends with \key{.in} that
  7228. provides the input for the Scheme program.
  7229. \begin{lstlisting}
  7230. (define (interp-tests name passes test-family test-nums) ...)
  7231. \end{lstlisting}
  7232. The compiler-tests function takes a compiler name (a string) a
  7233. description of the passes (as described above for
  7234. \code{interp-tests}), a test family name (a string), and a list of
  7235. test numbers (see the comment for interp-tests), and runs the compiler
  7236. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7237. machine code. It runs the machine code and checks that the output is
  7238. 42.
  7239. \begin{lstlisting}
  7240. (define (compiler-tests name passes test-family test-nums) ...)
  7241. \end{lstlisting}
  7242. The compile-file function takes a description of the compiler passes
  7243. (see the comment for \key{interp-tests}) and returns a function that,
  7244. given a program file name (a string ending in \key{.scm}), applies all
  7245. of the passes and writes the output to a file whose name is the same
  7246. as the program file name but with \key{.scm} replaced with \key{.s}.
  7247. \begin{lstlisting}
  7248. (define (compile-file passes)
  7249. (lambda (prog-file-name) ...))
  7250. \end{lstlisting}
  7251. \section{x86 Instruction Set Quick-Reference}
  7252. \label{sec:x86-quick-reference}
  7253. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7254. do. We write $A \to B$ to mean that the value of $A$ is written into
  7255. location $B$. Address offsets are given in bytes. The instruction
  7256. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7257. registers (such as $\%rax$), or memory references (such as
  7258. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7259. reference per instruction. Other operands must be immediates or
  7260. registers.
  7261. \begin{table}[tbp]
  7262. \centering
  7263. \begin{tabular}{l|l}
  7264. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7265. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7266. \texttt{negq} $A$ & $- A \to A$ \\
  7267. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7268. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7269. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7270. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7271. \texttt{retq} & Pops the return address and jumps to it \\
  7272. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7273. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7274. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7275. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7276. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7277. matches the condition code of the instruction, otherwise go to the
  7278. next instructions. The condition codes are \key{e} for ``equal'',
  7279. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7280. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7281. \texttt{jl} $L$ & \\
  7282. \texttt{jle} $L$ & \\
  7283. \texttt{jg} $L$ & \\
  7284. \texttt{jge} $L$ & \\
  7285. \texttt{jmp} $L$ & Jump to label $L$ \\
  7286. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7287. \texttt{movzbq} $A$, $B$ &
  7288. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7289. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7290. and the extra bytes of $B$ are set to zero.} \\
  7291. & \\
  7292. & \\
  7293. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7294. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7295. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7296. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7297. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7298. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7299. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7300. description of the condition codes. $A$ must be a single byte register
  7301. (e.g., \texttt{al} or \texttt{cl}).} \\
  7302. \texttt{setl} $A$ & \\
  7303. \texttt{setle} $A$ & \\
  7304. \texttt{setg} $A$ & \\
  7305. \texttt{setge} $A$ &
  7306. \end{tabular}
  7307. \vspace{5pt}
  7308. \caption{Quick-reference for the x86 instructions used in this book.}
  7309. \label{tab:x86-instr}
  7310. \end{table}
  7311. \bibliographystyle{plainnat}
  7312. \bibliography{all}
  7313. \end{document}
  7314. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7315. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7316. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7317. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7318. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7319. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7320. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7321. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7322. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7323. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7324. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7325. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7326. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7327. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7328. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7329. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7330. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7331. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7332. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7333. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7334. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7335. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7336. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7337. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7338. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7339. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7340. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7341. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7342. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7343. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7344. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7345. % LocalWords: struct symtab