book.tex 320 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \definecolor{lightgray}{gray}{1}
  53. \newcommand{\black}[1]{{\color{black} #1}}
  54. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  55. \newcommand{\gray}[1]{{\color{gray} #1}}
  56. %% For pictures
  57. \usepackage{tikz}
  58. \usetikzlibrary{arrows.meta}
  59. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  60. % Computer Modern is already the default. -Jeremy
  61. %\renewcommand{\ttdefault}{cmtt}
  62. \definecolor{comment-red}{rgb}{0.8,0,0}
  63. \if{0}
  64. % Peanut gallery comments:
  65. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  66. \newcommand{\margincomment}[1]{\marginpar{#1}}
  67. \else
  68. \newcommand{\rn}[1]{}
  69. \newcommand{\margincomment}[1]{}
  70. \fi
  71. \lstset{%
  72. language=Lisp,
  73. basicstyle=\ttfamily\small,
  74. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then},
  75. deletekeywords={read},
  76. escapechar=|,
  77. columns=flexible,
  78. moredelim=[is][\color{red}]{~}{~}
  79. }
  80. \newtheorem{theorem}{Theorem}
  81. \newtheorem{lemma}[theorem]{Lemma}
  82. \newtheorem{corollary}[theorem]{Corollary}
  83. \newtheorem{proposition}[theorem]{Proposition}
  84. \newtheorem{constraint}[theorem]{Constraint}
  85. \newtheorem{definition}[theorem]{Definition}
  86. \newtheorem{exercise}[theorem]{Exercise}
  87. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  88. % 'dedication' environment: To add a dedication paragraph at the start of book %
  89. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  90. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  91. \newenvironment{dedication}
  92. {
  93. \cleardoublepage
  94. \thispagestyle{empty}
  95. \vspace*{\stretch{1}}
  96. \hfill\begin{minipage}[t]{0.66\textwidth}
  97. \raggedright
  98. }
  99. {
  100. \end{minipage}
  101. \vspace*{\stretch{3}}
  102. \clearpage
  103. }
  104. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  105. % Chapter quote at the start of chapter %
  106. % Source: http://tex.stackexchange.com/a/53380 %
  107. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  108. \makeatletter
  109. \renewcommand{\@chapapp}{}% Not necessary...
  110. \newenvironment{chapquote}[2][2em]
  111. {\setlength{\@tempdima}{#1}%
  112. \def\chapquote@author{#2}%
  113. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  114. \itshape}
  115. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  116. \makeatother
  117. \input{defs}
  118. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  119. \title{\Huge \textbf{Essentials of Compilation} \\
  120. \huge An Incremental Approach}
  121. \author{\textsc{Jeremy G. Siek} \\
  122. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  123. Indiana University \\
  124. \\
  125. with contributions from: \\
  126. Carl Factora \\
  127. Andre Kuhlenschmidt \\
  128. Ryan R. Newton \\
  129. Ryan Scott \\
  130. Cameron Swords \\
  131. Michael M. Vitousek \\
  132. Michael Vollmer
  133. }
  134. \begin{document}
  135. \frontmatter
  136. \maketitle
  137. \begin{dedication}
  138. This book is dedicated to the programming language wonks at Indiana
  139. University.
  140. \end{dedication}
  141. \tableofcontents
  142. \listoffigures
  143. %\listoftables
  144. \mainmatter
  145. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  146. \chapter*{Preface}
  147. The tradition of compiler writing at Indiana University goes back to
  148. research and courses about programming languages by Daniel Friedman in
  149. the 1970's and 1980's. Dan conducted research on lazy
  150. evaluation~\citep{Friedman:1976aa} in the context of
  151. Lisp~\citep{McCarthy:1960dz} and then studied
  152. continuations~\citep{Felleisen:kx} and
  153. macros~\citep{Kohlbecker:1986dk} in the context of the
  154. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  155. of those courses, Kent Dybvig, went on to build Chez
  156. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  157. compiler for Scheme. After completing his Ph.D. at the University of
  158. North Carolina, Kent returned to teach at Indiana University.
  159. Throughout the 1990's and 2000's, Kent continued development of Chez
  160. Scheme and taught the compiler course.
  161. The compiler course evolved to incorporate novel pedagogical ideas
  162. while also including elements of effective real-world compilers. One
  163. of Dan's ideas was to split the compiler into many small ``passes'' so
  164. that the code for each pass would be easy to understood in isolation.
  165. (In contrast, most compilers of the time were organized into only a
  166. few monolithic passes for reasons of compile-time efficiency.) Kent,
  167. with later help from his students Dipanwita Sarkar and Andrew Keep,
  168. developed infrastructure to support this approach and evolved the
  169. course, first to use micro-sized passes and then into even smaller
  170. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  171. student in this compiler course in the early 2000's, as part of his
  172. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  173. the course immensely!
  174. During that time, another student named Abdulaziz Ghuloum observed
  175. that the front-to-back organization of the course made it difficult
  176. for students to understand the rationale for the compiler
  177. design. Abdulaziz proposed an incremental approach in which the
  178. students build the compiler in stages; they start by implementing a
  179. complete compiler for a very small subset of the input language and in
  180. each subsequent stage they add a language feature and add or modify
  181. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  182. the students see how the language features motivate aspects of the
  183. compiler design.
  184. After graduating from Indiana University in 2005, Jeremy went on to
  185. teach at the University of Colorado. He adapted the nano pass and
  186. incremental approaches to compiling a subset of the Python
  187. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  188. on the surface but there is a large overlap in the compiler techniques
  189. required for the two languages. Thus, Jeremy was able to teach much of
  190. the same content from the Indiana compiler course. He very much
  191. enjoyed teaching the course organized in this way, and even better,
  192. many of the students learned a lot and got excited about compilers.
  193. Jeremy returned to teach at Indiana University in 2013. In his
  194. absence the compiler course had switched from the front-to-back
  195. organization to a back-to-front organization. Seeing how well the
  196. incremental approach worked at Colorado, he started porting and
  197. adapting the structure of the Colorado course back into the land of
  198. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  199. the course is now about compiling a subset of Racket (and Typed
  200. Racket) to the x86 assembly language. The compiler is implemented in
  201. Racket 7.1~\citep{plt-tr}.
  202. This is the textbook for the incremental version of the compiler
  203. course at Indiana University (Spring 2016 - present) and it is the
  204. first open textbook for an Indiana compiler course. With this book we
  205. hope to make the Indiana compiler course available to people that have
  206. not had the chance to study in Bloomington in person. Many of the
  207. compiler design decisions in this book are drawn from the assignment
  208. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  209. are the most important topics from \cite{Dybvig:2010aa} but we have
  210. omitted topics that we think are less interesting conceptually and we
  211. have made simplifications to reduce complexity. In this way, this
  212. book leans more towards pedagogy than towards the efficiency of the
  213. generated code. Also, the book differs in places where we saw the
  214. opportunity to make the topics more fun, such as in relating register
  215. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  216. \section*{Prerequisites}
  217. The material in this book is challenging but rewarding. It is meant to
  218. prepare students for a lifelong career in programming languages.
  219. The book uses the Racket language both for the implementation of the
  220. compiler and for the language that is compiled, so a student should be
  221. proficient with Racket (or Scheme) prior to reading this book. There
  222. are many excellent resources for learning Scheme and
  223. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  224. is helpful but not necessary for the student to have prior exposure to
  225. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  226. obtain from a computer systems
  227. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  228. parts of x86-64 assembly language that are needed.
  229. %\section*{Structure of book}
  230. % You might want to add short description about each chapter in this book.
  231. %\section*{About the companion website}
  232. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  233. %\begin{itemize}
  234. % \item A link to (freely downlodable) latest version of this document.
  235. % \item Link to download LaTeX source for this document.
  236. % \item Miscellaneous material (e.g. suggested readings etc).
  237. %\end{itemize}
  238. \section*{Acknowledgments}
  239. Many people have contributed to the ideas, techniques, organization,
  240. and teaching of the materials in this book. We especially thank the
  241. following people.
  242. \begin{itemize}
  243. \item Bor-Yuh Evan Chang
  244. \item Kent Dybvig
  245. \item Daniel P. Friedman
  246. \item Ronald Garcia
  247. \item Abdulaziz Ghuloum
  248. \item Jay McCarthy
  249. \item Dipanwita Sarkar
  250. \item Andrew Keep
  251. \item Oscar Waddell
  252. \item Michael Wollowski
  253. \end{itemize}
  254. \mbox{}\\
  255. \noindent Jeremy G. Siek \\
  256. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  257. %\noindent Spring 2016
  258. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  259. \chapter{Preliminaries}
  260. \label{ch:trees-recur}
  261. In this chapter we review the basic tools that are needed to implement
  262. a compiler. Programs are typically input by a programmer as text,
  263. i.e., a sequence of characters. The program-as-text representation is
  264. called \emph{concrete syntax}. We use concrete syntax to concisely
  265. write down and talk about programs. Inside the compiler, we use
  266. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  267. that efficiently supports the operations that the compiler needs to
  268. perform.
  269. %
  270. The translation from concrete syntax to abstract syntax is a process
  271. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  272. and implementation of parsing in this book. A parser is provided in
  273. the supporting materials for translating from concrete syntax to
  274. abstract syntax for the languages used in this book.
  275. ASTs can be represented in many different ways inside the compiler,
  276. depending on the programming language used to write the compiler.
  277. %
  278. We use Racket's \code{struct} feature to represent ASTs
  279. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  280. of programming languages (Section~\ref{sec:grammar}) and pattern
  281. matching to inspect individual nodes in an AST
  282. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  283. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  284. chapter provides an brief introduction to these ideas.
  285. \section{Abstract Syntax Trees and Racket Structures}
  286. \label{sec:ast}
  287. Compilers use abstract syntax trees to represent programs because
  288. compilers often need to ask questions like: for a given part of a
  289. program, what kind of language feature is it? What are the sub-parts
  290. of this part of the program? Consider the program on the left and its
  291. AST on the right. This program is an addition and it has two
  292. sub-parts, a read operation and a negation. The negation has another
  293. sub-part, the integer constant \code{8}. By using a tree to represent
  294. the program, we can easily follow the links to go from one part of a
  295. program to its sub-parts.
  296. \begin{center}
  297. \begin{minipage}{0.4\textwidth}
  298. \begin{lstlisting}
  299. (+ (read) (- 8))
  300. \end{lstlisting}
  301. \end{minipage}
  302. \begin{minipage}{0.4\textwidth}
  303. \begin{equation}
  304. \begin{tikzpicture}
  305. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  306. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  307. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  308. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  309. \draw[->] (plus) to (read);
  310. \draw[->] (plus) to (minus);
  311. \draw[->] (minus) to (8);
  312. \end{tikzpicture}
  313. \label{eq:arith-prog}
  314. \end{equation}
  315. \end{minipage}
  316. \end{center}
  317. We use the standard terminology for trees to describe ASTs: each
  318. circle above is called a \emph{node}. The arrows connect a node to its
  319. \emph{children} (which are also nodes). The top-most node is the
  320. \emph{root}. Every node except for the root has a \emph{parent} (the
  321. node it is the child of). If a node has no children, it is a
  322. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  323. %% Recall that an \emph{symbolic expression} (S-expression) is either
  324. %% \begin{enumerate}
  325. %% \item an atom, or
  326. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  327. %% where $e_1$ and $e_2$ are each an S-expression.
  328. %% \end{enumerate}
  329. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  330. %% null value \code{'()}, etc. We can create an S-expression in Racket
  331. %% simply by writing a backquote (called a quasi-quote in Racket)
  332. %% followed by the textual representation of the S-expression. It is
  333. %% quite common to use S-expressions to represent a list, such as $a, b
  334. %% ,c$ in the following way:
  335. %% \begin{lstlisting}
  336. %% `(a . (b . (c . ())))
  337. %% \end{lstlisting}
  338. %% Each element of the list is in the first slot of a pair, and the
  339. %% second slot is either the rest of the list or the null value, to mark
  340. %% the end of the list. Such lists are so common that Racket provides
  341. %% special notation for them that removes the need for the periods
  342. %% and so many parenthesis:
  343. %% \begin{lstlisting}
  344. %% `(a b c)
  345. %% \end{lstlisting}
  346. %% The following expression creates an S-expression that represents AST
  347. %% \eqref{eq:arith-prog}.
  348. %% \begin{lstlisting}
  349. %% `(+ (read) (- 8))
  350. %% \end{lstlisting}
  351. %% When using S-expressions to represent ASTs, the convention is to
  352. %% represent each AST node as a list and to put the operation symbol at
  353. %% the front of the list. The rest of the list contains the children. So
  354. %% in the above case, the root AST node has operation \code{`+} and its
  355. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  356. %% diagram \eqref{eq:arith-prog}.
  357. %% To build larger S-expressions one often needs to splice together
  358. %% several smaller S-expressions. Racket provides the comma operator to
  359. %% splice an S-expression into a larger one. For example, instead of
  360. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  361. %% we could have first created an S-expression for AST
  362. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  363. %% S-expression.
  364. %% \begin{lstlisting}
  365. %% (define ast1.4 `(- 8))
  366. %% (define ast1.1 `(+ (read) ,ast1.4))
  367. %% \end{lstlisting}
  368. %% In general, the Racket expression that follows the comma (splice)
  369. %% can be any expression that produces an S-expression.
  370. We define a Racket \code{struct} for each kind of node. For this
  371. chapter we require just two kinds of nodes: one for integer constants
  372. and one for primitive operations. The following is the \code{struct}
  373. definition for integer constants.
  374. \begin{lstlisting}
  375. (struct Int (value))
  376. \end{lstlisting}
  377. An integer node includes just one thing: the integer value.
  378. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  379. \begin{lstlisting}
  380. (define eight (Int 8))
  381. \end{lstlisting}
  382. We say that the value created by \code{(Int 8)} is an
  383. \emph{instance} of the \code{Int} structure.
  384. The following is the \code{struct} definition for primitives operations.
  385. \begin{lstlisting}
  386. (struct Prim (op arg*))
  387. \end{lstlisting}
  388. A primitive operation node includes an operator symbol \code{op}
  389. and a list of children \code{arg*}. For example, to create
  390. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  391. \begin{lstlisting}
  392. (define neg-eight (Prim '- (list eight)))
  393. \end{lstlisting}
  394. Primitive operations may have zero or more children. The \code{read}
  395. operator has zero children:
  396. \begin{lstlisting}
  397. (define rd (Prim 'read '()))
  398. \end{lstlisting}
  399. whereas the addition operator has two children:
  400. \begin{lstlisting}
  401. (define ast1.1 (Prim '+ (list rd neg-eight)))
  402. \end{lstlisting}
  403. We have made a design choice regarding the \code{Prim} structure.
  404. Instead of using one structure for many different operations
  405. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  406. structure for each operation, as follows.
  407. \begin{lstlisting}
  408. (struct Read ())
  409. (struct Add (left right))
  410. (struct Neg (value))
  411. \end{lstlisting}
  412. The reason we choose to use just one structure is that in many parts
  413. of the compiler the code for the different primitive operators is the
  414. same, so we might as well just write that code once, which is enabled
  415. by using a single structure.
  416. When compiling a program such as \eqref{eq:arith-prog}, we need to
  417. know that the operation associated with the root node is addition and
  418. we need to be able to access its two children. Racket provides pattern
  419. matching over structures to support these kinds of queries, as we
  420. shall see in Section~\ref{sec:pattern-matching}.
  421. In this book, we often write down the concrete syntax of a program
  422. even when we really have in mind the AST because the concrete syntax
  423. is more concise. We recommend that, in your mind, you always think of
  424. programs as abstract syntax trees.
  425. \section{Grammars}
  426. \label{sec:grammar}
  427. A programming language can be thought of as a \emph{set} of programs.
  428. The set is typically infinite (one can always create larger and larger
  429. programs), so one cannot simply describe a language by listing all of
  430. the programs in the language. Instead we write down a set of rules, a
  431. \emph{grammar}, for building programs. Grammars are often used to
  432. define the concrete syntax of a language, but they can also be used to
  433. describe the abstract syntax. We shall write our rules in a variant of
  434. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  435. example, we describe a small language, named $R_0$, that consists of
  436. integers and arithmetic operations.
  437. The first grammar rule for the abstract syntax of $R_0$ says that an
  438. instance of the \code{Int} structure is an expression:
  439. \begin{equation}
  440. \Exp ::= \INT{\Int} \label{eq:arith-int}
  441. \end{equation}
  442. %
  443. Each rule has a left-hand-side and a right-hand-side. The way to read
  444. a rule is that if you have all the program parts on the
  445. right-hand-side, then you can create an AST node and categorize it
  446. according to the left-hand-side.
  447. %
  448. A name such as $\Exp$ that is
  449. defined by the grammar rules is a \emph{non-terminal}.
  450. %
  451. The name $\Int$ is a also a non-terminal, but instead of defining it
  452. with a grammar rule, we define it with the following explanation. We
  453. make the simplifying design decision that all of the languages in this
  454. book only handle machine-representable integers. On most modern
  455. machines this corresponds to integers represented with 64-bits, i.e.,
  456. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  457. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  458. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  459. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  460. that the sequence of decimals represent an integer in range $-2^{62}$
  461. to $2^{62}-1$.
  462. The second grammar rule is the \texttt{read} operation that receives
  463. an input integer from the user of the program.
  464. \begin{equation}
  465. \Exp ::= \READ{} \label{eq:arith-read}
  466. \end{equation}
  467. The third rule says that, given an $\Exp$ node, you can build another
  468. $\Exp$ node by negating it.
  469. \begin{equation}
  470. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  471. \end{equation}
  472. Symbols in typewriter font such as \key{-} and \key{read} are
  473. \emph{terminal} symbols and must literally appear in the program for
  474. the rule to be applicable.
  475. We can apply the rules to build ASTs in the $R_0$
  476. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  477. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  478. an $\Exp$.
  479. \begin{center}
  480. \begin{minipage}{0.4\textwidth}
  481. \begin{lstlisting}
  482. (Prim '- (list (Int 8)))
  483. \end{lstlisting}
  484. \end{minipage}
  485. \begin{minipage}{0.25\textwidth}
  486. \begin{equation}
  487. \begin{tikzpicture}
  488. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  489. \node[draw, circle] (8) at (0, -1.2) {$8$};
  490. \draw[->] (minus) to (8);
  491. \end{tikzpicture}
  492. \label{eq:arith-neg8}
  493. \end{equation}
  494. \end{minipage}
  495. \end{center}
  496. The next grammar rule defines addition expressions:
  497. \begin{equation}
  498. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  499. \end{equation}
  500. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  501. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  502. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  503. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  504. to show that
  505. \begin{lstlisting}
  506. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  507. \end{lstlisting}
  508. is an $\Exp$ in the $R_0$ language.
  509. If you have an AST for which the above rules do not apply, then the
  510. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  511. is not in $R_0$ because there are no rules for \code{+} with only one
  512. argument, nor for \key{-} with two arguments. Whenever we define a
  513. language with a grammar, the language only includes those programs
  514. that are justified by the rules.
  515. The last grammar rule for $R_0$ states that there is a \code{Program}
  516. node to mark the top of the whole program:
  517. \[
  518. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  519. \]
  520. The \code{Program} structure is defined as follows
  521. \begin{lstlisting}
  522. (struct Program (info body))
  523. \end{lstlisting}
  524. where \code{body} is an expression. In later chapters, the \code{info}
  525. part will be used to store auxiliary information but for now it is
  526. just the empty list.
  527. It is common to have many grammar rules with the same left-hand side
  528. but different right-hand sides, such as the rules for $\Exp$ in the
  529. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  530. combine several right-hand-sides into a single rule.
  531. We collect all of the grammar rules for the abstract syntax of $R_0$
  532. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  533. defined in Figure~\ref{fig:r0-concrete-syntax}.
  534. The \code{read-program} function provided in \code{utilities.rkt} of
  535. the support materials reads a program in from a file (the sequence of
  536. characters in the concrete syntax of Racket) and parses it into an
  537. abstract syntax tree. See the description of \code{read-program} in
  538. Appendix~\ref{appendix:utilities} for more details.
  539. \begin{figure}[tp]
  540. \fbox{
  541. \begin{minipage}{0.96\textwidth}
  542. \[
  543. \begin{array}{rcl}
  544. \begin{array}{rcl}
  545. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  546. R_0 &::=& \Exp
  547. \end{array}
  548. \end{array}
  549. \]
  550. \end{minipage}
  551. }
  552. \caption{The concrete syntax of $R_0$.}
  553. \label{fig:r0-concrete-syntax}
  554. \end{figure}
  555. \begin{figure}[tp]
  556. \fbox{
  557. \begin{minipage}{0.96\textwidth}
  558. \[
  559. \begin{array}{rcl}
  560. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  561. &\mid& \ADD{\Exp}{\Exp} \\
  562. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  563. \end{array}
  564. \]
  565. \end{minipage}
  566. }
  567. \caption{The abstract syntax of $R_0$.}
  568. \label{fig:r0-syntax}
  569. \end{figure}
  570. \section{Pattern Matching}
  571. \label{sec:pattern-matching}
  572. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  573. the parts of an AST node. Racket provides the \texttt{match} form to
  574. access the parts of a structure. Consider the following example and
  575. the output on the right.
  576. \begin{center}
  577. \begin{minipage}{0.5\textwidth}
  578. \begin{lstlisting}
  579. (match ast1.1
  580. [(Prim op (list child1 child2))
  581. (print op)])
  582. \end{lstlisting}
  583. \end{minipage}
  584. \vrule
  585. \begin{minipage}{0.25\textwidth}
  586. \begin{lstlisting}
  587. '+
  588. \end{lstlisting}
  589. \end{minipage}
  590. \end{center}
  591. In the above example, the \texttt{match} form takes the AST
  592. \eqref{eq:arith-prog} and binds its parts to the three pattern
  593. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  594. general, a match clause consists of a \emph{pattern} and a
  595. \emph{body}. Patterns are recursively defined to be either a pattern
  596. variable, a structure name followed by a pattern for each of the
  597. structure's arguments, or an S-expression (symbols, lists, etc.).
  598. (See Chapter 12 of The Racket
  599. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  600. and Chapter 9 of The Racket
  601. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  602. for a complete description of \code{match}.)
  603. %
  604. The body of a match clause may contain arbitrary Racket code. The
  605. pattern variables can be used in the scope of the body.
  606. A \code{match} form may contain several clauses, as in the following
  607. function \code{leaf?} that recognizes when an $R_0$ node is
  608. a leaf. The \code{match} proceeds through the clauses in order,
  609. checking whether the pattern can match the input AST. The
  610. body of the first clause that matches is executed. The output of
  611. \code{leaf?} for several ASTs is shown on the right.
  612. \begin{center}
  613. \begin{minipage}{0.6\textwidth}
  614. \begin{lstlisting}
  615. (define (leaf? arith)
  616. (match arith
  617. [(Int n) #t]
  618. [(Prim 'read '()) #t]
  619. [(Prim '- (list c1)) #f]
  620. [(Prim '+ (list c1 c2)) #f]))
  621. (leaf? (Prim 'read '()))
  622. (leaf? (Prim '- (list (Int 8))))
  623. (leaf? (Int 8))
  624. \end{lstlisting}
  625. \end{minipage}
  626. \vrule
  627. \begin{minipage}{0.25\textwidth}
  628. \begin{lstlisting}
  629. #t
  630. #f
  631. #t
  632. \end{lstlisting}
  633. \end{minipage}
  634. \end{center}
  635. When writing a \code{match}, we refer to the grammar definition to
  636. identify which non-terminal we are expecting to match against, then we
  637. make sure that 1) we have one clause for each alternative of that
  638. non-terminal and 2) that the pattern in each clause corresponds to the
  639. corresponding right-hand side of a grammar rule. For the \code{match}
  640. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  641. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  642. alternatives, so the \code{match} has 4 clauses. The pattern in each
  643. clause corresponds to the right-hand side of a grammar rule. For
  644. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  645. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  646. patterns, replace non-terminals such as $\Exp$ with pattern variables
  647. of your choice (e.g. \code{c1} and \code{c2}).
  648. \section{Recursion}
  649. \label{sec:recursion}
  650. Programs are inherently recursive. For example, an $R_0$ expression is
  651. often made of smaller expressions. Thus, the natural way to process an
  652. entire program is with a recursive function. As a first example of
  653. such a recursive function, we define \texttt{exp?} below, which takes
  654. an arbitrary value and determines whether or not it is an $R_0$
  655. expression.
  656. %
  657. When a recursive function is defined using a sequence of match clauses
  658. that correspond to a grammar, and the body of each clause makes a
  659. recursive call on each child node, then we say the function is defined
  660. by \emph{structural recursion}\footnote{This principle of structuring
  661. code according to the data definition is advocated in the book
  662. \emph{How to Design Programs}
  663. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  664. define a second function, named \code{R0?}, that determines whether a
  665. value is an $R_0$ program. In general we can expect to write one
  666. recursive function to handle each non-terminal in a grammar.
  667. %
  668. \begin{center}
  669. \begin{minipage}{0.7\textwidth}
  670. \begin{lstlisting}
  671. (define (exp? ast)
  672. (match ast
  673. [(Int n) #t]
  674. [(Prim 'read '()) #t]
  675. [(Prim '- (list e)) (exp? e)]
  676. [(Prim '+ (list e1 e2))
  677. (and (exp? e1) (exp? e2))]
  678. [else #f]))
  679. (define (R0? ast)
  680. (match ast
  681. [(Program '() e) (exp? e)]
  682. [else #f]))
  683. (R0? (Program '() ast1.1)
  684. (R0? (Program '()
  685. (Prim '- (list (Prim 'read '())
  686. (Prim '+ (list (Num 8)))))))
  687. \end{lstlisting}
  688. \end{minipage}
  689. \vrule
  690. \begin{minipage}{0.25\textwidth}
  691. \begin{lstlisting}
  692. #t
  693. #f
  694. \end{lstlisting}
  695. \end{minipage}
  696. \end{center}
  697. You may be tempted to merge the two functions into one, like this:
  698. \begin{center}
  699. \begin{minipage}{0.5\textwidth}
  700. \begin{lstlisting}
  701. (define (R0? ast)
  702. (match ast
  703. [(Int n) #t]
  704. [(Prim 'read '()) #t]
  705. [(Prim '- (list e)) (R0? e)]
  706. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  707. [(Program '() e) (R0? e)]
  708. [else #f]))
  709. \end{lstlisting}
  710. \end{minipage}
  711. \end{center}
  712. %
  713. Sometimes such a trick will save a few lines of code, especially when
  714. it comes to the \code{Program} wrapper. Yet this style is generally
  715. \emph{not} recommended because it can get you into trouble.
  716. %
  717. For example, the above function is subtly wrong:
  718. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  719. will return true, when it should return false.
  720. %% NOTE FIXME - must check for consistency on this issue throughout.
  721. \section{Interpreters}
  722. \label{sec:interp-R0}
  723. The meaning, or semantics, of a program is typically defined in the
  724. specification of the language. For example, the Scheme language is
  725. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  726. defined in its reference manual~\citep{plt-tr}. In this book we use an
  727. interpreter to define the meaning of each language that we consider,
  728. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  729. interpreter that is designated (by some people) as the definition of a
  730. language is called a \emph{definitional interpreter}. We warm up by
  731. creating a definitional interpreter for the $R_0$ language, which
  732. serves as a second example of structural recursion. The
  733. \texttt{interp-R0} function is defined in
  734. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  735. input program followed by a call to the \lstinline{interp-exp} helper
  736. function, which in turn has one match clause per grammar rule for
  737. $R_0$ expressions.
  738. \begin{figure}[tp]
  739. \begin{lstlisting}
  740. (define (interp-exp e)
  741. (match e
  742. [(Int n) n]
  743. [(Prim 'read '())
  744. (define r (read))
  745. (cond [(fixnum? r) r]
  746. [else (error 'interp-R0 "expected an integer" r)])]
  747. [(Prim '- (list e))
  748. (define v (interp-exp e))
  749. (fx- 0 v)]
  750. [(Prim '+ (list e1 e2))
  751. (define v1 (interp-exp e1))
  752. (define v2 (interp-exp e2))
  753. (fx+ v1 v2)]
  754. ))
  755. (define (interp-R0 p)
  756. (match p
  757. [(Program '() e) (interp-exp e)]
  758. ))
  759. \end{lstlisting}
  760. \caption{Interpreter for the $R_0$ language.}
  761. \label{fig:interp-R0}
  762. \end{figure}
  763. Let us consider the result of interpreting a few $R_0$ programs. The
  764. following program adds two integers.
  765. \begin{lstlisting}
  766. (+ 10 32)
  767. \end{lstlisting}
  768. The result is \key{42}. We wrote the above program in concrete syntax,
  769. whereas the parsed abstract syntax is:
  770. \begin{lstlisting}
  771. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  772. \end{lstlisting}
  773. The next example demonstrates that expressions may be nested within
  774. each other, in this case nesting several additions and negations.
  775. \begin{lstlisting}
  776. (+ 10 (- (+ 12 20)))
  777. \end{lstlisting}
  778. What is the result of the above program?
  779. As mentioned previously, the $R_0$ language does not support
  780. arbitrarily-large integers, but only $63$-bit integers, so we
  781. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  782. in Racket.
  783. Suppose
  784. \[
  785. n = 999999999999999999
  786. \]
  787. which indeed fits in $63$-bits. What happens when we run the
  788. following program in our interpreter?
  789. \begin{lstlisting}
  790. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  791. \end{lstlisting}
  792. It produces an error:
  793. \begin{lstlisting}
  794. fx+: result is not a fixnum
  795. \end{lstlisting}
  796. We establish the convention that if running the definitional
  797. interpreter on a program produces an error, then the meaning of that
  798. program is \emph{unspecified}. That means a compiler for the language
  799. is under no obligations regarding that program; it may or may not
  800. produce an executable, and if it does, that executable can do
  801. anything. This convention applies to the languages defined in this
  802. book, as a way to simplify the student's task of implementing them,
  803. but this convention is not applicable to all programming languages.
  804. Moving on to the last feature of the $R_0$ language, the \key{read}
  805. operation prompts the user of the program for an integer. Recall that
  806. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  807. \code{8}. So if we run
  808. \begin{lstlisting}
  809. (interp-R0 (Program '() ast1.1))
  810. \end{lstlisting}
  811. and if the input is \code{50}, then we get the answer to life, the
  812. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  813. Guide to the Galaxy} by Douglas Adams.}
  814. We include the \key{read} operation in $R_0$ so a clever student
  815. cannot implement a compiler for $R_0$ that simply runs the interpreter
  816. during compilation to obtain the output and then generates the trivial
  817. code to produce the output. (Yes, a clever student did this in the
  818. first instance of this course.)
  819. The job of a compiler is to translate a program in one language into a
  820. program in another language so that the output program behaves the
  821. same way as the input program does according to its definitional
  822. interpreter. This idea is depicted in the following diagram. Suppose
  823. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  824. interpreter for each language. Suppose that the compiler translates
  825. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  826. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  827. respective interpreters with input $i$ should yield the same output
  828. $o$.
  829. \begin{equation} \label{eq:compile-correct}
  830. \begin{tikzpicture}[baseline=(current bounding box.center)]
  831. \node (p1) at (0, 0) {$P_1$};
  832. \node (p2) at (3, 0) {$P_2$};
  833. \node (o) at (3, -2.5) {$o$};
  834. \path[->] (p1) edge [above] node {compile} (p2);
  835. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  836. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  837. \end{tikzpicture}
  838. \end{equation}
  839. In the next section we see our first example of a compiler.
  840. \section{Example Compiler: a Partial Evaluator}
  841. \label{sec:partial-evaluation}
  842. In this section we consider a compiler that translates $R_0$ programs
  843. into $R_0$ programs that may be more efficient, that is, this compiler
  844. is an optimizer. This optimizer eagerly computes the parts of the
  845. program that do not depend on any inputs, a process known as
  846. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  847. following program
  848. \begin{lstlisting}
  849. (+ (read) (- (+ 5 3)))
  850. \end{lstlisting}
  851. our compiler will translate it into the program
  852. \begin{lstlisting}
  853. (+ (read) -8)
  854. \end{lstlisting}
  855. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  856. evaluator for the $R_0$ language. The output of the partial evaluator
  857. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  858. recursion over $\Exp$ is captured in the \code{pe-exp} function
  859. whereas the code for partially evaluating the negation and addition
  860. operations is factored into two separate helper functions:
  861. \code{pe-neg} and \code{pe-add}. The input to these helper
  862. functions is the output of partially evaluating the children.
  863. \begin{figure}[tp]
  864. \begin{lstlisting}
  865. (define (pe-neg r)
  866. (match r
  867. [(Int n) (Int (fx- 0 n))]
  868. [else (Prim '- (list r))]))
  869. (define (pe-add r1 r2)
  870. (match* (r1 r2)
  871. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  872. [(_ _) (Prim '+ (list r1 r2))]))
  873. (define (pe-exp e)
  874. (match e
  875. [(Int n) (Int n)]
  876. [(Prim 'read '()) (Prim 'read '())]
  877. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  878. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  879. ))
  880. (define (pe-R0 p)
  881. (match p
  882. [(Program '() e) (Program '() (pe-exp e))]
  883. ))
  884. \end{lstlisting}
  885. \caption{A partial evaluator for $R_0$ expressions.}
  886. \label{fig:pe-arith}
  887. \end{figure}
  888. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  889. arguments are integers and if they are, perform the appropriate
  890. arithmetic. Otherwise, they create an AST node for the operation
  891. (either negation or addition).
  892. To gain some confidence that the partial evaluator is correct, we can
  893. test whether it produces programs that get the same result as the
  894. input programs. That is, we can test whether it satisfies Diagram
  895. \eqref{eq:compile-correct}. The following code runs the partial
  896. evaluator on several examples and tests the output program. The
  897. \texttt{parse-program} and \texttt{assert} functions are defined in
  898. Appendix~\ref{appendix:utilities}.\\
  899. \begin{minipage}{1.0\textwidth}
  900. \begin{lstlisting}
  901. (define (test-pe p)
  902. (assert "testing pe-R0"
  903. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  904. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  905. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  906. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  907. \end{lstlisting}
  908. \end{minipage}
  909. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  910. \chapter{Integers and Variables}
  911. \label{ch:int-exp}
  912. This chapter is about compiling the subset of Racket that includes
  913. integer arithmetic and local variable binding, which we name $R_1$, to
  914. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  915. to x86-64 simply as x86. The chapter begins with a description of the
  916. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  917. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  918. discuss only what is needed for compiling $R_1$. We introduce more of
  919. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  920. reflect on their differences and come up with a plan to break down the
  921. translation from $R_1$ to x86 into a handful of steps
  922. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  923. chapter give detailed hints regarding each step
  924. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  925. to give enough hints that the well-prepared reader, together with a
  926. few friends, can implement a compiler from $R_1$ to x86 in a couple
  927. weeks while at the same time leaving room for some fun and creativity.
  928. To give the reader a feeling for the scale of this first compiler, the
  929. instructor solution for the $R_1$ compiler is less than 500 lines of
  930. code.
  931. \section{The $R_1$ Language}
  932. \label{sec:s0}
  933. The $R_1$ language extends the $R_0$ language with variable
  934. definitions. The concrete syntax of the $R_1$ language is defined by
  935. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  936. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  937. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  938. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  939. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  940. \key{Program} struct to mark the top of the program.
  941. %% The $\itm{info}$
  942. %% field of the \key{Program} structure contains an \emph{association
  943. %% list} (a list of key-value pairs) that is used to communicate
  944. %% auxiliary data from one compiler pass the next.
  945. Despite the simplicity of the $R_1$ language, it is rich enough to
  946. exhibit several compilation techniques.
  947. \begin{figure}[tp]
  948. \centering
  949. \fbox{
  950. \begin{minipage}{0.96\textwidth}
  951. \[
  952. \begin{array}{rcl}
  953. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  954. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  955. R_1 &::=& \Exp
  956. \end{array}
  957. \]
  958. \end{minipage}
  959. }
  960. \caption{The concrete syntax of $R_1$.}
  961. \label{fig:r1-concrete-syntax}
  962. \end{figure}
  963. \begin{figure}[tp]
  964. \centering
  965. \fbox{
  966. \begin{minipage}{0.96\textwidth}
  967. \[
  968. \begin{array}{rcl}
  969. \Exp &::=& \INT{\Int} \mid \READ{} \\
  970. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  971. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  972. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  973. \end{array}
  974. \]
  975. \end{minipage}
  976. }
  977. \caption{The abstract syntax of $R_1$.}
  978. \label{fig:r1-syntax}
  979. \end{figure}
  980. Let us dive further into the syntax and semantics of the $R_1$
  981. language. The \key{Let} feature defines a variable for use within its
  982. body and initializes the variable with the value of an expression.
  983. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  984. The concrete syntax for \key{Let} is
  985. \begin{lstlisting}
  986. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  987. \end{lstlisting}
  988. For example, the following program initializes \code{x} to $32$ and then
  989. evaluates the body \code{(+ 10 x)}, producing $42$.
  990. \begin{lstlisting}
  991. (let ([x (+ 12 20)]) (+ 10 x))
  992. \end{lstlisting}
  993. When there are multiple \key{let}'s for the same variable, the closest
  994. enclosing \key{let} is used. That is, variable definitions overshadow
  995. prior definitions. Consider the following program with two \key{let}'s
  996. that define variables named \code{x}. Can you figure out the result?
  997. \begin{lstlisting}
  998. (let ([x 32]) (+ (let ([x 10]) x) x))
  999. \end{lstlisting}
  1000. For the purposes of depicting which variable uses correspond to which
  1001. definitions, the following shows the \code{x}'s annotated with
  1002. subscripts to distinguish them. Double check that your answer for the
  1003. above is the same as your answer for this annotated version of the
  1004. program.
  1005. \begin{lstlisting}
  1006. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1007. \end{lstlisting}
  1008. The initializing expression is always evaluated before the body of the
  1009. \key{let}, so in the following, the \key{read} for \code{x} is
  1010. performed before the \key{read} for \code{y}. Given the input
  1011. $52$ then $10$, the following produces $42$ (not $-42$).
  1012. \begin{lstlisting}
  1013. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1014. \end{lstlisting}
  1015. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1016. \small
  1017. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1018. An \emph{association list} (alist) is a list of key-value pairs.
  1019. For example, we can map people to their ages with an alist.
  1020. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1021. (define ages
  1022. '((jane . 25) (sam . 24) (kate . 45)))
  1023. \end{lstlisting}
  1024. The \emph{dictionary} interface is for mapping keys to values.
  1025. Every alist implements this interface. The package
  1026. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1027. provides many functions for working with dictionaries. Here
  1028. are a few of them:
  1029. \begin{description}
  1030. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1031. returns the value associated with the given $\itm{key}$.
  1032. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1033. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1034. but otherwise is the same as $\itm{dict}$.
  1035. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1036. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1037. of keys and values in $\itm{dict}$. For example, the following
  1038. creates a new alist in which the ages are incremented.
  1039. \end{description}
  1040. \vspace{-10pt}
  1041. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1042. (for/list ([(k v) (in-dict ages)])
  1043. (cons k (add1 v)))
  1044. \end{lstlisting}
  1045. \end{tcolorbox}
  1046. \end{wrapfigure}
  1047. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1048. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1049. \key{match} clauses for variables and for \key{let}. For \key{let},
  1050. we need a way to communicate the value of a variable to all the uses
  1051. of a variable. To accomplish this, we maintain a mapping from
  1052. variables to values. Throughout the compiler we often need to map
  1053. variables to information about them. We refer to these mappings as
  1054. \emph{environments}
  1055. \footnote{Another common term for environment in the compiler
  1056. literature is \emph{symbol table}.}. For simplicity, we use an
  1057. association list (alist) to represent the environment. The sidebar to
  1058. the right gives a brief introduction to alists and the
  1059. \code{racket/dict} package. The \code{interp-R1} function takes the
  1060. current environment, \code{env}, as an extra parameter. When the
  1061. interpreter encounters a variable, it finds the corresponding value
  1062. using the \code{dict-ref} function. When the interpreter encounters a
  1063. \key{Let}, it evaluates the initializing expression, extends the
  1064. environment with the result value bound to the variable, using
  1065. \code{dict-set}, then evaluates the body of the \key{Let}.
  1066. \begin{figure}[tp]
  1067. \begin{lstlisting}
  1068. (define (interp-exp env)
  1069. (lambda (e)
  1070. (match e
  1071. [(Int n) n]
  1072. [(Prim 'read '())
  1073. (define r (read))
  1074. (cond [(fixnum? r) r]
  1075. [else (error 'interp-R1 "expected an integer" r)])]
  1076. [(Prim '- (list e))
  1077. (define v ((interp-exp env) e))
  1078. (fx- 0 v)]
  1079. [(Prim '+ (list e1 e2))
  1080. (define v1 ((interp-exp env) e1))
  1081. (define v2 ((interp-exp env) e2))
  1082. (fx+ v1 v2)]
  1083. [(Var x) (dict-ref env x)]
  1084. [(Let x e body)
  1085. (define new-env (dict-set env x ((interp-exp env) e)))
  1086. ((interp-exp new-env) body)]
  1087. )))
  1088. (define (interp-R1 p)
  1089. (match p
  1090. [(Program '() e) ((interp-exp '()) e)]
  1091. ))
  1092. \end{lstlisting}
  1093. \caption{Interpreter for the $R_1$ language.}
  1094. \label{fig:interp-R1}
  1095. \end{figure}
  1096. The goal for this chapter is to implement a compiler that translates
  1097. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1098. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1099. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1100. is, they both output the same integer $n$. We depict this correctness
  1101. criteria in the following diagram.
  1102. \[
  1103. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1104. \node (p1) at (0, 0) {$P_1$};
  1105. \node (p2) at (4, 0) {$P_2$};
  1106. \node (o) at (4, -2) {$n$};
  1107. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1108. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1109. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1110. \end{tikzpicture}
  1111. \]
  1112. In the next section we introduce enough of the x86 assembly
  1113. language to compile $R_1$.
  1114. \section{The x86$_0$ Assembly Language}
  1115. \label{sec:x86}
  1116. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1117. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1118. %
  1119. An x86 program begins with a \code{main} label followed by a sequence
  1120. of instructions. In the grammar, the superscript $+$ is used to
  1121. indicate a sequence of one or more items, e.g., $\Instr^{+}$ is a
  1122. sequence of instructions.
  1123. %
  1124. An x86 program is stored in the computer's memory and the computer has
  1125. a \emph{program counter} that points to the address of the next
  1126. instruction to be executed. For most instructions, once the
  1127. instruction is executed, the program counter is incremented to point
  1128. to the immediately following instruction in memory. Most x86
  1129. instructions take two operands, where each operand is either an
  1130. integer constant (called \emph{immediate value}), a \emph{register},
  1131. or a memory location. A register is a special kind of variable. Each
  1132. one holds a 64-bit value; there are 16 registers in the computer and
  1133. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1134. as a mapping of 64-bit addresses to 64-bit values%
  1135. \footnote{This simple story suffices for describing how sequential
  1136. programs access memory but is not sufficient for multi-threaded
  1137. programs. However, multi-threaded execution is beyond the scope of
  1138. this book.}.
  1139. %
  1140. We use the AT\&T syntax expected by the GNU assembler, which comes
  1141. with the \key{gcc} compiler that we use for compiling assembly code to
  1142. machine code.
  1143. %
  1144. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1145. the x86 instructions used in this book.
  1146. % to do: finish treatment of imulq
  1147. % it's needed for vector's in R6/R7
  1148. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1149. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1150. && \key{r8} \mid \key{r9} \mid \key{r10}
  1151. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1152. \mid \key{r14} \mid \key{r15}}
  1153. \begin{figure}[tp]
  1154. \fbox{
  1155. \begin{minipage}{0.96\textwidth}
  1156. \[
  1157. \begin{array}{lcl}
  1158. \Reg &::=& \allregisters{} \\
  1159. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1160. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1161. \key{subq} \; \Arg\key{,} \Arg \mid
  1162. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1163. && \key{callq} \; \mathit{label} \mid
  1164. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1165. && \itm{label}\key{:}\; \Instr \\
  1166. \Prog &::= & \key{.globl main}\\
  1167. & & \key{main:} \; \Instr^{+}
  1168. \end{array}
  1169. \]
  1170. \end{minipage}
  1171. }
  1172. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1173. \label{fig:x86-0-concrete}
  1174. \end{figure}
  1175. An immediate value is written using the notation \key{\$}$n$ where $n$
  1176. is an integer.
  1177. %
  1178. A register is written with a \key{\%} followed by the register name,
  1179. such as \key{\%rax}.
  1180. %
  1181. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1182. which obtains the address stored in register $r$ and then adds $n$
  1183. bytes to the address. The resulting address is used to either load or
  1184. store to memory depending on whether it occurs as a source or
  1185. destination argument of an instruction.
  1186. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1187. source $s$ and destination $d$, applies the arithmetic operation, then
  1188. writes the result back to the destination $d$.
  1189. %
  1190. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1191. stores the result in $d$.
  1192. %
  1193. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1194. specified by the label and $\key{retq}$ returns from a procedure to
  1195. its caller. We discuss procedure calls in more detail later in this
  1196. chapter and in Chapter~\ref{ch:functions}. The
  1197. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1198. the address of the instruction after the specified label.
  1199. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1200. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1201. \key{main} procedure is externally visible, which is necessary so
  1202. that the operating system can call it. The label \key{main:}
  1203. indicates the beginning of the \key{main} procedure which is where
  1204. the operating system starts executing this program. The instruction
  1205. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1206. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1207. $10$ in \key{rax} and puts the result, $42$, back into
  1208. \key{rax}.
  1209. %
  1210. The last instruction, \key{retq}, finishes the \key{main} function by
  1211. returning the integer in \key{rax} to the operating system. The
  1212. operating system interprets this integer as the program's exit
  1213. code. By convention, an exit code of 0 indicates that a program
  1214. completed successfully, and all other exit codes indicate various
  1215. errors. Nevertheless, we return the result of the program as the exit
  1216. code.
  1217. %\begin{wrapfigure}{r}{2.25in}
  1218. \begin{figure}[tbp]
  1219. \begin{lstlisting}
  1220. .globl main
  1221. main:
  1222. movq $10, %rax
  1223. addq $32, %rax
  1224. retq
  1225. \end{lstlisting}
  1226. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1227. \label{fig:p0-x86}
  1228. %\end{wrapfigure}
  1229. \end{figure}
  1230. Unfortunately, x86 varies in a couple ways depending on what operating
  1231. system it is assembled in. The code examples shown here are correct on
  1232. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1233. labels like \key{main} must be prefixed with an underscore, as in
  1234. \key{\_main}.
  1235. We exhibit the use of memory for storing intermediate results in the
  1236. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1237. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1238. memory called the \emph{procedure call stack} (or \emph{stack} for
  1239. short). The stack consists of a separate \emph{frame} for each
  1240. procedure call. The memory layout for an individual frame is shown in
  1241. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1242. \emph{stack pointer} and points to the item at the top of the
  1243. stack. The stack grows downward in memory, so we increase the size of
  1244. the stack by subtracting from the stack pointer. In the context of a
  1245. procedure call, the \emph{return address} is the next instruction
  1246. after the call instruction on the caller side. During a function call,
  1247. the return address is pushed onto the stack. The register \key{rbp}
  1248. is the \emph{base pointer} and is used to access variables associated
  1249. with the current procedure call. The base pointer of the caller is
  1250. pushed onto the stack after the return address. We number the
  1251. variables from $1$ to $n$. Variable $1$ is stored at address
  1252. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1253. \begin{figure}[tbp]
  1254. \begin{lstlisting}
  1255. start:
  1256. movq $10, -8(%rbp)
  1257. negq -8(%rbp)
  1258. movq -8(%rbp), %rax
  1259. addq $52, %rax
  1260. jmp conclusion
  1261. .globl main
  1262. main:
  1263. pushq %rbp
  1264. movq %rsp, %rbp
  1265. subq $16, %rsp
  1266. jmp start
  1267. conclusion:
  1268. addq $16, %rsp
  1269. popq %rbp
  1270. retq
  1271. \end{lstlisting}
  1272. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1273. \label{fig:p1-x86}
  1274. \end{figure}
  1275. \begin{figure}[tbp]
  1276. \centering
  1277. \begin{tabular}{|r|l|} \hline
  1278. Position & Contents \\ \hline
  1279. 8(\key{\%rbp}) & return address \\
  1280. 0(\key{\%rbp}) & old \key{rbp} \\
  1281. -8(\key{\%rbp}) & variable $1$ \\
  1282. -16(\key{\%rbp}) & variable $2$ \\
  1283. \ldots & \ldots \\
  1284. 0(\key{\%rsp}) & variable $n$\\ \hline
  1285. \end{tabular}
  1286. \caption{Memory layout of a frame.}
  1287. \label{fig:frame}
  1288. \end{figure}
  1289. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1290. control is transfered from the operating system to the \code{main}
  1291. function. The operating system issues a \code{callq main} instruction
  1292. which pushes its return address on the stack and then jumps to
  1293. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1294. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1295. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1296. alignment (because the \code{callq} pushed the return address). The
  1297. first three instructions are the typical \emph{prelude} for a
  1298. procedure. The instruction \code{pushq \%rbp} saves the base pointer
  1299. for the caller onto the stack and subtracts $8$ from the stack
  1300. pointer. At this point the stack pointer is back to being 16-byte
  1301. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1302. base pointer so that it points the location of the old base
  1303. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1304. pointer down to make enough room for storing variables. This program
  1305. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1306. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1307. we are ready to make calls to other functions. The last instruction of
  1308. the prelude is \code{jmp start}, which transfers control to the
  1309. instructions that were generated from the Racket expression \code{(+
  1310. 10 32)}.
  1311. The four instructions under the label \code{start} carry out the work
  1312. of computing \code{(+ 52 (- 10)))}. The first instruction
  1313. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1314. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1315. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1316. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1317. \code{rax}, at which point \code{rax} contains $42$.
  1318. The three instructions under the label \code{conclusion} are the
  1319. typical \emph{conclusion} of a procedure. The first two instructions
  1320. are necessary to get the state of the machine back to where it was at
  1321. the beginning of the procedure. The instruction \key{addq \$16,
  1322. \%rsp} moves the stack pointer back to point at the old base
  1323. pointer. The amount added here needs to match the amount that was
  1324. subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1325. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1326. pointer. The last instruction, \key{retq}, jumps back to the
  1327. procedure that called this one and adds 8 to the stack pointer, which
  1328. returns the stack pointer to where it was prior to the procedure call.
  1329. The compiler needs a convenient representation for manipulating x86
  1330. programs, so we define an abstract syntax for x86 in
  1331. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1332. a subscript $0$ because later we introduce extended versions of this
  1333. assembly language. The main difference compared to the concrete syntax
  1334. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow labeled
  1335. instructions to appear anywhere, but instead organizes instructions
  1336. into groups called \emph{blocks} and associates a label with every
  1337. block, which is why the \key{CFG} struct (for control-flow graph)
  1338. includes an alist mapping labels to blocks. The reason for this
  1339. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1340. introduce conditional branching. The \code{Block} structure includes
  1341. an $\itm{info}$ field that is not needed for this chapter, but will
  1342. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1343. the $\itm{info}$ field should just contain an empty list.
  1344. \begin{figure}[tp]
  1345. \fbox{
  1346. \begin{minipage}{0.96\textwidth}
  1347. \small
  1348. \[
  1349. \begin{array}{lcl}
  1350. \Reg &::=& \allregisters{} \\
  1351. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1352. \mid \DEREF{\Reg}{\Int} \\
  1353. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1354. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1355. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1356. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1357. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1358. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1359. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1360. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1361. \end{array}
  1362. \]
  1363. \end{minipage}
  1364. }
  1365. \caption{The abstract syntax of x86$_0$ assembly.}
  1366. \label{fig:x86-0-ast}
  1367. \end{figure}
  1368. \section{Planning the trip to x86 via the $C_0$ language}
  1369. \label{sec:plan-s0-x86}
  1370. To compile one language to another it helps to focus on the
  1371. differences between the two languages because the compiler will need
  1372. to bridge those differences. What are the differences between $R_1$
  1373. and x86 assembly? Here are some of the most important ones:
  1374. \begin{enumerate}
  1375. \item[(a)] x86 arithmetic instructions typically have two arguments
  1376. and update the second argument in place. In contrast, $R_1$
  1377. arithmetic operations take two arguments and produce a new value.
  1378. An x86 instruction may have at most one memory-accessing argument.
  1379. Furthermore, some instructions place special restrictions on their
  1380. arguments.
  1381. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1382. whereas x86 instructions restrict their arguments to be integers
  1383. constants, registers, and memory locations.
  1384. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1385. sequence of instructions and jumps to labeled positions, whereas in
  1386. $R_1$ the order of evaluation is a left-to-right depth-first
  1387. traversal of the abstract syntax tree.
  1388. \item[(d)] An $R_1$ program can have any number of variables whereas
  1389. x86 has 16 registers and the procedure calls stack.
  1390. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1391. same name. The registers and memory locations of x86 all have unique
  1392. names or addresses.
  1393. \end{enumerate}
  1394. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1395. the problem into several steps, dealing with the above differences one
  1396. at a time. Each of these steps is called a \emph{pass} of the
  1397. compiler.
  1398. %
  1399. This terminology comes from each step traverses (i.e. passes over) the
  1400. AST of the program.
  1401. %
  1402. We begin by sketching how we might implement each pass, and give them
  1403. names. We then figure out an ordering of the passes and the
  1404. input/output language for each pass. The very first pass has $R_1$ as
  1405. its input language and the last pass has x86 as its output
  1406. language. In between we can choose whichever language is most
  1407. convenient for expressing the output of each pass, whether that be
  1408. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1409. Finally, to implement each pass we write one recursive function per
  1410. non-terminal in the grammar of the input language of the pass.
  1411. \begin{description}
  1412. \item[Pass \key{select-instructions}] To handle the difference between
  1413. $R_1$ operations and x86 instructions we convert each $R_1$
  1414. operation to a short sequence of instructions that accomplishes the
  1415. same task.
  1416. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1417. subexpression (i.e. operator and operand, and hence the name
  1418. \key{opera*}) is an \emph{atomic} expression (a variable or
  1419. integer), we introduce temporary variables to hold the results
  1420. of subexpressions.
  1421. \item[Pass \key{explicate-control}] To make the execution order of the
  1422. program explicit, we convert from the abstract syntax tree
  1423. representation into a \emph{control-flow graph} in which each node
  1424. contains a sequence of statements and the edges between nodes say
  1425. where to go at the end of the sequence.
  1426. \item[Pass \key{assign-homes}] To handle the difference between the
  1427. variables in $R_1$ versus the registers and stack locations in x86,
  1428. we map each variable to a register or stack location.
  1429. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1430. by renaming every variable to a unique name, so that shadowing no
  1431. longer occurs.
  1432. \end{description}
  1433. The next question is: in what order should we apply these passes? This
  1434. question can be challenging because it is difficult to know ahead of
  1435. time which orders will be better (easier to implement, produce more
  1436. efficient code, etc.) so oftentimes trial-and-error is
  1437. involved. Nevertheless, we can try to plan ahead and make educated
  1438. choices regarding the ordering.
  1439. Let us consider the ordering of \key{uniquify} and
  1440. \key{remove-complex-opera*}. The assignment of subexpressions to
  1441. temporary variables involves introducing new variables and moving
  1442. subexpressions, which might change the shadowing of variables and
  1443. inadvertently change the behavior of the program. But if we apply
  1444. \key{uniquify} first, this will not be an issue. Of course, this means
  1445. that in \key{remove-complex-opera*}, we need to ensure that the
  1446. temporary variables that it creates are unique.
  1447. What should be the ordering of \key{explicate-control} with respect to
  1448. \key{uniquify}? The \key{uniquify} pass should come first because
  1449. \key{explicate-control} changes all the \key{let}-bound variables to
  1450. become local variables whose scope is the entire program, which would
  1451. confuse variables with the same name.
  1452. %
  1453. Likewise, we place \key{explicate-control} after
  1454. \key{remove-complex-opera*} because \key{explicate-control} removes
  1455. the \key{let} form, but it is convenient to use \key{let} in the
  1456. output of \key{remove-complex-opera*}.
  1457. %
  1458. Regarding \key{assign-homes}, it is helpful to place
  1459. \key{explicate-control} first because \key{explicate-control} changes
  1460. \key{let}-bound variables into program-scope variables. This means
  1461. that the \key{assign-homes} pass can read off the variables from the
  1462. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1463. entire program in search of \key{let}-bound variables.
  1464. Last, we need to decide on the ordering of \key{select-instructions}
  1465. and \key{assign-homes}. These two passes are intertwined, creating a
  1466. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1467. have already determined which instructions will be used, because x86
  1468. instructions have restrictions about which of their arguments can be
  1469. registers versus stack locations. One might want to give preferential
  1470. treatment to variables that occur in register-argument positions. On
  1471. the other hand, it may turn out to be impossible to make sure that all
  1472. such variables are assigned to registers, and then one must redo the
  1473. selection of instructions. Some compilers handle this problem by
  1474. iteratively repeating these two passes until a good solution is found.
  1475. We shall use a simpler approach in which \key{select-instructions}
  1476. comes first, followed by the \key{assign-homes}, then a third
  1477. pass named \key{patch-instructions} that uses a reserved register to
  1478. patch-up outstanding problems regarding instructions with too many
  1479. memory accesses. The disadvantage of this approach is some programs
  1480. may not execute as efficiently as they would if we used the iterative
  1481. approach and used all of the registers for variables.
  1482. \begin{figure}[tbp]
  1483. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1484. \node (R1) at (0,2) {\large $R_1$};
  1485. \node (R1-2) at (3,2) {\large $R_1$};
  1486. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1487. %\node (C0-1) at (6,0) {\large $C_0$};
  1488. \node (C0-2) at (3,0) {\large $C_0$};
  1489. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1490. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1491. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1492. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1493. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1494. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1495. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1496. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1497. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1498. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1499. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1500. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1501. \end{tikzpicture}
  1502. \caption{Overview of the passes for compiling $R_1$. }
  1503. \label{fig:R1-passes}
  1504. \end{figure}
  1505. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1506. passes in the form of a graph. Each pass is an edge and the
  1507. input/output language of each pass is a node in the graph. The output
  1508. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1509. are still in the $R_1$ language, but the output of the pass
  1510. \key{explicate-control} is in a different language $C_0$ that is
  1511. designed to make the order of evaluation explicit in its syntax, which
  1512. we introduce in the next section. The \key{select-instruction} pass
  1513. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1514. \key{patch-instructions} passes input and output variants of x86
  1515. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1516. \key{print-x86}, which converts from the abstract syntax of
  1517. $\text{x86}_0$ to the concrete syntax of x86.
  1518. In the next sections we discuss the $C_0$ language and the
  1519. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1520. remainder of this chapter gives hints regarding the implementation of
  1521. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1522. \subsection{The $C_0$ Intermediate Language}
  1523. The output of \key{explicate-control} is similar to the $C$
  1524. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1525. categories for expressions and statements, so we name it $C_0$. The
  1526. concrete syntax for $C_0$ is defined in
  1527. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1528. is defined in Figure~\ref{fig:c0-syntax}.
  1529. %
  1530. The $C_0$ language supports the same operators as $R_1$ but the
  1531. arguments of operators are restricted to atomic expressions (variables
  1532. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1533. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1534. executed in sequence using the \key{Seq} form. A sequence of
  1535. statements always ends with \key{Return}, a guarantee that is baked
  1536. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1537. this non-terminal comes from the term \emph{tail position}, which
  1538. refers to an expression that is the last one to execute within a
  1539. function. (A expression in tail position may contain subexpressions,
  1540. and those may or may not be in tail position depending on the kind of
  1541. expression.)
  1542. A $C_0$ program consists of a control-flow graph (represented as an
  1543. alist mapping labels to tails). This is more general than
  1544. necessary for the present chapter, as we do not yet need to introduce
  1545. \key{goto} for jumping to labels, but it saves us from having to
  1546. change the syntax of the program construct in
  1547. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1548. \key{start}, and the whole program is its tail.
  1549. %
  1550. The $\itm{info}$ field of the \key{Program} form, after the
  1551. \key{explicate-control} pass, contains a mapping from the symbol
  1552. \key{locals} to a list of variables, that is, a list of all the
  1553. variables used in the program. At the start of the program, these
  1554. variables are uninitialized; they become initialized on their first
  1555. assignment.
  1556. \begin{figure}[tbp]
  1557. \fbox{
  1558. \begin{minipage}{0.96\textwidth}
  1559. \[
  1560. \begin{array}{lcl}
  1561. \Atm &::=& \Int \mid \Var \\
  1562. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1563. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1564. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1565. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1566. \end{array}
  1567. \]
  1568. \end{minipage}
  1569. }
  1570. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1571. \label{fig:c0-concrete-syntax}
  1572. \end{figure}
  1573. \begin{figure}[tbp]
  1574. \fbox{
  1575. \begin{minipage}{0.96\textwidth}
  1576. \[
  1577. \begin{array}{lcl}
  1578. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1579. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1580. &\mid& \ADD{\Atm}{\Atm}\\
  1581. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1582. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1583. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1584. \end{array}
  1585. \]
  1586. \end{minipage}
  1587. }
  1588. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1589. \label{fig:c0-syntax}
  1590. \end{figure}
  1591. %% The \key{select-instructions} pass is optimistic in the sense that it
  1592. %% treats variables as if they were all mapped to registers. The
  1593. %% \key{select-instructions} pass generates a program that consists of
  1594. %% x86 instructions but that still uses variables, so it is an
  1595. %% intermediate language that is technically different than x86, which
  1596. %% explains the asterisks in the diagram above.
  1597. %% In this Chapter we shall take the easy road to implementing
  1598. %% \key{assign-homes} and simply map all variables to stack locations.
  1599. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1600. %% smarter approach in which we make a best-effort to map variables to
  1601. %% registers, resorting to the stack only when necessary.
  1602. %% Once variables have been assigned to their homes, we can finalize the
  1603. %% instruction selection by dealing with an idiosyncrasy of x86
  1604. %% assembly. Many x86 instructions have two arguments but only one of the
  1605. %% arguments may be a memory reference (and the stack is a part of
  1606. %% memory). Because some variables may get mapped to stack locations,
  1607. %% some of our generated instructions may violate this restriction. The
  1608. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1609. %% replacing every violating instruction with a short sequence of
  1610. %% instructions that use the \key{rax} register. Once we have implemented
  1611. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1612. %% need to patch instructions will be relatively rare.
  1613. \subsection{The dialects of x86}
  1614. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1615. the pass \key{select-instructions}. It extends x86$_0$ with an
  1616. unbounded number of program-scope variables and has looser rules
  1617. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1618. output of \key{print-x86}, is the concrete syntax for x86.
  1619. \section{Uniquify Variables}
  1620. \label{sec:uniquify-s0}
  1621. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1622. programs in which every \key{let} uses a unique variable name. For
  1623. example, the \code{uniquify} pass should translate the program on the
  1624. left into the program on the right. \\
  1625. \begin{tabular}{lll}
  1626. \begin{minipage}{0.4\textwidth}
  1627. \begin{lstlisting}
  1628. (let ([x 32])
  1629. (+ (let ([x 10]) x) x))
  1630. \end{lstlisting}
  1631. \end{minipage}
  1632. &
  1633. $\Rightarrow$
  1634. &
  1635. \begin{minipage}{0.4\textwidth}
  1636. \begin{lstlisting}
  1637. (let ([x.1 32])
  1638. (+ (let ([x.2 10]) x.2) x.1))
  1639. \end{lstlisting}
  1640. \end{minipage}
  1641. \end{tabular} \\
  1642. %
  1643. The following is another example translation, this time of a program
  1644. with a \key{let} nested inside the initializing expression of another
  1645. \key{let}.\\
  1646. \begin{tabular}{lll}
  1647. \begin{minipage}{0.4\textwidth}
  1648. \begin{lstlisting}
  1649. (let ([x (let ([x 4])
  1650. (+ x 1))])
  1651. (+ x 2))
  1652. \end{lstlisting}
  1653. \end{minipage}
  1654. &
  1655. $\Rightarrow$
  1656. &
  1657. \begin{minipage}{0.4\textwidth}
  1658. \begin{lstlisting}
  1659. (let ([x.2 (let ([x.1 4])
  1660. (+ x.1 1))])
  1661. (+ x.2 2))
  1662. \end{lstlisting}
  1663. \end{minipage}
  1664. \end{tabular}
  1665. We recommend implementing \code{uniquify} by creating a function named
  1666. \code{uniquify-exp} that is structurally recursive function and mostly
  1667. just copies the input program. However, when encountering a \key{let},
  1668. it should generate a unique name for the variable (the Racket function
  1669. \code{gensym} is handy for this) and associate the old name with the
  1670. new unique name in an alist. The \code{uniquify-exp}
  1671. function will need to access this alist when it gets to a
  1672. variable reference, so we add another parameter to \code{uniquify-exp}
  1673. for the alist.
  1674. The skeleton of the \code{uniquify-exp} function is shown in
  1675. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1676. convenient to partially apply it to a symbol table and then apply it
  1677. to different expressions, as in the last clause for primitive
  1678. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1679. is useful for applying a function to each element of a list to produce
  1680. a new list.
  1681. \begin{exercise}
  1682. \normalfont % I don't like the italics for exercises. -Jeremy
  1683. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1684. implement the clauses for variables and for the \key{let} form.
  1685. \end{exercise}
  1686. \begin{figure}[tbp]
  1687. \begin{lstlisting}
  1688. (define (uniquify-exp symtab)
  1689. (lambda (e)
  1690. (match e
  1691. [(Var x) ___]
  1692. [(Int n) (Int n)]
  1693. [(Let x e body) ___]
  1694. [(Prim op es)
  1695. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1696. )))
  1697. (define (uniquify p)
  1698. (match p
  1699. [(Program '() e)
  1700. (Program '() ((uniquify-exp '()) e))]
  1701. )))
  1702. \end{lstlisting}
  1703. \caption{Skeleton for the \key{uniquify} pass.}
  1704. \label{fig:uniquify-s0}
  1705. \end{figure}
  1706. \begin{exercise}
  1707. \normalfont % I don't like the italics for exercises. -Jeremy
  1708. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1709. and checking whether the output programs produce the same result as
  1710. the input programs. The $R_1$ programs should be designed to test the
  1711. most interesting parts of the \key{uniquify} pass, that is, the
  1712. programs should include \key{let} forms, variables, and variables
  1713. that overshadow each other. The five programs should be in a
  1714. subdirectory named \key{tests} and they should have the same file name
  1715. except for a different integer at the end of the name, followed by the
  1716. ending \key{.rkt}. Use the \key{interp-tests} function
  1717. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1718. your \key{uniquify} pass on the example programs. See the
  1719. \key{run-tests.rkt} script in the student support code for an example
  1720. of how to use \key{interp-tests}.
  1721. \end{exercise}
  1722. \section{Remove Complex Operands}
  1723. \label{sec:remove-complex-opera-R1}
  1724. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1725. $R_1$ programs in which the arguments of operations are atomic
  1726. expressions. Put another way, this pass removes complex operands,
  1727. such as the expression \code{(- 10)} in the program below. This is
  1728. accomplished by introducing a new \key{let}-bound variable, binding
  1729. the complex operand to the new variable, and then using the new
  1730. variable in place of the complex operand, as shown in the output of
  1731. \code{remove-complex-opera*} on the right.\\
  1732. \begin{tabular}{lll}
  1733. \begin{minipage}{0.4\textwidth}
  1734. % s0_19.rkt
  1735. \begin{lstlisting}
  1736. (+ 52 (- 10))
  1737. \end{lstlisting}
  1738. \end{minipage}
  1739. &
  1740. $\Rightarrow$
  1741. &
  1742. \begin{minipage}{0.4\textwidth}
  1743. \begin{lstlisting}
  1744. (let ([tmp.1 (- 10)])
  1745. (+ 52 tmp.1))
  1746. \end{lstlisting}
  1747. \end{minipage}
  1748. \end{tabular}
  1749. \begin{figure}[tp]
  1750. \centering
  1751. \fbox{
  1752. \begin{minipage}{0.96\textwidth}
  1753. \[
  1754. \begin{array}{rcl}
  1755. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1756. \Exp &::=& \Atm \mid \READ{} \\
  1757. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1758. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1759. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1760. \end{array}
  1761. \]
  1762. \end{minipage}
  1763. }
  1764. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1765. \label{fig:r1-anf-syntax}
  1766. \end{figure}
  1767. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1768. this pass, language $R_1^{\dagger}$. The main difference is that
  1769. operator arguments are required to be atomic expressions. In the
  1770. literature this is called \emph{administrative normal form}, or ANF
  1771. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1772. We recommend implementing this pass with two mutually recursive
  1773. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1774. \code{rco-atom} to subexpressions that are required to be atomic and
  1775. to apply \code{rco-exp} to subexpressions that can be atomic or
  1776. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1777. $R_1$ expression as input. The \code{rco-exp} function returns an
  1778. expression. The \code{rco-atom} function returns two things: an
  1779. atomic expression and alist mapping temporary variables to complex
  1780. subexpressions. You can return multiple things from a function using
  1781. Racket's \key{values} form and you can receive multiple things from a
  1782. function call using the \key{define-values} form. If you are not
  1783. familiar with these features, review the Racket documentation. Also,
  1784. the \key{for/lists} form is useful for applying a function to each
  1785. element of a list, in the case where the function returns multiple
  1786. values.
  1787. The following shows the output of \code{rco-atom} on the expression
  1788. \code{(- 10)} (using concrete syntax to be concise).
  1789. \begin{tabular}{lll}
  1790. \begin{minipage}{0.4\textwidth}
  1791. \begin{lstlisting}
  1792. (- 10)
  1793. \end{lstlisting}
  1794. \end{minipage}
  1795. &
  1796. $\Rightarrow$
  1797. &
  1798. \begin{minipage}{0.4\textwidth}
  1799. \begin{lstlisting}
  1800. tmp.1
  1801. ((tmp.1 . (- 10)))
  1802. \end{lstlisting}
  1803. \end{minipage}
  1804. \end{tabular}
  1805. Take special care of programs such as the next one that \key{let}-bind
  1806. variables with integers or other variables. You should leave them
  1807. unchanged, as shown in to the program on the right \\
  1808. \begin{tabular}{lll}
  1809. \begin{minipage}{0.4\textwidth}
  1810. % s0_20.rkt
  1811. \begin{lstlisting}
  1812. (let ([a 42])
  1813. (let ([b a])
  1814. b))
  1815. \end{lstlisting}
  1816. \end{minipage}
  1817. &
  1818. $\Rightarrow$
  1819. &
  1820. \begin{minipage}{0.4\textwidth}
  1821. \begin{lstlisting}
  1822. (let ([a 42])
  1823. (let ([b a])
  1824. b))
  1825. \end{lstlisting}
  1826. \end{minipage}
  1827. \end{tabular} \\
  1828. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1829. produce the following output.\\
  1830. \begin{minipage}{0.4\textwidth}
  1831. \begin{lstlisting}
  1832. (let ([tmp.1 42])
  1833. (let ([a tmp.1])
  1834. (let ([tmp.2 a])
  1835. (let ([b tmp.2])
  1836. b))))
  1837. \end{lstlisting}
  1838. \end{minipage}
  1839. \begin{exercise}
  1840. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1841. it on all of the example programs that you created to test the
  1842. \key{uniquify} pass and create three new example programs that are
  1843. designed to exercise the interesting code in the
  1844. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1845. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1846. your passes on the example programs.
  1847. \end{exercise}
  1848. \section{Explicate Control}
  1849. \label{sec:explicate-control-r1}
  1850. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1851. programs that make the order of execution explicit in their
  1852. syntax. For now this amounts to flattening \key{let} constructs into a
  1853. sequence of assignment statements. For example, consider the following
  1854. $R_1$ program.\\
  1855. % s0_11.rkt
  1856. \begin{minipage}{0.96\textwidth}
  1857. \begin{lstlisting}
  1858. (let ([y (let ([x 20])
  1859. (+ x (let ([x 22]) x)))])
  1860. y)
  1861. \end{lstlisting}
  1862. \end{minipage}\\
  1863. %
  1864. The output of the previous pass and of \code{explicate-control} is
  1865. shown below. Recall that the right-hand-side of a \key{let} executes
  1866. before its body, so the order of evaluation for this program is to
  1867. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1868. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1869. output of \code{explicate-control} makes this ordering explicit.\\
  1870. \begin{tabular}{lll}
  1871. \begin{minipage}{0.4\textwidth}
  1872. \begin{lstlisting}
  1873. (let ([y (let ([x.1 20])
  1874. (let ([x.2 22])
  1875. (+ x.1 x.2)))])
  1876. y)
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. &
  1880. $\Rightarrow$
  1881. &
  1882. \begin{minipage}{0.4\textwidth}
  1883. \begin{lstlisting}
  1884. locals: y x.1 x.2
  1885. start:
  1886. x.1 = 20;
  1887. x.2 = 22;
  1888. y = (+ x.1 x.2);
  1889. return y;
  1890. \end{lstlisting}
  1891. \end{minipage}
  1892. \end{tabular}
  1893. We recommend implementing \code{explicate-control} using two mutually
  1894. recursive functions: \code{explicate-tail} and
  1895. \code{explicate-assign}. The first function should be applied to
  1896. expressions in tail position whereas the second should be applied to
  1897. expressions that occur on the right-hand-side of a \key{let}. The
  1898. \code{explicate-tail} function takes an $R_1$ expression as input and
  1899. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1900. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1901. function takes an $R_1$ expression, the variable that it is to be
  1902. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1903. assignment (e.g., the code generated for the body of the \key{let}).
  1904. It returns a $\Tail$ and a list of variables. The top-level
  1905. \code{explicate-control} function should invoke \code{explicate-tail}
  1906. on the body of the \key{program} and then associate the \code{locals}
  1907. symbol with the resulting list of variables in the $\itm{info}$ field,
  1908. as in the above example.
  1909. \section{Select Instructions}
  1910. \label{sec:select-r1}
  1911. In the \code{select-instructions} pass we begin the work of
  1912. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1913. this pass is a variant of x86 that still uses variables, so we add an
  1914. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1915. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1916. \code{select-instructions} in terms of three auxiliary functions, one
  1917. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1918. The cases for $\Atm$ are straightforward, variables stay
  1919. the same and integer constants are changed to immediates:
  1920. $\INT{n}$ changes to $\IMM{n}$.
  1921. Next we consider the cases for $\Stmt$, starting with arithmetic
  1922. operations. For example, in $C_0$ an addition operation can take the
  1923. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1924. need to use the \key{addq} instruction which does an in-place
  1925. update. So we must first move \code{10} to \code{x}. \\
  1926. \begin{tabular}{lll}
  1927. \begin{minipage}{0.4\textwidth}
  1928. \begin{lstlisting}
  1929. x = (+ 10 32);
  1930. \end{lstlisting}
  1931. \end{minipage}
  1932. &
  1933. $\Rightarrow$
  1934. &
  1935. \begin{minipage}{0.4\textwidth}
  1936. \begin{lstlisting}
  1937. movq $10, x
  1938. addq $32, x
  1939. \end{lstlisting}
  1940. \end{minipage}
  1941. \end{tabular} \\
  1942. %
  1943. There are cases that require special care to avoid generating
  1944. needlessly complicated code. If one of the arguments of the addition
  1945. is the same as the left-hand side of the assignment, then there is no
  1946. need for the extra move instruction. For example, the following
  1947. assignment statement can be translated into a single \key{addq}
  1948. instruction.\\
  1949. \begin{tabular}{lll}
  1950. \begin{minipage}{0.4\textwidth}
  1951. \begin{lstlisting}
  1952. x = (+ 10 x);
  1953. \end{lstlisting}
  1954. \end{minipage}
  1955. &
  1956. $\Rightarrow$
  1957. &
  1958. \begin{minipage}{0.4\textwidth}
  1959. \begin{lstlisting}
  1960. addq $10, x
  1961. \end{lstlisting}
  1962. \end{minipage}
  1963. \end{tabular} \\
  1964. The \key{read} operation does not have a direct counterpart in x86
  1965. assembly, so we have instead implemented this functionality in the C
  1966. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  1967. in the file \code{runtime.c}. In general, we refer to all of the
  1968. functionality in this file as the \emph{runtime system}, or simply the
  1969. \emph{runtime} for short. When compiling your generated x86 assembly
  1970. code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  1971. ``object file'', using \code{gcc} option \code{-c}) and link it into
  1972. the executable. For our purposes of code generation, all you need to
  1973. do is translate an assignment of \key{read} into some variable
  1974. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  1975. function followed by a move from \code{rax} to the left-hand side.
  1976. The move from \code{rax} is needed because the return value from
  1977. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1978. \begin{tabular}{lll}
  1979. \begin{minipage}{0.3\textwidth}
  1980. \begin{lstlisting}
  1981. |$\itm{var}$| = (read);
  1982. \end{lstlisting}
  1983. \end{minipage}
  1984. &
  1985. $\Rightarrow$
  1986. &
  1987. \begin{minipage}{0.3\textwidth}
  1988. \begin{lstlisting}
  1989. callq read_int
  1990. movq %rax, |$\itm{var}$|
  1991. \end{lstlisting}
  1992. \end{minipage}
  1993. \end{tabular} \\
  1994. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1995. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1996. assignment to the \key{rax} register followed by a jump to the
  1997. conclusion of the program (so the conclusion needs to be labeled).
  1998. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1999. recursively and append the resulting instructions.
  2000. \begin{exercise}
  2001. \normalfont
  2002. Implement the \key{select-instructions} pass and test it on all of the
  2003. example programs that you created for the previous passes and create
  2004. three new example programs that are designed to exercise all of the
  2005. interesting code in this pass. Use the \key{interp-tests} function
  2006. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2007. your passes on the example programs.
  2008. \end{exercise}
  2009. \section{Assign Homes}
  2010. \label{sec:assign-r1}
  2011. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2012. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2013. Thus, the \key{assign-homes} pass is responsible for placing all of
  2014. the program variables in registers or on the stack. For runtime
  2015. efficiency, it is better to place variables in registers, but as there
  2016. are only 16 registers, some programs must necessarily resort to
  2017. placing some variables on the stack. In this chapter we focus on the
  2018. mechanics of placing variables on the stack. We study an algorithm for
  2019. placing variables in registers in
  2020. Chapter~\ref{ch:register-allocation-r1}.
  2021. Consider again the following $R_1$ program.
  2022. % s0_20.rkt
  2023. \begin{lstlisting}
  2024. (let ([a 42])
  2025. (let ([b a])
  2026. b))
  2027. \end{lstlisting}
  2028. For reference, we repeat the output of \code{select-instructions} on
  2029. the left and show the output of \code{assign-homes} on the right.
  2030. Recall that \key{explicate-control} associated the list of
  2031. variables with the \code{locals} symbol in the program's $\itm{info}$
  2032. field, so \code{assign-homes} has convenient access to the them. In
  2033. this example, we assign variable \code{a} to stack location
  2034. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2035. \begin{tabular}{l}
  2036. \begin{minipage}{0.4\textwidth}
  2037. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2038. locals: a b
  2039. start:
  2040. movq $42, a
  2041. movq a, b
  2042. movq b, %rax
  2043. jmp conclusion
  2044. \end{lstlisting}
  2045. \end{minipage}
  2046. {$\Rightarrow$}
  2047. \begin{minipage}{0.4\textwidth}
  2048. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2049. stack-space: 16
  2050. start:
  2051. movq $42, -8(%rbp)
  2052. movq -8(%rbp), -16(%rbp)
  2053. movq -16(%rbp), %rax
  2054. jmp conclusion
  2055. \end{lstlisting}
  2056. \end{minipage}
  2057. \end{tabular} \\
  2058. In the process of assigning variables to stack locations, it is
  2059. convenient to compute and store the size of the frame (in bytes) in
  2060. the $\itm{info}$ field of the \key{Program} node, with the key
  2061. \code{stack-space}, which will be needed later to generate the
  2062. procedure conclusion. Some operating systems place restrictions on
  2063. the frame size. For example, Mac OS X requires the frame size to be a
  2064. multiple of 16 bytes.
  2065. \begin{exercise}
  2066. \normalfont Implement the \key{assign-homes} pass and test it on all
  2067. of the example programs that you created for the previous passes pass.
  2068. We recommend that \key{assign-homes} take an extra parameter that is a
  2069. mapping of variable names to homes (stack locations for now). Use the
  2070. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2071. \key{utilities.rkt} to test your passes on the example programs.
  2072. \end{exercise}
  2073. \section{Patch Instructions}
  2074. \label{sec:patch-s0}
  2075. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2076. programs to $\text{x86}_0$ programs by making sure that each
  2077. instruction adheres to the restrictions of the x86 assembly language.
  2078. In particular, at most one argument of an instruction may be a memory
  2079. reference.
  2080. We return to the following running example.
  2081. % s0_20.rkt
  2082. \begin{lstlisting}
  2083. (let ([a 42])
  2084. (let ([b a])
  2085. b))
  2086. \end{lstlisting}
  2087. After the \key{assign-homes} pass, the above program has been translated to
  2088. the following. \\
  2089. \begin{minipage}{0.5\textwidth}
  2090. \begin{lstlisting}
  2091. stack-space: 16
  2092. start:
  2093. movq $42, -8(%rbp)
  2094. movq -8(%rbp), -16(%rbp)
  2095. movq -16(%rbp), %rax
  2096. jmp conclusion
  2097. \end{lstlisting}
  2098. \end{minipage}\\
  2099. The second \key{movq} instruction is problematic because both
  2100. arguments are stack locations. We suggest fixing this problem by
  2101. moving from the source location to the register \key{rax} and then
  2102. from \key{rax} to the destination location, as follows.
  2103. \begin{lstlisting}
  2104. movq -8(%rbp), %rax
  2105. movq %rax, -16(%rbp)
  2106. \end{lstlisting}
  2107. \begin{exercise}
  2108. \normalfont
  2109. Implement the \key{patch-instructions} pass and test it on all of the
  2110. example programs that you created for the previous passes and create
  2111. three new example programs that are designed to exercise all of the
  2112. interesting code in this pass. Use the \key{interp-tests} function
  2113. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2114. your passes on the example programs.
  2115. \end{exercise}
  2116. \section{Print x86}
  2117. \label{sec:print-x86}
  2118. The last step of the compiler from $R_1$ to x86 is to convert the
  2119. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2120. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2121. \key{format} and \key{string-append} functions are useful in this
  2122. regard. The main work that this step needs to perform is to create the
  2123. \key{main} function and the standard instructions for its prelude and
  2124. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2125. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2126. variables, so we suggest computing it in the \key{assign-homes} pass
  2127. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2128. of the \key{program} node.
  2129. %% Your compiled code should print the result of the program's execution
  2130. %% by using the \code{print\_int} function provided in
  2131. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2132. %% far, this final result should be stored in the \key{rax} register.
  2133. %% We'll talk more about how to perform function calls with arguments in
  2134. %% general later on, but for now, place the following after the compiled
  2135. %% code for the $R_1$ program but before the conclusion:
  2136. %% \begin{lstlisting}
  2137. %% movq %rax, %rdi
  2138. %% callq print_int
  2139. %% \end{lstlisting}
  2140. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2141. %% stores the first argument to be passed into \key{print\_int}.
  2142. If you want your program to run on Mac OS X, your code needs to
  2143. determine whether or not it is running on a Mac, and prefix
  2144. underscores to labels like \key{main}. You can determine the platform
  2145. with the Racket call \code{(system-type 'os)}, which returns
  2146. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2147. %% In addition to
  2148. %% placing underscores on \key{main}, you need to put them in front of
  2149. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2150. %% \_print\_int}).
  2151. \begin{exercise}
  2152. \normalfont Implement the \key{print-x86} pass and test it on all of
  2153. the example programs that you created for the previous passes. Use the
  2154. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2155. \key{utilities.rkt} to test your complete compiler on the example
  2156. programs. See the \key{run-tests.rkt} script in the student support
  2157. code for an example of how to use \key{compiler-tests}. Also, remember
  2158. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2159. \key{gcc}.
  2160. \end{exercise}
  2161. \section{Challenge: Partial Evaluator for $R_1$}
  2162. \label{sec:pe-R1}
  2163. This section describes optional challenge exercises that involve
  2164. adapting and improving the partial evaluator for $R_0$ that was
  2165. introduced in Section~\ref{sec:partial-evaluation}.
  2166. \begin{exercise}\label{ex:pe-R1}
  2167. \normalfont
  2168. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2169. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2170. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2171. and variables to the $R_0$ language, so you will need to add cases for
  2172. them in the \code{pe-exp} function. Also, note that the \key{program}
  2173. form changes slightly to include an $\itm{info}$ field. Once
  2174. complete, add the partial evaluation pass to the front of your
  2175. compiler and make sure that your compiler still passes all of the
  2176. tests.
  2177. \end{exercise}
  2178. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2179. \begin{exercise}
  2180. \normalfont
  2181. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2182. \code{pe-add} auxiliary functions with functions that know more about
  2183. arithmetic. For example, your partial evaluator should translate
  2184. \begin{lstlisting}
  2185. (+ 1 (+ (read) 1))
  2186. \end{lstlisting}
  2187. into
  2188. \begin{lstlisting}
  2189. (+ 2 (read))
  2190. \end{lstlisting}
  2191. To accomplish this, the \code{pe-exp} function should produce output
  2192. in the form of the $\itm{residual}$ non-terminal of the following
  2193. grammar.
  2194. \[
  2195. \begin{array}{lcl}
  2196. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2197. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2198. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2199. \end{array}
  2200. \]
  2201. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2202. that their inputs are $\itm{residual}$ expressions and they should
  2203. return $\itm{residual}$ expressions. Once the improvements are
  2204. complete, make sure that your compiler still passes all of the tests.
  2205. After all, fast code is useless if it produces incorrect results!
  2206. \end{exercise}
  2207. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2208. \chapter{Register Allocation}
  2209. \label{ch:register-allocation-r1}
  2210. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2211. make our life easier. However, we can improve the performance of the
  2212. generated code if we instead place some variables into registers. The
  2213. CPU can access a register in a single cycle, whereas accessing the
  2214. stack takes many cycles if the relevant data is in cache or many more
  2215. to access main memory if the data is not in cache.
  2216. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2217. serves as a running example. We show the source program and also the
  2218. output of instruction selection. At that point the program is almost
  2219. x86 assembly but not quite; it still contains variables instead of
  2220. stack locations or registers.
  2221. \begin{figure}
  2222. \begin{minipage}{0.45\textwidth}
  2223. Example $R_1$ program:
  2224. % s0_28.rkt
  2225. \begin{lstlisting}
  2226. (let ([v 1])
  2227. (let ([w 42])
  2228. (let ([x (+ v 7)])
  2229. (let ([y x])
  2230. (let ([z (+ x w)])
  2231. (+ z (- y)))))))
  2232. \end{lstlisting}
  2233. \end{minipage}
  2234. \begin{minipage}{0.45\textwidth}
  2235. After instruction selection:
  2236. \begin{lstlisting}
  2237. locals: (v w x y z t)
  2238. start:
  2239. movq $1, v
  2240. movq $42, w
  2241. movq v, x
  2242. addq $7, x
  2243. movq x, y
  2244. movq x, z
  2245. addq w, z
  2246. movq y, t
  2247. negq t
  2248. movq z, %rax
  2249. addq t, %rax
  2250. jmp conclusion
  2251. \end{lstlisting}
  2252. \end{minipage}
  2253. \caption{An example program for register allocation.}
  2254. \label{fig:reg-eg}
  2255. \end{figure}
  2256. The goal of register allocation is to fit as many variables into
  2257. registers as possible. A program sometimes has more variables than
  2258. registers, so we cannot map each variable to a different
  2259. register. Fortunately, it is common for different variables to be
  2260. needed during different periods of time during program execution, and
  2261. in such cases several variables can be mapped to the same register.
  2262. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2263. After the variable \code{x} is moved to \code{z} it is no longer
  2264. needed. Variable \code{y}, on the other hand, is used only after this
  2265. point, so \code{x} and \code{y} could share the same register. The
  2266. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2267. where a variable is needed. Once we have that information, we compute
  2268. which variables are needed at the same time, i.e., which ones
  2269. \emph{interfere} with each other, and represent this relation as an
  2270. undirected graph whose vertices are variables and edges indicate when
  2271. two variables interfere (Section~\ref{sec:build-interference}). We
  2272. then model register allocation as a graph coloring problem, which we
  2273. discuss in Section~\ref{sec:graph-coloring}.
  2274. In the event that we run out of registers despite these efforts, we
  2275. place the remaining variables on the stack, similar to what we did in
  2276. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2277. for assigning a variable to a stack location. The process of spilling
  2278. variables is handled as part of the graph coloring process described
  2279. in \ref{sec:graph-coloring}.
  2280. We make the simplifying assumption that each variable is assigned to
  2281. one location (a register or stack address). A more sophisticated
  2282. approach is to assign a variable to one or more locations in different
  2283. regions of the program. For example, if a variable is used many times
  2284. in short sequence and then only used again after many other
  2285. instructions, it could be more efficient to assign the variable to a
  2286. register during the intial sequence and then move it to the stack for
  2287. the rest of its lifetime. We refer the interested reader to
  2288. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2289. about this approach.
  2290. % discuss prioritizing variables based on how much they are used.
  2291. \section{Registers and Calling Conventions}
  2292. \label{sec:calling-conventions}
  2293. As we perform register allocation, we need to be aware of the
  2294. conventions that govern the way in which registers interact with
  2295. function calls, such as calls to the \code{read\_int} function in our
  2296. generated code and even the call that the operating system makes to
  2297. execute our \code{main} function. The convention for x86 is that the
  2298. caller is responsible for freeing up some registers, the
  2299. \emph{caller-saved registers}, prior to the function call, and the
  2300. callee is responsible for preserving the values in some other
  2301. registers, the \emph{callee-saved registers}. The caller-saved
  2302. registers are
  2303. \begin{lstlisting}
  2304. rax rcx rdx rsi rdi r8 r9 r10 r11
  2305. \end{lstlisting}
  2306. while the callee-saved registers are
  2307. \begin{lstlisting}
  2308. rsp rbp rbx r12 r13 r14 r15
  2309. \end{lstlisting}
  2310. We can think about this caller/callee convention from two points of
  2311. view, the caller view and the callee view:
  2312. \begin{itemize}
  2313. \item The caller should assume that all the caller-saved registers get
  2314. overwritten with arbitrary values by the callee. On the other hand,
  2315. the caller can safely assume that all the callee-saved registers
  2316. contain the same values after the call that they did before the
  2317. call.
  2318. \item The callee can freely use any of the caller-saved registers.
  2319. However, if the callee wants to use a callee-saved register, the
  2320. callee must arrange to put the original value back in the register
  2321. prior to returning to the caller, which is usually accomplished by
  2322. saving the value to the stack in the prelude of the function and
  2323. restoring the value in the conclusion of the function.
  2324. \end{itemize}
  2325. The next question is how these calling conventions impact register
  2326. allocation. Consider the $R_1$ program in
  2327. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2328. example from the caller point of view and then from the callee point
  2329. of view.
  2330. The program makes two calls to the \code{read} function. Also, the
  2331. variable \code{x} is in-use during the second call to \code{read}, so
  2332. we need to make sure that the value in \code{x} does not get
  2333. accidentally wiped out by the call to \code{read}. One obvious
  2334. approach is to save all the values in caller-saved registers to the
  2335. stack prior to each function call, and restore them after each
  2336. call. That way, if the register allocator chooses to assign \code{x}
  2337. to a caller-saved register, its value will be preserved accross the
  2338. call to \code{read}. However, the disadvantage of this approach is
  2339. that saving and restoring to the stack is relatively slow. If \code{x}
  2340. is not used many times, it may be better to assign \code{x} to a stack
  2341. location in the first place. Or better yet, if we can arrange for
  2342. \code{x} to be placed in a callee-saved register, then it won't need
  2343. to be saved and restored during function calls.
  2344. The approach that we recommend is to treat variables differently
  2345. depending on whether they are in-use during a function call. If a
  2346. variable is in-use during a function call, then we never assign it to
  2347. a caller-saved register: we either assign it to a callee-saved
  2348. register or we spill it to the stack. If a variable is not in-use
  2349. during any function call, then we try the following alternatives in
  2350. order 1) look for an available caller-saved register (to leave room
  2351. for other variables in the callee-saved register), 2) look for a
  2352. callee-saved register, and 3) spill the variable to the stack.
  2353. It is straightforward to implement this approach in a graph coloring
  2354. register allocator. First, we know which variables are in-use during
  2355. every function call because we compute that information for every
  2356. instruciton (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2357. build the interference graph (Section~\ref{sec:build-interference}),
  2358. we can place an edge between each of these variables and the
  2359. caller-saved registers in the interference graph. This will prevent
  2360. the graph coloring algorithm from assigning those variables to
  2361. caller-saved registers.
  2362. Returning to the example in
  2363. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2364. generated x86 code on the right-hand side, focusing on the
  2365. \code{start} block. Notice that variable \code{x} is assigned to
  2366. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2367. place during the second call to \code{read\_int}. Next, notice that
  2368. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2369. because there are no function calls in the remainder of the block.
  2370. Next we analyze the example from the callee point of view, focusing on
  2371. the prelude and conclusion of the \code{main} function. As usual the
  2372. prelude begins with saving the \code{rbp} register to the stack and
  2373. setting the \code{rbp} to the current stack pointer. We now know why
  2374. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2375. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2376. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2377. variable (\code{x}). There are several more callee-saved register that
  2378. are not saved in the prelude because they were not assigned to
  2379. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2380. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2381. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2382. from the stack with a \code{popq} instruction.
  2383. \begin{figure}[tp]
  2384. \begin{minipage}{0.45\textwidth}
  2385. Example $R_1$ program:
  2386. %s0_14.rkt
  2387. \begin{lstlisting}
  2388. (let ([x (read)])
  2389. (let ([y (read)])
  2390. (+ (+ x y) 42)))
  2391. \end{lstlisting}
  2392. \end{minipage}
  2393. \begin{minipage}{0.45\textwidth}
  2394. Generated x86 assembly:
  2395. \begin{lstlisting}
  2396. start:
  2397. callq read_int
  2398. movq %rax, %rbx
  2399. callq read_int
  2400. movq %rax, %rcx
  2401. addq %rcx, %rbx
  2402. movq %rbx, %rax
  2403. addq $42, %rax
  2404. jmp _conclusion
  2405. .globl main
  2406. main:
  2407. pushq %rbp
  2408. movq %rsp, %rbp
  2409. pushq %rbx
  2410. subq $8, %rsp
  2411. jmp start
  2412. conclusion:
  2413. addq $8, %rsp
  2414. popq %rbx
  2415. popq %rbp
  2416. retq
  2417. \end{lstlisting}
  2418. \end{minipage}
  2419. \caption{An example with function calls.}
  2420. \label{fig:example-calling-conventions}
  2421. \end{figure}
  2422. \section{Liveness Analysis}
  2423. \label{sec:liveness-analysis-r1}
  2424. A variable is \emph{live} if the variable is used at some later point
  2425. in the program and there is not an intervening assignment to the
  2426. variable.
  2427. %
  2428. To understand the latter condition, consider the following code
  2429. fragment in which there are two writes to \code{b}. Are \code{a} and
  2430. \code{b} both live at the same time?
  2431. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2432. movq $5, a
  2433. movq $30, b
  2434. movq a, c
  2435. movq $10, b
  2436. addq b, c
  2437. \end{lstlisting}
  2438. The answer is no because the integer \code{30} written to \code{b} on
  2439. line 2 is never used. The variable \code{b} is read on line 5 and
  2440. there is an intervening write to \code{b} on line 4, so the read on
  2441. line 5 receives the value written on line 4, not line 2.
  2442. The live variables can be computed by traversing the instruction
  2443. sequence back to front (i.e., backwards in execution order). Let
  2444. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2445. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2446. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2447. variables before instruction $I_k$. The live variables after an
  2448. instruction are always the same as the live variables before the next
  2449. instruction.
  2450. \begin{equation} \label{eq:live-after-before-next}
  2451. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2452. \end{equation}
  2453. To start things off, there are no live variables after the last
  2454. instruction, so
  2455. \begin{equation}\label{eq:live-last-empty}
  2456. L_{\mathsf{after}}(n) = \emptyset
  2457. \end{equation}
  2458. We then apply the following rule repeatedly, traversing the
  2459. instruction sequence back to front.
  2460. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2461. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2462. \end{equation}
  2463. where $W(k)$ are the variables written to by instruction $I_k$ and
  2464. $R(k)$ are the variables read by instruction $I_k$.
  2465. Let us walk through the above example, applying these formulas
  2466. starting with the instruction on line 5. We collect the answers in the
  2467. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2468. instruction is $\emptyset$ because it is the last instruction
  2469. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2470. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2471. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2472. is
  2473. \[
  2474. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2475. \]
  2476. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2477. the live-before set from line 5 to be the live-after set for this
  2478. instruction (formula~\ref{eq:live-after-before-next}).
  2479. \[
  2480. L_{\mathsf{after}}(4) = \{ b, c \}
  2481. \]
  2482. This move instruction writes to $b$ and does not read from any
  2483. variables, so we have the following live-before set
  2484. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2485. \[
  2486. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2487. \]
  2488. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2489. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2490. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2491. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2492. variable that is not live and does not read from a variable.
  2493. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2494. because it writes to variable $a$.
  2495. \begin{center}
  2496. \begin{minipage}{0.45\textwidth}
  2497. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2498. movq $5, a
  2499. movq $30, b
  2500. movq a, c
  2501. movq $10, b
  2502. addq b, c
  2503. \end{lstlisting}
  2504. \end{minipage}
  2505. \vrule\hspace{10pt}
  2506. \begin{minipage}{0.45\textwidth}
  2507. \begin{align*}
  2508. L_{\mathsf{before}}(1)= \emptyset,
  2509. L_{\mathsf{after}}(1)= \{a\}\\
  2510. L_{\mathsf{before}}(2)= \{a\},
  2511. L_{\mathsf{after}}(2)= \{a\}\\
  2512. L_{\mathsf{before}}(3)= \{a\},
  2513. L_{\mathsf{after}}(2)= \{c\}\\
  2514. L_{\mathsf{before}}(4)= \{c\},
  2515. L_{\mathsf{after}}(4)= \{b,c\}\\
  2516. L_{\mathsf{before}}(5)= \{b,c\},
  2517. L_{\mathsf{after}}(5)= \emptyset
  2518. \end{align*}
  2519. \end{minipage}
  2520. \end{center}
  2521. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2522. for the running example program, with the live-before and live-after
  2523. sets shown between each instruction to make the figure easy to read.
  2524. \begin{figure}[tp]
  2525. \hspace{20pt}
  2526. \begin{minipage}{0.45\textwidth}
  2527. \begin{lstlisting}
  2528. |$\{\}$|
  2529. movq $1, v
  2530. |$\{v\}$|
  2531. movq $42, w
  2532. |$\{v,w\}$|
  2533. movq v, x
  2534. |$\{w,x\}$|
  2535. addq $7, x
  2536. |$\{w,x\}$|
  2537. movq x, y
  2538. |$\{w,x,y\}$|
  2539. movq x, z
  2540. |$\{w,y,z\}$|
  2541. addq w, z
  2542. |$\{y,z\}$|
  2543. movq y, t
  2544. |$\{t,z\}$|
  2545. negq t
  2546. |$\{t,z\}$|
  2547. movq z, %rax
  2548. |$\{t\}$|
  2549. addq t, %rax
  2550. |$\{\}$|
  2551. jmp conclusion
  2552. |$\{\}$|
  2553. \end{lstlisting}
  2554. \end{minipage}
  2555. \caption{The running example annotated with live-after sets.}
  2556. \label{fig:live-eg}
  2557. \end{figure}
  2558. \begin{exercise}\normalfont
  2559. Implement the compiler pass named \code{uncover-live} that computes
  2560. the live-after sets. We recommend storing the live-after sets (a list
  2561. of a set of variables) in the $\itm{info}$ field of the \key{Block}
  2562. structure. We recommend using the
  2563. \href{https://docs.racket-lang.org/reference/sets.html}{\code{racket/set}}
  2564. package for representing sets of variables.
  2565. %
  2566. We recommend organizing your code to use a helper function that takes
  2567. a list of instructions and an initial live-after set (typically empty)
  2568. and returns the list of live-after sets.
  2569. %
  2570. We recommend creating helper functions to 1) compute the set of
  2571. variables that appear in an argument (of an instruction), 2) compute
  2572. the variables read by an instruction which corresponds to the $R$
  2573. function discussed above, and 3) the variables written by an
  2574. instruction which corresponds to $W$.
  2575. \end{exercise}
  2576. \section{Building the Interference Graph}
  2577. \label{sec:build-interference}
  2578. Based on the liveness analysis, we know where each variable is needed.
  2579. However, during register allocation, we need to answer questions of
  2580. the specific form: are variables $u$ and $v$ live at the same time?
  2581. (And therefore cannot be assigned to the same register.) To make this
  2582. question easier to answer, we create an explicit data structure, an
  2583. \emph{interference graph}. An interference graph is an undirected
  2584. graph that has an edge between two variables if they are live at the
  2585. same time, that is, if they interfere with each other.
  2586. The most obvious way to compute the interference graph is to look at
  2587. the set of live variables between each statement in the program and
  2588. add an edge to the graph for every pair of variables in the same set.
  2589. This approach is less than ideal for two reasons. First, it can be
  2590. expensive because it takes $O(n^2)$ time to look at every pair in a
  2591. set of $n$ live variables. Second, there is a special case in which
  2592. two variables that are live at the same time do not actually interfere
  2593. with each other: when they both contain the same value because we have
  2594. assigned one to the other.
  2595. A better way to compute the interference graph is to focus on the
  2596. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2597. instruction to overwrite something in a live variable. So for each
  2598. instruction, we create an edge between the variable being written to
  2599. and all the \emph{other} live variables. (One should not create self
  2600. edges.) For a \key{callq} instruction, think of all caller-saved
  2601. registers as being written to, so an edge must be added between every
  2602. live variable and every caller-saved register. For \key{movq}, we deal
  2603. with the above-mentioned special case by not adding an edge between a
  2604. live variable $v$ and destination $d$ if $v$ matches the source of the
  2605. move. So we have the following three rules.
  2606. \begin{enumerate}
  2607. \item If instruction $I_k$ is an arithmetic instruction such as
  2608. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2609. L_{\mathsf{after}}(k)$ unless $v = d$.
  2610. \item If instruction $I_k$ is of the form \key{callq}
  2611. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2612. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2613. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2614. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2615. d$ or $v = s$.
  2616. \end{enumerate}
  2617. Working from the top to bottom of Figure~\ref{fig:live-eg}, apply the
  2618. above rules to each instruction. We highlight a few of the
  2619. instructions and then refer the reader to
  2620. Figure~\ref{fig:interference-results} all the interference results.
  2621. The first instruction is \lstinline{movq $1, v}, so rule 3 applies,
  2622. and the live-after set is $\{v\}$. We do not add any interference
  2623. edges because the one live variable $v$ is also the destination of
  2624. this instruction.
  2625. %
  2626. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2627. again, and the live-after set is $\{v,w\}$. So the target $w$ of
  2628. \key{movq} interferes with $v$.
  2629. %
  2630. Next we skip forward to the instruction \lstinline{movq x, y}.
  2631. \begin{figure}[tbp]
  2632. \begin{quote}
  2633. \begin{tabular}{ll}
  2634. \lstinline{movq $1, v}& no interference by rule 3,\\
  2635. \lstinline{movq $42, w}& $w$ interferes with $v$ by rule 3,\\
  2636. \lstinline{movq v, x}& $x$ interferes with $w$ by rule 3,\\
  2637. \lstinline{addq $7, x}& $x$ interferes with $w$ by rule 1,\\
  2638. \lstinline{movq x, y}& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2639. \lstinline{movq x, z}& $z$ interferes with $w$ and $y$ by rule 3,\\
  2640. \lstinline{addq w, z}& $z$ interferes with $y$ by rule 1, \\
  2641. \lstinline{movq y, t}& $t$ interferes with $z$ by rule 3, \\
  2642. \lstinline{negq t}& $t$ interferes with $z$ by rule 1, \\
  2643. \lstinline{movq z, %rax} & no interference (ignore rax), \\
  2644. \lstinline{addq t, %rax} & no interference (ignore rax). \\
  2645. \lstinline{jmp conclusion}& no interference.
  2646. \end{tabular}
  2647. \end{quote}
  2648. \caption{Interference results for the running example.}
  2649. \label{fig:interference-results}
  2650. \end{figure}
  2651. The resulting interference graph is shown in
  2652. Figure~\ref{fig:interfere}.
  2653. \begin{figure}[tbp]
  2654. \large
  2655. \[
  2656. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2657. \node (t1) at (0,2) {$t$};
  2658. \node (z) at (3,2) {$z$};
  2659. \node (x) at (6,2) {$x$};
  2660. \node (y) at (3,0) {$y$};
  2661. \node (w) at (6,0) {$w$};
  2662. \node (v) at (9,0) {$v$};
  2663. \draw (t1) to (z);
  2664. \draw (z) to (y);
  2665. \draw (z) to (w);
  2666. \draw (x) to (w);
  2667. \draw (y) to (w);
  2668. \draw (v) to (w);
  2669. \end{tikzpicture}
  2670. \]
  2671. \caption{The interference graph of the example program.}
  2672. \label{fig:interfere}
  2673. \end{figure}
  2674. %% Our next concern is to choose a data structure for representing the
  2675. %% interference graph. There are many choices for how to represent a
  2676. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2677. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2678. %% data structure is to study the algorithm that uses the data structure,
  2679. %% determine what operations need to be performed, and then choose the
  2680. %% data structure that provide the most efficient implementations of
  2681. %% those operations. Often times the choice of data structure can have an
  2682. %% effect on the time complexity of the algorithm, as it does here. If
  2683. %% you skim the next section, you will see that the register allocation
  2684. %% algorithm needs to ask the graph for all of its vertices and, given a
  2685. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2686. %% correct choice of graph representation is that of an adjacency
  2687. %% list. There are helper functions in \code{utilities.rkt} for
  2688. %% representing graphs using the adjacency list representation:
  2689. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2690. %% (Appendix~\ref{appendix:utilities}).
  2691. %% %
  2692. %% \margincomment{\footnotesize To do: change to use the
  2693. %% Racket graph library. \\ --Jeremy}
  2694. %% %
  2695. %% In particular, those functions use a hash table to map each vertex to
  2696. %% the set of adjacent vertices, and the sets are represented using
  2697. %% Racket's \key{set}, which is also a hash table.
  2698. \begin{exercise}\normalfont
  2699. Implement the compiler pass named \code{build-interference} according
  2700. to the algorithm suggested above. We recommend using the Racket
  2701. \code{graph} package to create and inspect the interference graph.
  2702. The output graph of this pass should be stored in the $\itm{info}$
  2703. field of the program, under the key \code{conflicts}.
  2704. \end{exercise}
  2705. \section{Graph Coloring via Sudoku}
  2706. \label{sec:graph-coloring}
  2707. We come to the main event, mapping variables to registers (or to stack
  2708. locations in the event that we run out of registers). We need to make
  2709. sure that two variables do not get mapped to the same register if the
  2710. two variables interfere with each other. Thinking about the
  2711. interference graph, this means that adjacent vertices must be mapped
  2712. to different registers. If we think of registers as colors, the
  2713. register allocation problem becomes the widely-studied graph coloring
  2714. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2715. The reader may be more familiar with the graph coloring problem than he
  2716. or she realizes; the popular game of Sudoku is an instance of the
  2717. graph coloring problem. The following describes how to build a graph
  2718. out of an initial Sudoku board.
  2719. \begin{itemize}
  2720. \item There is one vertex in the graph for each Sudoku square.
  2721. \item There is an edge between two vertices if the corresponding squares
  2722. are in the same row, in the same column, or if the squares are in
  2723. the same $3\times 3$ region.
  2724. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2725. \item Based on the initial assignment of numbers to squares in the
  2726. Sudoku board, assign the corresponding colors to the corresponding
  2727. vertices in the graph.
  2728. \end{itemize}
  2729. If you can color the remaining vertices in the graph with the nine
  2730. colors, then you have also solved the corresponding game of Sudoku.
  2731. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2732. the corresponding graph with colored vertices. We map the Sudoku
  2733. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2734. sampling of the vertices (the colored ones) because showing edges for
  2735. all of the vertices would make the graph unreadable.
  2736. \begin{figure}[tbp]
  2737. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2738. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2739. \caption{A Sudoku game board and the corresponding colored graph.}
  2740. \label{fig:sudoku-graph}
  2741. \end{figure}
  2742. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2743. strategies to come up with an algorithm for allocating registers. For
  2744. example, one of the basic techniques for Sudoku is called Pencil
  2745. Marks. The idea is to use a process of elimination to determine what
  2746. numbers no longer make sense for a square and write down those
  2747. numbers in the square (writing very small). For example, if the number
  2748. $1$ is assigned to a square, then by process of elimination, you can
  2749. write the pencil mark $1$ in all the squares in the same row, column,
  2750. and region. Many Sudoku computer games provide automatic support for
  2751. Pencil Marks.
  2752. %
  2753. The Pencil Marks technique corresponds to the notion of
  2754. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2755. vertex, in Sudoku terms, is the set of numbers that are no longer
  2756. available. In graph terminology, we have the following definition:
  2757. \begin{equation*}
  2758. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2759. \text{ and } \mathrm{color}(v) = c \}
  2760. \end{equation*}
  2761. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2762. edge with $u$.
  2763. Using the Pencil Marks technique leads to a simple strategy for
  2764. filling in numbers: if there is a square with only one possible number
  2765. left, then choose that number! But what if there are no squares with
  2766. only one possibility left? One brute-force approach is to try them
  2767. all: choose the first and if it ultimately leads to a solution,
  2768. great. If not, backtrack and choose the next possibility. One good
  2769. thing about Pencil Marks is that it reduces the degree of branching in
  2770. the search tree. Nevertheless, backtracking can be horribly time
  2771. consuming. One way to reduce the amount of backtracking is to use the
  2772. most-constrained-first heuristic. That is, when choosing a square,
  2773. always choose one with the fewest possibilities left (the vertex with
  2774. the highest saturation). The idea is that choosing highly constrained
  2775. squares earlier rather than later is better because later on there may
  2776. not be any possibilities left for those squares.
  2777. However, register allocation is easier than Sudoku because the
  2778. register allocator can map variables to stack locations when the
  2779. registers run out. Thus, it makes sense to drop backtracking in favor
  2780. of greedy search, that is, make the best choice at the time and keep
  2781. going. We still wish to minimize the number of colors needed, so
  2782. keeping the most-constrained-first heuristic is a good idea.
  2783. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2784. algorithm for register allocation based on saturation and the
  2785. most-constrained-first heuristic. It is roughly equivalent to the
  2786. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2787. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2788. Sudoku, the algorithm represents colors with integers. The first $k$
  2789. colors corresponding to the $k$ registers in a given machine and the
  2790. rest of the integers corresponding to stack locations.
  2791. \begin{figure}[btp]
  2792. \centering
  2793. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2794. Algorithm: DSATUR
  2795. Input: a graph |$G$|
  2796. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2797. |$W \gets \mathit{vertices}(G)$|
  2798. while |$W \neq \emptyset$| do
  2799. pick a vertex |$u$| from |$W$| with the highest saturation,
  2800. breaking ties randomly
  2801. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2802. |$\mathrm{color}[u] \gets c$|
  2803. |$W \gets W - \{u\}$|
  2804. \end{lstlisting}
  2805. \caption{The saturation-based greedy graph coloring algorithm.}
  2806. \label{fig:satur-algo}
  2807. \end{figure}
  2808. With this algorithm in hand, let us return to the running example and
  2809. consider how to color the interference graph in
  2810. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2811. colored and they are unsaturated, so we annotate each of them with a
  2812. dash for their color and an empty set for the saturation.
  2813. \[
  2814. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2815. \node (t1) at (0,2) {$t:-,\{\}$};
  2816. \node (z) at (3,2) {$z:-,\{\}$};
  2817. \node (x) at (6,2) {$x:-,\{\}$};
  2818. \node (y) at (3,0) {$y:-,\{\}$};
  2819. \node (w) at (6,0) {$w:-,\{\}$};
  2820. \node (v) at (9,0) {$v:-,\{\}$};
  2821. \draw (t1) to (z);
  2822. \draw (z) to (y);
  2823. \draw (z) to (w);
  2824. \draw (x) to (w);
  2825. \draw (y) to (w);
  2826. \draw (v) to (w);
  2827. \end{tikzpicture}
  2828. \]
  2829. The algorithm says to select a maximally saturated vertex and color it
  2830. $0$. In this case we have a 6-way tie, so we arbitrarily pick
  2831. $t$. We then mark color $0$ as no longer available for $z$ because
  2832. it interferes with $t$.
  2833. \[
  2834. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2835. \node (t1) at (0,2) {$t:0,\{\}$};
  2836. \node (z) at (3,2) {$z:-,\{0\}$};
  2837. \node (x) at (6,2) {$x:-,\{\}$};
  2838. \node (y) at (3,0) {$y:-,\{\}$};
  2839. \node (w) at (6,0) {$w:-,\{\}$};
  2840. \node (v) at (9,0) {$v:-,\{\}$};
  2841. \draw (t1) to (z);
  2842. \draw (z) to (y);
  2843. \draw (z) to (w);
  2844. \draw (x) to (w);
  2845. \draw (y) to (w);
  2846. \draw (v) to (w);
  2847. \end{tikzpicture}
  2848. \]
  2849. Next we repeat the process, selecting another maximally saturated
  2850. vertex, which is $z$, and color it with the first available number,
  2851. which is $1$.
  2852. \[
  2853. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2854. \node (t1) at (0,2) {$t:0,\{1\}$};
  2855. \node (z) at (3,2) {$z:1,\{0\}$};
  2856. \node (x) at (6,2) {$x:-,\{\}$};
  2857. \node (y) at (3,0) {$y:-,\{1\}$};
  2858. \node (w) at (6,0) {$w:-,\{1\}$};
  2859. \node (v) at (9,0) {$v:-,\{\}$};
  2860. \draw (t1) to (z);
  2861. \draw (z) to (y);
  2862. \draw (z) to (w);
  2863. \draw (x) to (w);
  2864. \draw (y) to (w);
  2865. \draw (v) to (w);
  2866. \end{tikzpicture}
  2867. \]
  2868. The most saturated vertices are now $w$ and $y$. We color $w$ with the
  2869. first available color, which is $0$.
  2870. \[
  2871. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2872. \node (t1) at (0,2) {$t:0,\{1\}$};
  2873. \node (z) at (3,2) {$z:1,\{0\}$};
  2874. \node (x) at (6,2) {$x:-,\{0\}$};
  2875. \node (y) at (3,0) {$y:-,\{0,1\}$};
  2876. \node (w) at (6,0) {$w:0,\{1\}$};
  2877. \node (v) at (9,0) {$v:-,\{0\}$};
  2878. \draw (t1) to (z);
  2879. \draw (z) to (y);
  2880. \draw (z) to (w);
  2881. \draw (x) to (w);
  2882. \draw (y) to (w);
  2883. \draw (v) to (w);
  2884. \end{tikzpicture}
  2885. \]
  2886. Vertex $y$ is now the most highly saturated, so we color $y$ with $2$.
  2887. We cannot choose $0$ or $1$ because those numbers are in $y$'s
  2888. saturation set. Indeed, $y$ interferes with $w$ and $z$, whose colors
  2889. are $0$ and $1$ respectively.
  2890. \[
  2891. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2892. \node (t1) at (0,2) {$t:0,\{1\}$};
  2893. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2894. \node (x) at (6,2) {$x:-,\{0\}$};
  2895. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2896. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2897. \node (v) at (9,0) {$v:-,\{0\}$};
  2898. \draw (t1) to (z);
  2899. \draw (z) to (y);
  2900. \draw (z) to (w);
  2901. \draw (x) to (w);
  2902. \draw (y) to (w);
  2903. \draw (v) to (w);
  2904. \end{tikzpicture}
  2905. \]
  2906. Now $x$ and $v$ are the most saturated, so we color $v$ it $1$.
  2907. \[
  2908. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2909. \node (t1) at (0,2) {$t:0,\{1\}$};
  2910. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2911. \node (x) at (6,2) {$x:-,\{0\}$};
  2912. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2913. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2914. \node (v) at (9,0) {$v:1,\{0\}$};
  2915. \draw (t1) to (z);
  2916. \draw (z) to (y);
  2917. \draw (z) to (w);
  2918. \draw (x) to (w);
  2919. \draw (y) to (w);
  2920. \draw (v) to (w);
  2921. \end{tikzpicture}
  2922. \]
  2923. In the last step of the algorithm, we color $x$ with $1$.
  2924. \[
  2925. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2926. \node (t1) at (0,2) {$t:0,\{1,\}$};
  2927. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2928. \node (x) at (6,2) {$x:1,\{0\}$};
  2929. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2930. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2931. \node (v) at (9,0) {$v:1,\{0\}$};
  2932. \draw (t1) to (z);
  2933. \draw (z) to (y);
  2934. \draw (z) to (w);
  2935. \draw (x) to (w);
  2936. \draw (y) to (w);
  2937. \draw (v) to (w);
  2938. \end{tikzpicture}
  2939. \]
  2940. With the coloring complete, we finalize the assignment of variables to
  2941. registers and stack locations. Recall that if we have $k$ registers,
  2942. we map the first $k$ colors to registers and the rest to stack
  2943. locations. Suppose for the moment that we have just one register to
  2944. use for register allocation, \key{rcx}. Then the following is the
  2945. mapping of colors to registers and stack allocations.
  2946. \[
  2947. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2948. \]
  2949. Putting this mapping together with the above coloring of the
  2950. variables, we arrive at the following assignment of variables to
  2951. registers and stack locations.
  2952. \begin{gather*}
  2953. \{ v \mapsto \key{\%rcx}, \,
  2954. w \mapsto \key{\%rcx}, \,
  2955. x \mapsto \key{-8(\%rbp)}, \\
  2956. y \mapsto \key{-16(\%rbp)}, \,
  2957. z\mapsto \key{-8(\%rbp)},
  2958. t\mapsto \key{\%rcx} \}
  2959. \end{gather*}
  2960. Applying this assignment to our running example, on the left, yields
  2961. the program on the right.
  2962. % why frame size of 32? -JGS
  2963. \begin{center}
  2964. \begin{minipage}{0.3\textwidth}
  2965. \begin{lstlisting}
  2966. movq $1, v
  2967. movq $42, w
  2968. movq v, x
  2969. addq $7, x
  2970. movq x, y
  2971. movq x, z
  2972. addq w, z
  2973. movq y, t
  2974. negq t
  2975. movq z, %rax
  2976. addq t, %rax
  2977. jmp conclusion
  2978. \end{lstlisting}
  2979. \end{minipage}
  2980. $\Rightarrow\qquad$
  2981. \begin{minipage}{0.45\textwidth}
  2982. \begin{lstlisting}
  2983. movq $1, %rcx
  2984. movq $42, %rcx
  2985. movq %rcx, -8(%rbp)
  2986. addq $7, -8(%rbp)
  2987. movq -8(%rbp), -16(%rbp)
  2988. movq -8(%rbp), -8(%rbp)
  2989. addq %rcx, -8(%rbp)
  2990. movq -16(%rbp), %rcx
  2991. negq %rcx
  2992. movq -8(%rbp), %rax
  2993. addq %rcx, %rax
  2994. jmp conclusion
  2995. \end{lstlisting}
  2996. \end{minipage}
  2997. \end{center}
  2998. The resulting program is almost an x86 program. The remaining step is
  2999. the patch instructions pass. In this example, the trivial move of
  3000. \code{-8(\%rbp)} to itself is deleted and the addition of
  3001. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3002. \code{rax} as follows.
  3003. \begin{lstlisting}
  3004. movq -8(%rbp), %rax
  3005. addq %rax, -16(%rbp)
  3006. \end{lstlisting}
  3007. An overview of all of the passes involved in register allocation is
  3008. shown in Figure~\ref{fig:reg-alloc-passes}.
  3009. \begin{figure}[tbp]
  3010. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3011. \node (R1) at (0,2) {\large $R_1$};
  3012. \node (R1-2) at (3,2) {\large $R_1$};
  3013. \node (R1-3) at (6,2) {\large $R_1$};
  3014. \node (C0-1) at (3,0) {\large $C_0$};
  3015. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3016. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3017. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3018. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3019. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3020. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3021. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3022. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3023. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3024. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3025. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3026. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3027. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3028. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3029. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3030. \end{tikzpicture}
  3031. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3032. \label{fig:reg-alloc-passes}
  3033. \end{figure}
  3034. \begin{exercise}\normalfont
  3035. Implement the pass \code{allocate-registers}, which should come
  3036. after the \code{build-interference} pass. The three new passes,
  3037. \code{uncover-live}, \code{build-interference}, and
  3038. \code{allocate-registers} replace the \code{assign-homes} pass of
  3039. Section~\ref{sec:assign-r1}.
  3040. We recommend that you create a helper function named
  3041. \code{color-graph} that takes an interference graph and a list of
  3042. all the variables in the program. This function should return a
  3043. mapping of variables to their colors (represented as natural
  3044. numbers). By creating this helper function, you will be able to
  3045. reuse it in Chapter~\ref{ch:functions} when you add support for
  3046. functions. The support code includes an implementation of the
  3047. priority queue data structure in the file
  3048. \code{priority\_queue.rkt}, which might come in handy for
  3049. prioritizing highly saturated nodes inside your \code{color-graph}
  3050. function.
  3051. Once you have obtained the coloring from \code{color-graph}, you can
  3052. assign the variables to registers or stack locations and then reuse
  3053. code from the \code{assign-homes} pass from
  3054. Section~\ref{sec:assign-r1} to replace the variables with their
  3055. assigned location.
  3056. Test your updated compiler by creating new example programs that
  3057. exercise all of the register allocation algorithm, such as forcing
  3058. variables to be spilled to the stack.
  3059. \end{exercise}
  3060. \section{Print x86 and Conventions for Registers}
  3061. \label{sec:print-x86-reg-alloc}
  3062. Recall that the \code{print-x86} pass generates the prelude and
  3063. conclusion instructions for the \code{main} function.
  3064. %
  3065. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3066. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3067. reason for this is that our \code{main} function must adhere to the
  3068. x86 calling conventions that we described in
  3069. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3070. allocator assigned variables to other callee-saved registers
  3071. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3072. saved to the stack in the prelude and restored in the conclusion. The
  3073. simplest approach is to save and restore all of the callee-saved
  3074. registers. The more efficient approach is to keep track of which
  3075. callee-saved registers were used and only save and restore
  3076. them. Either way, make sure to take this use of stack space into
  3077. account when you are calculating the size of the frame and adjusting
  3078. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3079. frame needs to be a multiple of 16 bytes!
  3080. \section{Challenge: Move Biasing}
  3081. \label{sec:move-biasing}
  3082. This section describes an optional enhancement to register allocation
  3083. for those students who are looking for an extra challenge or who have
  3084. a deeper interest in register allocation.
  3085. We return to the running example, but we remove the supposition that
  3086. we only have one register to use. So we have the following mapping of
  3087. color numbers to registers.
  3088. \[
  3089. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3090. \]
  3091. Using the same assignment of variables to color numbers that was
  3092. produced by the register allocator described in the last section, we
  3093. get the following program.
  3094. \begin{minipage}{0.3\textwidth}
  3095. \begin{lstlisting}
  3096. movq $1, v
  3097. movq $42, w
  3098. movq v, x
  3099. addq $7, x
  3100. movq x, y
  3101. movq x, z
  3102. addq w, z
  3103. movq y, t
  3104. negq t
  3105. movq z, %rax
  3106. addq t, %rax
  3107. jmp conclusion
  3108. \end{lstlisting}
  3109. \end{minipage}
  3110. $\Rightarrow\qquad$
  3111. \begin{minipage}{0.45\textwidth}
  3112. \begin{lstlisting}
  3113. movq $1, %rcx
  3114. movq $42, $rbx
  3115. movq %rcx, %rcx
  3116. addq $7, %rcx
  3117. movq %rcx, %rdx
  3118. movq %rcx, %rcx
  3119. addq %rbx, %rcx
  3120. movq %rdx, %rbx
  3121. negq %rbx
  3122. movq %rcx, %rax
  3123. addq %rbx, %rax
  3124. jmp conclusion
  3125. \end{lstlisting}
  3126. \end{minipage}
  3127. In the above output code there are two \key{movq} instructions that
  3128. can be removed because their source and target are the same. However,
  3129. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3130. register, we could instead remove three \key{movq} instructions. We
  3131. can accomplish this by taking into account which variables appear in
  3132. \key{movq} instructions with which other variables.
  3133. We say that two variables $p$ and $q$ are \emph{move related} if they
  3134. participate together in a \key{movq} instruction, that is, \key{movq}
  3135. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  3136. allocator chooses a color for a variable, it should prefer a color
  3137. that has already been used for a move-related variable (assuming that
  3138. they do not interfere). Of course, this preference should not override
  3139. the preference for registers over stack locations. This preference
  3140. should be used as a tie breaker when choosing between registers or
  3141. when choosing between stack locations.
  3142. We recommend representing the move relationships in a graph, similar
  3143. to how we represented interference. The following is the \emph{move
  3144. graph} for our running example.
  3145. \[
  3146. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3147. \node (t) at (0,2) {$t$};
  3148. \node (z) at (3,2) {$z$};
  3149. \node (x) at (6,2) {$x$};
  3150. \node (y) at (3,0) {$y$};
  3151. \node (w) at (6,0) {$w$};
  3152. \node (v) at (9,0) {$v$};
  3153. \draw (v) to (x);
  3154. \draw (x) to (y);
  3155. \draw (x) to (z);
  3156. \draw (y) to (t);
  3157. \end{tikzpicture}
  3158. \]
  3159. Now we replay the graph coloring, pausing to see the coloring of
  3160. $y$. Recall the following configuration. The most saturated vertices
  3161. were $w$ and $y$.
  3162. \[
  3163. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3164. \node (t1) at (0,2) {$t:0,\{1\}$};
  3165. \node (z) at (3,2) {$z:1,\{0\}$};
  3166. \node (x) at (6,2) {$x:-,\{\}$};
  3167. \node (y) at (3,0) {$y:-,\{1\}$};
  3168. \node (w) at (6,0) {$w:-,\{1\}$};
  3169. \node (v) at (9,0) {$v:-,\{\}$};
  3170. \draw (t1) to (z);
  3171. \draw (z) to (y);
  3172. \draw (z) to (w);
  3173. \draw (x) to (w);
  3174. \draw (y) to (w);
  3175. \draw (v) to (w);
  3176. \end{tikzpicture}
  3177. \]
  3178. %
  3179. Last time we chose to color $w$ with $0$. But this time we note that
  3180. $w$ is not move related to any vertex, and $y$ is move related to $t$.
  3181. So we choose to color $y$ the same color, $0$.
  3182. \[
  3183. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3184. \node (t1) at (0,2) {$t:0,\{1\}$};
  3185. \node (z) at (3,2) {$z:1,\{0\}$};
  3186. \node (x) at (6,2) {$x:-,\{\}$};
  3187. \node (y) at (3,0) {$y:0,\{1\}$};
  3188. \node (w) at (6,0) {$w:-,\{0,1\}$};
  3189. \node (v) at (9,0) {$v:-,\{\}$};
  3190. \draw (t1) to (z);
  3191. \draw (z) to (y);
  3192. \draw (z) to (w);
  3193. \draw (x) to (w);
  3194. \draw (y) to (w);
  3195. \draw (v) to (w);
  3196. \end{tikzpicture}
  3197. \]
  3198. Now $w$ is the most saturated, so we color it $2$.
  3199. \[
  3200. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3201. \node (t1) at (0,2) {$t:0,\{1\}$};
  3202. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3203. \node (x) at (6,2) {$x:-,\{2\}$};
  3204. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3205. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3206. \node (v) at (9,0) {$v:-,\{2\}$};
  3207. \draw (t1) to (z);
  3208. \draw (z) to (y);
  3209. \draw (z) to (w);
  3210. \draw (x) to (w);
  3211. \draw (y) to (w);
  3212. \draw (v) to (w);
  3213. \end{tikzpicture}
  3214. \]
  3215. At this point, vertices $x$ and $v$ are most saturated,
  3216. but $x$ is move related to $y$ and $z$, so we color $x$ to $0$
  3217. to match $y$. Finally, we color $v$ to $0$.
  3218. \[
  3219. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3220. \node (t) at (0,2) {$t:0,\{1\}$};
  3221. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3222. \node (x) at (6,2) {$x:0,\{2\}$};
  3223. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3224. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3225. \node (v) at (9,0) {$v:0,\{2\}$};
  3226. \draw (t) to (z);
  3227. \draw (z) to (y);
  3228. \draw (z) to (w);
  3229. \draw (x) to (w);
  3230. \draw (y) to (w);
  3231. \draw (v) to (w);
  3232. \end{tikzpicture}
  3233. \]
  3234. So we have the following assignment of variables to registers.
  3235. \begin{gather*}
  3236. \{ v \mapsto \key{\%rbx}, \,
  3237. w \mapsto \key{\%rdx}, \,
  3238. x \mapsto \key{\%rbx}, \\
  3239. y \mapsto \key{\%rbx}, \,
  3240. z\mapsto \key{\%rcx},
  3241. t\mapsto \key{\%rbx} \}
  3242. \end{gather*}
  3243. We apply this register assignment to the running example, on the left,
  3244. to obtain the code on right.
  3245. \begin{minipage}{0.3\textwidth}
  3246. \begin{lstlisting}
  3247. movq $1, v
  3248. movq $42, w
  3249. movq v, x
  3250. addq $7, x
  3251. movq x, y
  3252. movq x, z
  3253. addq w, z
  3254. movq y, t
  3255. negq t
  3256. movq z, %rax
  3257. addq t, %rax
  3258. jmp conclusion
  3259. \end{lstlisting}
  3260. \end{minipage}
  3261. $\Rightarrow\qquad$
  3262. \begin{minipage}{0.45\textwidth}
  3263. \begin{lstlisting}
  3264. movq $1, %rbx
  3265. movq $42, %rdx
  3266. movq %rbx, %rbx
  3267. addq $7, %rbx
  3268. movq %rbx, %rbx
  3269. movq %rbx, %rcx
  3270. addq %rdx, %rcx
  3271. movq %rbx, %rbx
  3272. negq %rbx
  3273. movq %rcx, %rax
  3274. addq %rbx, %rax
  3275. jmp conclusion
  3276. \end{lstlisting}
  3277. \end{minipage}
  3278. The \code{patch-instructions} then removes the three trivial moves
  3279. from \key{rbx} to \key{rbx} to obtain the following result.
  3280. \begin{minipage}{0.45\textwidth}
  3281. \begin{lstlisting}
  3282. movq $1, %rbx
  3283. movq $42, %rdx
  3284. addq $7, %rbx
  3285. movq %rbx, %rcx
  3286. addq %rdx, %rcx
  3287. negq %rbx
  3288. movq %rcx, %rax
  3289. addq %rbx, %rax
  3290. jmp conclusion
  3291. \end{lstlisting}
  3292. \end{minipage}
  3293. \begin{exercise}\normalfont
  3294. Change your implementation of \code{allocate-registers} to take move
  3295. biasing into account. Make sure that your compiler still passes all of
  3296. the previous tests. Create two new tests that include at least one
  3297. opportunity for move biasing and visually inspect the output x86
  3298. programs to make sure that your move biasing is working properly.
  3299. \end{exercise}
  3300. \margincomment{\footnotesize To do: another neat challenge would be to do
  3301. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3302. \section{Output of the Running Example}
  3303. \label{sec:reg-alloc-output}
  3304. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3305. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3306. and move biasing. To demonstrate both the use of registers and the
  3307. stack, we have limited the register allocator to use just two
  3308. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3309. \code{main} function, we push \code{rbx} onto the stack because it is
  3310. a callee-saved register and it was assigned to variable by the
  3311. register allocator. We substract \code{8} from the \code{rsp} at the
  3312. end of the prelude to reserve space for the one spilled variable.
  3313. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3314. Moving on the the \code{start} block, we see how the registers were
  3315. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3316. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3317. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3318. that the prelude saved the callee-save register \code{rbx} onto the
  3319. stack. The spilled variables must be placed lower on the stack than
  3320. the saved callee-save registers, so in this case \code{w} is placed at
  3321. \code{-16(\%rbp)}.
  3322. In the \code{conclusion}, we undo the work that was done in the
  3323. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3324. spilled variables), then we pop the old values of \code{rbx} and
  3325. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3326. return control to the operating system.
  3327. \begin{figure}[tbp]
  3328. % s0_28.rkt
  3329. % (use-minimal-set-of-registers! #t)
  3330. % and only rbx rcx
  3331. % tmp 0 rbx
  3332. % z 1 rcx
  3333. % y 0 rbx
  3334. % w 2 16(%rbp)
  3335. % v 0 rbx
  3336. % x 0 rbx
  3337. \begin{lstlisting}
  3338. start:
  3339. movq $1, %rbx
  3340. movq $42, -16(%rbp)
  3341. addq $7, %rbx
  3342. movq %rbx, %rcx
  3343. addq -16(%rbp), %rcx
  3344. negq %rbx
  3345. movq %rcx, %rax
  3346. addq %rbx, %rax
  3347. jmp conclusion
  3348. .globl main
  3349. main:
  3350. pushq %rbp
  3351. movq %rsp, %rbp
  3352. pushq %rbx
  3353. subq $8, %rsp
  3354. jmp start
  3355. conclusion:
  3356. addq $8, %rsp
  3357. popq %rbx
  3358. popq %rbp
  3359. retq
  3360. \end{lstlisting}
  3361. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3362. \label{fig:running-example-x86}
  3363. \end{figure}
  3364. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3365. \chapter{Booleans and Control Flow}
  3366. \label{ch:bool-types}
  3367. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3368. integers. In this chapter we add a second kind of value, the Booleans,
  3369. to create the $R_2$ language. The Boolean values \emph{true} and
  3370. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3371. Racket. The $R_2$ language includes several operations that involve
  3372. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3373. conditional \key{if} expression. With the addition of \key{if}
  3374. expressions, programs can have non-trivial control flow which which
  3375. significantly impacts the \code{explicate-control} and the liveness
  3376. analysis for register allocation. Also, because we now have two kinds
  3377. of values, we need to handle programs that apply an operation to the
  3378. wrong kind of value, such as \code{(not 1)}.
  3379. There are two language design options for such situations. One option
  3380. is to signal an error and the other is to provide a wider
  3381. interpretation of the operation. The Racket language uses a mixture of
  3382. these two options, depending on the operation and the kind of
  3383. value. For example, the result of \code{(not 1)} in Racket is
  3384. \code{\#f} because Racket treats non-zero integers as if they were
  3385. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3386. error in Racket stating that \code{car} expects a pair.
  3387. The Typed Racket language makes similar design choices as Racket,
  3388. except much of the error detection happens at compile time instead of
  3389. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3390. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3391. reports a compile-time error because Typed Racket expects the type of
  3392. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3393. For the $R_2$ language we choose to be more like Typed Racket in that
  3394. we shall perform type checking during compilation. In
  3395. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3396. is, how to compile a dynamically typed language like Racket. The
  3397. $R_2$ language is a subset of Typed Racket but by no means includes
  3398. all of Typed Racket. For many operations we take a narrower
  3399. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3400. This chapter is organized as follows. We begin by defining the syntax
  3401. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3402. then introduce the idea of type checking and build a type checker for
  3403. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3404. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3405. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3406. how our compiler passes need to change to accommodate Booleans and
  3407. conditional control flow.
  3408. \section{The $R_2$ Language}
  3409. \label{sec:r2-lang}
  3410. The concrete syntax of the $R_2$ language is defined in
  3411. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3412. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3413. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3414. and the conditional \code{if} expression. Also, we expand the
  3415. operators to include
  3416. \begin{enumerate}
  3417. \item subtraction on integers,
  3418. \item the logical operators \key{and}, \key{or} and \key{not},
  3419. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3420. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3421. comparing integers.
  3422. \end{enumerate}
  3423. \begin{figure}[tp]
  3424. \centering
  3425. \fbox{
  3426. \begin{minipage}{0.96\textwidth}
  3427. \[
  3428. \begin{array}{lcl}
  3429. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3430. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3431. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3432. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3433. &\mid& \itm{bool}
  3434. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3435. \mid (\key{not}\;\Exp) \\
  3436. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3437. R_2 &::=& \Exp
  3438. \end{array}
  3439. \]
  3440. \end{minipage}
  3441. }
  3442. \caption{The concrete syntax of $R_2$, extending $R_1$
  3443. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3444. \label{fig:r2-concrete-syntax}
  3445. \end{figure}
  3446. \begin{figure}[tp]
  3447. \centering
  3448. \fbox{
  3449. \begin{minipage}{0.96\textwidth}
  3450. \[
  3451. \begin{array}{lcl}
  3452. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3453. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3454. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3455. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3456. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3457. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3458. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3459. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3460. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3461. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3462. \end{array}
  3463. \]
  3464. \end{minipage}
  3465. }
  3466. \caption{The abstract syntax of $R_2$.}
  3467. \label{fig:r2-syntax}
  3468. \end{figure}
  3469. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3470. the parts that are the same as the interpreter for $R_1$
  3471. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3472. evaluate to the corresponding Boolean values. The conditional
  3473. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3474. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3475. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3476. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3477. you might expect, but note that the \code{and} operation is
  3478. short-circuiting. That is, given the expression
  3479. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3480. $e_1$ evaluates to \code{\#f}.
  3481. With the addition of the comparison operations, there are quite a few
  3482. primitive operations and the interpreter code for them could become
  3483. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3484. out the different parts of the code for primitive operations into the
  3485. \code{interp-op} function and the similar parts of the code into the
  3486. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3487. do not use \code{interp-op} for the \code{and} operation because of
  3488. the short-circuiting behavior in the order of evaluation of its
  3489. arguments.
  3490. \begin{figure}[tbp]
  3491. \begin{lstlisting}
  3492. (define (interp-op op)
  3493. (match op
  3494. ...
  3495. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3496. ['eq? (lambda (v1 v2)
  3497. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3498. (and (boolean? v1) (boolean? v2)))
  3499. (eq? v1 v2)]))]
  3500. ['< (lambda (v1 v2)
  3501. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3502. ['<= (lambda (v1 v2)
  3503. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3504. ['> (lambda (v1 v2)
  3505. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3506. ['>= (lambda (v1 v2)
  3507. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3508. [else (error 'interp-op "unknown operator")]))
  3509. (define (interp-exp env)
  3510. (lambda (e)
  3511. (define recur (interp-exp env))
  3512. (match e
  3513. ...
  3514. [(Bool b) b]
  3515. [(If cnd thn els)
  3516. (define b (recur cnd))
  3517. (match b
  3518. [#t (recur thn)]
  3519. [#f (recur els)])]
  3520. [(Prim 'and (list e1 e2))
  3521. (define v1 (recur e1))
  3522. (match v1
  3523. [#t (match (recur e2) [#t #t] [#f #f])]
  3524. [#f #f])]
  3525. [(Prim op args)
  3526. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3527. )))
  3528. (define (interp-R2 p)
  3529. (match p
  3530. [(Program info e)
  3531. ((interp-exp '()) e)]
  3532. ))
  3533. \end{lstlisting}
  3534. \caption{Interpreter for the $R_2$ language.}
  3535. \label{fig:interp-R2}
  3536. \end{figure}
  3537. \section{Type Checking $R_2$ Programs}
  3538. \label{sec:type-check-r2}
  3539. It is helpful to think about type checking in two complementary
  3540. ways. A type checker predicts the type of value that will be produced
  3541. by each expression in the program. For $R_2$, we have just two types,
  3542. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3543. \begin{lstlisting}
  3544. (+ 10 (- (+ 12 20)))
  3545. \end{lstlisting}
  3546. produces an \key{Integer} while
  3547. \begin{lstlisting}
  3548. (and (not #f) #t)
  3549. \end{lstlisting}
  3550. produces a \key{Boolean}.
  3551. Another way to think about type checking is that it enforces a set of
  3552. rules about which operators can be applied to which kinds of
  3553. values. For example, our type checker for $R_2$ will signal an error
  3554. for the below expression because, as we have seen above, the
  3555. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3556. checker enforces the rule that the argument of \code{not} must be a
  3557. \key{Boolean}.
  3558. \begin{lstlisting}
  3559. (not (+ 10 (- (+ 12 20))))
  3560. \end{lstlisting}
  3561. The type checker for $R_2$ is a structurally recursive function over
  3562. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3563. the \code{type-check-exp} function. Given an input expression
  3564. \code{e}, the type checker either returns a type (\key{Integer} or
  3565. \key{Boolean}) or it signals an error. The type of an integer literal
  3566. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3567. To handle variables, the type checker uses an environment that maps
  3568. variables to types. Consider the clause for \key{let}. We type check
  3569. the initializing expression to obtain its type \key{T} and then
  3570. associate type \code{T} with the variable \code{x} in the
  3571. environment. When the type checker encounters a use of variable
  3572. \code{x} in the body of the \key{let}, it can find its type in the
  3573. environment.
  3574. \begin{figure}[tbp]
  3575. \begin{lstlisting}
  3576. (define (type-check-exp env)
  3577. (lambda (e)
  3578. (match e
  3579. [(Var x) (dict-ref env x)]
  3580. [(Int n) 'Integer]
  3581. [(Bool b) 'Boolean]
  3582. [(Let x e body)
  3583. (define Te ((type-check-exp env) e))
  3584. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3585. Tb]
  3586. ...
  3587. [else
  3588. (error "type-check-exp couldn't match" e)])))
  3589. (define (type-check env)
  3590. (lambda (e)
  3591. (match e
  3592. [(Program info body)
  3593. (define Tb ((type-check-exp '()) body))
  3594. (unless (equal? Tb 'Integer)
  3595. (error "result of the program must be an integer, not " Tb))
  3596. (Program info body)]
  3597. )))
  3598. \end{lstlisting}
  3599. \caption{Skeleton of a type checker for the $R_2$ language.}
  3600. \label{fig:type-check-R2}
  3601. \end{figure}
  3602. \begin{exercise}\normalfont
  3603. Complete the implementation of \code{type-check-R2} and test it on 10
  3604. new example programs in $R_2$ that you choose based on how thoroughly
  3605. they test the type checking function. Half of the example programs
  3606. should have a type error to make sure that your type checker properly
  3607. rejects them. The other half of the example programs should not have
  3608. type errors. Your testing should check that the result of the type
  3609. checker agrees with the value returned by the interpreter, that is, if
  3610. the type checker returns \key{Integer}, then the interpreter should
  3611. return an integer. Likewise, if the type checker returns
  3612. \key{Boolean}, then the interpreter should return \code{\#t} or
  3613. \code{\#f}. Note that if your type checker does not signal an error
  3614. for a program, then interpreting that program should not encounter an
  3615. error. If it does, there is something wrong with your type checker.
  3616. \end{exercise}
  3617. \section{Shrink the $R_2$ Language}
  3618. \label{sec:shrink-r2}
  3619. The $R_2$ language includes several operators that are easily
  3620. expressible in terms of other operators. For example, subtraction is
  3621. expressible in terms of addition and negation.
  3622. \[
  3623. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3624. \]
  3625. Several of the comparison operations are expressible in terms of
  3626. less-than and logical negation.
  3627. \[
  3628. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3629. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3630. \]
  3631. The \key{let} is needed in the above translation to ensure that
  3632. expression $e_1$ is evaluated before $e_2$.
  3633. By performing these translations near the front-end of the compiler,
  3634. the later passes of the compiler do not need to deal with these
  3635. constructs, making those passes shorter. On the other hand, sometimes
  3636. these translations make it more difficult to generate the most
  3637. efficient code with respect to the number of instructions. However,
  3638. these differences typically do not affect the number of accesses to
  3639. memory, which is the primary factor that determines execution time on
  3640. modern computer architectures.
  3641. \begin{exercise}\normalfont
  3642. Implement the pass \code{shrink} that removes subtraction,
  3643. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3644. by translating them to other constructs in $R_2$. Create tests to
  3645. make sure that the behavior of all of these constructs stays the
  3646. same after translation.
  3647. \end{exercise}
  3648. \section{The x86$_1$ Language}
  3649. \label{sec:x86-1}
  3650. To implement the new logical operations, the comparison operations,
  3651. and the \key{if} expression, we need to delve further into the x86
  3652. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3653. larger subset of x86 that includes instructions for logical
  3654. operations, comparisons, and conditional jumps.
  3655. One small challenge is that x86 does not provide an instruction that
  3656. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3657. However, the \code{xorq} instruction can be used to encode \code{not}.
  3658. The \key{xorq} instruction takes two arguments, performs a pairwise
  3659. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3660. and writes the results into its second argument. Recall the truth
  3661. table for exclusive-or:
  3662. \begin{center}
  3663. \begin{tabular}{l|cc}
  3664. & 0 & 1 \\ \hline
  3665. 0 & 0 & 1 \\
  3666. 1 & 1 & 0
  3667. \end{tabular}
  3668. \end{center}
  3669. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3670. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3671. for the bit $1$, the result is the opposite of the second bit. Thus,
  3672. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3673. the first argument:
  3674. \[
  3675. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3676. \qquad\Rightarrow\qquad
  3677. \begin{array}{l}
  3678. \key{movq}~ \Arg\key{,} \Var\\
  3679. \key{xorq}~ \key{\$1,} \Var
  3680. \end{array}
  3681. \]
  3682. \begin{figure}[tp]
  3683. \fbox{
  3684. \begin{minipage}{0.96\textwidth}
  3685. \small
  3686. \[
  3687. \begin{array}{lcl}
  3688. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3689. \mid \BYTEREG{\code{'}\Reg} \\
  3690. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3691. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3692. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3693. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3694. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3695. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3696. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3697. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3698. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3699. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3700. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3701. &\mid& \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3702. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3703. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3704. \end{array}
  3705. \]
  3706. \end{minipage}
  3707. }
  3708. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3709. \label{fig:x86-1}
  3710. \end{figure}
  3711. Next we consider the x86 instructions that are relevant for compiling
  3712. the comparison operations. The \key{cmpq} instruction compares its two
  3713. arguments to determine whether one argument is less than, equal, or
  3714. greater than the other argument. The \key{cmpq} instruction is unusual
  3715. regarding the order of its arguments and where the result is
  3716. placed. The argument order is backwards: if you want to test whether
  3717. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3718. \key{cmpq} is placed in the special EFLAGS register. This register
  3719. cannot be accessed directly but it can be queried by a number of
  3720. instructions, including the \key{set} instruction. The \key{set}
  3721. instruction puts a \key{1} or \key{0} into its destination depending
  3722. on whether the comparison came out according to the condition code
  3723. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3724. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3725. The \key{set} instruction has an annoying quirk in that its
  3726. destination argument must be single byte register, such as \code{al},
  3727. which is part of the \code{rax} register. Thankfully, the
  3728. \key{movzbq} instruction can then be used to move from a single byte
  3729. register to a normal 64-bit register.
  3730. The x86 instruction for conditional jump are relevant to the
  3731. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3732. updates the program counter to point to the instruction after the
  3733. indicated label depending on whether the result in the EFLAGS register
  3734. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3735. instruction falls through to the next instruction. The abstract
  3736. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3737. that it separates the instruction name from the condition code. For
  3738. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3739. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3740. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3741. instruction to set the EFLAGS register.
  3742. \section{The $C_1$ Intermediate Language}
  3743. \label{sec:c1}
  3744. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3745. we need to grow that intermediate language to handle the new features
  3746. in $R_2$: Booleans and conditional expressions.
  3747. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3748. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3749. particular, we add logical and comparison operators to the $\Exp$
  3750. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3751. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3752. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3753. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3754. sequence of statements may now end with a \code{goto} or a conditional
  3755. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3756. depending on the outcome of the comparison. In
  3757. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3758. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3759. and \key{goto}'s.
  3760. \begin{figure}[tbp]
  3761. \fbox{
  3762. \begin{minipage}{0.96\textwidth}
  3763. \small
  3764. \[
  3765. \begin{array}{lcl}
  3766. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3767. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3768. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3769. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3770. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3771. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3772. \mid \key{goto}~\itm{label}\key{;}\\
  3773. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3774. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)^{+} }
  3775. \end{array}
  3776. \]
  3777. \end{minipage}
  3778. }
  3779. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3780. \label{fig:c1-concrete-syntax}
  3781. \end{figure}
  3782. \begin{figure}[tp]
  3783. \fbox{
  3784. \begin{minipage}{0.96\textwidth}
  3785. \small
  3786. \[
  3787. \begin{array}{lcl}
  3788. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3789. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3790. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3791. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3792. &\mid& \UNIOP{\key{'not}}{\Atm}
  3793. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3794. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3795. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3796. \mid \GOTO{\itm{label}} \\
  3797. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3798. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3799. \end{array}
  3800. \]
  3801. \end{minipage}
  3802. }
  3803. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  3804. (Figure~\ref{fig:c0-syntax}).}
  3805. \label{fig:c1-syntax}
  3806. \end{figure}
  3807. \section{Explicate Control}
  3808. \label{sec:explicate-control-r2}
  3809. Recall that the purpose of \code{explicate-control} is to make the
  3810. order of evaluation explicit in the syntax of the program. With the
  3811. addition of \key{if} in $R_2$ this get more interesting.
  3812. As a motivating example, consider the following program that has an
  3813. \key{if} expression nested in the predicate of another \key{if}.
  3814. % s1_41.rkt
  3815. \begin{center}
  3816. \begin{minipage}{0.96\textwidth}
  3817. \begin{lstlisting}
  3818. (let ([x (read)])
  3819. (let ([y (read)])
  3820. (if (if (< x 1) (eq? x 0) (eq? x 2))
  3821. (+ y 2)
  3822. (+ y 10))))
  3823. \end{lstlisting}
  3824. \end{minipage}
  3825. \end{center}
  3826. %
  3827. The naive way to compile \key{if} and the comparison would be to
  3828. handle each of them in isolation, regardless of their context. Each
  3829. comparison would be translated into a \key{cmpq} instruction followed
  3830. by a couple instructions to move the result from the EFLAGS register
  3831. into a general purpose register or stack location. Each \key{if} would
  3832. be translated into the combination of a \key{cmpq} and a conditional
  3833. jump. The generated code for the inner \key{if} in the above example
  3834. would be as follows.
  3835. \begin{center}
  3836. \begin{minipage}{0.96\textwidth}
  3837. \begin{lstlisting}
  3838. ...
  3839. cmpq $1, x ;; (< x 1)
  3840. setl %al
  3841. movzbq %al, tmp
  3842. cmpq $1, tmp ;; (if (< x 1) ...)
  3843. je then_branch_1
  3844. jmp else_branch_1
  3845. ...
  3846. \end{lstlisting}
  3847. \end{minipage}
  3848. \end{center}
  3849. However, if we take context into account we can do better and reduce
  3850. the use of \key{cmpq} and EFLAG-accessing instructions.
  3851. One idea is to try and reorganize the code at the level of $R_2$,
  3852. pushing the outer \key{if} inside the inner one. This would yield the
  3853. following code.
  3854. \begin{center}
  3855. \begin{minipage}{0.96\textwidth}
  3856. \begin{lstlisting}
  3857. (let ([x (read)])
  3858. (let ([y (read)])
  3859. (if (< x 1)
  3860. (if (eq? x 0)
  3861. (+ y 2)
  3862. (+ y 10))
  3863. (if (eq? x 2)
  3864. (+ y 2)
  3865. (+ y 10)))))
  3866. \end{lstlisting}
  3867. \end{minipage}
  3868. \end{center}
  3869. Unfortunately, this approach duplicates the two branches, and a
  3870. compiler must never duplicate code!
  3871. We need a way to perform the above transformation, but without
  3872. duplicating code. The solution is straightforward if we think at the
  3873. level of x86 assembly: we can label the code for each of the branches
  3874. and insert jumps in all the places that need to execute the
  3875. branches. Put another way, we need to move away from abstract syntax
  3876. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3877. use a standard program representation called a \emph{control flow
  3878. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3879. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3880. each edge represents a jump to another block. The \key{Program}
  3881. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3882. as an alist mapping labels to basic blocks. Each basic block is
  3883. represented by the $\Tail$ non-terminal.
  3884. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3885. \code{remove-complex-opera*} pass and then the
  3886. \code{explicate-control} pass on the example program. We walk through
  3887. the output program and then discuss the algorithm.
  3888. %
  3889. Following the order of evaluation in the output of
  3890. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  3891. and then the less-than-comparison to \code{1} in the predicate of the
  3892. inner \key{if}. In the output of \code{explicate-control}, in the
  3893. block labeled \code{start}, this becomes two assignment statements
  3894. followed by a conditional \key{goto} to label \code{block96} or
  3895. \code{block97}. The blocks associated with those labels contain the
  3896. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  3897. respectively. Regarding the block labeled with \code{block96}, we
  3898. start with the comparison to \code{0} and then have a conditional
  3899. goto, either to label \code{block92} or label \code{block93}, which
  3900. indirectly take us to labels \code{block90} and \code{block91}, the
  3901. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  3902. y 10)}. The story for the block labeled \code{block97} is similar.
  3903. \begin{figure}[tbp]
  3904. \begin{tabular}{lll}
  3905. \begin{minipage}{0.4\textwidth}
  3906. % s1_41.rkt
  3907. \begin{lstlisting}
  3908. (let ([x (read)])
  3909. (let ([y (read)])
  3910. (if (if (< x 1)
  3911. (eq? x 0)
  3912. (eq? x 2))
  3913. (+ y 2)
  3914. (+ y 10))))
  3915. \end{lstlisting}
  3916. \hspace{40pt}$\Downarrow$
  3917. \begin{lstlisting}
  3918. (let ([x (read)])
  3919. (let ([y (read)])
  3920. (if (if (< x 1)
  3921. (eq? x 0)
  3922. (eq? x 2))
  3923. (+ y 2)
  3924. (+ y 10))))
  3925. \end{lstlisting}
  3926. \end{minipage}
  3927. &
  3928. $\Rightarrow$
  3929. &
  3930. \begin{minipage}{0.55\textwidth}
  3931. \begin{lstlisting}
  3932. start:
  3933. x = (read);
  3934. y = (read);
  3935. if (< x 1)
  3936. goto block96;
  3937. else
  3938. goto block97;
  3939. block96:
  3940. if (eq? x 0)
  3941. goto block92;
  3942. else
  3943. goto block93;
  3944. block97:
  3945. if (eq? x 2)
  3946. goto block94;
  3947. else
  3948. goto block95;
  3949. block92:
  3950. goto block90;
  3951. block93:
  3952. goto block91;
  3953. block94:
  3954. goto block90;
  3955. block95:
  3956. goto block91;
  3957. block90:
  3958. return (+ y 2);
  3959. block91:
  3960. return (+ y 10);
  3961. \end{lstlisting}
  3962. \end{minipage}
  3963. \end{tabular}
  3964. \caption{Example translation from $R_2$ to $C_1$
  3965. via the \code{explicate-control}.}
  3966. \label{fig:explicate-control-s1-38}
  3967. \end{figure}
  3968. The nice thing about the output of \code{explicate-control} is that
  3969. there are no unnecessary comparisons and every comparison is part of a
  3970. conditional jump. The down-side of this output is that it includes
  3971. trivial blocks, such as the blocks labeled \code{block92} through
  3972. \code{block95}, that only jump to another block. We discuss a solution
  3973. to this problem in Section~\ref{sec:opt-jumps}.
  3974. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3975. \code{explicate-control} for $R_1$ using two mutually recursive
  3976. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3977. former function translates expressions in tail position whereas the
  3978. later function translates expressions on the right-hand-side of a
  3979. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3980. new kind of context to deal with: the predicate position of the
  3981. \key{if}. We need another function, \code{explicate-pred}, that takes
  3982. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  3983. the then-branch and else-branch. The output of \code{explicate-pred}
  3984. is a block and a list of formerly \key{let}-bound variables.
  3985. Note that the three explicate functions need to construct a
  3986. control-flow graph, which we recommend they do via updates to a global
  3987. variable.
  3988. In the following paragraphs we consider the specific additions to the
  3989. \code{explicate-tail} and \code{explicate-assign} functions, and some
  3990. of cases for the \code{explicate-pred} function.
  3991. The \code{explicate-tail} function needs an additional case for
  3992. \key{if}. The branches of the \key{if} inherit the current context, so
  3993. they are in tail position. Let $B_1$ be the result of
  3994. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  3995. is a $\Tail$ AST node. Let $B_2$ be the result of apply
  3996. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  3997. the $\Tail$ that results fromapplying \code{explicate-pred} to the
  3998. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  3999. \key{if} as a whole translates to block $B_3$.
  4000. \[
  4001. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4002. \]
  4003. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4004. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4005. should not be confused with the labels for the blocks that appear in
  4006. the generated code. We initially construct unlabeled blocks; we only
  4007. attach labels to blocks when we add them to the control-flow graph, as
  4008. we shall see in the next case.
  4009. Next consider the case for \key{if} in the \code{explicate-assign}
  4010. function. The context of the \key{if} is an assignment to some
  4011. variable $x$ and then the control continues to some block $B_1$. The
  4012. code that we generate for both the ``then'' and ``else'' branches
  4013. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4014. add it to the control flow graph with a fresh label $\ell_1$. The
  4015. branches of the \key{if} inherit the current context, so that are in
  4016. assignment positions. Let $B_2$ be the result of applying
  4017. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4018. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4019. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4020. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4021. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4022. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4023. $B_4$.
  4024. \[
  4025. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4026. \]
  4027. The function \code{explicate-pred} will need a case for every
  4028. expression that can have type \code{Boolean}. We detail a few cases
  4029. here and leave the rest for the reader. The input to this function is
  4030. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4031. the enclosing \key{if}. Suppose the expression is the Boolean
  4032. \code{\#t}. Then we can perform a kind of partial evaluation and
  4033. translate it to the ``then'' branch $B_1$. Likewise, we translate
  4034. \code{\#f} to the ``else`` branch $B_2$.
  4035. \[
  4036. \key{\#t} \quad\Rightarrow\quad B_1,
  4037. \qquad\qquad\qquad
  4038. \key{\#f} \quad\Rightarrow\quad B_2
  4039. \]
  4040. Next, suppose the expression is a less-than comparison. We translate
  4041. it to a conditional \code{goto}. We need labels for the two branches
  4042. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4043. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4044. less-than comparison is as follows.
  4045. \[
  4046. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4047. \begin{array}{l}
  4048. \key{if}~(\key{<}~e_1~e_2) \\
  4049. \qquad\key{goto}~\ell_1\key{;}\\
  4050. \key{else}\\
  4051. \qquad\key{goto}~\ell_2\key{;}
  4052. \end{array}
  4053. \]
  4054. The case for \key{if} in \code{explicate-pred} is particularly
  4055. illuminating as it deals with the challenges that we discussed above
  4056. regarding the example of the nested \key{if} expressions. Again, we
  4057. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4058. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4059. branches of the current \key{if} inherit their context from the
  4060. current one, that is, predicate context. So we apply
  4061. \code{explicate-pred} to the ``then'' branch with the two blocks
  4062. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4063. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4064. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4065. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4066. \[
  4067. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4068. \quad\Rightarrow\quad
  4069. B_5
  4070. \]
  4071. \begin{exercise}\normalfont
  4072. Implement the pass \code{explicate-control} by adding the cases for
  4073. \key{if} to the functions for tail and assignment contexts, and
  4074. implement \code{explicate-pred} for predicate contexts. Create test
  4075. cases that exercise all of the new cases in the code for this pass.
  4076. \end{exercise}
  4077. \section{Select Instructions}
  4078. \label{sec:select-r2}
  4079. Recall that the \code{select-instructions} pass lowers from our
  4080. $C$-like intermediate representation to the pseudo-x86 language, which
  4081. is suitable for conducting register allocation. The pass is
  4082. implemented using three auxiliary functions, one for each of the
  4083. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4084. For $\Atm$, we have new cases for the Booleans. We take the usual
  4085. approach of encoding them as integers, with true as 1 and false as 0.
  4086. \[
  4087. \key{\#t} \Rightarrow \key{1}
  4088. \qquad
  4089. \key{\#f} \Rightarrow \key{0}
  4090. \]
  4091. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4092. be implemented in terms of \code{xorq} as we discussed at the
  4093. beginning of this section. Given an assignment
  4094. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4095. if the left-hand side $\itm{var}$ is
  4096. the same as $\Atm$, then just the \code{xorq} suffices.
  4097. \[
  4098. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4099. \quad\Rightarrow\quad
  4100. \key{xorq}~\key{\$}1\key{,}~\Var
  4101. \]
  4102. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4103. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4104. x86. Then we have
  4105. \[
  4106. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4107. \quad\Rightarrow\quad
  4108. \begin{array}{l}
  4109. \key{movq}~\Arg\key{,}~\Var\\
  4110. \key{xorq}~\key{\$}1\key{,}~\Var
  4111. \end{array}
  4112. \]
  4113. Next consider the cases for \code{eq?} and less-than comparison.
  4114. Translating these operations to x86 is slightly involved due to the
  4115. unusual nature of the \key{cmpq} instruction discussed above. We
  4116. recommend translating an assignment from \code{eq?} into the following
  4117. sequence of three instructions. \\
  4118. \begin{tabular}{lll}
  4119. \begin{minipage}{0.4\textwidth}
  4120. \begin{lstlisting}
  4121. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4122. \end{lstlisting}
  4123. \end{minipage}
  4124. &
  4125. $\Rightarrow$
  4126. &
  4127. \begin{minipage}{0.4\textwidth}
  4128. \begin{lstlisting}
  4129. cmpq |$\Arg_2$|, |$\Arg_1$|
  4130. sete %al
  4131. movzbq %al, |$\Var$|
  4132. \end{lstlisting}
  4133. \end{minipage}
  4134. \end{tabular} \\
  4135. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4136. and conditional \key{goto}. Both are straightforward to handle. A
  4137. \key{goto} becomes a jump instruction.
  4138. \[
  4139. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4140. \]
  4141. A conditional \key{goto} becomes a compare instruction followed
  4142. by a conditional jump (for ``then'') and the fall-through is
  4143. to a regular jump (for ``else'').\\
  4144. \begin{tabular}{lll}
  4145. \begin{minipage}{0.4\textwidth}
  4146. \begin{lstlisting}
  4147. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4148. goto |$\ell_1$|;
  4149. else
  4150. goto |$\ell_2$|;
  4151. \end{lstlisting}
  4152. \end{minipage}
  4153. &
  4154. $\Rightarrow$
  4155. &
  4156. \begin{minipage}{0.4\textwidth}
  4157. \begin{lstlisting}
  4158. cmpq |$\Arg_2$|, |$\Arg_1$|
  4159. je |$\ell_1$|
  4160. jmp |$\ell_2$|
  4161. \end{lstlisting}
  4162. \end{minipage}
  4163. \end{tabular} \\
  4164. \begin{exercise}\normalfont
  4165. Expand your \code{select-instructions} pass to handle the new features
  4166. of the $R_2$ language. Test the pass on all the examples you have
  4167. created and make sure that you have some test programs that use the
  4168. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4169. the output using the \code{interp-x86} interpreter
  4170. (Appendix~\ref{appendix:interp}).
  4171. \end{exercise}
  4172. \section{Register Allocation}
  4173. \label{sec:register-allocation-r2}
  4174. The changes required for $R_2$ affect liveness analysis, building the
  4175. interference graph, and assigning homes, but the graph coloring
  4176. algorithm itself does not change.
  4177. \subsection{Liveness Analysis}
  4178. \label{sec:liveness-analysis-r2}
  4179. Recall that for $R_1$ we implemented liveness analysis for a single
  4180. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4181. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4182. produces many basic blocks arranged in a control-flow graph. The first
  4183. question we need to consider is: what order should we process the
  4184. basic blocks? Recall that to perform liveness analysis, we need to
  4185. know the live-after set. If a basic block has no successor blocks
  4186. (i.e. no out-edges in the control flow graph), then it has an empty
  4187. live-after set and we can immediately apply liveness analysis to
  4188. it. If a basic block has some successors, then we need to complete
  4189. liveness analysis on those blocks first. Furthermore, we know that
  4190. the control flow graph does not contain any cycles because $R_2$ does
  4191. not include loops
  4192. %
  4193. \footnote{If we were to add loops to the language, then the CFG could
  4194. contain cycles and we would instead need to use the classic worklist
  4195. algorithm for computing the fixed point of the liveness
  4196. analysis~\citep{Aho:1986qf}.}.
  4197. %
  4198. Returning to the question of what order should we process the basic
  4199. blocks, the answer is reverse topological order. We recommend using
  4200. the \code{tsort} (topological sort) and \code{transpose} functions of
  4201. the Racket \code{graph} package to obtain this ordering.
  4202. The next question is how to compute the live-after set of a block
  4203. given the live-before sets of all its successor blocks. (There can be
  4204. more than one because of conditional jumps.) During compilation we do
  4205. not know which way a conditional jump will go, so we do not know which
  4206. of the successor's live-before set to use. The solution to this
  4207. challenge is based on the observation that there is no harm to the
  4208. correctness of the compiler if we classify more variables as live than
  4209. the ones that are truly live during a particular execution of the
  4210. block. Thus, we can take the union of the live-before sets from all
  4211. the successors to be the live-after set for the block. Once we have
  4212. computed the live-after set, we can proceed to perform liveness
  4213. analysis on the block just as we did in
  4214. Section~\ref{sec:liveness-analysis-r1}.
  4215. The helper functions for computing the variables in an instruction's
  4216. argument and for computing the variables read-from ($R$) or written-to
  4217. ($W$) by an instruction need to be updated to handle the new kinds of
  4218. arguments and instructions in x86$_1$.
  4219. \subsection{Build Interference}
  4220. \label{sec:build-interference-r2}
  4221. Many of the new instructions in x86$_1$ can be handled in the same way
  4222. as the instructions in x86$_0$. Thus, if your code was already quite
  4223. general, it will not need to be changed to handle the new
  4224. instructions. If you code is not general enough, I recommend that you
  4225. change your code to be more general. For example, you can factor out
  4226. the computing of the the read and write sets for each kind of
  4227. instruction into two auxiliary functions.
  4228. Note that the \key{movzbq} instruction requires some special care,
  4229. just like the \key{movq} instruction. See rule number 3 in
  4230. Section~\ref{sec:build-interference}.
  4231. %% \subsection{Assign Homes}
  4232. %% \label{sec:assign-homes-r2}
  4233. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4234. %% to be updated to handle the \key{if} statement, simply by recursively
  4235. %% processing the child nodes. Hopefully your code already handles the
  4236. %% other new instructions, but if not, you can generalize your code.
  4237. \begin{exercise}\normalfont
  4238. Update the \code{register-allocation} pass so that it works for $R_2$
  4239. and test your compiler using your previously created programs on the
  4240. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4241. \end{exercise}
  4242. \section{Patch Instructions}
  4243. The second argument of the \key{cmpq} instruction must not be an
  4244. immediate value (such as an integer). So if you are comparing two
  4245. immediates, we recommend inserting a \key{movq} instruction to put the
  4246. second argument in \key{rax}.
  4247. %
  4248. The second argument of the \key{movzbq} must be a register.
  4249. %
  4250. There are no special restrictions on the x86 instructions \key{JmpIf}
  4251. and \key{Jmp}.
  4252. \begin{exercise}\normalfont
  4253. Update \code{patch-instructions} to handle the new x86 instructions.
  4254. Test your compiler using your previously created programs on the
  4255. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4256. \end{exercise}
  4257. \section{An Example Translation}
  4258. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4259. $R_2$ translated to x86, showing the results of
  4260. \code{explicate-control}, \code{select-instructions}, and the final
  4261. x86 assembly code.
  4262. \begin{figure}[tbp]
  4263. \begin{tabular}{lll}
  4264. \begin{minipage}{0.5\textwidth}
  4265. % s1_20.rkt
  4266. \begin{lstlisting}
  4267. (if (eq? (read) 1) 42 0)
  4268. \end{lstlisting}
  4269. $\Downarrow$
  4270. \begin{lstlisting}
  4271. start:
  4272. tmp7951 = (read);
  4273. if (eq? tmp7951 1) then
  4274. goto block7952;
  4275. else
  4276. goto block7953;
  4277. block7952:
  4278. return 42;
  4279. block7953:
  4280. return 0;
  4281. \end{lstlisting}
  4282. $\Downarrow$
  4283. \begin{lstlisting}
  4284. start:
  4285. callq read_int
  4286. movq %rax, tmp7951
  4287. cmpq $1, tmp7951
  4288. je block7952
  4289. jmp block7953
  4290. block7953:
  4291. movq $0, %rax
  4292. jmp conclusion
  4293. block7952:
  4294. movq $42, %rax
  4295. jmp conclusion
  4296. \end{lstlisting}
  4297. \end{minipage}
  4298. &
  4299. $\Rightarrow\qquad$
  4300. \begin{minipage}{0.4\textwidth}
  4301. \begin{lstlisting}
  4302. start:
  4303. callq read_int
  4304. movq %rax, %rcx
  4305. cmpq $1, %rcx
  4306. je block7952
  4307. jmp block7953
  4308. block7953:
  4309. movq $0, %rax
  4310. jmp conclusion
  4311. block7952:
  4312. movq $42, %rax
  4313. jmp conclusion
  4314. .globl main
  4315. main:
  4316. pushq %rbp
  4317. movq %rsp, %rbp
  4318. pushq %r13
  4319. pushq %r12
  4320. pushq %rbx
  4321. pushq %r14
  4322. subq $0, %rsp
  4323. jmp start
  4324. conclusion:
  4325. addq $0, %rsp
  4326. popq %r14
  4327. popq %rbx
  4328. popq %r12
  4329. popq %r13
  4330. popq %rbp
  4331. retq
  4332. \end{lstlisting}
  4333. \end{minipage}
  4334. \end{tabular}
  4335. \caption{Example compilation of an \key{if} expression to x86.}
  4336. \label{fig:if-example-x86}
  4337. \end{figure}
  4338. \begin{figure}[p]
  4339. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4340. \node (R2) at (0,2) {\large $R_2$};
  4341. \node (R2-2) at (3,2) {\large $R_2$};
  4342. \node (R2-3) at (6,2) {\large $R_2$};
  4343. \node (R2-4) at (9,2) {\large $R_2$};
  4344. \node (R2-5) at (9,0) {\large $R_2$};
  4345. \node (C1-1) at (3,-2) {\large $C_1$};
  4346. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}$};
  4347. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}$};
  4348. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}$};
  4349. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}$};
  4350. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}$};
  4351. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}$};
  4352. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4353. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4354. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4355. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4356. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4357. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4358. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4359. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4360. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4361. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4362. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4363. \end{tikzpicture}
  4364. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4365. \label{fig:R2-passes}
  4366. \end{figure}
  4367. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4368. compilation of $R_2$.
  4369. \section{Challenge: Optimize and Remove Jumps}
  4370. \label{sec:opt-jumps}
  4371. Recall that in the example output of \code{explicate-control} in
  4372. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4373. \code{block60} are trivial blocks, they do nothing but jump to another
  4374. block. The first goal of this challenge assignment is to remove those
  4375. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4376. \code{explicate-control} on the left and shows the result of bypassing
  4377. the trivial blocks on the right. Let us focus on \code{block61}. The
  4378. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4379. \code{block55}. The optimized code on the right of
  4380. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4381. \code{then} branch jumping directly to \code{block55}. The story is
  4382. similar for the \code{else} branch, as well as for the two branches in
  4383. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4384. have been optimized in this way, there are no longer any jumps to
  4385. blocks \code{block57} through \code{block60}, so they can be removed.
  4386. \begin{figure}[tbp]
  4387. \begin{tabular}{lll}
  4388. \begin{minipage}{0.4\textwidth}
  4389. \begin{lstlisting}
  4390. block62:
  4391. tmp54 = (read);
  4392. if (eq? tmp54 2) then
  4393. goto block59;
  4394. else
  4395. goto block60;
  4396. block61:
  4397. tmp53 = (read);
  4398. if (eq? tmp53 0) then
  4399. goto block57;
  4400. else
  4401. goto block58;
  4402. block60:
  4403. goto block56;
  4404. block59:
  4405. goto block55;
  4406. block58:
  4407. goto block56;
  4408. block57:
  4409. goto block55;
  4410. block56:
  4411. return (+ 700 77);
  4412. block55:
  4413. return (+ 10 32);
  4414. start:
  4415. tmp52 = (read);
  4416. if (eq? tmp52 1) then
  4417. goto block61;
  4418. else
  4419. goto block62;
  4420. \end{lstlisting}
  4421. \end{minipage}
  4422. &
  4423. $\Rightarrow$
  4424. &
  4425. \begin{minipage}{0.55\textwidth}
  4426. \begin{lstlisting}
  4427. block62:
  4428. tmp54 = (read);
  4429. if (eq? tmp54 2) then
  4430. goto block55;
  4431. else
  4432. goto block56;
  4433. block61:
  4434. tmp53 = (read);
  4435. if (eq? tmp53 0) then
  4436. goto block55;
  4437. else
  4438. goto block56;
  4439. block56:
  4440. return (+ 700 77);
  4441. block55:
  4442. return (+ 10 32);
  4443. start:
  4444. tmp52 = (read);
  4445. if (eq? tmp52 1) then
  4446. goto block61;
  4447. else
  4448. goto block62;
  4449. \end{lstlisting}
  4450. \end{minipage}
  4451. \end{tabular}
  4452. \caption{Optimize jumps by removing trivial blocks.}
  4453. \label{fig:optimize-jumps}
  4454. \end{figure}
  4455. The name of this pass is \code{optimize-jumps}. We recommend
  4456. implementing this pass in two phases. The first phrase builds a hash
  4457. table that maps labels to possibly improved labels. The second phase
  4458. changes the target of each \code{goto} to use the improved label. If
  4459. the label is for a trivial block, then the hash table should map the
  4460. label to the first non-trivial block that can be reached from this
  4461. label by jumping through trivial blocks. If the label is for a
  4462. non-trivial block, then the hash table should map the label to itself;
  4463. we do not want to change jumps to non-trivial blocks.
  4464. The first phase can be accomplished by constructing an empty hash
  4465. table, call it \code{short-cut}, and then iterating over the control
  4466. flow graph. Each time you encouter a block that is just a \code{goto},
  4467. then update the hash table, mapping the block's source to the target
  4468. of the \code{goto}. Also, the hash table may already have mapped some
  4469. labels to the block's source, to you must iterate through the hash
  4470. table and update all of those so that they instead map to the target
  4471. of the \code{goto}.
  4472. For the second phase, we recommend iterating through the $\Tail$ of
  4473. each block in the program, updating the target of every \code{goto}
  4474. according to the mapping in \code{short-cut}.
  4475. \begin{exercise}\normalfont
  4476. Implement the \code{optimize-jumps} pass and check that it remove
  4477. trivial blocks in a few example programs. Then check that your
  4478. compiler still passes all of your tests.
  4479. \end{exercise}
  4480. There is another opportunity for optimizing jumps that is apparent in
  4481. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4482. end with a jump to \code{block7953} and there are no other jumps to
  4483. \code{block7953} in the rest of the program. In this situation we can
  4484. avoid the runtime overhead of this jump by merging \code{block7953}
  4485. into the preceeding block, in this case the \code{start} block.
  4486. Figure~\ref{fig:remove-jumps} shows the output of
  4487. \code{select-instructions} on the left and the result of this
  4488. optimization on the right.
  4489. \begin{figure}[tbp]
  4490. \begin{tabular}{lll}
  4491. \begin{minipage}{0.5\textwidth}
  4492. % s1_20.rkt
  4493. \begin{lstlisting}
  4494. start:
  4495. callq read_int
  4496. movq %rax, tmp7951
  4497. cmpq $1, tmp7951
  4498. je block7952
  4499. jmp block7953
  4500. block7953:
  4501. movq $0, %rax
  4502. jmp conclusion
  4503. block7952:
  4504. movq $42, %rax
  4505. jmp conclusion
  4506. \end{lstlisting}
  4507. \end{minipage}
  4508. &
  4509. $\Rightarrow\qquad$
  4510. \begin{minipage}{0.4\textwidth}
  4511. \begin{lstlisting}
  4512. start:
  4513. callq read_int
  4514. movq %rax, tmp7951
  4515. cmpq $1, tmp7951
  4516. je block7952
  4517. movq $0, %rax
  4518. jmp conclusion
  4519. block7952:
  4520. movq $42, %rax
  4521. jmp conclusion
  4522. \end{lstlisting}
  4523. \end{minipage}
  4524. \end{tabular}
  4525. \caption{Merging basic blocks by removing unnecessary jumps.}
  4526. \label{fig:remove-jumps}
  4527. \end{figure}
  4528. \begin{exercise}\normalfont
  4529. Implement a pass named \code{remove-jumps} that merges basic blocks
  4530. into their preceeding basic block, when there is only one preceeding
  4531. block. Check that your pass accomplishes this goal on several test
  4532. programs and check that your compiler passes all of your tests.
  4533. \end{exercise}
  4534. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4535. \chapter{Tuples and Garbage Collection}
  4536. \label{ch:tuples}
  4537. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4538. add simple structures. \\ --Jeremy}
  4539. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4540. things to discuss in this chapter. \\ --Jeremy}
  4541. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4542. all the IR grammars are spelled out! \\ --Jeremy}
  4543. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4544. but keep type annotations on vector creation and local variables, function
  4545. parameters, etc. \\ --Jeremy}
  4546. \margincomment{\scriptsize Be more explicit about how to deal with
  4547. the root stack. \\ --Jeremy}
  4548. In this chapter we study the implementation of mutable tuples (called
  4549. ``vectors'' in Racket). This language feature is the first to use the
  4550. computer's \emph{heap} because the lifetime of a Racket tuple is
  4551. indefinite, that is, a tuple lives forever from the programmer's
  4552. viewpoint. Of course, from an implementer's viewpoint, it is important
  4553. to reclaim the space associated with a tuple when it is no longer
  4554. needed, which is why we also study \emph{garbage collection}
  4555. techniques in this chapter.
  4556. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4557. interpreter and type checker. The $R_3$ language extends the $R_2$
  4558. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4559. \code{void} value. The reason for including the later is that the
  4560. \code{vector-set!} operation returns a value of type
  4561. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4562. called the \code{Unit} type in the programming languages
  4563. literature. Racket's \code{Void} type is inhabited by a single value
  4564. \code{void} which corresponds to \code{unit} or \code{()} in the
  4565. literature~\citep{Pierce:2002hj}.}.
  4566. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4567. copying live objects back and forth between two halves of the
  4568. heap. The garbage collector requires coordination with the compiler so
  4569. that it can see all of the \emph{root} pointers, that is, pointers in
  4570. registers or on the procedure call stack.
  4571. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4572. discuss all the necessary changes and additions to the compiler
  4573. passes, including a new compiler pass named \code{expose-allocation}.
  4574. \section{The $R_3$ Language}
  4575. \label{sec:r3}
  4576. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4577. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4578. $R_3$ language includes three new forms: \code{vector} for creating a
  4579. tuple, \code{vector-ref} for reading an element of a tuple, and
  4580. \code{vector-set!} for writing to an element of a tuple. The program
  4581. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4582. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4583. the 3-tuple, demonstrating that tuples are first-class values. The
  4584. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4585. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4586. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4587. 1-tuple. So the result of the program is \code{42}.
  4588. \begin{figure}[tbp]
  4589. \centering
  4590. \fbox{
  4591. \begin{minipage}{0.96\textwidth}
  4592. \[
  4593. \begin{array}{lcl}
  4594. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4595. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4596. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4597. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4598. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4599. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4600. \mid (\key{and}\;\Exp\;\Exp)
  4601. \mid (\key{or}\;\Exp\;\Exp)
  4602. \mid (\key{not}\;\Exp) } \\
  4603. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4604. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4605. &\mid& (\key{vector}\;\Exp^{+})
  4606. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4607. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4608. &\mid& (\key{void}) \\
  4609. R_3 &::=& \Exp
  4610. \end{array}
  4611. \]
  4612. \end{minipage}
  4613. }
  4614. \caption{The concrete syntax of $R_3$, extending $R_2$
  4615. (Figure~\ref{fig:r2-concrete-syntax}).}
  4616. \label{fig:r3-concrete-syntax}
  4617. \end{figure}
  4618. \begin{figure}[tbp]
  4619. \begin{lstlisting}
  4620. (let ([t (vector 40 #t (vector 2))])
  4621. (if (vector-ref t 1)
  4622. (+ (vector-ref t 0)
  4623. (vector-ref (vector-ref t 2) 0))
  4624. 44))
  4625. \end{lstlisting}
  4626. \caption{Example program that creates tuples and reads from them.}
  4627. \label{fig:vector-eg}
  4628. \end{figure}
  4629. \begin{figure}[tp]
  4630. \centering
  4631. \fbox{
  4632. \begin{minipage}{0.96\textwidth}
  4633. \[
  4634. \begin{array}{lcl}
  4635. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4636. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4637. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4638. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4639. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4640. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4641. &\mid& \gray{ \BOOL{\itm{bool}}
  4642. \mid \AND{\Exp}{\Exp} }\\
  4643. &\mid& \gray{ \OR{\Exp}{\Exp}
  4644. \mid \NOT{\Exp} } \\
  4645. &\mid& \gray{ \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp}
  4646. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4647. &\mid& \VECTOR{\Exp} \\
  4648. &\mid& \VECREF{\Exp}{\Int}\\
  4649. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4650. &\mid& \VOID{} \\
  4651. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4652. \end{array}
  4653. \]
  4654. \end{minipage}
  4655. }
  4656. \caption{The abstract syntax of $R_3$.}
  4657. \label{fig:r3-syntax}
  4658. \end{figure}
  4659. Tuples are our first encounter with heap-allocated data, which raises
  4660. several interesting issues. First, variable binding performs a
  4661. shallow-copy when dealing with tuples, which means that different
  4662. variables can refer to the same tuple, that is, different variables
  4663. can be \emph{aliases} for the same entity. Consider the following
  4664. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4665. Thus, the mutation through \code{t2} is visible when referencing the
  4666. tuple from \code{t1}, so the result of this program is \code{42}.
  4667. \begin{center}
  4668. \begin{minipage}{0.96\textwidth}
  4669. \begin{lstlisting}
  4670. (let ([t1 (vector 3 7)])
  4671. (let ([t2 t1])
  4672. (let ([_ (vector-set! t2 0 42)])
  4673. (vector-ref t1 0))))
  4674. \end{lstlisting}
  4675. \end{minipage}
  4676. \end{center}
  4677. The next issue concerns the lifetime of tuples. Of course, they are
  4678. created by the \code{vector} form, but when does their lifetime end?
  4679. Notice that $R_3$ does not include an operation for deleting
  4680. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  4681. of static scoping. For example, the following program returns
  4682. \code{42} even though the variable \code{w} goes out of scope prior to
  4683. the \code{vector-ref} that reads from the vector it was bound to.
  4684. \begin{center}
  4685. \begin{minipage}{0.96\textwidth}
  4686. \begin{lstlisting}
  4687. (let ([v (vector (vector 44))])
  4688. (let ([x (let ([w (vector 42)])
  4689. (let ([_ (vector-set! v 0 w)])
  4690. 0))])
  4691. (+ x (vector-ref (vector-ref v 0) 0))))
  4692. \end{lstlisting}
  4693. \end{minipage}
  4694. \end{center}
  4695. From the perspective of programmer-observable behavior, tuples live
  4696. forever. Of course, if they really lived forever, then many programs
  4697. would run out of memory.\footnote{The $R_3$ language does not have
  4698. looping or recursive functions, so it is nigh impossible to write a
  4699. program in $R_3$ that will run out of memory. However, we add
  4700. recursive functions in the next Chapter!} A Racket implementation
  4701. must therefore perform automatic garbage collection.
  4702. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4703. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4704. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4705. operations in Racket. One subtle point is that the \code{vector-set!}
  4706. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4707. can be passed around just like other values inside an $R_3$ program
  4708. and a \code{\#<void>} value can be compared for equality with another
  4709. \code{\#<void>} value. However, there are no other operations specific
  4710. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  4711. the \code{void?} predicate that returns \code{\#t} when applied to
  4712. \code{\#<void>} and \code{\#f} otherwise.
  4713. \begin{figure}[tbp]
  4714. \begin{lstlisting}
  4715. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4716. (define (interp-op op)
  4717. (match op
  4718. ...
  4719. ['vector vector]
  4720. ['vector-ref vector-ref]
  4721. ['vector-set! vector-set!]
  4722. [else (error 'interp-op "unknown operator")]))
  4723. (define (interp-exp env)
  4724. (lambda (e)
  4725. (define recur (interp-exp env))
  4726. (match e
  4727. ...
  4728. )))
  4729. (define (interp-R3 p)
  4730. (match p
  4731. [(Program '() e)
  4732. ((interp-exp '()) e)]
  4733. ))
  4734. \end{lstlisting}
  4735. \caption{Interpreter for the $R_3$ language.}
  4736. \label{fig:interp-R3}
  4737. \end{figure}
  4738. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4739. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4740. need to know which variables contain pointers into the heap, that is,
  4741. which variables contain vectors. Also, when allocating a vector, we
  4742. need to know which elements of the vector are pointers. We can obtain
  4743. this information during type checking. The type checker in
  4744. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4745. expression, it also wraps every sub-expression $e$ with the form
  4746. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4747. Subsequently, in the \code{uncover-locals} pass
  4748. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4749. propagated to all variables (including the temporaries generated by
  4750. \code{remove-complex-opera*}).
  4751. \begin{figure}[hb]
  4752. \begin{lstlisting}
  4753. (define (type-check-exp env)
  4754. (lambda (e)
  4755. (define recur (type-check-exp env))
  4756. (match e
  4757. ...
  4758. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4759. [(Prim 'vector es)
  4760. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  4761. (let ([t `(Vector ,@t*)])
  4762. (values (HasType (Prim 'vector e*) t) t))]
  4763. [(Prim 'vector-ref (list e (Int i)))
  4764. (define-values (e^ t) (recur e))
  4765. (match t
  4766. [`(Vector ,ts ...)
  4767. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4768. (error 'type-check-exp "invalid index ~a" i))
  4769. (let ([t (list-ref ts i)])
  4770. (values
  4771. (HasType (Prim 'vector-ref
  4772. (list e^ (HasType (Int i) 'Integer)))
  4773. t)
  4774. t))]
  4775. [else (error "expected a vector in vector-ref, not" t)])]
  4776. [(Prim 'eq? (list e1 e2))
  4777. (define-values (e1^ T1) (recur e1))
  4778. (define-values (e2^ T2) (recur e2))
  4779. (unless (equal? T1 T2)
  4780. (error "arguments of eq? must have the same type, but are not"
  4781. (list T1 T2)))
  4782. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4783. ...
  4784. )))
  4785. \end{lstlisting}
  4786. \caption{Type checker for the $R_3$ language.}
  4787. \label{fig:typecheck-R3}
  4788. \end{figure}
  4789. \section{Garbage Collection}
  4790. \label{sec:GC}
  4791. Here we study a relatively simple algorithm for garbage collection
  4792. that is the basis of state-of-the-art garbage
  4793. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4794. particular, we describe a two-space copying
  4795. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4796. perform the
  4797. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4798. coarse-grained depiction of what happens in a two-space collector,
  4799. showing two time steps, prior to garbage collection (on the top) and
  4800. after garbage collection (on the bottom). In a two-space collector,
  4801. the heap is divided into two parts named the FromSpace and the
  4802. ToSpace. Initially, all allocations go to the FromSpace until there is
  4803. not enough room for the next allocation request. At that point, the
  4804. garbage collector goes to work to make more room.
  4805. The garbage collector must be careful not to reclaim tuples that will
  4806. be used by the program in the future. Of course, it is impossible in
  4807. general to predict what a program will do, but we can over approximate
  4808. the will-be-used tuples by preserving all tuples that could be
  4809. accessed by \emph{any} program given the current computer state. A
  4810. program could access any tuple whose address is in a register or on
  4811. the procedure call stack. These addresses are called the \emph{root
  4812. set}. In addition, a program could access any tuple that is
  4813. transitively reachable from the root set. Thus, it is safe for the
  4814. garbage collector to reclaim the tuples that are not reachable in this
  4815. way.
  4816. So the goal of the garbage collector is twofold:
  4817. \begin{enumerate}
  4818. \item preserve all tuple that are reachable from the root set via a
  4819. path of pointers, that is, the \emph{live} tuples, and
  4820. \item reclaim the memory of everything else, that is, the
  4821. \emph{garbage}.
  4822. \end{enumerate}
  4823. A copying collector accomplishes this by copying all of the live
  4824. objects from the FromSpace into the ToSpace and then performs a slight
  4825. of hand, treating the ToSpace as the new FromSpace and the old
  4826. FromSpace as the new ToSpace. In the example of
  4827. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4828. root set, one in a register and two on the stack. All of the live
  4829. objects have been copied to the ToSpace (the right-hand side of
  4830. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4831. pointer relationships. For example, the pointer in the register still
  4832. points to a 2-tuple whose first element is a 3-tuple and whose second
  4833. element is a 2-tuple. There are four tuples that are not reachable
  4834. from the root set and therefore do not get copied into the ToSpace.
  4835. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  4836. created by a well-typed program in $R_3$ because it contains a
  4837. cycle. However, creating cycles will be possible once we get to $R_6$.
  4838. We design the garbage collector to deal with cycles to begin with so
  4839. we will not need to revisit this issue.
  4840. \begin{figure}[tbp]
  4841. \centering
  4842. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4843. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4844. \caption{A copying collector in action.}
  4845. \label{fig:copying-collector}
  4846. \end{figure}
  4847. There are many alternatives to copying collectors (and their bigger
  4848. siblings, the generational collectors) when its comes to garbage
  4849. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  4850. reference counting~\citep{Collins:1960aa}. The strengths of copying
  4851. collectors are that allocation is fast (just a comparison and pointer
  4852. increment), there is no fragmentation, cyclic garbage is collected,
  4853. and the time complexity of collection only depends on the amount of
  4854. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  4855. main disadvantage of a two-space copying collector is that it uses a
  4856. lot of space, though that problem is ameliorated in generational
  4857. collectors. Racket and Scheme programs tend to allocate many small
  4858. objects and generate a lot of garbage, so copying and generational
  4859. collectors are a good fit. Garbage collection is an active research
  4860. topic, especially concurrent garbage
  4861. collection~\citep{Tene:2011kx}. Researchers are continuously
  4862. developing new techniques and revisiting old
  4863. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  4864. meet every year at the International Symposium on Memory Management to
  4865. present these findings.
  4866. \subsection{Graph Copying via Cheney's Algorithm}
  4867. \label{sec:cheney}
  4868. Let us take a closer look at the copying of the live objects. The
  4869. allocated objects and pointers can be viewed as a graph and we need to
  4870. copy the part of the graph that is reachable from the root set. To
  4871. make sure we copy all of the reachable vertices in the graph, we need
  4872. an exhaustive graph traversal algorithm, such as depth-first search or
  4873. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  4874. such algorithms take into account the possibility of cycles by marking
  4875. which vertices have already been visited, so as to ensure termination
  4876. of the algorithm. These search algorithms also use a data structure
  4877. such as a stack or queue as a to-do list to keep track of the vertices
  4878. that need to be visited. We shall use breadth-first search and a trick
  4879. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  4880. and copying tuples into the ToSpace.
  4881. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4882. copy progresses. The queue is represented by a chunk of contiguous
  4883. memory at the beginning of the ToSpace, using two pointers to track
  4884. the front and the back of the queue. The algorithm starts by copying
  4885. all tuples that are immediately reachable from the root set into the
  4886. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4887. old tuple to indicate that it has been visited. We discuss how this
  4888. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  4889. pointers inside the copied tuples in the queue still point back to the
  4890. FromSpace. Once the initial queue has been created, the algorithm
  4891. enters a loop in which it repeatedly processes the tuple at the front
  4892. of the queue and pops it off the queue. To process a tuple, the
  4893. algorithm copies all the tuple that are directly reachable from it to
  4894. the ToSpace, placing them at the back of the queue. The algorithm then
  4895. updates the pointers in the popped tuple so they point to the newly
  4896. copied tuples.
  4897. \begin{figure}[tbp]
  4898. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4899. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4900. \label{fig:cheney}
  4901. \end{figure}
  4902. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  4903. tuple whose second element is $42$ to the back of the queue. The other
  4904. pointer goes to a tuple that has already been copied, so we do not
  4905. need to copy it again, but we do need to update the pointer to the new
  4906. location. This can be accomplished by storing a \emph{forwarding}
  4907. pointer to the new location in the old tuple, back when we initially
  4908. copied the tuple into the ToSpace. This completes one step of the
  4909. algorithm. The algorithm continues in this way until the front of the
  4910. queue is empty, that is, until the front catches up with the back.
  4911. \subsection{Data Representation}
  4912. \label{sec:data-rep-gc}
  4913. The garbage collector places some requirements on the data
  4914. representations used by our compiler. First, the garbage collector
  4915. needs to distinguish between pointers and other kinds of data. There
  4916. are several ways to accomplish this.
  4917. \begin{enumerate}
  4918. \item Attached a tag to each object that identifies what type of
  4919. object it is~\citep{McCarthy:1960dz}.
  4920. \item Store different types of objects in different
  4921. regions~\citep{Steele:1977ab}.
  4922. \item Use type information from the program to either generate
  4923. type-specific code for collecting or to generate tables that can
  4924. guide the
  4925. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4926. \end{enumerate}
  4927. Dynamically typed languages, such as Lisp, need to tag objects
  4928. anyways, so option 1 is a natural choice for those languages.
  4929. However, $R_3$ is a statically typed language, so it would be
  4930. unfortunate to require tags on every object, especially small and
  4931. pervasive objects like integers and Booleans. Option 3 is the
  4932. best-performing choice for statically typed languages, but comes with
  4933. a relatively high implementation complexity. To keep this chapter
  4934. within a 2-week time budget, we recommend a combination of options 1
  4935. and 2, using separate strategies for the stack and the heap.
  4936. Regarding the stack, we recommend using a separate stack for pointers,
  4937. which we call a \emph{root stack} (a.k.a. ``shadow
  4938. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  4939. is, when a local variable needs to be spilled and is of type
  4940. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  4941. stack instead of the normal procedure call stack. Furthermore, we
  4942. always spill vector-typed variables if they are live during a call to
  4943. the collector, thereby ensuring that no pointers are in registers
  4944. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  4945. example from Figure~\ref{fig:copying-collector} and contrasts it with
  4946. the data layout using a root stack. The root stack contains the two
  4947. pointers from the regular stack and also the pointer in the second
  4948. register.
  4949. \begin{figure}[tbp]
  4950. \centering \includegraphics[width=0.65\textwidth]{figs/root-stack}
  4951. \caption{Maintaining a root stack to facilitate garbage collection.}
  4952. \label{fig:shadow-stack}
  4953. \end{figure}
  4954. The problem of distinguishing between pointers and other kinds of data
  4955. also arises inside of each tuple on the heap. We solve this problem by
  4956. attaching a tag, an extra 64-bits, to each
  4957. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  4958. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  4959. that we have drawn the bits in a big-endian way, from right-to-left,
  4960. with bit location 0 (the least significant bit) on the far right,
  4961. which corresponds to the direction of the x86 shifting instructions
  4962. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  4963. is dedicated to specifying which elements of the tuple are pointers,
  4964. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  4965. indicates there is a pointer and a 0 bit indicates some other kind of
  4966. data. The pointer mask starts at bit location 7. We have limited
  4967. tuples to a maximum size of 50 elements, so we just need 50 bits for
  4968. the pointer mask. The tag also contains two other pieces of
  4969. information. The length of the tuple (number of elements) is stored in
  4970. bits location 1 through 6. Finally, the bit at location 0 indicates
  4971. whether the tuple has yet to be copied to the ToSpace. If the bit has
  4972. value 1, then this tuple has not yet been copied. If the bit has
  4973. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  4974. of a pointer are always zero anyways because our tuples are 8-byte
  4975. aligned.)
  4976. \begin{figure}[tbp]
  4977. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4978. \caption{Representation of tuples in the heap.}
  4979. \label{fig:tuple-rep}
  4980. \end{figure}
  4981. \subsection{Implementation of the Garbage Collector}
  4982. \label{sec:organize-gz}
  4983. An implementation of the copying collector is provided in the
  4984. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  4985. interface to the garbage collector that is used by the compiler. The
  4986. \code{initialize} function creates the FromSpace, ToSpace, and root
  4987. stack and should be called in the prelude of the \code{main}
  4988. function. The \code{initialize} function puts the address of the
  4989. beginning of the FromSpace into the global variable
  4990. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  4991. the address that is 1-past the last element of the FromSpace. (We use
  4992. half-open intervals to represent chunks of
  4993. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  4994. points to the first element of the root stack.
  4995. As long as there is room left in the FromSpace, your generated code
  4996. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4997. %
  4998. The amount of room left in FromSpace is the difference between the
  4999. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5000. function should be called when there is not enough room left in the
  5001. FromSpace for the next allocation. The \code{collect} function takes
  5002. a pointer to the current top of the root stack (one past the last item
  5003. that was pushed) and the number of bytes that need to be
  5004. allocated. The \code{collect} function performs the copying collection
  5005. and leaves the heap in a state such that the next allocation will
  5006. succeed.
  5007. \begin{figure}[tbp]
  5008. \begin{lstlisting}
  5009. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5010. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5011. int64_t* free_ptr;
  5012. int64_t* fromspace_begin;
  5013. int64_t* fromspace_end;
  5014. int64_t** rootstack_begin;
  5015. \end{lstlisting}
  5016. \caption{The compiler's interface to the garbage collector.}
  5017. \label{fig:gc-header}
  5018. \end{figure}
  5019. %% \begin{exercise}
  5020. %% In the file \code{runtime.c} you will find the implementation of
  5021. %% \code{initialize} and a partial implementation of \code{collect}.
  5022. %% The \code{collect} function calls another function, \code{cheney},
  5023. %% to perform the actual copy, and that function is left to the reader
  5024. %% to implement. The following is the prototype for \code{cheney}.
  5025. %% \begin{lstlisting}
  5026. %% static void cheney(int64_t** rootstack_ptr);
  5027. %% \end{lstlisting}
  5028. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5029. %% rootstack (which is an array of pointers). The \code{cheney} function
  5030. %% also communicates with \code{collect} through the global
  5031. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5032. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5033. %% the ToSpace:
  5034. %% \begin{lstlisting}
  5035. %% static int64_t* tospace_begin;
  5036. %% static int64_t* tospace_end;
  5037. %% \end{lstlisting}
  5038. %% The job of the \code{cheney} function is to copy all the live
  5039. %% objects (reachable from the root stack) into the ToSpace, update
  5040. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5041. %% update the root stack so that it points to the objects in the
  5042. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5043. %% and ToSpace.
  5044. %% \end{exercise}
  5045. %% \section{Compiler Passes}
  5046. %% \label{sec:code-generation-gc}
  5047. The introduction of garbage collection has a non-trivial impact on our
  5048. compiler passes. We introduce two new compiler passes named
  5049. \code{expose-allocation} and \code{uncover-locals}. We make
  5050. significant changes to \code{select-instructions},
  5051. \code{build-interference}, \code{allocate-registers}, and
  5052. \code{print-x86} and make minor changes in severl more passes. The
  5053. following program will serve as our running example. It creates two
  5054. tuples, one nested inside the other. Both tuples have length one. The
  5055. program accesses the element in the inner tuple tuple via two vector
  5056. references.
  5057. % tests/s2_17.rkt
  5058. \begin{lstlisting}
  5059. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5060. \end{lstlisting}
  5061. \section{Shrink}
  5062. \label{sec:shrink-R3}
  5063. Recall that the \code{shrink} pass translates the primitives operators
  5064. into a smaller set of primitives. Because this pass comes after type
  5065. checking, but before the passes that require the type information in
  5066. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5067. to wrap \code{HasType} around each AST node that it generates.
  5068. \section{Expose Allocation}
  5069. \label{sec:expose-allocation}
  5070. The pass \code{expose-allocation} lowers the \code{vector} creation
  5071. form into a conditional call to the collector followed by the
  5072. allocation. We choose to place the \code{expose-allocation} pass
  5073. before \code{remove-complex-opera*} because the code generated by
  5074. \code{expose-allocation} contains complex operands. We also place
  5075. \code{expose-allocation} before \code{explicate-control} because
  5076. \code{expose-allocation} introduces new variables using \code{let},
  5077. but \code{let} is gone after \code{explicate-control}.
  5078. The output of \code{expose-allocation} is a language that extends
  5079. $R_3$ with the three new forms that we use in the translation of the
  5080. \code{vector} form.
  5081. \[
  5082. \begin{array}{lcl}
  5083. \Exp &::=& \cdots
  5084. \mid (\key{collect} \,\itm{int})
  5085. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5086. \mid (\key{global-value} \,\itm{name})
  5087. \end{array}
  5088. \]
  5089. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5090. $n$ bytes. It will become a call to the \code{collect} function in
  5091. \code{runtime.c} in \code{select-instructions}. The
  5092. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements. The
  5093. $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5094. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5095. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5096. a global variable, such as \code{free\_ptr}.
  5097. In the following, we show the transformation for the \code{vector}
  5098. form into 1) a sequence of let-bindings for the initializing
  5099. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5100. \code{allocate}, and 4) the initialization of the vector. In the
  5101. following, \itm{len} refers to the length of the vector and
  5102. \itm{bytes} is how many total bytes need to be allocated for the
  5103. vector, which is 8 for the tag plus \itm{len} times 8.
  5104. \begin{lstlisting}
  5105. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5106. |$\Longrightarrow$|
  5107. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5108. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5109. (global-value fromspace_end))
  5110. (void)
  5111. (collect |\itm{bytes}|))])
  5112. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5113. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5114. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5115. |$v$|) ... )))) ...)
  5116. \end{lstlisting}
  5117. In the above, we suppressed all of the \code{has-type} forms in the
  5118. output for the sake of readability. The placement of the initializing
  5119. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5120. sequence of \code{vector-set!} is important, as those expressions may
  5121. trigger garbage collection and we cannot have an allocated but
  5122. uninitialized tuple on the heap during a collection.
  5123. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5124. \code{expose-allocation} pass on our running example.
  5125. \begin{figure}[tbp]
  5126. % tests/s2_17.rkt
  5127. \begin{lstlisting}
  5128. (vector-ref
  5129. (vector-ref
  5130. (let ([vecinit7976
  5131. (let ([vecinit7972 42])
  5132. (let ([collectret7974
  5133. (if (< (+ free_ptr 16) fromspace_end)
  5134. (void)
  5135. (collect 16)
  5136. )])
  5137. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5138. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5139. alloc7971)
  5140. )
  5141. )
  5142. )
  5143. ])
  5144. (let ([collectret7978
  5145. (if (< (+ free_ptr 16) fromspace_end)
  5146. (void)
  5147. (collect 16)
  5148. )])
  5149. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5150. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5151. alloc7975)
  5152. )
  5153. )
  5154. )
  5155. 0)
  5156. 0)
  5157. \end{lstlisting}
  5158. \caption{Output of the \code{expose-allocation} pass, minus
  5159. all of the \code{HasType} forms.}
  5160. \label{fig:expose-alloc-output}
  5161. \end{figure}
  5162. \section{Remove Complex Operands}
  5163. \label{sec:remove-complex-opera-R2}
  5164. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5165. should all be treated as complex operands. A new case for
  5166. \code{HasType} is needed and the case for \code{Prim} needs to be
  5167. handled carefully to prevent the \code{Prim} node from being separated
  5168. from its enclosing \code{HasType}.
  5169. \section{Explicate Control and the $C_2$ language}
  5170. \label{sec:explicate-control-r3}
  5171. \begin{figure}[tp]
  5172. \fbox{
  5173. \begin{minipage}{0.96\textwidth}
  5174. \small
  5175. \[
  5176. \begin{array}{lcl}
  5177. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5178. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5179. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5180. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5181. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5182. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5183. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  5184. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  5185. &\mid& (\key{GlobalValue} \,\itm{name}) \mid (\key{Void})\\
  5186. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5187. \mid (\key{Collect} \,\itm{int}) \\
  5188. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5189. \mid \GOTO{\itm{label}} } \\
  5190. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5191. C_2 & ::= & \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)^{+}}}
  5192. \end{array}
  5193. \]
  5194. \end{minipage}
  5195. }
  5196. \caption{The abstract syntax $C_2$, an extention of $C_1$
  5197. (Figure~\ref{fig:c1-syntax}).}
  5198. \label{fig:c2-syntax}
  5199. \end{figure}
  5200. The output of \code{explicate-control} is a program in the
  5201. intermediate language $C_2$, whose abstract syntax is defined in
  5202. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  5203. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5204. \key{global-value} expressions and the \code{collect} statement. The
  5205. \code{explicate-control} pass can treat these new forms much like the
  5206. other forms.
  5207. \section{Uncover Locals}
  5208. \label{sec:uncover-locals-r3}
  5209. Recall that the \code{explicate-control} function collects all of the
  5210. local variables so that it can store them in the $\itm{info}$ field of
  5211. the \code{Program} structure. Also recall that we need to know the
  5212. types of all the local variables for purposes of identifying the root
  5213. set for the garbage collector. Thus, we create a pass named
  5214. \code{uncover-locals} to collect not just the variables but the
  5215. variables and their types in the form of an alist. Thanks to the
  5216. \code{HasType} nodes, the types are readily available at every
  5217. assignment to a variable. We recommend storing the resulting alist in
  5218. the $\itm{info}$ field of the program, associated with the
  5219. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5220. of the \code{uncover-locals} pass on the running example.
  5221. \begin{figure}[tbp]
  5222. % tests/s2_17.rkt
  5223. \begin{lstlisting}
  5224. locals:
  5225. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5226. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5227. collectret7974 : 'Void, initret7977 : 'Void,
  5228. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5229. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5230. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5231. vecinit7972 : 'Integer, initret7973 : 'Void,
  5232. block7991:
  5233. (collect 16)
  5234. goto block7989;
  5235. block7990:
  5236. collectret7974 = (void);
  5237. goto block7989;
  5238. block7989:
  5239. alloc7971 = (allocate 1 (Vector Integer));
  5240. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5241. vecinit7976 = alloc7971;
  5242. tmp7982 = free_ptr;
  5243. tmp7983 = (+ tmp7982 16);
  5244. tmp7984 = fromspace_end;
  5245. if (< tmp7983 tmp7984) then
  5246. goto block7987;
  5247. else
  5248. goto block7988;
  5249. block7988:
  5250. (collect 16)
  5251. goto block7986;
  5252. block7987:
  5253. collectret7978 = (void);
  5254. goto block7986;
  5255. block7986:
  5256. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5257. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5258. tmp7985 = (vector-ref alloc7975 0);
  5259. return (vector-ref tmp7985 0);
  5260. start:
  5261. vecinit7972 = 42;
  5262. tmp7979 = free_ptr;
  5263. tmp7980 = (+ tmp7979 16);
  5264. tmp7981 = fromspace_end;
  5265. if (< tmp7980 tmp7981) then
  5266. goto block7990;
  5267. else
  5268. goto block7991;
  5269. \end{lstlisting}
  5270. \caption{Output of \code{uncover-locals} for the running example.}
  5271. \label{fig:uncover-locals-r3}
  5272. \end{figure}
  5273. \clearpage
  5274. \section{Select Instructions and the x86$_2$ Language}
  5275. \label{sec:select-instructions-gc}
  5276. %% void (rep as zero)
  5277. %% allocate
  5278. %% collect (callq collect)
  5279. %% vector-ref
  5280. %% vector-set!
  5281. %% global-value (postpone)
  5282. In this pass we generate x86 code for most of the new operations that
  5283. were needed to compile tuples, including \code{allocate},
  5284. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  5285. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  5286. The \code{vector-ref} and \code{vector-set!} forms translate into
  5287. \code{movq} instructions with the appropriate \key{deref}. (The
  5288. plus one is to get past the tag at the beginning of the tuple
  5289. representation.)
  5290. \begin{lstlisting}
  5291. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  5292. |$\Longrightarrow$|
  5293. (movq |$\itm{vec}'$| (reg r11))
  5294. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  5295. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  5296. |$\Longrightarrow$|
  5297. (movq |$\itm{vec}'$| (reg r11))
  5298. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  5299. (movq (int 0) |$\itm{lhs}$|)
  5300. \end{lstlisting}
  5301. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  5302. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  5303. register \code{r11} ensures that offsets are only performed with
  5304. register operands. This requires removing \code{r11} from
  5305. consideration by the register allocating.
  5306. We compile the \code{allocate} form to operations on the
  5307. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5308. is the next free address in the FromSpace, so we move it into the
  5309. \itm{lhs} and then move it forward by enough space for the tuple being
  5310. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5311. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5312. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5313. how the tag is organized. We recommend using the Racket operations
  5314. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  5315. The type annotation in the \code{vector} form is used to determine the
  5316. pointer mask region of the tag.
  5317. \begin{lstlisting}
  5318. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  5319. |$\Longrightarrow$|
  5320. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  5321. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  5322. (movq |$\itm{lhs}'$| (reg r11))
  5323. (movq (int |$\itm{tag}$|) (deref r11 0))
  5324. \end{lstlisting}
  5325. The \code{collect} form is compiled to a call to the \code{collect}
  5326. function in the runtime. The arguments to \code{collect} are the top
  5327. of the root stack and the number of bytes that need to be allocated.
  5328. We shall use a dedicated register, \code{r15}, to store the pointer to
  5329. the top of the root stack. So \code{r15} is not available for use by
  5330. the register allocator.
  5331. \begin{lstlisting}
  5332. (collect |$\itm{bytes}$|)
  5333. |$\Longrightarrow$|
  5334. (movq (reg r15) (reg rdi))
  5335. (movq |\itm{bytes}| (reg rsi))
  5336. (callq collect)
  5337. \end{lstlisting}
  5338. \begin{figure}[tp]
  5339. \fbox{
  5340. \begin{minipage}{0.96\textwidth}
  5341. \[
  5342. \begin{array}{lcl}
  5343. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5344. \mid (\key{deref}\,\Reg\,\Int) } \\
  5345. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  5346. \mid (\key{global-value}\; \itm{name}) \\
  5347. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5348. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  5349. (\key{subq} \; \Arg\; \Arg) \mid
  5350. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  5351. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  5352. (\key{pushq}\;\Arg) \mid
  5353. (\key{popq}\;\Arg) \mid
  5354. (\key{retq})} \\
  5355. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5356. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5357. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5358. \mid (\key{jmp} \; \itm{label})
  5359. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  5360. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  5361. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  5362. \end{array}
  5363. \]
  5364. \end{minipage}
  5365. }
  5366. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5367. \label{fig:x86-2}
  5368. \end{figure}
  5369. The syntax of the $x86_2$ language is defined in
  5370. Figure~\ref{fig:x86-2}. It differs from x86$_1$ just in the addition
  5371. of the form for global variables.
  5372. %
  5373. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5374. \code{select-instructions} pass on the running example.
  5375. \begin{figure}[tbp]
  5376. \centering
  5377. \begin{minipage}{0.75\textwidth}
  5378. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5379. (program
  5380. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5381. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5382. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5383. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5384. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5385. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5386. ((block63 . (block ()
  5387. (movq (reg r15) (reg rdi))
  5388. (movq (int 16) (reg rsi))
  5389. (callq collect)
  5390. (jmp block61)))
  5391. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5392. (block61 . (block ()
  5393. (movq (global-value free_ptr) (var alloc43))
  5394. (addq (int 16) (global-value free_ptr))
  5395. (movq (var alloc43) (reg r11))
  5396. (movq (int 3) (deref r11 0))
  5397. (movq (var alloc43) (reg r11))
  5398. (movq (var vecinit44) (deref r11 8))
  5399. (movq (int 0) (var initret45))
  5400. (movq (var alloc43) (var vecinit48))
  5401. (movq (global-value free_ptr) (var tmp54))
  5402. (movq (var tmp54) (var tmp55))
  5403. (addq (int 16) (var tmp55))
  5404. (movq (global-value fromspace_end) (var tmp56))
  5405. (cmpq (var tmp56) (var tmp55))
  5406. (jmp-if l block59)
  5407. (jmp block60)))
  5408. (block60 . (block ()
  5409. (movq (reg r15) (reg rdi))
  5410. (movq (int 16) (reg rsi))
  5411. (callq collect)
  5412. (jmp block58))
  5413. (block59 . (block ()
  5414. (movq (int 0) (var collectret50))
  5415. (jmp block58)))
  5416. (block58 . (block ()
  5417. (movq (global-value free_ptr) (var alloc47))
  5418. (addq (int 16) (global-value free_ptr))
  5419. (movq (var alloc47) (reg r11))
  5420. (movq (int 131) (deref r11 0))
  5421. (movq (var alloc47) (reg r11))
  5422. (movq (var vecinit48) (deref r11 8))
  5423. (movq (int 0) (var initret49))
  5424. (movq (var alloc47) (reg r11))
  5425. (movq (deref r11 8) (var tmp57))
  5426. (movq (var tmp57) (reg r11))
  5427. (movq (deref r11 8) (reg rax))
  5428. (jmp conclusion)))
  5429. (start . (block ()
  5430. (movq (int 42) (var vecinit44))
  5431. (movq (global-value free_ptr) (var tmp51))
  5432. (movq (var tmp51) (var tmp52))
  5433. (addq (int 16) (var tmp52))
  5434. (movq (global-value fromspace_end) (var tmp53))
  5435. (cmpq (var tmp53) (var tmp52))
  5436. (jmp-if l block62)
  5437. (jmp block63))))))
  5438. \end{lstlisting}
  5439. \end{minipage}
  5440. \caption{Output of the \code{select-instructions} pass.}
  5441. \label{fig:select-instr-output-gc}
  5442. \end{figure}
  5443. \clearpage
  5444. \section{Register Allocation}
  5445. \label{sec:reg-alloc-gc}
  5446. As discussed earlier in this chapter, the garbage collector needs to
  5447. access all the pointers in the root set, that is, all variables that
  5448. are vectors. It will be the responsibility of the register allocator
  5449. to make sure that:
  5450. \begin{enumerate}
  5451. \item the root stack is used for spilling vector-typed variables, and
  5452. \item if a vector-typed variable is live during a call to the
  5453. collector, it must be spilled to ensure it is visible to the
  5454. collector.
  5455. \end{enumerate}
  5456. The later responsibility can be handled during construction of the
  5457. inference graph, by adding interference edges between the call-live
  5458. vector-typed variables and all the callee-saved registers. (They
  5459. already interfere with the caller-saved registers.) The type
  5460. information for variables is in the \code{program} form, so we
  5461. recommend adding another parameter to the \code{build-interference}
  5462. function to communicate this alist.
  5463. The spilling of vector-typed variables to the root stack can be
  5464. handled after graph coloring, when choosing how to assign the colors
  5465. (integers) to registers and stack locations. The \code{program} output
  5466. of this pass changes to also record the number of spills to the root
  5467. stack.
  5468. % build-interference
  5469. %
  5470. % callq
  5471. % extra parameter for var->type assoc. list
  5472. % update 'program' and 'if'
  5473. % allocate-registers
  5474. % allocate spilled vectors to the rootstack
  5475. % don't change color-graph
  5476. \section{Print x86}
  5477. \label{sec:print-x86-gc}
  5478. \margincomment{\scriptsize We need to show the translation to x86 and what
  5479. to do about global-value. \\ --Jeremy}
  5480. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5481. \code{print-x86} pass on the running example. In the prelude and
  5482. conclusion of the \code{main} function, we treat the root stack very
  5483. much like the regular stack in that we move the root stack pointer
  5484. (\code{r15}) to make room for all of the spills to the root stack,
  5485. except that the root stack grows up instead of down. For the running
  5486. example, there was just one spill so we increment \code{r15} by 8
  5487. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5488. One issue that deserves special care is that there may be a call to
  5489. \code{collect} prior to the initializing assignments for all the
  5490. variables in the root stack. We do not want the garbage collector to
  5491. accidentally think that some uninitialized variable is a pointer that
  5492. needs to be followed. Thus, we zero-out all locations on the root
  5493. stack in the prelude of \code{main}. In
  5494. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5495. %
  5496. \lstinline{movq $0, (%r15)}
  5497. %
  5498. accomplishes this task. The garbage collector tests each root to see
  5499. if it is null prior to dereferencing it.
  5500. \begin{figure}[htbp]
  5501. \begin{minipage}[t]{0.5\textwidth}
  5502. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5503. _block58:
  5504. movq _free_ptr(%rip), %rcx
  5505. addq $16, _free_ptr(%rip)
  5506. movq %rcx, %r11
  5507. movq $131, 0(%r11)
  5508. movq %rcx, %r11
  5509. movq -8(%r15), %rax
  5510. movq %rax, 8(%r11)
  5511. movq $0, %rdx
  5512. movq %rcx, %r11
  5513. movq 8(%r11), %rcx
  5514. movq %rcx, %r11
  5515. movq 8(%r11), %rax
  5516. jmp _conclusion
  5517. _block59:
  5518. movq $0, %rcx
  5519. jmp _block58
  5520. _block62:
  5521. movq $0, %rcx
  5522. jmp _block61
  5523. _block60:
  5524. movq %r15, %rdi
  5525. movq $16, %rsi
  5526. callq _collect
  5527. jmp _block58
  5528. _block63:
  5529. movq %r15, %rdi
  5530. movq $16, %rsi
  5531. callq _collect
  5532. jmp _block61
  5533. _start:
  5534. movq $42, %rbx
  5535. movq _free_ptr(%rip), %rdx
  5536. addq $16, %rdx
  5537. movq _fromspace_end(%rip), %rcx
  5538. cmpq %rcx, %rdx
  5539. jl _block62
  5540. jmp _block63
  5541. \end{lstlisting}
  5542. \end{minipage}
  5543. \begin{minipage}[t]{0.45\textwidth}
  5544. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5545. _block61:
  5546. movq _free_ptr(%rip), %rcx
  5547. addq $16, _free_ptr(%rip)
  5548. movq %rcx, %r11
  5549. movq $3, 0(%r11)
  5550. movq %rcx, %r11
  5551. movq %rbx, 8(%r11)
  5552. movq $0, %rdx
  5553. movq %rcx, -8(%r15)
  5554. movq _free_ptr(%rip), %rcx
  5555. addq $16, %rcx
  5556. movq _fromspace_end(%rip), %rdx
  5557. cmpq %rdx, %rcx
  5558. jl _block59
  5559. jmp _block60
  5560. .globl _main
  5561. _main:
  5562. pushq %rbp
  5563. movq %rsp, %rbp
  5564. pushq %r12
  5565. pushq %rbx
  5566. pushq %r13
  5567. pushq %r14
  5568. subq $0, %rsp
  5569. movq $16384, %rdi
  5570. movq $16, %rsi
  5571. callq _initialize
  5572. movq _rootstack_begin(%rip), %r15
  5573. movq $0, (%r15)
  5574. addq $8, %r15
  5575. jmp _start
  5576. _conclusion:
  5577. subq $8, %r15
  5578. addq $0, %rsp
  5579. popq %r14
  5580. popq %r13
  5581. popq %rbx
  5582. popq %r12
  5583. popq %rbp
  5584. retq
  5585. \end{lstlisting}
  5586. \end{minipage}
  5587. \caption{Output of the \code{print-x86} pass.}
  5588. \label{fig:print-x86-output-gc}
  5589. \end{figure}
  5590. \margincomment{\scriptsize Suggest an implementation strategy
  5591. in which the students first do the code gen and test that
  5592. without GC (just use a big heap), then after that is debugged,
  5593. implement the GC. \\ --Jeremy}
  5594. \begin{figure}[p]
  5595. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5596. \node (R3) at (0,2) {\large $R_3$};
  5597. \node (R3-2) at (3,2) {\large $R_3$};
  5598. \node (R3-3) at (6,2) {\large $R_3$};
  5599. \node (R3-4) at (9,2) {\large $R_3$};
  5600. \node (R3-5) at (9,0) {\large $R_3$};
  5601. \node (R3-6) at (6,0) {\large $R_3$};
  5602. \node (C2-4) at (3,-2) {\large $C_2$};
  5603. \node (C2-3) at (0,-2) {\large $C_2$};
  5604. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5605. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5606. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5607. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5608. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5609. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5610. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5611. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5612. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5613. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5614. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5615. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5616. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5617. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5618. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5619. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5620. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5621. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5622. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5623. \end{tikzpicture}
  5624. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5625. \label{fig:R3-passes}
  5626. \end{figure}
  5627. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5628. for the compilation of $R_3$.
  5629. \section{Challenge: Simple Structures}
  5630. \label{sec:simple-structures}
  5631. \begin{figure}[tbp]
  5632. \centering
  5633. \fbox{
  5634. \begin{minipage}{0.96\textwidth}
  5635. \[
  5636. \begin{array}{lcl}
  5637. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5638. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  5639. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5640. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  5641. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  5642. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5643. \mid (\key{and}\;\Exp\;\Exp)
  5644. \mid (\key{or}\;\Exp\;\Exp)
  5645. \mid (\key{not}\;\Exp) } \\
  5646. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5647. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  5648. &\mid& \gray{ (\key{vector}\;\Exp^{+})
  5649. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  5650. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  5651. &\mid& \gray{ (\key{void}) } \\
  5652. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type]^{*}))\\
  5653. R_3 &::=& \Def^{*} \; \Exp
  5654. \end{array}
  5655. \]
  5656. \end{minipage}
  5657. }
  5658. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  5659. (Figure~\ref{fig:r3-concrete-syntax}).}
  5660. \label{fig:r3s-concrete-syntax}
  5661. \end{figure}
  5662. \section{Challenge: Generational Collection}
  5663. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5664. \chapter{Functions}
  5665. \label{ch:functions}
  5666. This chapter studies the compilation of functions at the level of
  5667. abstraction of the C language. This corresponds to a subset of Typed
  5668. Racket in which only top-level function definitions are allowed. These
  5669. kind of functions are an important stepping stone to implementing
  5670. lexically-scoped functions in the form of \key{lambda} abstractions,
  5671. which is the topic of Chapter~\ref{ch:lambdas}.
  5672. \section{The $R_4$ Language}
  5673. The syntax for function definitions and function application is shown
  5674. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5675. Programs in $R_4$ start with zero or more function definitions. The
  5676. function names from these definitions are in-scope for the entire
  5677. program, including all other function definitions (so the ordering of
  5678. function definitions does not matter). The syntax for function
  5679. application does not include an explicit keyword, which is error prone
  5680. when using \code{match}. To alleviate this problem, we change the
  5681. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5682. during type checking.
  5683. Functions are first-class in the sense that a function pointer is data
  5684. and can be stored in memory or passed as a parameter to another
  5685. function. Thus, we introduce a function type, written
  5686. \begin{lstlisting}
  5687. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5688. \end{lstlisting}
  5689. for a function whose $n$ parameters have the types $\Type_1$ through
  5690. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5691. these functions (with respect to Racket functions) is that they are
  5692. not lexically scoped. That is, the only external entities that can be
  5693. referenced from inside a function body are other globally-defined
  5694. functions. The syntax of $R_4$ prevents functions from being nested
  5695. inside each other.
  5696. \begin{figure}[tp]
  5697. \centering
  5698. \fbox{
  5699. \begin{minipage}{0.96\textwidth}
  5700. \[
  5701. \begin{array}{lcl}
  5702. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5703. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5704. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5705. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5706. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5707. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5708. \mid (\key{and}\;\Exp\;\Exp)
  5709. \mid (\key{or}\;\Exp\;\Exp)
  5710. \mid (\key{not}\;\Exp)} \\
  5711. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5712. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5713. (\key{vector-ref}\;\Exp\;\Int)} \\
  5714. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5715. &\mid& (\Exp \; \Exp^{*}) \\
  5716. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5717. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5718. \end{array}
  5719. \]
  5720. \end{minipage}
  5721. }
  5722. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5723. with functions.}
  5724. \label{fig:r4-syntax}
  5725. \end{figure}
  5726. The program in Figure~\ref{fig:r4-function-example} is a
  5727. representative example of defining and using functions in $R_4$. We
  5728. define a function \code{map-vec} that applies some other function
  5729. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5730. vector containing the results. We also define a function \code{add1}
  5731. that does what its name suggests. The program then applies
  5732. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5733. \code{(vector 1 42)}, from which we return the \code{42}.
  5734. \begin{figure}[tbp]
  5735. \begin{lstlisting}
  5736. (program ()
  5737. (define (map-vec [f : (Integer -> Integer)]
  5738. [v : (Vector Integer Integer)])
  5739. : (Vector Integer Integer)
  5740. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5741. (define (add1 [x : Integer]) : Integer
  5742. (+ x 1))
  5743. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5744. )
  5745. \end{lstlisting}
  5746. \caption{Example of using functions in $R_4$.}
  5747. \label{fig:r4-function-example}
  5748. \end{figure}
  5749. The definitional interpreter for $R_4$ is in
  5750. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5751. responsible for setting up the mutual recursion between the top-level
  5752. function definitions. We use the classic back-patching approach that
  5753. uses mutable variables and makes two passes over the function
  5754. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5755. top-level environment using a mutable cons cell for each function
  5756. definition. Note that the \code{lambda} value for each function is
  5757. incomplete; it does not yet include the environment. Once the
  5758. top-level environment is constructed, we then iterate over it and
  5759. update the \code{lambda} value's to use the top-level environment.
  5760. \begin{figure}[tp]
  5761. \begin{lstlisting}
  5762. (define (interp-exp env)
  5763. (lambda (e)
  5764. (define recur (interp-exp env))
  5765. (match e
  5766. ...
  5767. [`(,fun ,args ...)
  5768. (define arg-vals (for/list ([e args]) (recur e)))
  5769. (define fun-val (recur fun))
  5770. (match fun-val
  5771. [`(lambda (,xs ...) ,body ,fun-env)
  5772. (define new-env (append (map cons xs arg-vals) fun-env))
  5773. ((interp-exp new-env) body)]
  5774. [else (error "interp-exp, expected function, not" fun-val)])]
  5775. [else (error 'interp-exp "unrecognized expression")]
  5776. )))
  5777. (define (interp-def d)
  5778. (match d
  5779. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5780. (mcons f `(lambda ,xs ,body ()))]
  5781. ))
  5782. (define (interp-R4 p)
  5783. (match p
  5784. [`(program ,ds ... ,body)
  5785. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5786. (for/list ([b top-level])
  5787. (set-mcdr! b (match (mcdr b)
  5788. [`(lambda ,xs ,body ())
  5789. `(lambda ,xs ,body ,top-level)])))
  5790. ((interp-exp top-level) body))]
  5791. ))
  5792. \end{lstlisting}
  5793. \caption{Interpreter for the $R_4$ language.}
  5794. \label{fig:interp-R4}
  5795. \end{figure}
  5796. \section{Functions in x86}
  5797. \label{sec:fun-x86}
  5798. \margincomment{\tiny Make sure callee-saved registers are discussed
  5799. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5800. \margincomment{\tiny Talk about the return address on the
  5801. stack and what callq and retq does.\\ --Jeremy }
  5802. The x86 architecture provides a few features to support the
  5803. implementation of functions. We have already seen that x86 provides
  5804. labels so that one can refer to the location of an instruction, as is
  5805. needed for jump instructions. Labels can also be used to mark the
  5806. beginning of the instructions for a function. Going further, we can
  5807. obtain the address of a label by using the \key{leaq} instruction and
  5808. \key{rip}-relative addressing. For example, the following puts the
  5809. address of the \code{add1} label into the \code{rbx} register.
  5810. \begin{lstlisting}
  5811. leaq add1(%rip), %rbx
  5812. \end{lstlisting}
  5813. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5814. instruction for jumping to a function whose location is given by a
  5815. label. Here we instead will be jumping to a function whose location is
  5816. given by an address, that is, we need to make an \emph{indirect
  5817. function call}. The x86 syntax is to give the register name prefixed
  5818. with an asterisk.
  5819. \begin{lstlisting}
  5820. callq *%rbx
  5821. \end{lstlisting}
  5822. \subsection{Calling Conventions}
  5823. The \code{callq} instruction provides partial support for implementing
  5824. functions, but it does not handle (1) parameter passing, (2) saving
  5825. and restoring frames on the procedure call stack, or (3) determining
  5826. how registers are shared by different functions. These issues require
  5827. coordination between the caller and the callee, which is often
  5828. assembly code written by different programmers or generated by
  5829. different compilers. As a result, people have developed
  5830. \emph{conventions} that govern how functions calls are performed.
  5831. Here we shall use the same conventions used by the \code{gcc}
  5832. compiler~\citep{Matz:2013aa}.
  5833. Regarding (1) parameter passing, the convention is to use the
  5834. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5835. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5836. than six arguments, then the convention is to use space on the frame
  5837. of the caller for the rest of the arguments. However, to ease the
  5838. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5839. we shall arrange to never have more than six arguments.
  5840. %
  5841. The register \code{rax} is for the return value of the function.
  5842. Regarding (2) frames and the procedure call stack, the convention is
  5843. that the stack grows down, with each function call using a chunk of
  5844. space called a frame. The caller sets the stack pointer, register
  5845. \code{rsp}, to the last data item in its frame. The callee must not
  5846. change anything in the caller's frame, that is, anything that is at or
  5847. above the stack pointer. The callee is free to use locations that are
  5848. below the stack pointer.
  5849. Regarding (3) the sharing of registers between different functions,
  5850. recall from Section~\ref{sec:calling-conventions} that the registers
  5851. are divided into two groups, the caller-saved registers and the
  5852. callee-saved registers. The caller should assume that all the
  5853. caller-saved registers get overwritten with arbitrary values by the
  5854. callee. Thus, the caller should either 1) not put values that are live
  5855. across a call in caller-saved registers, or 2) save and restore values
  5856. that are live across calls. We shall recommend option 1). On the flip
  5857. side, if the callee wants to use a callee-saved register, the callee
  5858. must save the contents of those registers on their stack frame and
  5859. then put them back prior to returning to the caller. The base
  5860. pointer, register \code{rbp}, is used as a point-of-reference within a
  5861. frame, so that each local variable can be accessed at a fixed offset
  5862. from the base pointer.
  5863. %
  5864. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5865. frames.
  5866. %% If we were to use stack arguments, they would be between the
  5867. %% caller locals and the callee return address.
  5868. \begin{figure}[tbp]
  5869. \centering
  5870. \begin{tabular}{r|r|l|l} \hline
  5871. Caller View & Callee View & Contents & Frame \\ \hline
  5872. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5873. 0(\key{\%rbp}) & & old \key{rbp} \\
  5874. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5875. \ldots & & \ldots \\
  5876. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5877. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5878. \ldots & & \ldots \\
  5879. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5880. %% & & \\
  5881. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5882. %% & \ldots & \ldots \\
  5883. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5884. \hline
  5885. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5886. & 0(\key{\%rbp}) & old \key{rbp} \\
  5887. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5888. & \ldots & \ldots \\
  5889. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5890. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5891. & \ldots & \ldots \\
  5892. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5893. \end{tabular}
  5894. \caption{Memory layout of caller and callee frames.}
  5895. \label{fig:call-frames}
  5896. \end{figure}
  5897. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5898. %% local variables and for storing the values of callee-saved registers
  5899. %% (we shall refer to all of these collectively as ``locals''), and that
  5900. %% at the beginning of a function we move the stack pointer \code{rsp}
  5901. %% down to make room for them.
  5902. %% We recommend storing the local variables
  5903. %% first and then the callee-saved registers, so that the local variables
  5904. %% can be accessed using \code{rbp} the same as before the addition of
  5905. %% functions.
  5906. %% To make additional room for passing arguments, we shall
  5907. %% move the stack pointer even further down. We count how many stack
  5908. %% arguments are needed for each function call that occurs inside the
  5909. %% body of the function and find their maximum. Adding this number to the
  5910. %% number of locals gives us how much the \code{rsp} should be moved at
  5911. %% the beginning of the function. In preparation for a function call, we
  5912. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5913. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5914. %% so on.
  5915. %% Upon calling the function, the stack arguments are retrieved by the
  5916. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5917. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5918. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5919. %% the layout of the caller and callee frames. Notice how important it is
  5920. %% that we correctly compute the maximum number of arguments needed for
  5921. %% function calls; if that number is too small then the arguments and
  5922. %% local variables will smash into each other!
  5923. \subsection{Efficient Tail Calls}
  5924. \label{sec:tail-call}
  5925. In general, the amount of stack space used by a program is determined
  5926. by the longest chain of nested function calls. That is, if function
  5927. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5928. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5929. $n$ can grow quite large in the case of recursive or mutually
  5930. recursive functions. However, in some cases we can arrange to use only
  5931. constant space, i.e. $O(1)$, instead of $O(n)$.
  5932. If a function call is the last action in a function body, then that
  5933. call is said to be a \emph{tail call}. In such situations, the frame
  5934. of the caller is no longer needed, so we can pop the caller's frame
  5935. before making the tail call. With this approach, a recursive function
  5936. that only makes tail calls will only use $O(1)$ stack space.
  5937. Functional languages like Racket typically rely heavily on recursive
  5938. functions, so they typically guarantee that all tail calls will be
  5939. optimized in this way.
  5940. However, some care is needed with regards to argument passing in tail
  5941. calls. As mentioned above, for arguments beyond the sixth, the
  5942. convention is to use space in the caller's frame for passing
  5943. arguments. But here we've popped the caller's frame and can no longer
  5944. use it. Another alternative is to use space in the callee's frame for
  5945. passing arguments. However, this option is also problematic because
  5946. the caller and callee's frame overlap in memory. As we begin to copy
  5947. the arguments from their sources in the caller's frame, the target
  5948. locations in the callee's frame might overlap with the sources for
  5949. later arguments! We solve this problem by not using the stack for
  5950. parameter passing but instead use the heap, as we describe in the
  5951. Section~\ref{sec:limit-functions-r4}.
  5952. As mentioned above, for a tail call we pop the caller's frame prior to
  5953. making the tail call. The instructions for popping a frame are the
  5954. instructions that we usually place in the conclusion of a
  5955. function. Thus, we also need to place such code immediately before
  5956. each tail call. These instructions include restoring the callee-saved
  5957. registers, so it is good that the argument passing registers are all
  5958. caller-saved registers.
  5959. One last note regarding which instruction to use to make the tail
  5960. call. When the callee is finished, it should not return to the current
  5961. function, but it should return to the function that called the current
  5962. one. Thus, the return address that is already on the stack is the
  5963. right one, and we should not use \key{callq} to make the tail call, as
  5964. that would unnecessarily overwrite the return address. Instead we can
  5965. simply use the \key{jmp} instruction. Like the indirect function call,
  5966. we write an indirect jump with a register prefixed with an asterisk.
  5967. We recommend using \code{rax} to hold the jump target because the
  5968. preceding ``conclusion'' overwrites just about everything else.
  5969. \begin{lstlisting}
  5970. jmp *%rax
  5971. \end{lstlisting}
  5972. %% Now that we have a good understanding of functions as they appear in
  5973. %% $R_4$ and the support for functions in x86, we need to plan the
  5974. %% changes to our compiler, that is, do we need any new passes and/or do
  5975. %% we need to change any existing passes? Also, do we need to add new
  5976. %% kinds of AST nodes to any of the intermediate languages?
  5977. \section{Shrink $R_4$}
  5978. \label{sec:shrink-r4}
  5979. The \code{shrink} pass performs a couple minor modifications to the
  5980. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5981. field to each function definition:
  5982. \begin{lstlisting}
  5983. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5984. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5985. \end{lstlisting}
  5986. and introduces an explicit \code{main} function.\\
  5987. \begin{tabular}{lll}
  5988. \begin{minipage}{0.45\textwidth}
  5989. \begin{lstlisting}
  5990. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5991. \end{lstlisting}
  5992. \end{minipage}
  5993. &
  5994. $\Rightarrow$
  5995. &
  5996. \begin{minipage}{0.45\textwidth}
  5997. \begin{lstlisting}
  5998. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5999. \end{lstlisting}
  6000. \end{minipage}
  6001. \end{tabular} \\
  6002. where $\itm{mainDef}$ is
  6003. \begin{lstlisting}
  6004. (define (main) : Integer () |$\Exp'$|)
  6005. \end{lstlisting}
  6006. \section{Reveal Functions and the $F_1$ language}
  6007. \label{sec:reveal-functions-r4}
  6008. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  6009. compilation because it conflates the use of function names and local
  6010. variables. This is a problem because we need to compile the use of a
  6011. function name differently than the use of a local variable; we need to
  6012. use \code{leaq} to convert the function name (a label in x86) to an
  6013. address in a register. Thus, it is a good idea to create a new pass
  6014. that changes function references from just a symbol $f$ to
  6015. \code{(fun-ref $f$)}. A good name for this pass is
  6016. \code{reveal-functions} and the output language, $F_1$, is defined in
  6017. Figure~\ref{fig:f1-syntax}.
  6018. \begin{figure}[tp]
  6019. \centering
  6020. \fbox{
  6021. \begin{minipage}{0.96\textwidth}
  6022. \[
  6023. \begin{array}{lcl}
  6024. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6025. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6026. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  6027. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  6028. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  6029. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6030. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6031. (\key{vector-ref}\;\Exp\;\Int)} \\
  6032. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  6033. (\key{app}\; \Exp \; \Exp^{*})} \\
  6034. &\mid& (\key{fun-ref}\, \itm{label}) \\
  6035. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6036. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  6037. \end{array}
  6038. \]
  6039. \end{minipage}
  6040. }
  6041. \caption{The $F_1$ language, an extension of $R_4$
  6042. (Figure~\ref{fig:r4-syntax}).}
  6043. \label{fig:f1-syntax}
  6044. \end{figure}
  6045. %% Distinguishing between calls in tail position and non-tail position
  6046. %% requires the pass to have some notion of context. We recommend using
  6047. %% two mutually recursive functions, one for processing expressions in
  6048. %% tail position and another for the rest.
  6049. Placing this pass after \code{uniquify} is a good idea, because it
  6050. will make sure that there are no local variables and functions that
  6051. share the same name. On the other hand, \code{reveal-functions} needs
  6052. to come before the \code{explicate-control} pass because that pass
  6053. will help us compile \code{fun-ref} into assignment statements.
  6054. \section{Limit Functions}
  6055. \label{sec:limit-functions-r4}
  6056. This pass transforms functions so that they have at most six
  6057. parameters and transforms all function calls so that they pass at most
  6058. six arguments. A simple strategy for imposing an argument limit of
  6059. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  6060. into a vector, making that subsequent vector the $n$th argument.
  6061. \begin{tabular}{lll}
  6062. \begin{minipage}{0.2\textwidth}
  6063. \begin{lstlisting}
  6064. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  6065. \end{lstlisting}
  6066. \end{minipage}
  6067. &
  6068. $\Rightarrow$
  6069. &
  6070. \begin{minipage}{0.4\textwidth}
  6071. \begin{lstlisting}
  6072. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  6073. \end{lstlisting}
  6074. \end{minipage}
  6075. \end{tabular}
  6076. In the body of the function, all occurrences of the $i$th argument in
  6077. which $i>5$ must be replaced with a \code{vector-ref}.
  6078. \section{Remove Complex Operators and Operands}
  6079. \label{sec:rco-r4}
  6080. The primary decisions to make for this pass is whether to classify
  6081. \code{fun-ref} and \code{app} as either simple or complex
  6082. expressions. Recall that a simple expression will eventually end up as
  6083. just an ``immediate'' argument of an x86 instruction. Function
  6084. application will be translated to a sequence of instructions, so
  6085. \code{app} must be classified as complex expression. Regarding
  6086. \code{fun-ref}, as discussed above, the function label needs to
  6087. be converted to an address using the \code{leaq} instruction. Thus,
  6088. even though \code{fun-ref} seems rather simple, it needs to be
  6089. classified as a complex expression so that we generate an assignment
  6090. statement with a left-hand side that can serve as the target of the
  6091. \code{leaq}.
  6092. \section{Explicate Control and the $C_3$ language}
  6093. \label{sec:explicate-control-r4}
  6094. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  6095. \key{explicate-control}. The three mutually recursive functions for
  6096. this pass, for assignment, tail, and predicate contexts, must all be
  6097. updated with cases for \code{fun-ref} and \code{app}. In
  6098. assignment and predicate contexts, \code{app} becomes \code{call},
  6099. whereas in tail position \code{app} becomes \code{tailcall}. We
  6100. recommend defining a new function for processing function definitions.
  6101. This code is similar to the case for \code{program} in $R_3$. The
  6102. top-level \code{explicate-control} function that handles the
  6103. \code{program} form of $R_4$ can then apply this new function to all
  6104. the function definitions.
  6105. \begin{figure}[tp]
  6106. \fbox{
  6107. \begin{minipage}{0.96\textwidth}
  6108. \[
  6109. \begin{array}{lcl}
  6110. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6111. \\
  6112. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6113. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  6114. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  6115. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6116. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  6117. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6118. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  6119. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6120. \mid (\key{collect} \,\itm{int}) }\\
  6121. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6122. &\mid& \gray{(\key{goto}\,\itm{label})
  6123. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6124. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  6125. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  6126. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  6127. \end{array}
  6128. \]
  6129. \end{minipage}
  6130. }
  6131. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  6132. \label{fig:c3-syntax}
  6133. \end{figure}
  6134. \section{Uncover Locals}
  6135. \label{sec:uncover-locals-r4}
  6136. The function for processing $\Tail$ should be updated with a case for
  6137. \code{tailcall}. We also recommend creating a new function for
  6138. processing function definitions. Each function definition in $C_3$ has
  6139. its own set of local variables, so the code for function definitions
  6140. should be similar to the case for the \code{program} form in $C_2$.
  6141. \section{Select Instructions and the x86$_3$ Language}
  6142. \label{sec:select-r4}
  6143. The output of select instructions is a program in the x86$_3$
  6144. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6145. \begin{figure}[tp]
  6146. \fbox{
  6147. \begin{minipage}{0.96\textwidth}
  6148. \[
  6149. \begin{array}{lcl}
  6150. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6151. \mid (\key{deref}\,\Reg\,\Int) } \\
  6152. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6153. \mid (\key{global-value}\; \itm{name}) } \\
  6154. &\mid& (\key{fun-ref}\; \itm{label})\\
  6155. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6156. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6157. (\key{subq} \; \Arg\; \Arg) \mid
  6158. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6159. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6160. (\key{pushq}\;\Arg) \mid
  6161. (\key{popq}\;\Arg) \mid
  6162. (\key{retq}) } \\
  6163. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6164. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6165. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6166. \mid (\key{jmp} \; \itm{label})
  6167. \mid (\key{j}\itm{cc} \; \itm{label})
  6168. \mid (\key{label} \; \itm{label}) } \\
  6169. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6170. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  6171. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  6172. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  6173. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  6174. \end{array}
  6175. \]
  6176. \end{minipage}
  6177. }
  6178. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6179. \label{fig:x86-3}
  6180. \end{figure}
  6181. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  6182. as follows: \\
  6183. \begin{tabular}{lll}
  6184. \begin{minipage}{0.45\textwidth}
  6185. \begin{lstlisting}
  6186. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  6187. \end{lstlisting}
  6188. \end{minipage}
  6189. &
  6190. $\Rightarrow$
  6191. &
  6192. \begin{minipage}{0.4\textwidth}
  6193. \begin{lstlisting}
  6194. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  6195. \end{lstlisting}
  6196. \end{minipage}
  6197. \end{tabular} \\
  6198. Regarding function definitions, we need to remove their parameters and
  6199. instead perform parameter passing in terms of the conventions
  6200. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  6201. in the argument passing registers, and inside the function we should
  6202. generate a \code{movq} instruction for each parameter, to move the
  6203. argument value from the appropriate register to a new local variable
  6204. with the same name as the old parameter.
  6205. Next, consider the compilation of function calls, which have the
  6206. following form upon input to \code{select-instructions}.
  6207. \begin{lstlisting}
  6208. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  6209. \end{lstlisting}
  6210. In the mirror image of handling the parameters of function
  6211. definitions, the arguments \itm{args} need to be moved to the argument
  6212. passing registers.
  6213. %
  6214. Once the instructions for parameter passing have been generated, the
  6215. function call itself can be performed with an indirect function call,
  6216. for which I recommend creating the new instruction
  6217. \code{indirect-callq}. Of course, the return value from the function
  6218. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  6219. \begin{lstlisting}
  6220. (indirect-callq |\itm{fun}|)
  6221. (movq (reg rax) |\itm{lhs}|)
  6222. \end{lstlisting}
  6223. Regarding tail calls, the parameter passing is the same as non-tail
  6224. calls: generate instructions to move the arguments into to the
  6225. argument passing registers. After that we need to pop the frame from
  6226. the procedure call stack. However, we do not yet know how big the
  6227. frame is; that gets determined during register allocation. So instead
  6228. of generating those instructions here, we invent a new instruction
  6229. that means ``pop the frame and then do an indirect jump'', which we
  6230. name \code{tail-jmp}.
  6231. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6232. using the label \code{start} for the initial block of a program, and
  6233. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6234. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  6235. can be compiled to an assignment to \code{rax} followed by a jump to
  6236. \code{conclusion}. With the addition of function definitions, we will
  6237. have a starting block and conclusion for each function, but their
  6238. labels need to be unique. We recommend prepending the function's name
  6239. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6240. labels. (Alternatively, one could \code{gensym} labels for the start
  6241. and conclusion and store them in the $\itm{info}$ field of the
  6242. function definition.)
  6243. \section{Uncover Live}
  6244. %% The rest of the passes need only minor modifications to handle the new
  6245. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6246. %% \code{leaq}.
  6247. Inside \code{uncover-live}, when computing the $W$ set (written
  6248. variables) for an \code{indirect-callq} instruction, we recommend
  6249. including all the caller-saved registers, which will have the affect
  6250. of making sure that no caller-saved register actually needs to be
  6251. saved.
  6252. \section{Build Interference Graph}
  6253. With the addition of function definitions, we compute an interference
  6254. graph for each function (not just one for the whole program).
  6255. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6256. spill vector-typed variables that are live during a call to the
  6257. \code{collect}. With the addition of functions to our language, we
  6258. need to revisit this issue. Many functions will perform allocation and
  6259. therefore have calls to the collector inside of them. Thus, we should
  6260. not only spill a vector-typed variable when it is live during a call
  6261. to \code{collect}, but we should spill the variable if it is live
  6262. during any function call. Thus, in the \code{build-interference} pass,
  6263. we recommend adding interference edges between call-live vector-typed
  6264. variables and the callee-saved registers (in addition to the usual
  6265. addition of edges between call-live variables and the caller-saved
  6266. registers).
  6267. \section{Patch Instructions}
  6268. In \code{patch-instructions}, you should deal with the x86
  6269. idiosyncrasy that the destination argument of \code{leaq} must be a
  6270. register. Additionally, you should ensure that the argument of
  6271. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  6272. code generation more convenient, because we will be trampling many
  6273. registers before the tail call (as explained below).
  6274. \section{Print x86}
  6275. For the \code{print-x86} pass, we recommend the following translations:
  6276. \begin{lstlisting}
  6277. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6278. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6279. \end{lstlisting}
  6280. Handling \code{tail-jmp} requires a bit more care. A straightforward
  6281. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  6282. is what we will want to do, but before the jump we need to pop the
  6283. current frame. So we need to restore the state of the registers to the
  6284. point they were at when the current function was called. This
  6285. sequence of instructions is the same as the code for the conclusion of
  6286. a function.
  6287. Note that your \code{print-x86} pass needs to add the code for saving
  6288. and restoring callee-saved registers, if you have not already
  6289. implemented that. This is necessary when generating code for function
  6290. definitions.
  6291. \section{An Example Translation}
  6292. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6293. function in $R_4$ to x86. The figure also includes the results of the
  6294. \code{explicate-control} and \code{select-instructions} passes. We
  6295. have omitted the \code{has-type} AST nodes for readability. Can you
  6296. see any ways to improve the translation?
  6297. \begin{figure}[tbp]
  6298. \begin{tabular}{ll}
  6299. \begin{minipage}{0.45\textwidth}
  6300. % s3_2.rkt
  6301. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6302. (program
  6303. (define (add [x : Integer]
  6304. [y : Integer])
  6305. : Integer (+ x y))
  6306. (add 40 2))
  6307. \end{lstlisting}
  6308. $\Downarrow$
  6309. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6310. (program ()
  6311. (define (add86 [x87 : Integer]
  6312. [y88 : Integer]) : Integer ()
  6313. ((add86start . (return (+ x87 y88)))))
  6314. (define (main) : Integer ()
  6315. ((mainstart .
  6316. (seq (assign tmp89 (fun-ref add86))
  6317. (tailcall tmp89 40 2))))))
  6318. \end{lstlisting}
  6319. \end{minipage}
  6320. &
  6321. $\Rightarrow$
  6322. \begin{minipage}{0.5\textwidth}
  6323. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6324. (program ()
  6325. (define (add86)
  6326. ((locals (x87 . Integer) (y88 . Integer))
  6327. (num-params . 2))
  6328. ((add86start .
  6329. (block ()
  6330. (movq (reg rcx) (var x87))
  6331. (movq (reg rdx) (var y88))
  6332. (movq (var x87) (reg rax))
  6333. (addq (var y88) (reg rax))
  6334. (jmp add86conclusion)))))
  6335. (define (main)
  6336. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6337. (num-params . 0))
  6338. ((mainstart .
  6339. (block ()
  6340. (leaq (fun-ref add86) (var tmp89))
  6341. (movq (int 40) (reg rcx))
  6342. (movq (int 2) (reg rdx))
  6343. (tail-jmp (var tmp89))))))
  6344. \end{lstlisting}
  6345. $\Downarrow$
  6346. \end{minipage}
  6347. \end{tabular}
  6348. \begin{tabular}{lll}
  6349. \begin{minipage}{0.3\textwidth}
  6350. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6351. _add90start:
  6352. movq %rcx, %rsi
  6353. movq %rdx, %rcx
  6354. movq %rsi, %rax
  6355. addq %rcx, %rax
  6356. jmp _add90conclusion
  6357. .globl _add90
  6358. .align 16
  6359. _add90:
  6360. pushq %rbp
  6361. movq %rsp, %rbp
  6362. pushq %r12
  6363. pushq %rbx
  6364. pushq %r13
  6365. pushq %r14
  6366. subq $0, %rsp
  6367. jmp _add90start
  6368. _add90conclusion:
  6369. addq $0, %rsp
  6370. popq %r14
  6371. popq %r13
  6372. popq %rbx
  6373. popq %r12
  6374. subq $0, %r15
  6375. popq %rbp
  6376. retq
  6377. \end{lstlisting}
  6378. \end{minipage}
  6379. &
  6380. \begin{minipage}{0.3\textwidth}
  6381. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6382. _mainstart:
  6383. leaq _add90(%rip), %rsi
  6384. movq $40, %rcx
  6385. movq $2, %rdx
  6386. movq %rsi, %rax
  6387. addq $0, %rsp
  6388. popq %r14
  6389. popq %r13
  6390. popq %rbx
  6391. popq %r12
  6392. subq $0, %r15
  6393. popq %rbp
  6394. jmp *%rax
  6395. .globl _main
  6396. .align 16
  6397. _main:
  6398. pushq %rbp
  6399. movq %rsp, %rbp
  6400. pushq %r12
  6401. pushq %rbx
  6402. pushq %r13
  6403. pushq %r14
  6404. subq $0, %rsp
  6405. movq $16384, %rdi
  6406. movq $16, %rsi
  6407. callq _initialize
  6408. movq _rootstack_begin(%rip), %r15
  6409. jmp _mainstart
  6410. \end{lstlisting}
  6411. \end{minipage}
  6412. &
  6413. \begin{minipage}{0.3\textwidth}
  6414. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6415. _mainconclusion:
  6416. addq $0, %rsp
  6417. popq %r14
  6418. popq %r13
  6419. popq %rbx
  6420. popq %r12
  6421. subq $0, %r15
  6422. popq %rbp
  6423. retq
  6424. \end{lstlisting}
  6425. \end{minipage}
  6426. \end{tabular}
  6427. \caption{Example compilation of a simple function to x86.}
  6428. \label{fig:add-fun}
  6429. \end{figure}
  6430. \begin{exercise}\normalfont
  6431. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6432. Create 5 new programs that use functions, including examples that pass
  6433. functions and return functions from other functions and including
  6434. recursive functions. Test your compiler on these new programs and all
  6435. of your previously created test programs.
  6436. \end{exercise}
  6437. \begin{figure}[p]
  6438. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6439. \node (R4) at (0,2) {\large $R_4$};
  6440. \node (R4-2) at (3,2) {\large $R_4$};
  6441. \node (R4-3) at (6,2) {\large $R_4$};
  6442. \node (F1-1) at (12,0) {\large $F_1$};
  6443. \node (F1-2) at (9,0) {\large $F_1$};
  6444. \node (F1-3) at (6,0) {\large $F_1$};
  6445. \node (F1-4) at (3,0) {\large $F_1$};
  6446. \node (C3-1) at (6,-2) {\large $C_3$};
  6447. \node (C3-2) at (3,-2) {\large $C_3$};
  6448. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6449. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6450. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6451. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6452. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6453. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6454. \path[->,bend left=15] (R4) edge [above] node
  6455. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6456. \path[->,bend left=15] (R4-2) edge [above] node
  6457. {\ttfamily\footnotesize uniquify} (R4-3);
  6458. \path[->,bend left=15] (R4-3) edge [right] node
  6459. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6460. \path[->,bend left=15] (F1-1) edge [below] node
  6461. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6462. \path[->,bend right=15] (F1-2) edge [above] node
  6463. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6464. \path[->,bend right=15] (F1-3) edge [above] node
  6465. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6466. \path[->,bend left=15] (F1-4) edge [right] node
  6467. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6468. \path[->,bend left=15] (C3-1) edge [below] node
  6469. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6470. \path[->,bend right=15] (C3-2) edge [left] node
  6471. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6472. \path[->,bend left=15] (x86-2) edge [left] node
  6473. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6474. \path[->,bend right=15] (x86-2-1) edge [below] node
  6475. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6476. \path[->,bend right=15] (x86-2-2) edge [left] node
  6477. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6478. \path[->,bend left=15] (x86-3) edge [above] node
  6479. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6480. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6481. \end{tikzpicture}
  6482. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6483. \label{fig:R4-passes}
  6484. \end{figure}
  6485. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6486. the compilation of $R_4$.
  6487. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6488. \chapter{Lexically Scoped Functions}
  6489. \label{ch:lambdas}
  6490. This chapter studies lexically scoped functions as they appear in
  6491. functional languages such as Racket. By lexical scoping we mean that a
  6492. function's body may refer to variables whose binding site is outside
  6493. of the function, in an enclosing scope.
  6494. %
  6495. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6496. anonymous function defined using the \key{lambda} form. The body of
  6497. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6498. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6499. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6500. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6501. returned from the function \code{f}. Below the definition of \code{f},
  6502. we have two calls to \code{f} with different arguments for \code{x},
  6503. first \code{5} then \code{3}. The functions returned from \code{f} are
  6504. bound to variables \code{g} and \code{h}. Even though these two
  6505. functions were created by the same \code{lambda}, they are really
  6506. different functions because they use different values for
  6507. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6508. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6509. the result of this program is \code{42}.
  6510. \begin{figure}[btp]
  6511. % s4_6.rkt
  6512. \begin{lstlisting}
  6513. (define (f [x : Integer]) : (Integer -> Integer)
  6514. (let ([y 4])
  6515. (lambda: ([z : Integer]) : Integer
  6516. (+ x (+ y z)))))
  6517. (let ([g (f 5)])
  6518. (let ([h (f 3)])
  6519. (+ (g 11) (h 15))))
  6520. \end{lstlisting}
  6521. \caption{Example of a lexically scoped function.}
  6522. \label{fig:lexical-scoping}
  6523. \end{figure}
  6524. \section{The $R_5$ Language}
  6525. The syntax for this language with anonymous functions and lexical
  6526. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6527. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6528. for function application. In this chapter we shall describe how to
  6529. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6530. into a combination of functions (as in $R_4$) and tuples (as in
  6531. $R_3$).
  6532. \begin{figure}[tp]
  6533. \centering
  6534. \fbox{
  6535. \begin{minipage}{0.96\textwidth}
  6536. \[
  6537. \begin{array}{lcl}
  6538. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6539. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6540. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6541. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6542. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6543. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6544. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6545. \mid (\key{and}\;\Exp\;\Exp)
  6546. \mid (\key{or}\;\Exp\;\Exp)
  6547. \mid (\key{not}\;\Exp) } \\
  6548. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6549. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6550. (\key{vector-ref}\;\Exp\;\Int)} \\
  6551. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6552. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6553. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6554. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6555. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6556. \end{array}
  6557. \]
  6558. \end{minipage}
  6559. }
  6560. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6561. with \key{lambda}.}
  6562. \label{fig:r5-syntax}
  6563. \end{figure}
  6564. To compile lexically-scoped functions to top-level function
  6565. definitions, the compiler will need to provide special treatment to
  6566. variable occurrences such as \code{x} and \code{y} in the body of the
  6567. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6568. of $R_4$ may not refer to variables defined outside the function. To
  6569. identify such variable occurrences, we review the standard notion of
  6570. free variable.
  6571. \begin{definition}
  6572. A variable is \emph{free with respect to an expression} $e$ if the
  6573. variable occurs inside $e$ but does not have an enclosing binding in
  6574. $e$.
  6575. \end{definition}
  6576. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6577. free with respect to the expression \code{(+ x (+ y z))}. On the
  6578. other hand, only \code{x} and \code{y} are free with respect to the
  6579. following expression because \code{z} is bound by the \code{lambda}.
  6580. \begin{lstlisting}
  6581. (lambda: ([z : Integer]) : Integer
  6582. (+ x (+ y z)))
  6583. \end{lstlisting}
  6584. Once we have identified the free variables of a \code{lambda}, we need
  6585. to arrange for some way to transport, at runtime, the values of those
  6586. variables from the point where the \code{lambda} was created to the
  6587. point where the \code{lambda} is applied. Referring again to
  6588. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6589. needs to be used in the application of \code{g} to \code{11}, but the
  6590. binding of \code{x} to \code{3} needs to be used in the application of
  6591. \code{h} to \code{15}. An efficient solution to the problem, due to
  6592. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6593. free variables together with the function pointer for the lambda's
  6594. code, an arrangement called a \emph{flat closure} (which we shorten to
  6595. just ``closure'') . Fortunately, we have all the ingredients to make
  6596. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6597. Chapter~\ref{ch:functions} gave us function pointers. The function
  6598. pointer shall reside at index $0$ and the values for free variables
  6599. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6600. the two closures created by the two calls to \code{f} in
  6601. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6602. the same \key{lambda}, they share the same function pointer but differ
  6603. in the values for the free variable \code{x}.
  6604. \begin{figure}[tbp]
  6605. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6606. \caption{Example closure representation for the \key{lambda}'s
  6607. in Figure~\ref{fig:lexical-scoping}.}
  6608. \label{fig:closures}
  6609. \end{figure}
  6610. \section{Interpreting $R_5$}
  6611. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6612. $R_5$. The clause for \key{lambda} saves the current environment
  6613. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6614. the environment from the \key{lambda}, the \code{lam-env}, when
  6615. interpreting the body of the \key{lambda}. The \code{lam-env}
  6616. environment is extended with the mapping of parameters to argument
  6617. values.
  6618. \begin{figure}[tbp]
  6619. \begin{lstlisting}
  6620. (define (interp-exp env)
  6621. (lambda (e)
  6622. (define recur (interp-exp env))
  6623. (match e
  6624. ...
  6625. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6626. `(lambda ,xs ,body ,env)]
  6627. [`(app ,fun ,args ...)
  6628. (define fun-val ((interp-exp env) fun))
  6629. (define arg-vals (map (interp-exp env) args))
  6630. (match fun-val
  6631. [`(lambda (,xs ...) ,body ,lam-env)
  6632. (define new-env (append (map cons xs arg-vals) lam-env))
  6633. ((interp-exp new-env) body)]
  6634. [else (error "interp-exp, expected function, not" fun-val)])]
  6635. [else (error 'interp-exp "unrecognized expression")]
  6636. )))
  6637. \end{lstlisting}
  6638. \caption{Interpreter for $R_5$.}
  6639. \label{fig:interp-R5}
  6640. \end{figure}
  6641. \section{Type Checking $R_5$}
  6642. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6643. \key{lambda} form. The body of the \key{lambda} is checked in an
  6644. environment that includes the current environment (because it is
  6645. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6646. require the body's type to match the declared return type.
  6647. \begin{figure}[tbp]
  6648. \begin{lstlisting}
  6649. (define (typecheck-R5 env)
  6650. (lambda (e)
  6651. (match e
  6652. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6653. (define new-env (append (map cons xs Ts) env))
  6654. (define bodyT ((typecheck-R5 new-env) body))
  6655. (cond [(equal? rT bodyT)
  6656. `(,@Ts -> ,rT)]
  6657. [else
  6658. (error "mismatch in return type" bodyT rT)])]
  6659. ...
  6660. )))
  6661. \end{lstlisting}
  6662. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6663. \label{fig:typecheck-R5}
  6664. \end{figure}
  6665. \section{Closure Conversion}
  6666. The compiling of lexically-scoped functions into top-level function
  6667. definitions is accomplished in the pass \code{convert-to-closures}
  6668. that comes after \code{reveal-functions} and before
  6669. \code{limit-functions}.
  6670. As usual, we shall implement the pass as a recursive function over the
  6671. AST. All of the action is in the clauses for \key{lambda} and
  6672. \key{app}. We transform a \key{lambda} expression into an expression
  6673. that creates a closure, that is, creates a vector whose first element
  6674. is a function pointer and the rest of the elements are the free
  6675. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6676. generated to identify the function.
  6677. \begin{tabular}{lll}
  6678. \begin{minipage}{0.4\textwidth}
  6679. \begin{lstlisting}
  6680. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6681. \end{lstlisting}
  6682. \end{minipage}
  6683. &
  6684. $\Rightarrow$
  6685. &
  6686. \begin{minipage}{0.4\textwidth}
  6687. \begin{lstlisting}
  6688. (vector |\itm{name}| |\itm{fvs}| ...)
  6689. \end{lstlisting}
  6690. \end{minipage}
  6691. \end{tabular} \\
  6692. %
  6693. In addition to transforming each \key{lambda} into a \key{vector}, we
  6694. must create a top-level function definition for each \key{lambda}, as
  6695. shown below.\\
  6696. \begin{minipage}{0.8\textwidth}
  6697. \begin{lstlisting}
  6698. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6699. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6700. ...
  6701. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6702. |\itm{body'}|)...))
  6703. \end{lstlisting}
  6704. \end{minipage}\\
  6705. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6706. parameters are the normal parameters of the \key{lambda}. The types
  6707. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6708. underscore is a dummy type because it is rather difficult to give a
  6709. type to the function in the closure's type, and it does not matter.
  6710. The sequence of \key{let} forms bind the free variables to their
  6711. values obtained from the closure.
  6712. We transform function application into code that retrieves the
  6713. function pointer from the closure and then calls the function, passing
  6714. in the closure as the first argument. We bind $e'$ to a temporary
  6715. variable to avoid code duplication.
  6716. \begin{tabular}{lll}
  6717. \begin{minipage}{0.3\textwidth}
  6718. \begin{lstlisting}
  6719. (app |$e$| |\itm{es}| ...)
  6720. \end{lstlisting}
  6721. \end{minipage}
  6722. &
  6723. $\Rightarrow$
  6724. &
  6725. \begin{minipage}{0.5\textwidth}
  6726. \begin{lstlisting}
  6727. (let ([|\itm{tmp}| |$e'$|])
  6728. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6729. \end{lstlisting}
  6730. \end{minipage}
  6731. \end{tabular} \\
  6732. There is also the question of what to do with top-level function
  6733. definitions. To maintain a uniform translation of function
  6734. application, we turn function references into closures.
  6735. \begin{tabular}{lll}
  6736. \begin{minipage}{0.3\textwidth}
  6737. \begin{lstlisting}
  6738. (fun-ref |$f$|)
  6739. \end{lstlisting}
  6740. \end{minipage}
  6741. &
  6742. $\Rightarrow$
  6743. &
  6744. \begin{minipage}{0.5\textwidth}
  6745. \begin{lstlisting}
  6746. (vector (fun-ref |$f$|))
  6747. \end{lstlisting}
  6748. \end{minipage}
  6749. \end{tabular} \\
  6750. %
  6751. The top-level function definitions need to be updated as well to take
  6752. an extra closure parameter.
  6753. \section{An Example Translation}
  6754. \label{sec:example-lambda}
  6755. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6756. conversion for the example program demonstrating lexical scoping that
  6757. we discussed at the beginning of this chapter.
  6758. \begin{figure}[h]
  6759. \begin{minipage}{0.8\textwidth}
  6760. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6761. (program
  6762. (define (f [x : Integer]) : (Integer -> Integer)
  6763. (let ([y 4])
  6764. (lambda: ([z : Integer]) : Integer
  6765. (+ x (+ y z)))))
  6766. (let ([g (f 5)])
  6767. (let ([h (f 3)])
  6768. (+ (g 11) (h 15)))))
  6769. \end{lstlisting}
  6770. $\Downarrow$
  6771. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6772. (program (type Integer)
  6773. (define (f (x : Integer)) : (Integer -> Integer)
  6774. (let ((y 4))
  6775. (lambda: ((z : Integer)) : Integer
  6776. (+ x (+ y z)))))
  6777. (let ((g (app (fun-ref f) 5)))
  6778. (let ((h (app (fun-ref f) 3)))
  6779. (+ (app g 11) (app h 15)))))
  6780. \end{lstlisting}
  6781. $\Downarrow$
  6782. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6783. (program (type Integer)
  6784. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6785. (let ((y 4))
  6786. (vector (fun-ref lam.1) x y)))
  6787. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6788. (let ((x (vector-ref clos.2 1)))
  6789. (let ((y (vector-ref clos.2 2)))
  6790. (+ x (+ y z)))))
  6791. (let ((g (let ((t.1 (vector (fun-ref f))))
  6792. (app (vector-ref t.1 0) t.1 5))))
  6793. (let ((h (let ((t.2 (vector (fun-ref f))))
  6794. (app (vector-ref t.2 0) t.2 3))))
  6795. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6796. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6797. \end{lstlisting}
  6798. \end{minipage}
  6799. \caption{Example of closure conversion.}
  6800. \label{fig:lexical-functions-example}
  6801. \end{figure}
  6802. \begin{figure}[p]
  6803. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6804. \node (R4) at (0,2) {\large $R_4$};
  6805. \node (R4-2) at (3,2) {\large $R_4$};
  6806. \node (R4-3) at (6,2) {\large $R_4$};
  6807. \node (F1-1) at (12,0) {\large $F_1$};
  6808. \node (F1-2) at (9,0) {\large $F_1$};
  6809. \node (F1-3) at (6,0) {\large $F_1$};
  6810. \node (F1-4) at (3,0) {\large $F_1$};
  6811. \node (F1-5) at (0,0) {\large $F_1$};
  6812. \node (C3-1) at (6,-2) {\large $C_3$};
  6813. \node (C3-2) at (3,-2) {\large $C_3$};
  6814. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6815. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6816. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6817. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6818. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6819. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6820. \path[->,bend left=15] (R4) edge [above] node
  6821. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6822. \path[->,bend left=15] (R4-2) edge [above] node
  6823. {\ttfamily\footnotesize uniquify} (R4-3);
  6824. \path[->] (R4-3) edge [right] node
  6825. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6826. \path[->,bend left=15] (F1-1) edge [below] node
  6827. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6828. \path[->,bend right=15] (F1-2) edge [above] node
  6829. {\ttfamily\footnotesize limit-functions} (F1-3);
  6830. \path[->,bend right=15] (F1-3) edge [above] node
  6831. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6832. \path[->,bend right=15] (F1-4) edge [above] node
  6833. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6834. \path[->] (F1-5) edge [left] node
  6835. {\ttfamily\footnotesize explicate-control} (C3-1);
  6836. \path[->,bend left=15] (C3-1) edge [below] node
  6837. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6838. \path[->,bend right=15] (C3-2) edge [left] node
  6839. {\ttfamily\footnotesize select-instr.} (x86-2);
  6840. \path[->,bend left=15] (x86-2) edge [left] node
  6841. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6842. \path[->,bend right=15] (x86-2-1) edge [below] node
  6843. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6844. \path[->,bend right=15] (x86-2-2) edge [left] node
  6845. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6846. \path[->,bend left=15] (x86-3) edge [above] node
  6847. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6848. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6849. \end{tikzpicture}
  6850. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6851. functions.}
  6852. \label{fig:R5-passes}
  6853. \end{figure}
  6854. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6855. for the compilation of $R_5$.
  6856. \begin{exercise}\normalfont
  6857. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6858. Create 5 new programs that use \key{lambda} functions and make use of
  6859. lexical scoping. Test your compiler on these new programs and all of
  6860. your previously created test programs.
  6861. \end{exercise}
  6862. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6863. \chapter{Dynamic Typing}
  6864. \label{ch:type-dynamic}
  6865. In this chapter we discuss the compilation of a dynamically typed
  6866. language, named $R_7$, that is a subset of the Racket
  6867. language. (Recall that in the previous chapters we have studied
  6868. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6869. languages, an expression may produce values of differing
  6870. type. Consider the following example with a conditional expression
  6871. that may return a Boolean or an integer depending on the input to the
  6872. program.
  6873. \begin{lstlisting}
  6874. (not (if (eq? (read) 1) #f 0))
  6875. \end{lstlisting}
  6876. Languages that allow expressions to produce different kinds of values
  6877. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6878. such as subtype polymorphism and parametric
  6879. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6880. talking about here does not have a special name, but it is the usual
  6881. kind that arises in dynamically typed languages.
  6882. Another characteristic of dynamically typed languages is that
  6883. primitive operations, such as \code{not}, are often defined to operate
  6884. on many different types of values. In fact, in Racket, the \code{not}
  6885. operator produces a result for any kind of value: given \code{\#f} it
  6886. returns \code{\#t} and given anything else it returns \code{\#f}.
  6887. Furthermore, even when primitive operations restrict their inputs to
  6888. values of a certain type, this restriction is enforced at runtime
  6889. instead of during compilation. For example, the following vector
  6890. reference results in a run-time contract violation.
  6891. \begin{lstlisting}
  6892. (vector-ref (vector 42) #t)
  6893. \end{lstlisting}
  6894. \begin{figure}[tp]
  6895. \centering
  6896. \fbox{
  6897. \begin{minipage}{0.97\textwidth}
  6898. \[
  6899. \begin{array}{rcl}
  6900. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6901. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6902. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6903. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6904. &\mid& \key{\#t} \mid \key{\#f}
  6905. \mid (\key{and}\;\Exp\;\Exp)
  6906. \mid (\key{or}\;\Exp\;\Exp)
  6907. \mid (\key{not}\;\Exp) \\
  6908. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6909. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6910. (\key{vector-ref}\;\Exp\;\Exp) \\
  6911. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6912. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6913. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6914. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6915. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6916. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6917. \end{array}
  6918. \]
  6919. \end{minipage}
  6920. }
  6921. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6922. \label{fig:r7-syntax}
  6923. \end{figure}
  6924. The syntax of $R_7$, our subset of Racket, is defined in
  6925. Figure~\ref{fig:r7-syntax}.
  6926. %
  6927. The definitional interpreter for $R_7$ is given in
  6928. Figure~\ref{fig:interp-R7}.
  6929. \begin{figure}[tbp]
  6930. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6931. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6932. (define (valid-op? op) (member op '(+ - and or not)))
  6933. (define (interp-r7 env)
  6934. (lambda (ast)
  6935. (define recur (interp-r7 env))
  6936. (match ast
  6937. [(? symbol?) (lookup ast env)]
  6938. [(? integer?) `(inject ,ast Integer)]
  6939. [#t `(inject #t Boolean)]
  6940. [#f `(inject #f Boolean)]
  6941. [`(read) `(inject ,(read-fixnum) Integer)]
  6942. [`(lambda (,xs ...) ,body)
  6943. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6944. [`(define (,f ,xs ...) ,body)
  6945. (mcons f `(lambda ,xs ,body))]
  6946. [`(program ,ds ... ,body)
  6947. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6948. (for/list ([b top-level])
  6949. (set-mcdr! b (match (mcdr b)
  6950. [`(lambda ,xs ,body)
  6951. `(inject (lambda ,xs ,body ,top-level)
  6952. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6953. ((interp-r7 top-level) body))]
  6954. [`(vector ,(app recur elts) ...)
  6955. (define tys (map get-tagged-type elts))
  6956. `(inject ,(apply vector elts) (Vector ,@tys))]
  6957. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6958. (match v1
  6959. [`(inject ,vec ,ty)
  6960. (vector-set! vec n v2)
  6961. `(inject (void) Void)])]
  6962. [`(vector-ref ,(app recur v) ,n)
  6963. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6964. [`(let ([,x ,(app recur v)]) ,body)
  6965. ((interp-r7 (cons (cons x v) env)) body)]
  6966. [`(,op ,es ...) #:when (valid-op? op)
  6967. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6968. [`(eq? ,(app recur l) ,(app recur r))
  6969. `(inject ,(equal? l r) Boolean)]
  6970. [`(if ,(app recur q) ,t ,f)
  6971. (match q
  6972. [`(inject #f Boolean) (recur f)]
  6973. [else (recur t)])]
  6974. [`(,(app recur f-val) ,(app recur vs) ...)
  6975. (match f-val
  6976. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6977. (define new-env (append (map cons xs vs) lam-env))
  6978. ((interp-r7 new-env) body)]
  6979. [else (error "interp-r7, expected function, not" f-val)])])))
  6980. \end{lstlisting}
  6981. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6982. \label{fig:interp-R7}
  6983. \end{figure}
  6984. Let us consider how we might compile $R_7$ to x86, thinking about the
  6985. first example above. Our bit-level representation of the Boolean
  6986. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6987. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6988. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6989. general, cannot be determined at compile time, but depends on the
  6990. runtime type of its input, as in the example above that depends on the
  6991. result of \code{(read)}.
  6992. The way around this problem is to include information about a value's
  6993. runtime type in the value itself, so that this information can be
  6994. inspected by operators such as \code{not}. In particular, we shall
  6995. steal the 3 right-most bits from our 64-bit values to encode the
  6996. runtime type. We shall use $001$ to identify integers, $100$ for
  6997. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6998. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6999. define the following auxiliary function.
  7000. \begin{align*}
  7001. \itm{tagof}(\key{Integer}) &= 001 \\
  7002. \itm{tagof}(\key{Boolean}) &= 100 \\
  7003. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7004. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7005. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7006. \itm{tagof}(\key{Void}) &= 101
  7007. \end{align*}
  7008. (We shall say more about the new \key{Vectorof} type shortly.)
  7009. This stealing of 3 bits comes at some
  7010. price: our integers are reduced to ranging from $-2^{60}$ to
  7011. $2^{60}$. The stealing does not adversely affect vectors and
  7012. procedures because those values are addresses, and our addresses are
  7013. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7014. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7015. bits with the tag and we can simply zero-out the tag to recover the
  7016. original address.
  7017. In some sense, these tagged values are a new kind of value. Indeed,
  7018. we can extend our \emph{typed} language with tagged values by adding a
  7019. new type to classify them, called \key{Any}, and with operations for
  7020. creating and using tagged values, yielding the $R_6$ language that we
  7021. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7022. fundamental support for polymorphism and runtime types that we need to
  7023. support dynamic typing.
  7024. There is an interesting interaction between tagged values and garbage
  7025. collection. A variable of type \code{Any} might refer to a vector and
  7026. therefore it might be a root that needs to be inspected and copied
  7027. during garbage collection. Thus, we need to treat variables of type
  7028. \code{Any} in a similar way to variables of type \code{Vector} for
  7029. purposes of register allocation, which we discuss in
  7030. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7031. variable of type \code{Any} is spilled, it must be spilled to the root
  7032. stack. But this means that the garbage collector needs to be able to
  7033. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7034. value that points to a tuple, and (3) a tagged value that is not a
  7035. tuple. We enable this differentiation by choosing not to use the tag
  7036. $000$. Instead, that bit pattern is reserved for identifying plain old
  7037. pointers to tuples. On the other hand, if one of the first three bits
  7038. is set, then we have a tagged value, and inspecting the tag can
  7039. differentiation between vectors ($010$) and the other kinds of values.
  7040. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  7041. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7042. extend our compiler to handle the new features of $R_6$
  7043. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7044. \ref{sec:register-allocation-r6}).
  7045. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7046. \label{sec:r6-lang}
  7047. \begin{figure}[tp]
  7048. \centering
  7049. \fbox{
  7050. \begin{minipage}{0.97\textwidth}
  7051. \[
  7052. \begin{array}{lcl}
  7053. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7054. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7055. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  7056. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  7057. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  7058. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7059. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7060. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7061. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7062. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7063. \mid (\key{and}\;\Exp\;\Exp)
  7064. \mid (\key{or}\;\Exp\;\Exp)
  7065. \mid (\key{not}\;\Exp)} \\
  7066. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7067. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  7068. (\key{vector-ref}\;\Exp\;\Int)} \\
  7069. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7070. &\mid& \gray{(\Exp \; \Exp^{*})
  7071. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  7072. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7073. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7074. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7075. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  7076. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  7077. \end{array}
  7078. \]
  7079. \end{minipage}
  7080. }
  7081. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7082. with \key{Any}.}
  7083. \label{fig:r6-syntax}
  7084. \end{figure}
  7085. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7086. $(\key{inject}\; e\; T)$ form converts the value produced by
  7087. expression $e$ of type $T$ into a tagged value. The
  7088. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7089. expression $e$ into a value of type $T$ or else halts the program if
  7090. the type tag is equivalent to $T$. We treat
  7091. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7092. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7093. Note that in both \key{inject} and
  7094. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7095. which simplifies the implementation and corresponds with what is
  7096. needed for compiling untyped Racket. The type predicates,
  7097. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7098. if the tag corresponds to the predicate, and return \key{\#t}
  7099. otherwise.
  7100. %
  7101. Selections from the type checker for $R_6$ are shown in
  7102. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7103. Figure~\ref{fig:interp-R6}.
  7104. \begin{figure}[btp]
  7105. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7106. (define (flat-ty? ty) ...)
  7107. (define (typecheck-R6 env)
  7108. (lambda (e)
  7109. (define recur (typecheck-R6 env))
  7110. (match e
  7111. [`(inject ,e ,ty)
  7112. (unless (flat-ty? ty)
  7113. (error "may only inject a value of flat type, not ~a" ty))
  7114. (define-values (new-e e-ty) (recur e))
  7115. (cond
  7116. [(equal? e-ty ty)
  7117. (values `(inject ,new-e ,ty) 'Any)]
  7118. [else
  7119. (error "inject expected ~a to have type ~a" e ty)])]
  7120. [`(project ,e ,ty)
  7121. (unless (flat-ty? ty)
  7122. (error "may only project to a flat type, not ~a" ty))
  7123. (define-values (new-e e-ty) (recur e))
  7124. (cond
  7125. [(equal? e-ty 'Any)
  7126. (values `(project ,new-e ,ty) ty)]
  7127. [else
  7128. (error "project expected ~a to have type Any" e)])]
  7129. [`(vector-ref ,e ,i)
  7130. (define-values (new-e e-ty) (recur e))
  7131. (match e-ty
  7132. [`(Vector ,ts ...) ...]
  7133. [`(Vectorof ,ty)
  7134. (unless (exact-nonnegative-integer? i)
  7135. (error 'type-check "invalid index ~a" i))
  7136. (values `(vector-ref ,new-e ,i) ty)]
  7137. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7138. ...
  7139. )))
  7140. \end{lstlisting}
  7141. \caption{Type checker for parts of the $R_6$ language.}
  7142. \label{fig:typecheck-R6}
  7143. \end{figure}
  7144. % to do: add rules for vector-ref, etc. for Vectorof
  7145. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7146. \begin{figure}[btp]
  7147. \begin{lstlisting}
  7148. (define primitives (set 'boolean? ...))
  7149. (define (interp-op op)
  7150. (match op
  7151. ['boolean? (lambda (v)
  7152. (match v
  7153. [`(tagged ,v1 Boolean) #t]
  7154. [else #f]))]
  7155. ...))
  7156. ;; Equivalence of flat types
  7157. (define (tyeq? t1 t2)
  7158. (match `(,t1 ,t2)
  7159. [`((Vectorof Any) (Vector ,t2s ...))
  7160. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7161. [`((Vector ,t1s ...) (Vectorof Any))
  7162. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7163. [else (equal? t1 t2)]))
  7164. (define (interp-R6 env)
  7165. (lambda (ast)
  7166. (match ast
  7167. [`(inject ,e ,t)
  7168. `(tagged ,((interp-R6 env) e) ,t)]
  7169. [`(project ,e ,t2)
  7170. (define v ((interp-R6 env) e))
  7171. (match v
  7172. [`(tagged ,v1 ,t1)
  7173. (cond [(tyeq? t1 t2)
  7174. v1]
  7175. [else
  7176. (error "in project, type mismatch" t1 t2)])]
  7177. [else
  7178. (error "in project, expected tagged value" v)])]
  7179. ...)))
  7180. \end{lstlisting}
  7181. \caption{Interpreter for $R_6$.}
  7182. \label{fig:interp-R6}
  7183. \end{figure}
  7184. %\clearpage
  7185. \section{Shrinking $R_6$}
  7186. \label{sec:shrink-r6}
  7187. In the \code{shrink} pass we recommend compiling \code{project} into
  7188. an explicit \code{if} expression that uses three new operations:
  7189. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7190. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7191. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7192. value from a tagged value. Finally, the \code{exit} operation ends the
  7193. execution of the program by invoking the operating system's
  7194. \code{exit} function. So the translation for \code{project} is as
  7195. follows. (We have omitted the \code{has-type} AST nodes to make this
  7196. output more readable.)
  7197. \begin{tabular}{lll}
  7198. \begin{minipage}{0.3\textwidth}
  7199. \begin{lstlisting}
  7200. (project |$e$| |$\Type$|)
  7201. \end{lstlisting}
  7202. \end{minipage}
  7203. &
  7204. $\Rightarrow$
  7205. &
  7206. \begin{minipage}{0.5\textwidth}
  7207. \begin{lstlisting}
  7208. (let ([|$\itm{tmp}$| |$e'$|])
  7209. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7210. (value-of-any |$\itm{tmp}$|)
  7211. (exit)))
  7212. \end{lstlisting}
  7213. \end{minipage}
  7214. \end{tabular} \\
  7215. Similarly, we recommend translating the type predicates
  7216. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7217. \section{Instruction Selection for $R_6$}
  7218. \label{sec:select-r6}
  7219. \paragraph{Inject}
  7220. We recommend compiling an \key{inject} as follows if the type is
  7221. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7222. destination to the left by the number of bits specified its source
  7223. argument (in this case $3$, the length of the tag) and it preserves
  7224. the sign of the integer. We use the \key{orq} instruction to combine
  7225. the tag and the value to form the tagged value. \\
  7226. \begin{tabular}{lll}
  7227. \begin{minipage}{0.4\textwidth}
  7228. \begin{lstlisting}
  7229. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7230. \end{lstlisting}
  7231. \end{minipage}
  7232. &
  7233. $\Rightarrow$
  7234. &
  7235. \begin{minipage}{0.5\textwidth}
  7236. \begin{lstlisting}
  7237. (movq |$e'$| |\itm{lhs}'|)
  7238. (salq (int 3) |\itm{lhs}'|)
  7239. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7240. \end{lstlisting}
  7241. \end{minipage}
  7242. \end{tabular} \\
  7243. The instruction selection for vectors and procedures is different
  7244. because their is no need to shift them to the left. The rightmost 3
  7245. bits are already zeros as described above. So we just combine the
  7246. value and the tag using \key{orq}. \\
  7247. \begin{tabular}{lll}
  7248. \begin{minipage}{0.4\textwidth}
  7249. \begin{lstlisting}
  7250. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7251. \end{lstlisting}
  7252. \end{minipage}
  7253. &
  7254. $\Rightarrow$
  7255. &
  7256. \begin{minipage}{0.5\textwidth}
  7257. \begin{lstlisting}
  7258. (movq |$e'$| |\itm{lhs}'|)
  7259. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7260. \end{lstlisting}
  7261. \end{minipage}
  7262. \end{tabular}
  7263. \paragraph{Tag of Any}
  7264. Recall that the \code{tag-of-any} operation extracts the type tag from
  7265. a value of type \code{Any}. The type tag is the bottom three bits, so
  7266. we obtain the tag by taking the bitwise-and of the value with $111$
  7267. ($7$ in decimal).
  7268. \begin{tabular}{lll}
  7269. \begin{minipage}{0.4\textwidth}
  7270. \begin{lstlisting}
  7271. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7272. \end{lstlisting}
  7273. \end{minipage}
  7274. &
  7275. $\Rightarrow$
  7276. &
  7277. \begin{minipage}{0.5\textwidth}
  7278. \begin{lstlisting}
  7279. (movq |$e'$| |\itm{lhs}'|)
  7280. (andq (int 7) |\itm{lhs}'|)
  7281. \end{lstlisting}
  7282. \end{minipage}
  7283. \end{tabular}
  7284. \paragraph{Value of Any}
  7285. Like \key{inject}, the instructions for \key{value-of-any} are
  7286. different depending on whether the type $T$ is a pointer (vector or
  7287. procedure) or not (Integer or Boolean). The following shows the
  7288. instruction selection for Integer and Boolean. We produce an untagged
  7289. value by shifting it to the right by 3 bits.
  7290. %
  7291. \\
  7292. \begin{tabular}{lll}
  7293. \begin{minipage}{0.4\textwidth}
  7294. \begin{lstlisting}
  7295. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7296. \end{lstlisting}
  7297. \end{minipage}
  7298. &
  7299. $\Rightarrow$
  7300. &
  7301. \begin{minipage}{0.5\textwidth}
  7302. \begin{lstlisting}
  7303. (movq |$e'$| |\itm{lhs}'|)
  7304. (sarq (int 3) |\itm{lhs}'|)
  7305. \end{lstlisting}
  7306. \end{minipage}
  7307. \end{tabular} \\
  7308. %
  7309. In the case for vectors and procedures, there is no need to
  7310. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7311. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7312. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7313. \code{movq} into the destination $\itm{lhs}$. We then generate
  7314. \code{andq} with the tagged value to get the desired result. \\
  7315. %
  7316. \begin{tabular}{lll}
  7317. \begin{minipage}{0.4\textwidth}
  7318. \begin{lstlisting}
  7319. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7320. \end{lstlisting}
  7321. \end{minipage}
  7322. &
  7323. $\Rightarrow$
  7324. &
  7325. \begin{minipage}{0.5\textwidth}
  7326. \begin{lstlisting}
  7327. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7328. (andq |$e'$| |\itm{lhs}'|)
  7329. \end{lstlisting}
  7330. \end{minipage}
  7331. \end{tabular}
  7332. %% \paragraph{Type Predicates} We leave it to the reader to
  7333. %% devise a sequence of instructions to implement the type predicates
  7334. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7335. \section{Register Allocation for $R_6$}
  7336. \label{sec:register-allocation-r6}
  7337. As mentioned above, a variable of type \code{Any} might refer to a
  7338. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7339. of type \code{Any} in the same way that it treats variables of type
  7340. \code{Vector} for purposes of garbage collection. In particular,
  7341. \begin{itemize}
  7342. \item If a variable of type \code{Any} is live during a function call,
  7343. then it must be spilled. One way to accomplish this is to augment
  7344. the pass \code{build-interference} to mark all variables that are
  7345. live after a \code{callq} as interfering with all the registers.
  7346. \item If a variable of type \code{Any} is spilled, it must be spilled
  7347. to the root stack instead of the normal procedure call stack.
  7348. \end{itemize}
  7349. \begin{exercise}\normalfont
  7350. Expand your compiler to handle $R_6$ as discussed in the last few
  7351. sections. Create 5 new programs that use the \code{Any} type and the
  7352. new operations (\code{inject}, \code{project}, \code{boolean?},
  7353. etc.). Test your compiler on these new programs and all of your
  7354. previously created test programs.
  7355. \end{exercise}
  7356. \section{Compiling $R_7$ to $R_6$}
  7357. \label{sec:compile-r7}
  7358. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7359. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7360. given a subexpression $e$ of $R_7$, the pass will produce an
  7361. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7362. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7363. the Boolean \code{\#t}, which must be injected to produce an
  7364. expression of type \key{Any}.
  7365. %
  7366. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7367. addition, is representative of compilation for many operations: the
  7368. arguments have type \key{Any} and must be projected to \key{Integer}
  7369. before the addition can be performed.
  7370. The compilation of \key{lambda} (third row of
  7371. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7372. produce type annotations: we simply use \key{Any}.
  7373. %
  7374. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7375. has to account for some differences in behavior between $R_7$ and
  7376. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7377. kind of values can be used in various places. For example, the
  7378. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7379. the arguments need not be of the same type (but in that case, the
  7380. result will be \code{\#f}).
  7381. \begin{figure}[btp]
  7382. \centering
  7383. \begin{tabular}{|lll|} \hline
  7384. \begin{minipage}{0.25\textwidth}
  7385. \begin{lstlisting}
  7386. #t
  7387. \end{lstlisting}
  7388. \end{minipage}
  7389. &
  7390. $\Rightarrow$
  7391. &
  7392. \begin{minipage}{0.6\textwidth}
  7393. \begin{lstlisting}
  7394. (inject #t Boolean)
  7395. \end{lstlisting}
  7396. \end{minipage}
  7397. \\[2ex]\hline
  7398. \begin{minipage}{0.25\textwidth}
  7399. \begin{lstlisting}
  7400. (+ |$e_1$| |$e_2$|)
  7401. \end{lstlisting}
  7402. \end{minipage}
  7403. &
  7404. $\Rightarrow$
  7405. &
  7406. \begin{minipage}{0.6\textwidth}
  7407. \begin{lstlisting}
  7408. (inject
  7409. (+ (project |$e'_1$| Integer)
  7410. (project |$e'_2$| Integer))
  7411. Integer)
  7412. \end{lstlisting}
  7413. \end{minipage}
  7414. \\[2ex]\hline
  7415. \begin{minipage}{0.25\textwidth}
  7416. \begin{lstlisting}
  7417. (lambda (|$x_1 \ldots$|) |$e$|)
  7418. \end{lstlisting}
  7419. \end{minipage}
  7420. &
  7421. $\Rightarrow$
  7422. &
  7423. \begin{minipage}{0.6\textwidth}
  7424. \begin{lstlisting}
  7425. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7426. (Any|$\ldots$|Any -> Any))
  7427. \end{lstlisting}
  7428. \end{minipage}
  7429. \\[2ex]\hline
  7430. \begin{minipage}{0.25\textwidth}
  7431. \begin{lstlisting}
  7432. (app |$e_0$| |$e_1 \ldots e_n$|)
  7433. \end{lstlisting}
  7434. \end{minipage}
  7435. &
  7436. $\Rightarrow$
  7437. &
  7438. \begin{minipage}{0.6\textwidth}
  7439. \begin{lstlisting}
  7440. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7441. |$e'_1 \ldots e'_n$|)
  7442. \end{lstlisting}
  7443. \end{minipage}
  7444. \\[2ex]\hline
  7445. \begin{minipage}{0.25\textwidth}
  7446. \begin{lstlisting}
  7447. (vector-ref |$e_1$| |$e_2$|)
  7448. \end{lstlisting}
  7449. \end{minipage}
  7450. &
  7451. $\Rightarrow$
  7452. &
  7453. \begin{minipage}{0.6\textwidth}
  7454. \begin{lstlisting}
  7455. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7456. (let ([tmp2 (project |$e'_2$| Integer)])
  7457. (vector-ref tmp1 tmp2)))
  7458. \end{lstlisting}
  7459. \end{minipage}
  7460. \\[2ex]\hline
  7461. \begin{minipage}{0.25\textwidth}
  7462. \begin{lstlisting}
  7463. (if |$e_1$| |$e_2$| |$e_3$|)
  7464. \end{lstlisting}
  7465. \end{minipage}
  7466. &
  7467. $\Rightarrow$
  7468. &
  7469. \begin{minipage}{0.6\textwidth}
  7470. \begin{lstlisting}
  7471. (if (eq? |$e'_1$| (inject #f Boolean))
  7472. |$e'_3$|
  7473. |$e'_2$|)
  7474. \end{lstlisting}
  7475. \end{minipage}
  7476. \\[2ex]\hline
  7477. \begin{minipage}{0.25\textwidth}
  7478. \begin{lstlisting}
  7479. (eq? |$e_1$| |$e_2$|)
  7480. \end{lstlisting}
  7481. \end{minipage}
  7482. &
  7483. $\Rightarrow$
  7484. &
  7485. \begin{minipage}{0.6\textwidth}
  7486. \begin{lstlisting}
  7487. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7488. \end{lstlisting}
  7489. \end{minipage}
  7490. \\[2ex]\hline
  7491. \end{tabular}
  7492. \caption{Compiling $R_7$ to $R_6$.}
  7493. \label{fig:compile-r7-r6}
  7494. \end{figure}
  7495. \begin{exercise}\normalfont
  7496. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7497. Create tests for $R_7$ by adapting all of your previous test programs
  7498. by removing type annotations. Add 5 more tests programs that
  7499. specifically rely on the language being dynamically typed. That is,
  7500. they should not be legal programs in a statically typed language, but
  7501. nevertheless, they should be valid $R_7$ programs that run to
  7502. completion without error.
  7503. \end{exercise}
  7504. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7505. \chapter{Gradual Typing}
  7506. \label{ch:gradual-typing}
  7507. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7508. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7509. \chapter{Parametric Polymorphism}
  7510. \label{ch:parametric-polymorphism}
  7511. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7512. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7513. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7514. \chapter{High-level Optimization}
  7515. \label{ch:high-level-optimization}
  7516. This chapter will present a procedure inlining pass based on the
  7517. algorithm of \citet{Waddell:1997fk}.
  7518. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7519. \chapter{Appendix}
  7520. \section{Interpreters}
  7521. \label{appendix:interp}
  7522. We provide several interpreters in the \key{interp.rkt} file. The
  7523. \key{interp-scheme} function takes an AST in one of the Racket-like
  7524. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7525. the program, returning the result value. The \key{interp-C} function
  7526. interprets an AST for a program in one of the C-like languages ($C_0,
  7527. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7528. for an x86 program.
  7529. \section{Utility Functions}
  7530. \label{appendix:utilities}
  7531. The utility function described in this section can be found in the
  7532. \key{utilities.rkt} file.
  7533. The \key{read-program} function takes a file path and parses that file
  7534. (it must be a Racket program) into an abstract syntax tree with a
  7535. \key{Program} node at the top.
  7536. The \key{parse-program} function takes an S-expression representation
  7537. of an AST and converts it into the struct-based representation.
  7538. The \key{assert} function displays the error message \key{msg} if the
  7539. Boolean \key{bool} is false.
  7540. \begin{lstlisting}
  7541. (define (assert msg bool) ...)
  7542. \end{lstlisting}
  7543. % remove discussion of lookup? -Jeremy
  7544. The \key{lookup} function takes a key and an alist, and returns the
  7545. first value that is associated with the given key, if there is one. If
  7546. not, an error is triggered. The alist may contain both immutable
  7547. pairs (built with \key{cons}) and mutable pairs (built with
  7548. \key{mcons}).
  7549. The \key{map2} function ...
  7550. %% \subsection{Graphs}
  7551. %% \begin{itemize}
  7552. %% \item The \code{make-graph} function takes a list of vertices
  7553. %% (symbols) and returns a graph.
  7554. %% \item The \code{add-edge} function takes a graph and two vertices and
  7555. %% adds an edge to the graph that connects the two vertices. The graph
  7556. %% is updated in-place. There is no return value for this function.
  7557. %% \item The \code{adjacent} function takes a graph and a vertex and
  7558. %% returns the set of vertices that are adjacent to the given
  7559. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7560. %% used with functions from the \code{racket/set} module.
  7561. %% \item The \code{vertices} function takes a graph and returns the list
  7562. %% of vertices in the graph.
  7563. %% \end{itemize}
  7564. \subsection{Testing}
  7565. The \key{interp-tests} function takes a compiler name (a string), a
  7566. description of the passes, an interpreter for the source language, a
  7567. test family name (a string), and a list of test numbers, and runs the
  7568. compiler passes and the interpreters to check whether the passes
  7569. correct. The description of the passes is a list with one entry per
  7570. pass. An entry is a list with three things: a string giving the name
  7571. of the pass, the function that implements the pass (a translator from
  7572. AST to AST), and a function that implements the interpreter (a
  7573. function from AST to result value) for the language of the output of
  7574. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7575. good choice. The \key{interp-tests} function assumes that the
  7576. subdirectory \key{tests} has a collection of Scheme programs whose names
  7577. all start with the family name, followed by an underscore and then the
  7578. test number, ending in \key{.scm}. Also, for each Scheme program there
  7579. is a file with the same number except that it ends with \key{.in} that
  7580. provides the input for the Scheme program.
  7581. \begin{lstlisting}
  7582. (define (interp-tests name passes test-family test-nums) ...)
  7583. \end{lstlisting}
  7584. The compiler-tests function takes a compiler name (a string) a
  7585. description of the passes (as described above for
  7586. \code{interp-tests}), a test family name (a string), and a list of
  7587. test numbers (see the comment for interp-tests), and runs the compiler
  7588. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7589. machine code. It runs the machine code and checks that the output is
  7590. 42.
  7591. \begin{lstlisting}
  7592. (define (compiler-tests name passes test-family test-nums) ...)
  7593. \end{lstlisting}
  7594. The compile-file function takes a description of the compiler passes
  7595. (see the comment for \key{interp-tests}) and returns a function that,
  7596. given a program file name (a string ending in \key{.scm}), applies all
  7597. of the passes and writes the output to a file whose name is the same
  7598. as the program file name but with \key{.scm} replaced with \key{.s}.
  7599. \begin{lstlisting}
  7600. (define (compile-file passes)
  7601. (lambda (prog-file-name) ...))
  7602. \end{lstlisting}
  7603. \section{x86 Instruction Set Quick-Reference}
  7604. \label{sec:x86-quick-reference}
  7605. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7606. do. We write $A \to B$ to mean that the value of $A$ is written into
  7607. location $B$. Address offsets are given in bytes. The instruction
  7608. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7609. registers (such as $\%rax$), or memory references (such as
  7610. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7611. reference per instruction. Other operands must be immediates or
  7612. registers.
  7613. \begin{table}[tbp]
  7614. \centering
  7615. \begin{tabular}{l|l}
  7616. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7617. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7618. \texttt{negq} $A$ & $- A \to A$ \\
  7619. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7620. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7621. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7622. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7623. \texttt{retq} & Pops the return address and jumps to it \\
  7624. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7625. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7626. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7627. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7628. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7629. matches the condition code of the instruction, otherwise go to the
  7630. next instructions. The condition codes are \key{e} for ``equal'',
  7631. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7632. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7633. \texttt{jl} $L$ & \\
  7634. \texttt{jle} $L$ & \\
  7635. \texttt{jg} $L$ & \\
  7636. \texttt{jge} $L$ & \\
  7637. \texttt{jmp} $L$ & Jump to label $L$ \\
  7638. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7639. \texttt{movzbq} $A$, $B$ &
  7640. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7641. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7642. and the extra bytes of $B$ are set to zero.} \\
  7643. & \\
  7644. & \\
  7645. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7646. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7647. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7648. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7649. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7650. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7651. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7652. description of the condition codes. $A$ must be a single byte register
  7653. (e.g., \texttt{al} or \texttt{cl}).} \\
  7654. \texttt{setl} $A$ & \\
  7655. \texttt{setle} $A$ & \\
  7656. \texttt{setg} $A$ & \\
  7657. \texttt{setge} $A$ &
  7658. \end{tabular}
  7659. \vspace{5pt}
  7660. \caption{Quick-reference for the x86 instructions used in this book.}
  7661. \label{tab:x86-instr}
  7662. \end{table}
  7663. \bibliographystyle{plainnat}
  7664. \bibliography{all}
  7665. \end{document}
  7666. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7667. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7668. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7669. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7670. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7671. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7672. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7673. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7674. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7675. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7676. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7677. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7678. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7679. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7680. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7681. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7682. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7683. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7684. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7685. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7686. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7687. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7688. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7689. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7690. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7691. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7692. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7693. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7694. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7695. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7696. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7697. % LocalWords: struct symtab