book.tex 215 KB

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