book.tex 240 KB

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