book.tex 306 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192
  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. %% For pictures
  56. \usepackage{tikz}
  57. \usetikzlibrary{arrows.meta}
  58. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  59. % Computer Modern is already the default. -Jeremy
  60. %\renewcommand{\ttdefault}{cmtt}
  61. \definecolor{comment-red}{rgb}{0.8,0,0}
  62. \if{0}
  63. % Peanut gallery comments:
  64. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  65. \newcommand{\margincomment}[1]{\marginpar{#1}}
  66. \else
  67. \newcommand{\rn}[1]{}
  68. \newcommand{\margincomment}[1]{}
  69. \fi
  70. \lstset{%
  71. language=Lisp,
  72. basicstyle=\ttfamily\small,
  73. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then},
  74. deletekeywords={read},
  75. escapechar=|,
  76. columns=flexible,
  77. moredelim=[is][\color{red}]{~}{~}
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge An Incremental Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. The tradition of compiler writing at Indiana University goes back to
  147. research and courses about programming languages by Daniel Friedman in
  148. the 1970's and 1980's. Dan conducted research on lazy
  149. evaluation~\citep{Friedman:1976aa} in the context of
  150. Lisp~\citep{McCarthy:1960dz} and then studied
  151. continuations~\citep{Felleisen:kx} and
  152. macros~\citep{Kohlbecker:1986dk} in the context of the
  153. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  154. of those courses, Kent Dybvig, went on to build Chez
  155. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  156. compiler for Scheme. After completing his Ph.D. at the University of
  157. North Carolina, Kent returned to teach at Indiana University.
  158. Throughout the 1990's and 2000's, Kent continued development of Chez
  159. Scheme and taught the compiler course.
  160. The compiler course evolved to incorporate novel pedagogical ideas
  161. while also including elements of effective real-world compilers. One
  162. of Dan's ideas was to split the compiler into many small ``passes'' so
  163. that the code for each pass would be easy to understood in isolation.
  164. (In contrast, most compilers of the time were organized into only a
  165. few monolithic passes for reasons of compile-time efficiency.) Kent,
  166. with later help from his students Dipanwita Sarkar and Andrew Keep,
  167. developed infrastructure to support this approach and evolved the
  168. course, first to use micro-sized passes and then into even smaller
  169. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  170. student in this compiler course in the early 2000's, as part of his
  171. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  172. the course immensely!
  173. During that time, another student named Abdulaziz Ghuloum observed
  174. that the front-to-back organization of the course made it difficult
  175. for students to understand the rationale for the compiler
  176. design. Abdulaziz proposed an incremental approach in which the
  177. students build the compiler in stages; they start by implementing a
  178. complete compiler for a very small subset of the input language and in
  179. each subsequent stage they add a language feature and add or modify
  180. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  181. the students see how the language features motivate aspects of the
  182. compiler design.
  183. After graduating from Indiana University in 2005, Jeremy went on to
  184. teach at the University of Colorado. He adapted the nano pass and
  185. incremental approaches to compiling a subset of the Python
  186. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  187. on the surface but there is a large overlap in the compiler techniques
  188. required for the two languages. Thus, Jeremy was able to teach much of
  189. the same content from the Indiana compiler course. He very much
  190. enjoyed teaching the course organized in this way, and even better,
  191. many of the students learned a lot and got excited about compilers.
  192. Jeremy returned to teach at Indiana University in 2013. In his
  193. absence the compiler course had switched from the front-to-back
  194. organization to a back-to-front organization. Seeing how well the
  195. incremental approach worked at Colorado, he started porting and
  196. adapting the structure of the Colorado course back into the land of
  197. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  198. the course is now about compiling a subset of Racket (and Typed
  199. Racket) to the x86 assembly language. The compiler is implemented in
  200. Racket 7.1~\citep{plt-tr}.
  201. This is the textbook for the incremental version of the compiler
  202. course at Indiana University (Spring 2016 - present) and it is the
  203. first open textbook for an Indiana compiler course. With this book we
  204. hope to make the Indiana compiler course available to people that have
  205. not had the chance to study in Bloomington in person. Many of the
  206. compiler design decisions in this book are drawn from the assignment
  207. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  208. are the most important topics from \cite{Dybvig:2010aa} but we have
  209. omitted topics that we think are less interesting conceptually and we
  210. have made simplifications to reduce complexity. In this way, this
  211. book leans more towards pedagogy than towards the efficiency of the
  212. generated code. Also, the book differs in places where we saw the
  213. opportunity to make the topics more fun, such as in relating register
  214. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  215. \section*{Prerequisites}
  216. The material in this book is challenging but rewarding. It is meant to
  217. prepare students for a lifelong career in programming languages.
  218. The book uses the Racket language both for the implementation of the
  219. compiler and for the language that is compiled, so a student should be
  220. proficient with Racket (or Scheme) prior to reading this book. There
  221. are many excellent resources for learning Scheme and
  222. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  223. is helpful but not necessary for the student to have prior exposure to
  224. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  225. obtain from a computer systems
  226. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  227. parts of x86-64 assembly language that are needed.
  228. %\section*{Structure of book}
  229. % You might want to add short description about each chapter in this book.
  230. %\section*{About the companion website}
  231. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  232. %\begin{itemize}
  233. % \item A link to (freely downlodable) latest version of this document.
  234. % \item Link to download LaTeX source for this document.
  235. % \item Miscellaneous material (e.g. suggested readings etc).
  236. %\end{itemize}
  237. \section*{Acknowledgments}
  238. Many people have contributed to the ideas, techniques, organization,
  239. and teaching of the materials in this book. We especially thank the
  240. following people.
  241. \begin{itemize}
  242. \item Bor-Yuh Evan Chang
  243. \item Kent Dybvig
  244. \item Daniel P. Friedman
  245. \item Ronald Garcia
  246. \item Abdulaziz Ghuloum
  247. \item Jay McCarthy
  248. \item Dipanwita Sarkar
  249. \item Andrew Keep
  250. \item Oscar Waddell
  251. \item Michael Wollowski
  252. \end{itemize}
  253. \mbox{}\\
  254. \noindent Jeremy G. Siek \\
  255. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  256. %\noindent Spring 2016
  257. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  258. \chapter{Preliminaries}
  259. \label{ch:trees-recur}
  260. In this chapter we review the basic tools that are needed to implement
  261. a compiler. Programs are typically input by a programmer as text,
  262. i.e., a sequence of characters. The program-as-text representation is
  263. called \emph{concrete syntax}. We use concrete syntax to concisely
  264. write down and talk about programs. Inside the compiler, we use
  265. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  266. that efficiently supports the operations that the compiler needs to
  267. perform.
  268. %
  269. The translation from concrete syntax to abstract syntax is a process
  270. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  271. and implementation of parsing in this book. A parser is provided in
  272. the supporting materials for translating from concrete syntax to
  273. abstract syntax for the languages used in this book.
  274. ASTs can be represented in many different ways inside the compiler,
  275. depending on the programming language used to write the compiler.
  276. %
  277. We use Racket's \code{struct} feature to represent ASTs
  278. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  279. of programming languages (Section~\ref{sec:grammar}) and pattern
  280. matching to inspect individual nodes in an AST
  281. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  282. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  283. chapter provides an brief introduction to these ideas.
  284. \section{Abstract Syntax Trees and Racket Structures}
  285. \label{sec:ast}
  286. Compilers use abstract syntax trees to represent programs because
  287. compilers often need to ask questions like: for a given part of a
  288. program, what kind of language feature is it? What are the sub-parts
  289. of this part of the program? Consider the program on the left and its
  290. AST on the right. This program is an addition and it has two
  291. sub-parts, a read operation and a negation. The negation has another
  292. sub-part, the integer constant \code{8}. By using a tree to represent
  293. the program, we can easily follow the links to go from one part of a
  294. program to its sub-parts.
  295. \begin{center}
  296. \begin{minipage}{0.4\textwidth}
  297. \begin{lstlisting}
  298. (+ (read) (- 8))
  299. \end{lstlisting}
  300. \end{minipage}
  301. \begin{minipage}{0.4\textwidth}
  302. \begin{equation}
  303. \begin{tikzpicture}
  304. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  305. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  306. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  307. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  308. \draw[->] (plus) to (read);
  309. \draw[->] (plus) to (minus);
  310. \draw[->] (minus) to (8);
  311. \end{tikzpicture}
  312. \label{eq:arith-prog}
  313. \end{equation}
  314. \end{minipage}
  315. \end{center}
  316. We use the standard terminology for trees to describe ASTs: each
  317. circle above is called a \emph{node}. The arrows connect a node to its
  318. \emph{children} (which are also nodes). The top-most node is the
  319. \emph{root}. Every node except for the root has a \emph{parent} (the
  320. node it is the child of). If a node has no children, it is a
  321. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  322. %% Recall that an \emph{symbolic expression} (S-expression) is either
  323. %% \begin{enumerate}
  324. %% \item an atom, or
  325. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  326. %% where $e_1$ and $e_2$ are each an S-expression.
  327. %% \end{enumerate}
  328. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  329. %% null value \code{'()}, etc. We can create an S-expression in Racket
  330. %% simply by writing a backquote (called a quasi-quote in Racket)
  331. %% followed by the textual representation of the S-expression. It is
  332. %% quite common to use S-expressions to represent a list, such as $a, b
  333. %% ,c$ in the following way:
  334. %% \begin{lstlisting}
  335. %% `(a . (b . (c . ())))
  336. %% \end{lstlisting}
  337. %% Each element of the list is in the first slot of a pair, and the
  338. %% second slot is either the rest of the list or the null value, to mark
  339. %% the end of the list. Such lists are so common that Racket provides
  340. %% special notation for them that removes the need for the periods
  341. %% and so many parenthesis:
  342. %% \begin{lstlisting}
  343. %% `(a b c)
  344. %% \end{lstlisting}
  345. %% The following expression creates an S-expression that represents AST
  346. %% \eqref{eq:arith-prog}.
  347. %% \begin{lstlisting}
  348. %% `(+ (read) (- 8))
  349. %% \end{lstlisting}
  350. %% When using S-expressions to represent ASTs, the convention is to
  351. %% represent each AST node as a list and to put the operation symbol at
  352. %% the front of the list. The rest of the list contains the children. So
  353. %% in the above case, the root AST node has operation \code{`+} and its
  354. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  355. %% diagram \eqref{eq:arith-prog}.
  356. %% To build larger S-expressions one often needs to splice together
  357. %% several smaller S-expressions. Racket provides the comma operator to
  358. %% splice an S-expression into a larger one. For example, instead of
  359. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  360. %% we could have first created an S-expression for AST
  361. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  362. %% S-expression.
  363. %% \begin{lstlisting}
  364. %% (define ast1.4 `(- 8))
  365. %% (define ast1.1 `(+ (read) ,ast1.4))
  366. %% \end{lstlisting}
  367. %% In general, the Racket expression that follows the comma (splice)
  368. %% can be any expression that produces an S-expression.
  369. We define a Racket \code{struct} for each kind of node. For this
  370. chapter we require just two kinds of nodes: one for integer constants
  371. and one for primitive operations. The following is the \code{struct}
  372. definition for integer constants.
  373. \begin{lstlisting}
  374. (struct Int (value))
  375. \end{lstlisting}
  376. An integer node includes just one thing: the integer value.
  377. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  378. \begin{lstlisting}
  379. (define eight (Int 8))
  380. \end{lstlisting}
  381. We say that the value created by \code{(Int 8)} is an
  382. \emph{instance} of the \code{Int} structure.
  383. The following is the \code{struct} definition for primitives operations.
  384. \begin{lstlisting}
  385. (struct Prim (op arg*))
  386. \end{lstlisting}
  387. A primitive operation node includes an operator symbol \code{op}
  388. and a list of children \code{arg*}. For example, to create
  389. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  390. \begin{lstlisting}
  391. (define neg-eight (Prim '- (list eight)))
  392. \end{lstlisting}
  393. Primitive operations may have zero or more children. The \code{read}
  394. operator has zero children:
  395. \begin{lstlisting}
  396. (define rd (Prim 'read '()))
  397. \end{lstlisting}
  398. whereas the addition operator has two children:
  399. \begin{lstlisting}
  400. (define ast1.1 (Prim '+ (list rd neg-eight)))
  401. \end{lstlisting}
  402. We have made a design choice regarding the \code{Prim} structure.
  403. Instead of using one structure for many different operations
  404. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  405. structure for each operation, as follows.
  406. \begin{lstlisting}
  407. (struct Read ())
  408. (struct Add (left right))
  409. (struct Neg (value))
  410. \end{lstlisting}
  411. The reason we choose to use just one structure is that in many parts
  412. of the compiler the code for the different primitive operators is the
  413. same, so we might as well just write that code once, which is enabled
  414. by using a single structure.
  415. When compiling a program such as \eqref{eq:arith-prog}, we need to
  416. know that the operation associated with the root node is addition and
  417. we need to be able to access its two children. Racket provides pattern
  418. matching over structures to support these kinds of queries, as we
  419. shall see in Section~\ref{sec:pattern-matching}.
  420. In this book, we often write down the concrete syntax of a program
  421. even when we really have in mind the AST because the concrete syntax
  422. is more concise. We recommend that, in your mind, you always think of
  423. programs as abstract syntax trees.
  424. \section{Grammars}
  425. \label{sec:grammar}
  426. A programming language can be thought of as a \emph{set} of programs.
  427. The set is typically infinite (one can always create larger and larger
  428. programs), so one cannot simply describe a language by listing all of
  429. the programs in the language. Instead we write down a set of rules, a
  430. \emph{grammar}, for building programs. Grammars are often used to
  431. define the concrete syntax of a language, but they can also be used to
  432. describe the abstract syntax. We shall write our rules in a variant of
  433. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  434. example, we describe a small language, named $R_0$, that consists of
  435. integers and arithmetic operations.
  436. The first grammar rule for the abstract syntax of $R_0$ says that an
  437. instance of the \code{Int} structure is an expression:
  438. \begin{equation}
  439. \Exp ::= \INT{\Int} \label{eq:arith-int}
  440. \end{equation}
  441. %
  442. Each rule has a left-hand-side and a right-hand-side. The way to read
  443. a rule is that if you have all the program parts on the
  444. right-hand-side, then you can create an AST node and categorize it
  445. according to the left-hand-side.
  446. %
  447. A name such as $\Exp$ that is
  448. defined by the grammar rules is a \emph{non-terminal}.
  449. %
  450. The name $\Int$ is a also a non-terminal, but instead of defining it
  451. with a grammar rule, we define it with the following explanation. We
  452. make the simplifying design decision that all of the languages in this
  453. book only handle machine-representable integers. On most modern
  454. machines this corresponds to integers represented with 64-bits, i.e.,
  455. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  456. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  457. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  458. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  459. that the sequence of decimals represent an integer in range $-2^{62}$
  460. to $2^{62}-1$.
  461. The second grammar rule is the \texttt{read} operation that receives
  462. an input integer from the user of the program.
  463. \begin{equation}
  464. \Exp ::= \READ{} \label{eq:arith-read}
  465. \end{equation}
  466. The third rule says that, given an $\Exp$ node, you can build another
  467. $\Exp$ node by negating it.
  468. \begin{equation}
  469. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  470. \end{equation}
  471. Symbols in typewriter font such as \key{-} and \key{read} are
  472. \emph{terminal} symbols and must literally appear in the program for
  473. the rule to be applicable.
  474. We can apply the rules to build ASTs in the $R_0$
  475. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  476. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  477. an $\Exp$.
  478. \begin{center}
  479. \begin{minipage}{0.4\textwidth}
  480. \begin{lstlisting}
  481. (Prim '- (list (Int 8)))
  482. \end{lstlisting}
  483. \end{minipage}
  484. \begin{minipage}{0.25\textwidth}
  485. \begin{equation}
  486. \begin{tikzpicture}
  487. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  488. \node[draw, circle] (8) at (0, -1.2) {$8$};
  489. \draw[->] (minus) to (8);
  490. \end{tikzpicture}
  491. \label{eq:arith-neg8}
  492. \end{equation}
  493. \end{minipage}
  494. \end{center}
  495. The next grammar rule defines addition expressions:
  496. \begin{equation}
  497. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  498. \end{equation}
  499. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  500. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  501. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  502. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  503. to show that
  504. \begin{lstlisting}
  505. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  506. \end{lstlisting}
  507. is an $\Exp$ in the $R_0$ language.
  508. If you have an AST for which the above rules do not apply, then the
  509. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  510. is not in $R_0$ because there are no rules for \code{+} with only one
  511. argument, nor for \key{-} with two arguments. Whenever we define a
  512. language with a grammar, the language only includes those programs
  513. that are justified by the rules.
  514. The last grammar rule for $R_0$ states that there is a \code{Program}
  515. node to mark the top of the whole program:
  516. \[
  517. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  518. \]
  519. The \code{Program} structure is defined as follows
  520. \begin{lstlisting}
  521. (struct Program (info body))
  522. \end{lstlisting}
  523. where \code{body} is an expression. In later chapters, the \code{info}
  524. part will be used to store auxiliary information but for now it is
  525. just the empty list.
  526. It is common to have many grammar rules with the same left-hand side
  527. but different right-hand sides, such as the rules for $\Exp$ in the
  528. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  529. combine several right-hand-sides into a single rule.
  530. We collect all of the grammar rules for the abstract syntax of $R_0$
  531. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  532. defined in Figure~\ref{fig:r0-concrete-syntax}.
  533. The \code{read-program} function provided in \code{utilities.rkt} of
  534. the support materials reads a program in from a file (the sequence of
  535. characters in the concrete syntax of Racket) and parses it into an
  536. abstract syntax tree. See the description of \code{read-program} in
  537. Appendix~\ref{appendix:utilities} for more details.
  538. \begin{figure}[tp]
  539. \fbox{
  540. \begin{minipage}{0.96\textwidth}
  541. \[
  542. \begin{array}{rcl}
  543. \begin{array}{rcl}
  544. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  545. R_0 &::=& \Exp
  546. \end{array}
  547. \end{array}
  548. \]
  549. \end{minipage}
  550. }
  551. \caption{The concrete syntax of $R_0$.}
  552. \label{fig:r0-concrete-syntax}
  553. \end{figure}
  554. \begin{figure}[tp]
  555. \fbox{
  556. \begin{minipage}{0.96\textwidth}
  557. \[
  558. \begin{array}{rcl}
  559. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  560. &\mid& \ADD{\Exp}{\Exp} \\
  561. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  562. \end{array}
  563. \]
  564. \end{minipage}
  565. }
  566. \caption{The abstract syntax of $R_0$.}
  567. \label{fig:r0-syntax}
  568. \end{figure}
  569. \section{Pattern Matching}
  570. \label{sec:pattern-matching}
  571. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  572. the parts of an AST node. Racket provides the \texttt{match} form to
  573. access the parts of a structure. Consider the following example and
  574. the output on the right.
  575. \begin{center}
  576. \begin{minipage}{0.5\textwidth}
  577. \begin{lstlisting}
  578. (match ast1.1
  579. [(Prim op (list child1 child2))
  580. (print op)])
  581. \end{lstlisting}
  582. \end{minipage}
  583. \vrule
  584. \begin{minipage}{0.25\textwidth}
  585. \begin{lstlisting}
  586. '+
  587. \end{lstlisting}
  588. \end{minipage}
  589. \end{center}
  590. In the above example, the \texttt{match} form takes the AST
  591. \eqref{eq:arith-prog} and binds its parts to the three pattern
  592. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  593. general, a match clause consists of a \emph{pattern} and a
  594. \emph{body}. Patterns are recursively defined to be either a pattern
  595. variable, a structure name followed by a pattern for each of the
  596. structure's arguments, or an S-expression (symbols, lists, etc.).
  597. (See Chapter 12 of The Racket
  598. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  599. and Chapter 9 of The Racket
  600. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  601. for a complete description of \code{match}.)
  602. %
  603. The body of a match clause may contain arbitrary Racket code. The
  604. pattern variables can be used in the scope of the body.
  605. A \code{match} form may contain several clauses, as in the following
  606. function \code{leaf?} that recognizes when an $R_0$ node is
  607. a leaf. The \code{match} proceeds through the clauses in order,
  608. checking whether the pattern can match the input AST. The
  609. body of the first clause that matches is executed. The output of
  610. \code{leaf?} for several ASTs is shown on the right.
  611. \begin{center}
  612. \begin{minipage}{0.6\textwidth}
  613. \begin{lstlisting}
  614. (define (leaf? arith)
  615. (match arith
  616. [(Int n) #t]
  617. [(Prim 'read '()) #t]
  618. [(Prim '- (list c1)) #f]
  619. [(Prim '+ (list c1 c2)) #f]))
  620. (leaf? (Prim 'read '()))
  621. (leaf? (Prim '- (list (Int 8))))
  622. (leaf? (Int 8))
  623. \end{lstlisting}
  624. \end{minipage}
  625. \vrule
  626. \begin{minipage}{0.25\textwidth}
  627. \begin{lstlisting}
  628. #t
  629. #f
  630. #t
  631. \end{lstlisting}
  632. \end{minipage}
  633. \end{center}
  634. When writing a \code{match}, we refer to the grammar definition to
  635. identify which non-terminal we are expecting to match against, then we
  636. make sure that 1) we have one clause for each alternative of that
  637. non-terminal and 2) that the pattern in each clause corresponds to the
  638. corresponding right-hand side of a grammar rule. For the \code{match}
  639. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  640. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  641. alternatives, so the \code{match} has 4 clauses. The pattern in each
  642. clause corresponds to the right-hand side of a grammar rule. For
  643. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  644. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  645. patterns, replace non-terminals such as $\Exp$ with pattern variables
  646. of your choice (e.g. \code{c1} and \code{c2}).
  647. \section{Recursion}
  648. \label{sec:recursion}
  649. Programs are inherently recursive. For example, an $R_0$ expression is
  650. often made of smaller expressions. Thus, the natural way to process an
  651. entire program is with a recursive function. As a first example of
  652. such a recursive function, we define \texttt{exp?} below, which takes
  653. an arbitrary value and determines whether or not it is an $R_0$
  654. expression.
  655. %
  656. When a recursive function is defined using a sequence of match clauses
  657. that correspond to a grammar, and the body of each clause makes a
  658. recursive call on each child node, then we say the function is defined
  659. by \emph{structural recursion}\footnote{This principle of structuring
  660. code according to the data definition is advocated in the book
  661. \emph{How to Design Programs}
  662. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  663. define a second function, named \code{R0?}, that determines whether a
  664. value is an $R_0$ program. In general we can expect to write one
  665. recursive function to handle each non-terminal in a grammar.
  666. %
  667. \begin{center}
  668. \begin{minipage}{0.7\textwidth}
  669. \begin{lstlisting}
  670. (define (exp? ast)
  671. (match ast
  672. [(Int n) #t]
  673. [(Prim 'read '()) #t]
  674. [(Prim '- (list e)) (exp? e)]
  675. [(Prim '+ (list e1 e2))
  676. (and (exp? e1) (exp? e2))]
  677. [else #f]))
  678. (define (R0? ast)
  679. (match ast
  680. [(Program '() e) (exp? e)]
  681. [else #f]))
  682. (R0? (Program '() ast1.1)
  683. (R0? (Program '()
  684. (Prim '- (list (Prim 'read '())
  685. (Prim '+ (list (Num 8)))))))
  686. \end{lstlisting}
  687. \end{minipage}
  688. \vrule
  689. \begin{minipage}{0.25\textwidth}
  690. \begin{lstlisting}
  691. #t
  692. #f
  693. \end{lstlisting}
  694. \end{minipage}
  695. \end{center}
  696. You may be tempted to merge the two functions into one, like this:
  697. \begin{center}
  698. \begin{minipage}{0.5\textwidth}
  699. \begin{lstlisting}
  700. (define (R0? ast)
  701. (match ast
  702. [(Int n) #t]
  703. [(Prim 'read '()) #t]
  704. [(Prim '- (list e)) (R0? e)]
  705. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  706. [(Program '() e) (R0? e)]
  707. [else #f]))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \end{center}
  711. %
  712. Sometimes such a trick will save a few lines of code, especially when
  713. it comes to the \code{Program} wrapper. Yet this style is generally
  714. \emph{not} recommended because it can get you into trouble.
  715. %
  716. For example, the above function is subtly wrong:
  717. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  718. will return true, when it should return false.
  719. %% NOTE FIXME - must check for consistency on this issue throughout.
  720. \section{Interpreters}
  721. \label{sec:interp-R0}
  722. The meaning, or semantics, of a program is typically defined in the
  723. specification of the language. For example, the Scheme language is
  724. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  725. defined in its reference manual~\citep{plt-tr}. In this book we use an
  726. interpreter to define the meaning of each language that we consider,
  727. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  728. interpreter that is designated (by some people) as the definition of a
  729. language is called a \emph{definitional interpreter}. We warm up by
  730. creating a definitional interpreter for the $R_0$ language, which
  731. serves as a second example of structural recursion. The
  732. \texttt{interp-R0} function is defined in
  733. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  734. input program followed by a call to the \lstinline{interp-exp} helper
  735. function, which in turn has one match clause per grammar rule for
  736. $R_0$ expressions.
  737. \begin{figure}[tbp]
  738. \begin{lstlisting}
  739. (define (interp-exp e)
  740. (match e
  741. [(Int n) n]
  742. [(Prim 'read '())
  743. (define r (read))
  744. (cond [(fixnum? r) r]
  745. [else (error 'interp-R1 "expected an integer" r)])]
  746. [(Prim '- (list e))
  747. (define v (interp-exp e))
  748. (fx- 0 v)]
  749. [(Prim '+ (list e1 e2))
  750. (define v1 (interp-exp e1))
  751. (define v2 (interp-exp e2))
  752. (fx+ v1 v2)]
  753. ))
  754. (define (interp-R0 p)
  755. (match p
  756. [(Program '() e) (interp-exp e)]
  757. ))
  758. \end{lstlisting}
  759. \caption{Interpreter for the $R_0$ language.}
  760. \label{fig:interp-R0}
  761. \end{figure}
  762. Let us consider the result of interpreting a few $R_0$ programs. The
  763. following program adds two integers.
  764. \begin{lstlisting}
  765. (+ 10 32)
  766. \end{lstlisting}
  767. The result is \key{42}. We wrote the above program in concrete syntax,
  768. whereas the parsed abstract syntax is:
  769. \begin{lstlisting}
  770. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  771. \end{lstlisting}
  772. The next example demonstrates that expressions may be nested within
  773. each other, in this case nesting several additions and negations.
  774. \begin{lstlisting}
  775. (+ 10 (- (+ 12 20)))
  776. \end{lstlisting}
  777. What is the result of the above program?
  778. As mentioned previously, the $R_0$ language does not support
  779. arbitrarily-large integers, but only $63$-bit integers, so we
  780. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  781. in Racket.
  782. Suppose
  783. \[
  784. n = 999999999999999999
  785. \]
  786. which indeed fits in $63$-bits. What happens when we run the
  787. following program in our interpreter?
  788. \begin{lstlisting}
  789. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  790. \end{lstlisting}
  791. It produces an error:
  792. \begin{lstlisting}
  793. fx+: result is not a fixnum
  794. \end{lstlisting}
  795. We establish the convention that if running the definitional
  796. interpreter on a program produces an error, then the meaning of that
  797. program is \emph{unspecified}. That means a compiler for the language
  798. is under no obligations regarding that program; it may or may not
  799. produce an executable, and if it does, that executable can do
  800. anything. This convention applies to the languages defined in this
  801. book, as a way to simplify the student's task of implementing them,
  802. but this convention is not applicable to all programming languages.
  803. Moving on to the last feature of the $R_0$ language, the \key{read}
  804. operation prompts the user of the program for an integer. Recall that
  805. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  806. \code{8}. So if we run
  807. \begin{lstlisting}
  808. (interp-R0 ast1.1)
  809. \end{lstlisting}
  810. and if the input is \code{50}, then we get the answer to life, the
  811. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  812. Guide to the Galaxy} by Douglas Adams.}
  813. We include the \key{read} operation in $R_0$ so a clever student
  814. cannot implement a compiler for $R_0$ that simply runs the interpreter
  815. during compilation to obtain the output and then generates the trivial
  816. code to produce the output. (Yes, a clever student did this in the
  817. first instance of this course.)
  818. The job of a compiler is to translate a program in one language into a
  819. program in another language so that the output program behaves the
  820. same way as the input program does according to its definitional
  821. interpreter. This idea is depicted in the following diagram. Suppose
  822. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  823. interpreter for each language. Suppose that the compiler translates
  824. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  825. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  826. respective interpreters with input $i$ should yield the same output
  827. $o$.
  828. \begin{equation} \label{eq:compile-correct}
  829. \begin{tikzpicture}[baseline=(current bounding box.center)]
  830. \node (p1) at (0, 0) {$P_1$};
  831. \node (p2) at (3, 0) {$P_2$};
  832. \node (o) at (3, -2.5) {$o$};
  833. \path[->] (p1) edge [above] node {compile} (p2);
  834. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  835. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  836. \end{tikzpicture}
  837. \end{equation}
  838. In the next section we see our first example of a compiler.
  839. \section{Example Compiler: a Partial Evaluator}
  840. \label{sec:partial-evaluation}
  841. In this section we consider a compiler that translates $R_0$ programs
  842. into $R_0$ programs that may be more efficient, that is, this compiler
  843. is an optimizer. This optimizer eagerly computes the parts of the
  844. program that do not depend on any inputs, a process known as
  845. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  846. following program
  847. \begin{lstlisting}
  848. (+ (read) (- (+ 5 3)))
  849. \end{lstlisting}
  850. our compiler will translate it into the program
  851. \begin{lstlisting}
  852. (+ (read) -8)
  853. \end{lstlisting}
  854. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  855. evaluator for the $R_0$ language. The output of the partial evaluator
  856. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  857. recursion over $\Exp$ is captured in the \code{pe-exp} function
  858. whereas the code for partially evaluating the negation and addition
  859. operations is factored into two separate helper functions:
  860. \code{pe-neg} and \code{pe-add}. The input to these helper
  861. functions is the output of partially evaluating the children.
  862. \begin{figure}[tbp]
  863. \begin{lstlisting}
  864. (define (pe-neg r)
  865. (match r
  866. [(Int n) (Int (fx- 0 n))]
  867. [else (Prim '- (list r))]))
  868. (define (pe-add r1 r2)
  869. (match* (r1 r2)
  870. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  871. [(_ _) (Prim '+ (list r1 r2))]))
  872. (define (pe-exp e)
  873. (match e
  874. [(Int n) (Int n)]
  875. [(Prim 'read '()) (Prim 'read '())]
  876. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  877. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  878. ))
  879. (define (pe-R0 p)
  880. (match p
  881. [(Program info e) (Program info (pe-exp e))]
  882. ))
  883. \end{lstlisting}
  884. \caption{A partial evaluator for $R_0$ expressions.}
  885. \label{fig:pe-arith}
  886. \end{figure}
  887. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  888. arguments are integers and if they are, perform the appropriate
  889. arithmetic. Otherwise, they create an AST node for the operation
  890. (either negation or addition).
  891. To gain some confidence that the partial evaluator is correct, we can
  892. test whether it produces programs that get the same result as the
  893. input programs. That is, we can test whether it satisfies Diagram
  894. \eqref{eq:compile-correct}. The following code runs the partial
  895. evaluator on several examples and tests the output program. The
  896. \texttt{parse-program} and \texttt{assert} functions are defined in
  897. Appendix~\ref{appendix:utilities}.\\
  898. \begin{minipage}{1.0\textwidth}
  899. \begin{lstlisting}
  900. (define (test-pe p)
  901. (assert "testing pe-R0"
  902. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  903. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  904. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  905. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  906. \end{lstlisting}
  907. \end{minipage}
  908. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  909. \chapter{Integers and Variables}
  910. \label{ch:int-exp}
  911. This chapter is about compiling the subset of Racket that includes
  912. integer arithmetic and local variable binding, which we name $R_1$, to
  913. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  914. to x86-64 simply as x86. The chapter begins with a description of the
  915. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  916. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  917. discuss only what is needed for compiling $R_1$. We introduce more of
  918. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  919. reflect on their differences and come up with a plan to break down the
  920. translation from $R_1$ to x86 into a handful of steps
  921. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  922. chapter give detailed hints regarding each step
  923. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  924. to give enough hints that the well-prepared reader, together with a
  925. few friends, can implement a compiler from $R_1$ to x86 in a couple
  926. weeks while at the same time leaving room for some fun and creativity.
  927. To give the reader a feeling for the scale of this first compiler, the
  928. instructor solution for the $R_1$ compiler is less than 500 lines of
  929. code.
  930. \section{The $R_1$ Language}
  931. \label{sec:s0}
  932. The $R_1$ language extends the $R_0$ language with variable
  933. definitions. The concrete syntax of the $R_1$ language is defined by
  934. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  935. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  936. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  937. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  938. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  939. \key{Program} struct to mark the top of the program.
  940. %% The $\itm{info}$
  941. %% field of the \key{Program} structure contains an \emph{association
  942. %% list} (a list of key-value pairs) that is used to communicate
  943. %% auxiliary data from one compiler pass the next.
  944. Despite the simplicity of the $R_1$ language, it is rich enough to
  945. exhibit several compilation techniques.
  946. \begin{figure}[btp]
  947. \centering
  948. \fbox{
  949. \begin{minipage}{0.96\textwidth}
  950. \[
  951. \begin{array}{rcl}
  952. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  953. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  954. R_1 &::=& \Exp
  955. \end{array}
  956. \]
  957. \end{minipage}
  958. }
  959. \caption{The concrete syntax of $R_1$.}
  960. \label{fig:r1-concrete-syntax}
  961. \end{figure}
  962. \begin{figure}[btp]
  963. \centering
  964. \fbox{
  965. \begin{minipage}{0.96\textwidth}
  966. \[
  967. \begin{array}{rcl}
  968. \Exp &::=& \INT{\Int} \mid \READ{} \\
  969. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  970. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  971. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  972. \end{array}
  973. \]
  974. \end{minipage}
  975. }
  976. \caption{The abstract syntax of $R_1$.}
  977. \label{fig:r1-syntax}
  978. \end{figure}
  979. Let us dive further into the syntax and semantics of the $R_1$
  980. language. The \key{Let} feature defines a variable for use within its
  981. body and initializes the variable with the value of an expression.
  982. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  983. The concrete syntax for \key{Let} is
  984. \begin{lstlisting}
  985. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  986. \end{lstlisting}
  987. For example, the following program initializes \code{x} to $32$ and then
  988. evaluates the body \code{(+ 10 x)}, producing $42$.
  989. \begin{lstlisting}
  990. (let ([x (+ 12 20)]) (+ 10 x))
  991. \end{lstlisting}
  992. When there are multiple \key{let}'s for the same variable, the closest
  993. enclosing \key{let} is used. That is, variable definitions overshadow
  994. prior definitions. Consider the following program with two \key{let}'s
  995. that define variables named \code{x}. Can you figure out the result?
  996. \begin{lstlisting}
  997. (let ([x 32]) (+ (let ([x 10]) x) x))
  998. \end{lstlisting}
  999. For the purposes of depicting which variable uses correspond to which
  1000. definitions, the following shows the \code{x}'s annotated with
  1001. subscripts to distinguish them. Double check that your answer for the
  1002. above is the same as your answer for this annotated version of the
  1003. program.
  1004. \begin{lstlisting}
  1005. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1006. \end{lstlisting}
  1007. The initializing expression is always evaluated before the body of the
  1008. \key{let}, so in the following, the \key{read} for \code{x} is
  1009. performed before the \key{read} for \code{y}. Given the input
  1010. $52$ then $10$, the following produces $42$ (not $-42$).
  1011. \begin{lstlisting}
  1012. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1013. \end{lstlisting}
  1014. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1015. \small
  1016. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1017. An \emph{association list} (alist) is a list of key-value pairs.
  1018. For example, we can map people to their ages with an alist.
  1019. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1020. (define ages
  1021. '((jane . 25) (sam . 24) (kate . 45)))
  1022. \end{lstlisting}
  1023. The \emph{dictionary} interface is for mapping keys to values.
  1024. Every alist implements this interface. The package
  1025. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1026. provides many functions for working with dictionaries. Here
  1027. are a few of them:
  1028. \begin{description}
  1029. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1030. returns the value associated with the given $\itm{key}$.
  1031. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1032. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1033. but otherwise is the same as $\itm{dict}$.
  1034. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1035. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1036. of keys and values in $\itm{dict}$. For example, the following
  1037. creates a new alist in which the ages are incremented by one.
  1038. \end{description}
  1039. \vspace{-10pt}
  1040. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1041. (for/list ([(k v) (in-dict ages)])
  1042. (cons k (add1 v)))
  1043. \end{lstlisting}
  1044. \end{tcolorbox}
  1045. \end{wrapfigure}
  1046. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1047. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1048. \key{match} clauses for variables and for \key{let}. For \key{let},
  1049. we need a way to communicate the value of a variable to all the uses
  1050. of a variable. To accomplish this, we maintain a mapping from
  1051. variables to values. Throughout the compiler we often need to map
  1052. variables to information about them. We refer to these mappings as
  1053. \emph{environments}
  1054. \footnote{Another common term for environment in the compiler
  1055. literature is \emph{symbol table}.}. For simplicity, we use an
  1056. association list (alist) to represent the environment. The sidebar to
  1057. the right gives a brief introduction to alists and the
  1058. \code{racket/dict} package. The \code{interp-R1} function takes the
  1059. current environment, \code{env}, as an extra parameter. When the
  1060. interpreter encounters a variable, it finds the corresponding value
  1061. using the \code{dict-ref} function. When the interpreter encounters a
  1062. \key{Let}, it evaluates the initializing expression, extends the
  1063. environment with the result value bound to the variable, using
  1064. \code{dict-set}, then evaluates the body of the \key{Let}.
  1065. \begin{figure}[tbp]
  1066. \begin{lstlisting}
  1067. (define (interp-exp env)
  1068. (lambda (e)
  1069. (match e
  1070. [(Int n) n]
  1071. [(Prim 'read '())
  1072. (define r (read))
  1073. (cond [(fixnum? r) r]
  1074. [else (error 'interp-R1 "expected an integer" r)])]
  1075. [(Prim '- (list e))
  1076. (define v ((interp-exp env) e))
  1077. (fx- 0 v)]
  1078. [(Prim '+ (list e1 e2))
  1079. (define v1 ((interp-exp env) e1))
  1080. (define v2 ((interp-exp env) e2))
  1081. (fx+ v1 v2)]
  1082. [(Var x) (dict-ref env x)]
  1083. [(Let x e body)
  1084. (define new-env (dict-set env x ((interp-exp env) e)))
  1085. ((interp-exp new-env) body)]
  1086. )))
  1087. (define (interp-R1 p)
  1088. (match p
  1089. [(Program info e) ((interp-exp '()) e)]
  1090. ))
  1091. \end{lstlisting}
  1092. \caption{Interpreter for the $R_1$ language.}
  1093. \label{fig:interp-R1}
  1094. \end{figure}
  1095. The goal for this chapter is to implement a compiler that translates
  1096. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1097. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1098. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1099. is, they both output the same integer $n$. We depict this correctness
  1100. criteria in the following diagram.
  1101. \[
  1102. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1103. \node (p1) at (0, 0) {$P_1$};
  1104. \node (p2) at (4, 0) {$P_2$};
  1105. \node (o) at (4, -2) {$n$};
  1106. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1107. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1108. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1109. \end{tikzpicture}
  1110. \]
  1111. In the next section we introduce enough of the x86 assembly
  1112. language to compile $R_1$.
  1113. \section{The x86 Assembly Language}
  1114. \label{sec:x86}
  1115. Figure~\ref{fig:x86-a} defines the concrete syntax for the subset of
  1116. the x86 assembly language needed for this chapter.
  1117. %
  1118. An x86 program is a sequence of instructions. The program is stored in
  1119. the computer's memory and the computer has a \emph{program counter}
  1120. that points to the address of the next instruction to be executed. For
  1121. most instructions, once the instruction is executed, the program
  1122. counter is incremented to point to the immediately following
  1123. instruction in memory. Most x86 instructions take two operands, where
  1124. each operand is either an integer constant (called \emph{immediate
  1125. value}), a \emph{register}, or a \emph{memory} location. A register
  1126. is a special kind of variable. Each one holds a 64-bit value; there
  1127. are 16 registers in the computer and their names are given in
  1128. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  1129. addresses to 64-bit values%
  1130. \footnote{This simple story suffices for describing how sequential
  1131. programs access memory but is not sufficient for multi-threaded
  1132. programs. However, multi-threaded execution is beyond the scope of
  1133. this book.}.
  1134. %
  1135. We use the AT\&T syntax expected by the GNU assembler, which comes
  1136. with the \key{gcc} compiler that we use for compiling assembly code to
  1137. machine code.
  1138. %
  1139. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1140. the x86 instructions used in this book.
  1141. % to do: finish treatment of imulq
  1142. % it's needed for vector's in R6/R7
  1143. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1144. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1145. && \key{r8} \mid \key{r9} \mid \key{r10}
  1146. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1147. \mid \key{r14} \mid \key{r15}}
  1148. \begin{figure}[tp]
  1149. \fbox{
  1150. \begin{minipage}{0.96\textwidth}
  1151. \[
  1152. \begin{array}{lcl}
  1153. \Reg &::=& \allregisters{} \\
  1154. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1155. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1156. \key{subq} \; \Arg\key{,} \Arg \mid
  1157. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1158. && \key{callq} \; \mathit{label} \mid
  1159. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1160. \Prog &::= & \key{.globl main}\\
  1161. & & \key{main:} \; \Instr^{+}
  1162. \end{array}
  1163. \]
  1164. \end{minipage}
  1165. }
  1166. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1167. \label{fig:x86-a}
  1168. \end{figure}
  1169. An immediate value is written using the notation \key{\$}$n$ where $n$
  1170. is an integer.
  1171. %
  1172. A register is written with a \key{\%} followed by the register name,
  1173. such as \key{\%rax}.
  1174. %
  1175. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1176. which obtains the address stored in register $r$ and then adds $n$
  1177. bytes to the address. The resulting address is used to either load or
  1178. store to memory depending on whether it occurs as a source or
  1179. destination argument of an instruction.
  1180. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1181. source $s$ and destination $d$, applies the arithmetic operation, then
  1182. writes the result back to the destination $d$.
  1183. %
  1184. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1185. stores the result in $d$.
  1186. %
  1187. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1188. specified by the label. We discuss procedure calls in more detail
  1189. later in this chapter and in Chapter~\ref{ch:functions}.
  1190. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1191. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1192. \key{main} procedure is externally visible, which is necessary so
  1193. that the operating system can call it. The label \key{main:}
  1194. indicates the beginning of the \key{main} procedure which is where
  1195. the operating system starts executing this program. The instruction
  1196. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1197. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1198. $10$ in \key{rax} and puts the result, $42$, back into
  1199. \key{rax}.
  1200. %
  1201. The last instruction, \key{retq}, finishes the \key{main} function by
  1202. returning the integer in \key{rax} to the operating system. The
  1203. operating system interprets this integer as the program's exit
  1204. code. By convention, an exit code of 0 indicates that a program
  1205. completed successfully, and all other exit codes indicate various
  1206. errors. Nevertheless, we return the result of the program as the exit
  1207. code.
  1208. %\begin{wrapfigure}{r}{2.25in}
  1209. \begin{figure}[tbp]
  1210. \begin{lstlisting}
  1211. .globl main
  1212. main:
  1213. movq $10, %rax
  1214. addq $32, %rax
  1215. retq
  1216. \end{lstlisting}
  1217. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1218. \label{fig:p0-x86}
  1219. %\end{wrapfigure}
  1220. \end{figure}
  1221. Unfortunately, x86 varies in a couple ways depending on what operating
  1222. system it is assembled in. The code examples shown here are correct on
  1223. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1224. labels like \key{main} must be prefixed with an underscore, as in
  1225. \key{\_main}.
  1226. We exhibit the use of memory for storing intermediate results in the
  1227. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1228. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1229. region of memory called the \emph{procedure call stack} (or
  1230. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1231. for each procedure call. The memory layout for an individual frame is
  1232. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1233. \emph{stack pointer} and points to the item at the top of the
  1234. stack. The stack grows downward in memory, so we increase the size of
  1235. the stack by subtracting from the stack pointer. Some operating
  1236. systems require the frame size to be a multiple of 16 bytes. In the
  1237. context of a procedure call, the \emph{return address} is the next
  1238. instruction after the call instruction on the caller side. During a
  1239. function call, the return address is pushed onto the stack. The
  1240. register \key{rbp} is the \emph{base pointer} which serves two
  1241. purposes: 1) it saves the location of the stack pointer for the
  1242. calling procedure and 2) it is used to access variables associated
  1243. with the current procedure. The base pointer of the calling procedure
  1244. is pushed onto the stack after the return address. We number the
  1245. variables from $1$ to $n$. Variable $1$ is stored at address
  1246. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1247. \begin{figure}[tbp]
  1248. \begin{lstlisting}
  1249. start:
  1250. movq $10, -8(%rbp)
  1251. negq -8(%rbp)
  1252. movq -8(%rbp), %rax
  1253. addq $52, %rax
  1254. jmp conclusion
  1255. .globl main
  1256. main:
  1257. pushq %rbp
  1258. movq %rsp, %rbp
  1259. subq $16, %rsp
  1260. jmp start
  1261. conclusion:
  1262. addq $16, %rsp
  1263. popq %rbp
  1264. retq
  1265. \end{lstlisting}
  1266. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1267. \label{fig:p1-x86}
  1268. \end{figure}
  1269. \begin{figure}[tbp]
  1270. \centering
  1271. \begin{tabular}{|r|l|} \hline
  1272. Position & Contents \\ \hline
  1273. 8(\key{\%rbp}) & return address \\
  1274. 0(\key{\%rbp}) & old \key{rbp} \\
  1275. -8(\key{\%rbp}) & variable $1$ \\
  1276. -16(\key{\%rbp}) & variable $2$ \\
  1277. \ldots & \ldots \\
  1278. 0(\key{\%rsp}) & variable $n$\\ \hline
  1279. \end{tabular}
  1280. \caption{Memory layout of a frame.}
  1281. \label{fig:frame}
  1282. \end{figure}
  1283. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1284. three instructions are the typical \emph{prelude} for a procedure.
  1285. The instruction \key{pushq \%rbp} saves the base pointer for the
  1286. caller onto the stack and subtracts $8$ from the stack pointer. The
  1287. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1288. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1289. stack pointer down to make enough room for storing variables. This
  1290. program needs one variable ($8$ bytes) but because the frame size is
  1291. required to be a multiple of 16 bytes, the space for variables is
  1292. rounded to 16 bytes.
  1293. The four instructions under the label \code{start} carry out the work
  1294. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1295. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1296. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1297. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1298. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1299. \key{rax}, at which point \key{rax} contains $42$.
  1300. The three instructions under the label \code{conclusion} are the
  1301. typical \emph{finale} of a procedure. The first two instructions are
  1302. necessary to get the state of the machine back to where it was at the
  1303. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1304. moves the stack pointer back to point at the old base pointer. The
  1305. amount added here needs to match the amount that was subtracted in the
  1306. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1307. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1308. instruction, \key{retq}, jumps back to the procedure that called this
  1309. one and adds 8 to the stack pointer, which returns the stack pointer
  1310. to where it was prior to the procedure call.
  1311. The compiler will need a convenient representation for manipulating
  1312. x86 programs, so we define an abstract syntax for x86 in
  1313. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1314. a subscript $0$ because later we introduce extended versions of this
  1315. assembly language. The main difference compared to the concrete syntax
  1316. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1317. instructions to appear anywhere, but instead organizes instructions
  1318. into groups called \emph{blocks} and associates a label with every
  1319. block, which is why the \key{CFG} struct (for control-flow graph)
  1320. includes an alist mapping labels to blocks. The reason for
  1321. this organization becomes apparent in Chapter~\ref{ch:bool-types} when
  1322. we introduce conditional branching.
  1323. \begin{figure}[tp]
  1324. \fbox{
  1325. \begin{minipage}{0.96\textwidth}
  1326. \small
  1327. \[
  1328. \begin{array}{lcl}
  1329. \Reg &::=& \allregisters{} \\
  1330. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1331. \mid \DEREF{\Reg}{\Int} \\
  1332. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1333. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1334. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1335. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1336. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1337. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \\
  1338. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1339. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1340. \end{array}
  1341. \]
  1342. \end{minipage}
  1343. }
  1344. \caption{Abstract syntax of $x86_0$ assembly.}
  1345. \label{fig:x86-ast-a}
  1346. \end{figure}
  1347. \section{Planning the trip to x86 via the $C_0$ language}
  1348. \label{sec:plan-s0-x86}
  1349. To compile one language to another it helps to focus on the
  1350. differences between the two languages because the compiler will need
  1351. to bridge those differences. What are the differences between $R_1$
  1352. and x86 assembly? Here are some of the most important ones:
  1353. \begin{enumerate}
  1354. \item[(a)] x86 arithmetic instructions typically have two arguments
  1355. and update the second argument in place. In contrast, $R_1$
  1356. arithmetic operations take two arguments and produce a new value.
  1357. An x86 instruction may have at most one memory-accessing argument.
  1358. Furthermore, some instructions place special restrictions on their
  1359. arguments.
  1360. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1361. whereas x86 instructions restrict their arguments to be integers
  1362. constants, registers, and memory locations.
  1363. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1364. sequence of instructions and jumps to labeled positions, whereas in
  1365. $R_1$ the order of evaluation is a left-to-right depth-first
  1366. traversal of the abstract syntax tree.
  1367. \item[(d)] An $R_1$ program can have any number of variables whereas
  1368. x86 has 16 registers and the procedure calls stack.
  1369. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1370. same name. The registers and memory locations of x86 all have unique
  1371. names or addresses.
  1372. \end{enumerate}
  1373. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1374. the problem into several steps, dealing with the above differences one
  1375. at a time. Each of these steps is called a \emph{pass} of the
  1376. compiler.
  1377. %
  1378. This terminology comes from each step traverses (i.e. passes over) the
  1379. AST of the program.
  1380. %
  1381. We begin by sketching how we might implement each pass, and give them
  1382. names. We then figure out an ordering of the passes and the
  1383. input/output language for each pass. The very first pass has $R_1$ as
  1384. its input language and the last pass has x86 as its output
  1385. language. In between we can choose whichever language is most
  1386. convenient for expressing the output of each pass, whether that be
  1387. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1388. Finally, to implement each pass we write one recursive function per
  1389. non-terminal in the grammar of the input language of the pass.
  1390. \begin{description}
  1391. \item[Pass \key{select-instructions}] To handle the difference between
  1392. $R_1$ operations and x86 instructions we convert each $R_1$
  1393. operation to a short sequence of instructions that accomplishes the
  1394. same task.
  1395. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1396. subexpression (i.e. operator and operand, and hence the name
  1397. \key{opera*}) is an \emph{atomic} expression (a variable or
  1398. integer), we introduce temporary variables to hold the results
  1399. of subexpressions.
  1400. \item[Pass \key{explicate-control}] To make the execution order of the
  1401. program explicit, we convert from the abstract syntax tree
  1402. representation into a \emph{control-flow graph} in which each node
  1403. contains a sequence of statements and the edges between nodes say
  1404. where to go at the end of the sequence.
  1405. \item[Pass \key{assign-homes}] To handle the difference between the
  1406. variables in $R_1$ versus the registers and stack locations in x86,
  1407. we assignment of each variable to a register or stack location.
  1408. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1409. by renaming every variable to a unique name, so that shadowing no
  1410. longer occurs.
  1411. \end{description}
  1412. The next question is: in what order should we apply these passes? This
  1413. question can be challenging because it is difficult to know ahead of
  1414. time which orders will be better (easier to implement, produce more
  1415. efficient code, etc.) so oftentimes trial-and-error is
  1416. involved. Nevertheless, we can try to plan ahead and make educated
  1417. choices regarding the ordering.
  1418. Let us consider the ordering of \key{uniquify} and
  1419. \key{remove-complex-opera*}. The assignment of subexpressions to
  1420. temporary variables involves introducing new variables and moving
  1421. subexpressions, which might change the shadowing of variables and
  1422. inadvertently change the behavior of the program. But if we apply
  1423. \key{uniquify} first, this will not be an issue. Of course, this means
  1424. that in \key{remove-complex-opera*}, we need to ensure that the
  1425. temporary variables that it creates are unique.
  1426. What should be the ordering of \key{explicate-control} with respect to
  1427. \key{uniquify}? The \key{uniquify} pass should come first because
  1428. \key{explicate-control} changes all the \key{let}-bound variables to
  1429. become local variables whose scope is the entire program, which would
  1430. confuse variables with the same name.
  1431. %
  1432. Likewise, we place \key{explicate-control} after
  1433. \key{remove-complex-opera*} because \key{explicate-control} removes
  1434. the \key{let} form, but it is convenient to use \key{let} in the
  1435. output of \key{remove-complex-opera*}.
  1436. %
  1437. Regarding \key{assign-homes}, it is helpful to place
  1438. \key{explicate-control} first because \key{explicate-control} changes
  1439. \key{let}-bound variables into program-scope variables. This means
  1440. that the \key{assign-homes} pass can read off the variables from the
  1441. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1442. entire program in search of \key{let}-bound variables.
  1443. Last, we need to decide on the ordering of \key{select-instructions}
  1444. and \key{assign-homes}. These two passes are intertwined, creating a
  1445. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1446. have already determined which instructions will be used, because x86
  1447. instructions have restrictions about which of their arguments can be
  1448. registers versus stack locations. One might want to give preferential
  1449. treatment to variables that occur in register-argument positions. On
  1450. the other hand, it may turn out to be impossible to make sure that all
  1451. such variables are assigned to registers, and then one must redo the
  1452. selection of instructions. Some compilers handle this problem by
  1453. iteratively repeating these two passes until a good solution is found.
  1454. We shall use a simpler approach in which \key{select-instructions}
  1455. comes first, followed by the \key{assign-homes}, then a third
  1456. pass named \key{patch-instructions} that uses a reserved register to
  1457. patch-up outstanding problems regarding instructions with too many
  1458. memory accesses. The disadvantage of this approach is some programs
  1459. may not execute as efficiently as they would if we used the iterative
  1460. approach and used all of the registers for variables.
  1461. \begin{figure}[tbp]
  1462. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1463. \node (R1) at (0,2) {\large $R_1$};
  1464. \node (R1-2) at (3,2) {\large $R_1$};
  1465. \node (R1-3) at (6,2) {\large $R_1$};
  1466. %\node (C0-1) at (6,0) {\large $C_0$};
  1467. \node (C0-2) at (3,0) {\large $C_0$};
  1468. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1469. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1470. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1471. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1472. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1473. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1474. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1475. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1476. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1477. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1478. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1479. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1480. \end{tikzpicture}
  1481. \caption{Overview of the passes for compiling $R_1$. }
  1482. \label{fig:R1-passes}
  1483. \end{figure}
  1484. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1485. passes in the form of a graph. Each pass is an edge and the
  1486. input/output language of each pass is a node in the graph. The output
  1487. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1488. are still in the $R_1$ language, but the output of the pass
  1489. \key{explicate-control} is in a different language $C_0$ that is
  1490. designed to make the order of evaluation explicit in its syntax, which
  1491. we introduce in the next section. The \key{select-instruction} pass
  1492. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1493. \key{patch-instructions} passes input and output variants of x86
  1494. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1495. \key{print-x86}, which converts from the abstract syntax of
  1496. $\text{x86}_0$ to the concrete syntax of x86.
  1497. In the next sections we discuss the $C_0$ language and the
  1498. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1499. remainder of this chapter gives hints regarding the implementation of
  1500. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1501. \subsection{The $C_0$ Intermediate Language}
  1502. The output of \key{explicate-control} is similar to the $C$
  1503. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1504. categories for expressions and statements, so we name it $C_0$. The
  1505. concrete syntax for $C_0$ is defined in
  1506. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1507. is defined in Figure~\ref{fig:c0-syntax}.
  1508. %
  1509. The $C_0$ language supports the same operators as $R_1$ but the
  1510. arguments of operators are restricted to atomic expressions (variables
  1511. and integers), thanks to the \key{remove-complex-opera*} pass. In the
  1512. literature this style of intermediate language is called
  1513. administrative normal form, or ANF for
  1514. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{Let}
  1515. expressions, $C_0$ has assignment statements which can be executed in
  1516. sequence using the \key{Seq} form. A sequence of statements always
  1517. ends with \key{Return}, a guarantee that is baked into the grammar
  1518. rules for the \itm{tail} non-terminal. The naming of this non-terminal
  1519. comes from the term \emph{tail position}, which refers to an
  1520. expression that is the last one to execute within a function. (A
  1521. expression in tail position may contain subexpressions, and those may
  1522. or may not be in tail position depending on the kind of expression.)
  1523. A $C_0$ program consists of a control-flow graph (represented as an
  1524. alist mapping labels to tails). This is more general than
  1525. necessary for the present chapter, as we do not yet need to introduce
  1526. \key{goto} for jumping to labels, but it saves us from having to
  1527. change the syntax of the program construct in
  1528. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1529. \key{start}, and the whole program is its tail.
  1530. %
  1531. The $\itm{info}$ field of the \key{Program} form, after the
  1532. \key{explicate-control} pass, contains a mapping from the symbol
  1533. \key{locals} to a list of variables, that is, a list of all the
  1534. variables used in the program. At the start of the program, these
  1535. variables are uninitialized; they become initialized on their first
  1536. assignment.
  1537. \begin{figure}[tbp]
  1538. \fbox{
  1539. \begin{minipage}{0.96\textwidth}
  1540. \[
  1541. \begin{array}{lcl}
  1542. \Atm &::=& \Int \mid \Var \\
  1543. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1544. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1545. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1546. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1547. \end{array}
  1548. \]
  1549. \end{minipage}
  1550. }
  1551. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1552. \label{fig:c0-concrete-syntax}
  1553. \end{figure}
  1554. \begin{figure}[tbp]
  1555. \fbox{
  1556. \begin{minipage}{0.96\textwidth}
  1557. \[
  1558. \begin{array}{lcl}
  1559. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1560. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1561. &\mid& \ADD{\Atm}{\Atm}\\
  1562. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1563. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1564. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1565. \end{array}
  1566. \]
  1567. \end{minipage}
  1568. }
  1569. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1570. \label{fig:c0-syntax}
  1571. \end{figure}
  1572. %% The \key{select-instructions} pass is optimistic in the sense that it
  1573. %% treats variables as if they were all mapped to registers. The
  1574. %% \key{select-instructions} pass generates a program that consists of
  1575. %% x86 instructions but that still uses variables, so it is an
  1576. %% intermediate language that is technically different than x86, which
  1577. %% explains the asterisks in the diagram above.
  1578. %% In this Chapter we shall take the easy road to implementing
  1579. %% \key{assign-homes} and simply map all variables to stack locations.
  1580. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1581. %% smarter approach in which we make a best-effort to map variables to
  1582. %% registers, resorting to the stack only when necessary.
  1583. %% Once variables have been assigned to their homes, we can finalize the
  1584. %% instruction selection by dealing with an idiosyncrasy of x86
  1585. %% assembly. Many x86 instructions have two arguments but only one of the
  1586. %% arguments may be a memory reference (and the stack is a part of
  1587. %% memory). Because some variables may get mapped to stack locations,
  1588. %% some of our generated instructions may violate this restriction. The
  1589. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1590. %% replacing every violating instruction with a short sequence of
  1591. %% instructions that use the \key{rax} register. Once we have implemented
  1592. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1593. %% need to patch instructions will be relatively rare.
  1594. \subsection{The dialects of x86}
  1595. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1596. the pass \key{select-instructions}. It extends $x86_0$ with an
  1597. unbounded number of program-scope variables and has looser rules
  1598. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1599. output of \key{print-x86}, is the concrete syntax for x86.
  1600. \section{Uniquify Variables}
  1601. \label{sec:uniquify-s0}
  1602. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1603. programs in which every \key{let} uses a unique variable name. For
  1604. example, the \code{uniquify} pass should translate the program on the
  1605. left into the program on the right. \\
  1606. \begin{tabular}{lll}
  1607. \begin{minipage}{0.4\textwidth}
  1608. \begin{lstlisting}
  1609. (let ([x 32])
  1610. (+ (let ([x 10]) x) x))
  1611. \end{lstlisting}
  1612. \end{minipage}
  1613. &
  1614. $\Rightarrow$
  1615. &
  1616. \begin{minipage}{0.4\textwidth}
  1617. \begin{lstlisting}
  1618. (let ([x.1 32])
  1619. (+ (let ([x.2 10]) x.2) x.1))
  1620. \end{lstlisting}
  1621. \end{minipage}
  1622. \end{tabular} \\
  1623. %
  1624. The following is another example translation, this time of a program
  1625. with a \key{let} nested inside the initializing expression of another
  1626. \key{let}.\\
  1627. \begin{tabular}{lll}
  1628. \begin{minipage}{0.4\textwidth}
  1629. \begin{lstlisting}
  1630. (let ([x (let ([x 4])
  1631. (+ x 1))])
  1632. (+ x 2))
  1633. \end{lstlisting}
  1634. \end{minipage}
  1635. &
  1636. $\Rightarrow$
  1637. &
  1638. \begin{minipage}{0.4\textwidth}
  1639. \begin{lstlisting}
  1640. (let ([x.2 (let ([x.1 4])
  1641. (+ x.1 1))])
  1642. (+ x.2 2))
  1643. \end{lstlisting}
  1644. \end{minipage}
  1645. \end{tabular}
  1646. We recommend implementing \code{uniquify} by creating a function named
  1647. \code{uniquify-exp} that is structurally recursive function and mostly
  1648. just copies the input program. However, when encountering a \key{let},
  1649. it should generate a unique name for the variable (the Racket function
  1650. \code{gensym} is handy for this) and associate the old name with the
  1651. new unique name in an alist. The \code{uniquify-exp}
  1652. function will need to access this alist when it gets to a
  1653. variable reference, so we add another parameter to \code{uniquify-exp}
  1654. for the alist.
  1655. The skeleton of the \code{uniquify-exp} function is shown in
  1656. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1657. convenient to partially apply it to a symbol table and then apply it
  1658. to different expressions, as in the last clause for primitive
  1659. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1660. is useful for applying a function to each element of a list to produce
  1661. a new list.
  1662. \begin{exercise}
  1663. \normalfont % I don't like the italics for exercises. -Jeremy
  1664. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1665. implement the clauses for variables and for the \key{let} form.
  1666. \end{exercise}
  1667. \begin{figure}[tbp]
  1668. \begin{lstlisting}
  1669. (define (uniquify-exp symtab)
  1670. (lambda (e)
  1671. (match e
  1672. [(Var x) ___]
  1673. [(Int n) (Int n)]
  1674. [(Let x e body) ___]
  1675. [(Prim op es)
  1676. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1677. )))
  1678. (define (uniquify p)
  1679. (match p
  1680. [(Program info e)
  1681. (Program info ((uniquify-exp '()) e))]
  1682. )))
  1683. \end{lstlisting}
  1684. \caption{Skeleton for the \key{uniquify} pass.}
  1685. \label{fig:uniquify-s0}
  1686. \end{figure}
  1687. \begin{exercise}
  1688. \normalfont % I don't like the italics for exercises. -Jeremy
  1689. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1690. and checking whether the output programs produce the same result as
  1691. the input programs. The $R_1$ programs should be designed to test the
  1692. most interesting parts of the \key{uniquify} pass, that is, the
  1693. programs should include \key{let} forms, variables, and variables
  1694. that overshadow each other. The five programs should be in a
  1695. subdirectory named \key{tests} and they should have the same file name
  1696. except for a different integer at the end of the name, followed by the
  1697. ending \key{.rkt}. Use the \key{interp-tests} function
  1698. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1699. your \key{uniquify} pass on the example programs. See the
  1700. \key{run-tests.rkt} script in the student support code for an example
  1701. of how to use \key{interp-tests}.
  1702. \end{exercise}
  1703. \section{Remove Complex Operands}
  1704. \label{sec:remove-complex-opera-r1}
  1705. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1706. $R_1$ programs in which the arguments of operations are atomic
  1707. expressions. Put another way, this pass removes complex operands,
  1708. such as the expression \code{(- 10)} in the program below. This is
  1709. accomplished by introducing a new \key{let}-bound variable, binding
  1710. the complex operand to the new variable, and then using the new
  1711. variable in place of the complex operand, as shown in the output of
  1712. \code{remove-complex-opera*} on the right.\\
  1713. \begin{tabular}{lll}
  1714. \begin{minipage}{0.4\textwidth}
  1715. % s0_19.rkt
  1716. \begin{lstlisting}
  1717. (+ 52 (- 10))
  1718. \end{lstlisting}
  1719. \end{minipage}
  1720. &
  1721. $\Rightarrow$
  1722. &
  1723. \begin{minipage}{0.4\textwidth}
  1724. \begin{lstlisting}
  1725. (let ([tmp.1 (- 10)])
  1726. (+ 52 tmp.1))
  1727. \end{lstlisting}
  1728. \end{minipage}
  1729. \end{tabular}
  1730. We recommend implementing this pass with two mutually recursive
  1731. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1732. \code{rco-atom} to subexpressions that need to become atomic and to
  1733. apply \code{rco-exp} to subexpressions that can be atomic or complex.
  1734. Both functions take an $R_1$ expression as input. The \code{rco-exp}
  1735. function returns an expression. The \code{rco-atom} function returns
  1736. two things: an atomic expression and alist mapping
  1737. temporary variables to complex subexpressions. You can return multiple
  1738. things from a function using Racket's \key{values} form and you can
  1739. receive multiple things from a function call using the
  1740. \key{define-values} form. If you are not familiar with these features,
  1741. review the Racket documentation. Also, the \key{for/lists} form is
  1742. useful for applying a function to each element of a list, in the case
  1743. where the function returns multiple values.
  1744. The following shows the output of \code{rco-atom} on the expression
  1745. \code{(- 10)} (using concrete syntax to be concise).
  1746. \begin{tabular}{lll}
  1747. \begin{minipage}{0.4\textwidth}
  1748. \begin{lstlisting}
  1749. (- 10)
  1750. \end{lstlisting}
  1751. \end{minipage}
  1752. &
  1753. $\Rightarrow$
  1754. &
  1755. \begin{minipage}{0.4\textwidth}
  1756. \begin{lstlisting}
  1757. tmp.1
  1758. ((tmp.1 . (- 10)))
  1759. \end{lstlisting}
  1760. \end{minipage}
  1761. \end{tabular}
  1762. Take special care of programs such as the next one that \key{let}-bind
  1763. variables with integers or other variables. You should leave them
  1764. unchanged, as shown in to the program on the right \\
  1765. \begin{tabular}{lll}
  1766. \begin{minipage}{0.4\textwidth}
  1767. % s0_20.rkt
  1768. \begin{lstlisting}
  1769. (let ([a 42])
  1770. (let ([b a])
  1771. b))
  1772. \end{lstlisting}
  1773. \end{minipage}
  1774. &
  1775. $\Rightarrow$
  1776. &
  1777. \begin{minipage}{0.4\textwidth}
  1778. \begin{lstlisting}
  1779. (let ([a 42])
  1780. (let ([b a])
  1781. b))
  1782. \end{lstlisting}
  1783. \end{minipage}
  1784. \end{tabular} \\
  1785. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1786. produce the following output.\\
  1787. \begin{minipage}{0.4\textwidth}
  1788. \begin{lstlisting}
  1789. (let ([tmp.1 42])
  1790. (let ([a tmp.1])
  1791. (let ([tmp.2 a])
  1792. (let ([b tmp.2])
  1793. b))))
  1794. \end{lstlisting}
  1795. \end{minipage}
  1796. \begin{exercise}
  1797. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1798. it on all of the example programs that you created to test the
  1799. \key{uniquify} pass and create three new example programs that are
  1800. designed to exercise the interesting code in the
  1801. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1802. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1803. your passes on the example programs.
  1804. \end{exercise}
  1805. \section{Explicate Control}
  1806. \label{sec:explicate-control-r1}
  1807. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1808. programs that make the order of execution explicit in their
  1809. syntax. For now this amounts to flattening \key{let} constructs into a
  1810. sequence of assignment statements. For example, consider the following
  1811. $R_1$ program.\\
  1812. % s0_11.rkt
  1813. \begin{minipage}{0.96\textwidth}
  1814. \begin{lstlisting}
  1815. (let ([y (let ([x 20])
  1816. (+ x (let ([x 22]) x)))])
  1817. y)
  1818. \end{lstlisting}
  1819. \end{minipage}\\
  1820. %
  1821. The output of the previous pass and of \code{explicate-control} is
  1822. shown below. Recall that the right-hand-side of a \key{let} executes
  1823. before its body, so the order of evaluation for this program is to
  1824. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1825. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1826. output of \code{explicate-control} makes this ordering explicit.\\
  1827. \begin{tabular}{lll}
  1828. \begin{minipage}{0.4\textwidth}
  1829. \begin{lstlisting}
  1830. (let ([y (let ([x.1 20])
  1831. (let ([x.2 22])
  1832. (+ x.1 x.2)))])
  1833. y)
  1834. \end{lstlisting}
  1835. \end{minipage}
  1836. &
  1837. $\Rightarrow$
  1838. &
  1839. \begin{minipage}{0.4\textwidth}
  1840. \begin{lstlisting}
  1841. locals: y x.1 x.2
  1842. start:
  1843. x.1 = 20;
  1844. x.2 = 22;
  1845. y = (+ x.1 x.2);
  1846. return y;
  1847. \end{lstlisting}
  1848. \end{minipage}
  1849. \end{tabular}
  1850. We recommend implementing \code{explicate-control} using two mutually
  1851. recursive functions: \code{explicate-tail} and
  1852. \code{explicate-assign}. The first function should be applied to
  1853. expressions in tail position whereas the second should be applied to
  1854. expressions that occur on the right-hand-side of a \key{let}. The
  1855. \code{explicate-tail} function takes an $R_1$ expression as input and
  1856. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1857. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1858. function takes an $R_1$ expression, the variable that it is to be
  1859. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1860. assignment (e.g., the code generated for the body of the \key{let}).
  1861. It returns a $\Tail$ and a list of variables. The top-level
  1862. \code{explicate-control} function should invoke \code{explicate-tail}
  1863. on the body of the \key{program} and then associate the \code{locals}
  1864. symbol with the resulting list of variables in the $\itm{info}$ field,
  1865. as in the above example.
  1866. \section{Select Instructions}
  1867. \label{sec:select-r1}
  1868. In the \code{select-instructions} pass we begin the work of
  1869. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1870. this pass is a variant of x86 that still uses variables, so we add an
  1871. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1872. syntax of Figure~\ref{fig:x86-ast-a}. We recommend implementing the
  1873. \code{select-instructions} in terms of three auxiliary functions, one
  1874. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1875. The cases for $\Atm$ are straightforward, variables stay
  1876. the same and integer constants are changed to immediates:
  1877. $\INT{n}$ changes to $\IMM{n}$.
  1878. Next we consider the cases for $\Stmt$, starting with arithmetic
  1879. operations. For example, in $C_0$ an addition operation can take the
  1880. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1881. need to use the \key{addq} instruction which does an in-place
  1882. update. So we must first move \code{10} to \code{x}. \\
  1883. \begin{tabular}{lll}
  1884. \begin{minipage}{0.4\textwidth}
  1885. \begin{lstlisting}
  1886. x = (+ 10 32);
  1887. \end{lstlisting}
  1888. \end{minipage}
  1889. &
  1890. $\Rightarrow$
  1891. &
  1892. \begin{minipage}{0.4\textwidth}
  1893. \begin{lstlisting}
  1894. movq $10, x
  1895. addq $32, x
  1896. \end{lstlisting}
  1897. \end{minipage}
  1898. \end{tabular} \\
  1899. %
  1900. There are cases that require special care to avoid generating
  1901. needlessly complicated code. If one of the arguments of the addition
  1902. is the same as the left-hand side of the assignment, then there is no
  1903. need for the extra move instruction. For example, the following
  1904. assignment statement can be translated into a single \key{addq}
  1905. instruction.\\
  1906. \begin{tabular}{lll}
  1907. \begin{minipage}{0.4\textwidth}
  1908. \begin{lstlisting}
  1909. x = (+ 10 x);
  1910. \end{lstlisting}
  1911. \end{minipage}
  1912. &
  1913. $\Rightarrow$
  1914. &
  1915. \begin{minipage}{0.4\textwidth}
  1916. \begin{lstlisting}
  1917. addq $10, x
  1918. \end{lstlisting}
  1919. \end{minipage}
  1920. \end{tabular} \\
  1921. The \key{read} operation does not have a direct counterpart in x86
  1922. assembly, so we have instead implemented this functionality in the C
  1923. language, with the function \code{read\_int} in the file
  1924. \code{runtime.c}. In general, we refer to all of the functionality in
  1925. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1926. for short. When compiling your generated x86 assembly code, you need
  1927. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1928. using \code{gcc} option \code{-c}) and link it into the
  1929. executable. For our purposes of code generation, all you need to do is
  1930. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1931. (for left-hand side) into a call to the \code{read\_int} function
  1932. followed by a move from \code{rax} to the left-hand side. The move
  1933. from \code{rax} is needed because the return value from
  1934. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1935. \begin{tabular}{lll}
  1936. \begin{minipage}{0.3\textwidth}
  1937. \begin{lstlisting}
  1938. |$\itm{var}$| = (read);
  1939. \end{lstlisting}
  1940. \end{minipage}
  1941. &
  1942. $\Rightarrow$
  1943. &
  1944. \begin{minipage}{0.3\textwidth}
  1945. \begin{lstlisting}
  1946. callq read_int
  1947. movq %rax, |$\itm{var}$|
  1948. \end{lstlisting}
  1949. \end{minipage}
  1950. \end{tabular} \\
  1951. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1952. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1953. assignment to the \key{rax} register followed by a jump to the
  1954. conclusion of the program (so the conclusion needs to be labeled).
  1955. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1956. recursively and append the resulting instructions.
  1957. \begin{exercise}
  1958. \normalfont
  1959. Implement the \key{select-instructions} pass and test it on all of the
  1960. example programs that you created for the previous passes and create
  1961. three new example programs that are designed to exercise all of the
  1962. interesting code in this pass. Use the \key{interp-tests} function
  1963. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1964. your passes on the example programs.
  1965. \end{exercise}
  1966. \section{Assign Homes}
  1967. \label{sec:assign-r1}
  1968. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1969. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1970. Thus, the \key{assign-homes} pass is responsible for placing all of
  1971. the program variables in registers or on the stack. For runtime
  1972. efficiency, it is better to place variables in registers, but as there
  1973. are only 16 registers, some programs must necessarily resort to
  1974. placing some variables on the stack. In this chapter we focus on the
  1975. mechanics of placing variables on the stack. We study an algorithm for
  1976. placing variables in registers in
  1977. Chapter~\ref{ch:register-allocation-r1}.
  1978. Consider again the following $R_1$ program.
  1979. % s0_20.rkt
  1980. \begin{lstlisting}
  1981. (let ([a 42])
  1982. (let ([b a])
  1983. b))
  1984. \end{lstlisting}
  1985. For reference, we repeat the output of \code{select-instructions} on
  1986. the left and show the output of \code{assign-homes} on the right.
  1987. Recall that \key{explicate-control} associated the list of
  1988. variables with the \code{locals} symbol in the program's $\itm{info}$
  1989. field, so \code{assign-homes} has convenient access to the them. In
  1990. this example, we assign variable \code{a} to stack location
  1991. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1992. \begin{tabular}{l}
  1993. \begin{minipage}{0.4\textwidth}
  1994. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1995. locals: a b
  1996. start:
  1997. movq $42, a
  1998. movq a, b
  1999. movq b, %rax
  2000. jmp conclusion
  2001. \end{lstlisting}
  2002. \end{minipage}
  2003. {$\Rightarrow$}
  2004. \begin{minipage}{0.4\textwidth}
  2005. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2006. stack-space: 16
  2007. start:
  2008. movq $42, -8(%rbp)
  2009. movq -8(%rbp), -16(%rbp)
  2010. movq -16(%rbp), %rax
  2011. jmp conclusion
  2012. \end{lstlisting}
  2013. \end{minipage}
  2014. \end{tabular} \\
  2015. In the process of assigning variables to stack locations, it is
  2016. convenient to compute and store the size of the frame (in bytes) in
  2017. the $\itm{info}$ field of the \key{Program} node, with the key
  2018. \code{stack-space}, which will be needed later to generate the
  2019. procedure conclusion. Some operating systems place restrictions on
  2020. the frame size. For example, Mac OS X requires the frame size to be a
  2021. multiple of 16 bytes.
  2022. \begin{exercise}
  2023. \normalfont Implement the \key{assign-homes} pass and test it on all
  2024. of the example programs that you created for the previous passes pass.
  2025. We recommend that \key{assign-homes} take an extra parameter that is a
  2026. mapping of variable names to homes (stack locations for now). Use the
  2027. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2028. \key{utilities.rkt} to test your passes on the example programs.
  2029. \end{exercise}
  2030. \section{Patch Instructions}
  2031. \label{sec:patch-s0}
  2032. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2033. programs to $\text{x86}_0$ programs by making sure that each
  2034. instruction adheres to the restrictions of the x86 assembly language.
  2035. In particular, at most one argument of an instruction may be a memory
  2036. reference.
  2037. We return to the following running example.
  2038. % s0_20.rkt
  2039. \begin{lstlisting}
  2040. (let ([a 42])
  2041. (let ([b a])
  2042. b))
  2043. \end{lstlisting}
  2044. After the \key{assign-homes} pass, the above program has been translated to
  2045. the following. \\
  2046. \begin{minipage}{0.5\textwidth}
  2047. \begin{lstlisting}
  2048. stack-space: 16
  2049. start:
  2050. movq $42, -8(%rbp)
  2051. movq -8(%rbp), -16(%rbp)
  2052. movq -16(%rbp), %rax
  2053. jmp conclusion
  2054. \end{lstlisting}
  2055. \end{minipage}\\
  2056. The second \key{movq} instruction is problematic because both
  2057. arguments are stack locations. We suggest fixing this problem by
  2058. moving from the source location to the register \key{rax} and then
  2059. from \key{rax} to the destination location, as follows.
  2060. \begin{lstlisting}
  2061. movq -8(%rbp), %rax
  2062. movq %rax, -16(%rbp)
  2063. \end{lstlisting}
  2064. \begin{exercise}
  2065. \normalfont
  2066. Implement the \key{patch-instructions} pass and test it on all of the
  2067. example programs that you created for the previous passes and create
  2068. three new example programs that are designed to exercise all of the
  2069. interesting code in this pass. Use the \key{interp-tests} function
  2070. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2071. your passes on the example programs.
  2072. \end{exercise}
  2073. \section{Print x86}
  2074. \label{sec:print-x86}
  2075. The last step of the compiler from $R_1$ to x86 is to convert the
  2076. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  2077. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  2078. \key{format} and \key{string-append} functions are useful in this
  2079. regard. The main work that this step needs to perform is to create the
  2080. \key{main} function and the standard instructions for its prelude and
  2081. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2082. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2083. variables, so we suggest computing it in the \key{assign-homes} pass
  2084. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2085. of the \key{program} node.
  2086. %% Your compiled code should print the result of the program's execution
  2087. %% by using the \code{print\_int} function provided in
  2088. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2089. %% far, this final result should be stored in the \key{rax} register.
  2090. %% We'll talk more about how to perform function calls with arguments in
  2091. %% general later on, but for now, place the following after the compiled
  2092. %% code for the $R_1$ program but before the conclusion:
  2093. %% \begin{lstlisting}
  2094. %% movq %rax, %rdi
  2095. %% callq print_int
  2096. %% \end{lstlisting}
  2097. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2098. %% stores the first argument to be passed into \key{print\_int}.
  2099. If you want your program to run on Mac OS X, your code needs to
  2100. determine whether or not it is running on a Mac, and prefix
  2101. underscores to labels like \key{main}. You can determine the platform
  2102. with the Racket call \code{(system-type 'os)}, which returns
  2103. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2104. %% In addition to
  2105. %% placing underscores on \key{main}, you need to put them in front of
  2106. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2107. %% \_print\_int}).
  2108. \begin{exercise}
  2109. \normalfont Implement the \key{print-x86} pass and test it on all of
  2110. the example programs that you created for the previous passes. Use the
  2111. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2112. \key{utilities.rkt} to test your complete compiler on the example
  2113. programs. See the \key{run-tests.rkt} script in the student support
  2114. code for an example of how to use \key{compiler-tests}. Also, remember
  2115. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2116. \key{gcc}.
  2117. \end{exercise}
  2118. \section{Challenge: Partial Evaluator for $R_1$}
  2119. \label{sec:pe-R1}
  2120. This section describes optional challenge exercises that involve
  2121. adapting and improving the partial evaluator for $R_0$ that was
  2122. introduced in Section~\ref{sec:partial-evaluation}.
  2123. \begin{exercise}\label{ex:pe-R1}
  2124. \normalfont
  2125. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2126. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2127. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2128. and variables to the $R_0$ language, so you will need to add cases for
  2129. them in the \code{pe-exp} function. Also, note that the \key{program}
  2130. form changes slightly to include an $\itm{info}$ field. Once
  2131. complete, add the partial evaluation pass to the front of your
  2132. compiler and make sure that your compiler still passes all of the
  2133. tests.
  2134. \end{exercise}
  2135. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2136. \begin{exercise}
  2137. \normalfont
  2138. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2139. \code{pe-add} auxiliary functions with functions that know more about
  2140. arithmetic. For example, your partial evaluator should translate
  2141. \begin{lstlisting}
  2142. (+ 1 (+ (read) 1))
  2143. \end{lstlisting}
  2144. into
  2145. \begin{lstlisting}
  2146. (+ 2 (read))
  2147. \end{lstlisting}
  2148. To accomplish this, the \code{pe-exp} function should produce output
  2149. in the form of the $\itm{residual}$ non-terminal of the following
  2150. grammar.
  2151. \[
  2152. \begin{array}{lcl}
  2153. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2154. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2155. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2156. \end{array}
  2157. \]
  2158. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2159. that their inputs are $\itm{residual}$ expressions and they should
  2160. return $\itm{residual}$ expressions. Once the improvements are
  2161. complete, make sure that your compiler still passes all of the tests.
  2162. After all, fast code is useless if it produces incorrect results!
  2163. \end{exercise}
  2164. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2165. \chapter{Register Allocation}
  2166. \label{ch:register-allocation-r1}
  2167. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2168. make our life easier. However, we can improve the performance of the
  2169. generated code if we instead place some variables into registers. The
  2170. CPU can access a register in a single cycle, whereas accessing the
  2171. stack takes many cycles if the relevant data is in cache or many more
  2172. to access main memory if the data is not in cache.
  2173. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2174. serves as a running example. We show the source program and also the
  2175. output of instruction selection. At that point the program is almost
  2176. x86 assembly but not quite; it still contains variables instead of
  2177. stack locations or registers.
  2178. \begin{figure}
  2179. \begin{minipage}{0.45\textwidth}
  2180. Example $R_1$ program:
  2181. % s0_22.rkt
  2182. \begin{lstlisting}
  2183. (let ([v 1])
  2184. (let ([w 46])
  2185. (let ([x (+ v 7)])
  2186. (let ([y (+ 4 x)])
  2187. (let ([z (+ x w)])
  2188. (+ z (- y)))))))
  2189. \end{lstlisting}
  2190. \end{minipage}
  2191. \begin{minipage}{0.45\textwidth}
  2192. After instruction selection:
  2193. \begin{lstlisting}
  2194. locals: v w x y z t.1
  2195. start:
  2196. movq $1, v
  2197. movq $46, w
  2198. movq v, x
  2199. addq $7, x
  2200. movq x, y
  2201. addq $4, y
  2202. movq x, z
  2203. addq w, z
  2204. movq y, t.1
  2205. negq t.1
  2206. movq z, %rax
  2207. addq t.1, %rax
  2208. jmp conclusion
  2209. \end{lstlisting}
  2210. \end{minipage}
  2211. \caption{An example program for register allocation.}
  2212. \label{fig:reg-eg}
  2213. \end{figure}
  2214. The goal of register allocation is to fit as many variables into
  2215. registers as possible. A program sometimes has more variables than
  2216. registers, so we cannot map each variable to a different
  2217. register. Fortunately, it is common for different variables to be
  2218. needed during different periods of time during program execution, and
  2219. in such cases several variables can be mapped to the same register.
  2220. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2221. After the variable \code{x} is moved to \code{z} it is no longer
  2222. needed. Variable \code{y}, on the other hand, is used only after this
  2223. point, so \code{x} and \code{y} could share the same register. The
  2224. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2225. where a variable is needed. Once we have that information, we compute
  2226. which variables are needed at the same time, i.e., which ones
  2227. \emph{interfere}, and represent this relation as an undirected graph
  2228. whose vertices are variables and edges indicate when two variables
  2229. interfere with each other (Section~\ref{sec:build-interference}). We
  2230. then model register allocation as a graph coloring problem, which we
  2231. discuss in Section~\ref{sec:graph-coloring}.
  2232. In the event that we run out of registers despite these efforts, we
  2233. place the remaining variables on the stack, similar to what we did in
  2234. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2235. for assigning a variable to a stack location. The process of spilling
  2236. variables is handled as part of the graph coloring process described
  2237. in \ref{sec:graph-coloring}.
  2238. \section{Registers and Calling Conventions}
  2239. \label{sec:calling-conventions}
  2240. As we perform register allocation, we need to be aware of the
  2241. conventions that govern the way in which registers interact with
  2242. function calls, such as calls to the \code{read\_int} function. The
  2243. convention for x86 is that the caller is responsible for freeing up
  2244. some registers, the \emph{caller-saved registers}, prior to the
  2245. function call, and the callee is responsible for saving and restoring
  2246. some other registers, the \emph{callee-saved registers}, before and
  2247. after using them. The caller-saved registers are
  2248. \begin{lstlisting}
  2249. rax rdx rcx rsi rdi r8 r9 r10 r11
  2250. \end{lstlisting}
  2251. while the callee-saved registers are
  2252. \begin{lstlisting}
  2253. rsp rbp rbx r12 r13 r14 r15
  2254. \end{lstlisting}
  2255. Another way to think about this caller/callee convention is the
  2256. following. The caller should assume that all the caller-saved registers
  2257. get overwritten with arbitrary values by the callee. On the other
  2258. hand, the caller can safely assume that all the callee-saved registers
  2259. contain the same values after the call that they did before the call.
  2260. The callee can freely use any of the caller-saved registers. However,
  2261. if the callee wants to use a callee-saved register, the callee must
  2262. arrange to put the original value back in the register prior to
  2263. returning to the caller, which is usually accomplished by saving and
  2264. restoring the value from the stack.
  2265. \section{Liveness Analysis}
  2266. \label{sec:liveness-analysis-r1}
  2267. A variable is \emph{live} if the variable is used at some later point
  2268. in the program and there is not an intervening assignment to the
  2269. variable.
  2270. %
  2271. To understand the latter condition, consider the following code
  2272. fragment in which there are two writes to \code{b}. Are \code{a} and
  2273. \code{b} both live at the same time?
  2274. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2275. movq $5, a
  2276. movq $30, b
  2277. movq a, c
  2278. movq $10, b
  2279. addq b, c
  2280. \end{lstlisting}
  2281. The answer is no because the integer \code{30} written to \code{b} on
  2282. line 2 is never used. The variable \code{b} is read on line 5 and
  2283. there is an intervening write to \code{b} on line 4, so the read on
  2284. line 5 receives the value written on line 4, not line 2.
  2285. The live variables can be computed by traversing the instruction
  2286. sequence back to front (i.e., backwards in execution order). Let
  2287. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2288. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2289. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2290. variables before instruction $I_k$. The live variables after an
  2291. instruction are always the same as the live variables before the next
  2292. instruction.
  2293. \begin{equation} \label{eq:live-after-before-next}
  2294. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2295. \end{equation}
  2296. To start things off, there are no live variables after the last
  2297. instruction, so
  2298. \begin{equation}\label{eq:live-last-empty}
  2299. L_{\mathsf{after}}(n) = \emptyset
  2300. \end{equation}
  2301. We then apply the following rule repeatedly, traversing the
  2302. instruction sequence back to front.
  2303. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2304. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2305. \end{equation}
  2306. where $W(k)$ are the variables written to by instruction $I_k$ and
  2307. $R(k)$ are the variables read by instruction $I_k$.
  2308. Let us walk through the above example, applying these formulas
  2309. starting with the instruction on line 5. We collect the answers in the
  2310. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2311. instruction is $\emptyset$ because it is the last instruction
  2312. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2313. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2314. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2315. is
  2316. \[
  2317. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2318. \]
  2319. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2320. the live-before set from line 5 to be the live-after set for this
  2321. instruction (formula~\ref{eq:live-after-before-next}).
  2322. \[
  2323. L_{\mathsf{after}}(4) = \{ b, c \}
  2324. \]
  2325. This move instruction writes to $b$ and does not read from any
  2326. variables, so we have the following live-before set
  2327. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2328. \[
  2329. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2330. \]
  2331. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2332. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2333. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2334. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2335. variable that is not live and does not read from a variable.
  2336. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2337. because it writes to variable $a$.
  2338. \begin{center}
  2339. \begin{minipage}{0.45\textwidth}
  2340. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2341. movq $5, a
  2342. movq $30, b
  2343. movq a, c
  2344. movq $10, b
  2345. addq b, c
  2346. \end{lstlisting}
  2347. \end{minipage}
  2348. \vrule\hspace{10pt}
  2349. \begin{minipage}{0.45\textwidth}
  2350. \begin{align*}
  2351. L_{\mathsf{before}}(1)= \emptyset,
  2352. L_{\mathsf{after}}(1)= \{a\}\\
  2353. L_{\mathsf{before}}(2)= \{a\},
  2354. L_{\mathsf{after}}(2)= \{a\}\\
  2355. L_{\mathsf{before}}(3)= \{a\},
  2356. L_{\mathsf{after}}(2)= \{c\}\\
  2357. L_{\mathsf{before}}(4)= \{c\},
  2358. L_{\mathsf{after}}(4)= \{b,c\}\\
  2359. L_{\mathsf{before}}(5)= \{b,c\},
  2360. L_{\mathsf{after}}(5)= \emptyset
  2361. \end{align*}
  2362. \end{minipage}
  2363. \end{center}
  2364. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2365. for the running example program, with each instruction aligned with
  2366. its $L_{\mathtt{after}}$ set to make the figure easy to read.
  2367. \begin{figure}[tbp]
  2368. \hspace{20pt}
  2369. \begin{minipage}{0.45\textwidth}
  2370. \begin{lstlisting}[numbers=left]
  2371. movq $1, v
  2372. movq $46, w
  2373. movq v, x
  2374. addq $7, x
  2375. movq x, y
  2376. addq $4, y
  2377. movq x, z
  2378. addq w, z
  2379. movq y, t.1
  2380. negq t.1)
  2381. movq z, %rax
  2382. addq t.1, %rax
  2383. jmp conclusion
  2384. \end{lstlisting}
  2385. \end{minipage}
  2386. \vrule\hspace{10pt}
  2387. \begin{minipage}{0.45\textwidth}
  2388. \begin{lstlisting}
  2389. |$\{\}$|
  2390. |$\{v \}$|
  2391. |$\{v,w\}$|
  2392. |$\{w,x\}$|
  2393. |$\{w,x\}$|
  2394. |$\{w,x,y\}$|
  2395. |$\{w,x,y\}$|
  2396. |$\{w,y,z\}$|
  2397. |$\{y,z\}$|
  2398. |$\{z,t.1\}$|
  2399. |$\{z,t.1\}$|
  2400. |$\{t.1\}$|
  2401. |$\{\}$|
  2402. |$\{\}$|
  2403. \end{lstlisting}
  2404. \end{minipage}
  2405. \caption{The running example annotated with live-after sets.}
  2406. \label{fig:live-eg}
  2407. \end{figure}
  2408. \begin{exercise}\normalfont
  2409. Implement the compiler pass named \code{uncover-live} that computes
  2410. the live-after sets. We recommend storing the live-after sets (a list
  2411. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2412. structure.
  2413. %
  2414. We recommend organizing your code to use a helper function that takes
  2415. a list of instructions and an initial live-after set (typically empty)
  2416. and returns the list of live-after sets.
  2417. %
  2418. We recommend creating helper functions to 1) compute the set of
  2419. variables that appear in an argument (of an instruction), 2) compute
  2420. the variables read by an instruction which corresponds to the $R$
  2421. function discussed above, and 3) the variables written by an
  2422. instruction which corresponds to $W$.
  2423. \end{exercise}
  2424. \section{Building the Interference Graph}
  2425. \label{sec:build-interference}
  2426. Based on the liveness analysis, we know where each variable is needed.
  2427. However, during register allocation, we need to answer questions of
  2428. the specific form: are variables $u$ and $v$ live at the same time?
  2429. (And therefore cannot be assigned to the same register.) To make this
  2430. question easier to answer, we create an explicit data structure, an
  2431. \emph{interference graph}. An interference graph is an undirected
  2432. graph that has an edge between two variables if they are live at the
  2433. same time, that is, if they interfere with each other.
  2434. The most obvious way to compute the interference graph is to look at
  2435. the set of live variables between each statement in the program and
  2436. add an edge to the graph for every pair of variables in the same set.
  2437. This approach is less than ideal for two reasons. First, it can be
  2438. expensive because it takes $O(n^2)$ time to look at every pair in a
  2439. set of $n$ live variables. Second, there is a special case in which
  2440. two variables that are live at the same time do not actually interfere
  2441. with each other: when they both contain the same value because we have
  2442. assigned one to the other.
  2443. A better way to compute the interference graph is to focus on the
  2444. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2445. instruction to overwrite something in a live variable. So for each
  2446. instruction, we create an edge between the variable being written to
  2447. and all the \emph{other} live variables. (One should not create self
  2448. edges.) For a \key{callq} instruction, think of all caller-saved
  2449. registers as being written to, so an edge must be added between every
  2450. live variable and every caller-saved register. For \key{movq}, we deal
  2451. with the above-mentioned special case by not adding an edge between a
  2452. live variable $v$ and destination $d$ if $v$ matches the source of the
  2453. move. So we have the following three rules.
  2454. \begin{enumerate}
  2455. \item If instruction $I_k$ is an arithmetic instruction such as
  2456. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2457. L_{\mathsf{after}}(k)$ unless $v = d$.
  2458. \item If instruction $I_k$ is of the form \key{callq}
  2459. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2460. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2461. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2462. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2463. d$ or $v = s$.
  2464. \end{enumerate}
  2465. \margincomment{JM: I think you could give examples of each one of these
  2466. using the example program and use those to help explain why these
  2467. rules are correct.\\
  2468. JS: Agreed.}
  2469. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2470. the following interference for the instruction at the specified line
  2471. number.
  2472. \begin{quote}
  2473. Line 2: no interference,\\
  2474. Line 3: $w$ interferes with $v$,\\
  2475. Line 4: $x$ interferes with $w$,\\
  2476. Line 5: $x$ interferes with $w$,\\
  2477. Line 6: $y$ interferes with $w$,\\
  2478. Line 7: $y$ interferes with $w$ and $x$,\\
  2479. Line 8: $z$ interferes with $w$ and $y$,\\
  2480. Line 9: $z$ interferes with $y$, \\
  2481. Line 10: $t.1$ interferes with $z$, \\
  2482. Line 11: $t.1$ interferes with $z$, \\
  2483. Line 12: no interference, \\
  2484. Line 13: no interference. \\
  2485. Line 14: no interference.
  2486. \end{quote}
  2487. The resulting interference graph is shown in
  2488. Figure~\ref{fig:interfere}.
  2489. \begin{figure}[tbp]
  2490. \large
  2491. \[
  2492. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2493. \node (v) at (0,0) {$v$};
  2494. \node (w) at (2,0) {$w$};
  2495. \node (x) at (4,0) {$x$};
  2496. \node (t1) at (6,-2) {$t.1$};
  2497. \node (y) at (2,-2) {$y$};
  2498. \node (z) at (4,-2) {$z$};
  2499. \draw (v) to (w);
  2500. \foreach \i in {w,x,y}
  2501. {
  2502. \foreach \j in {w,x,y}
  2503. {
  2504. \draw (\i) to (\j);
  2505. }
  2506. }
  2507. \draw (z) to (w);
  2508. \draw (z) to (y);
  2509. \draw (t1) to (z);
  2510. \end{tikzpicture}
  2511. \]
  2512. \caption{The interference graph of the example program.}
  2513. \label{fig:interfere}
  2514. \end{figure}
  2515. %% Our next concern is to choose a data structure for representing the
  2516. %% interference graph. There are many choices for how to represent a
  2517. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2518. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2519. %% data structure is to study the algorithm that uses the data structure,
  2520. %% determine what operations need to be performed, and then choose the
  2521. %% data structure that provide the most efficient implementations of
  2522. %% those operations. Often times the choice of data structure can have an
  2523. %% effect on the time complexity of the algorithm, as it does here. If
  2524. %% you skim the next section, you will see that the register allocation
  2525. %% algorithm needs to ask the graph for all of its vertices and, given a
  2526. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2527. %% correct choice of graph representation is that of an adjacency
  2528. %% list. There are helper functions in \code{utilities.rkt} for
  2529. %% representing graphs using the adjacency list representation:
  2530. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2531. %% (Appendix~\ref{appendix:utilities}).
  2532. %% %
  2533. %% \margincomment{\footnotesize To do: change to use the
  2534. %% Racket graph library. \\ --Jeremy}
  2535. %% %
  2536. %% In particular, those functions use a hash table to map each vertex to
  2537. %% the set of adjacent vertices, and the sets are represented using
  2538. %% Racket's \key{set}, which is also a hash table.
  2539. \begin{exercise}\normalfont
  2540. Implement the compiler pass named \code{build-interference} according
  2541. to the algorithm suggested above. We recommend using the Racket
  2542. \code{graph} package to create and inspect the interference graph.
  2543. The output graph of this pass should be stored in the $\itm{info}$
  2544. field of the program, under the key \code{conflicts}.
  2545. \end{exercise}
  2546. \section{Graph Coloring via Sudoku}
  2547. \label{sec:graph-coloring}
  2548. We come to the main event, mapping variables to registers (or to stack
  2549. locations in the event that we run out of registers). We need to make
  2550. sure that two variables do not get mapped to the same register if the
  2551. two variables interfere with each other. Thinking about the
  2552. interference graph, this means that adjacent vertices must be mapped
  2553. to different registers. If we think of registers as colors, the
  2554. register allocation problem becomes the widely-studied graph coloring
  2555. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2556. The reader may be more familiar with the graph coloring problem than he
  2557. or she realizes; the popular game of Sudoku is an instance of the
  2558. graph coloring problem. The following describes how to build a graph
  2559. out of an initial Sudoku board.
  2560. \begin{itemize}
  2561. \item There is one vertex in the graph for each Sudoku square.
  2562. \item There is an edge between two vertices if the corresponding squares
  2563. are in the same row, in the same column, or if the squares are in
  2564. the same $3\times 3$ region.
  2565. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2566. \item Based on the initial assignment of numbers to squares in the
  2567. Sudoku board, assign the corresponding colors to the corresponding
  2568. vertices in the graph.
  2569. \end{itemize}
  2570. If you can color the remaining vertices in the graph with the nine
  2571. colors, then you have also solved the corresponding game of Sudoku.
  2572. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2573. the corresponding graph with colored vertices. We map the Sudoku
  2574. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2575. sampling of the vertices (the colored ones) because showing edges for
  2576. all of the vertices would make the graph unreadable.
  2577. \begin{figure}[tbp]
  2578. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2579. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2580. \caption{A Sudoku game board and the corresponding colored graph.}
  2581. \label{fig:sudoku-graph}
  2582. \end{figure}
  2583. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2584. strategies to come up with an algorithm for allocating registers. For
  2585. example, one of the basic techniques for Sudoku is called Pencil
  2586. Marks. The idea is to use a process of elimination to determine what
  2587. numbers no longer make sense for a square and write down those
  2588. numbers in the square (writing very small). For example, if the number
  2589. $1$ is assigned to a square, then by process of elimination, you can
  2590. write the pencil mark $1$ in all the squares in the same row, column,
  2591. and region. Many Sudoku computer games provide automatic support for
  2592. Pencil Marks.
  2593. %
  2594. The Pencil Marks technique corresponds to the notion of
  2595. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2596. vertex, in Sudoku terms, is the set of numbers that are no longer
  2597. available. In graph terminology, we have the following definition:
  2598. \begin{equation*}
  2599. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2600. \text{ and } \mathrm{color}(v) = c \}
  2601. \end{equation*}
  2602. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2603. edge with $u$.
  2604. Using the Pencil Marks technique leads to a simple strategy for
  2605. filling in numbers: if there is a square with only one possible number
  2606. left, then choose that number! But what if there are no squares with
  2607. only one possibility left? One brute-force approach is to try them
  2608. all: choose the first and if it ultimately leads to a solution,
  2609. great. If not, backtrack and choose the next possibility. One good
  2610. thing about Pencil Marks is that it reduces the degree of branching in
  2611. the search tree. Nevertheless, backtracking can be horribly time
  2612. consuming. One way to reduce the amount of backtracking is to use the
  2613. most-constrained-first heuristic. That is, when choosing a square,
  2614. always choose one with the fewest possibilities left (the vertex with
  2615. the highest saturation). The idea is that choosing highly constrained
  2616. squares earlier rather than later is better because later on there may
  2617. not be any possibilities left for those squares.
  2618. In some sense, register allocation is easier than Sudoku because the
  2619. register allocator can choose to map variables to stack locations when
  2620. the registers run out. Thus, it makes sense to drop backtracking in
  2621. favor of greedy search, that is, make the best choice at the time and
  2622. keep going. We still wish to minimize the number of colors needed, so
  2623. keeping the most-constrained-first heuristic is a good idea.
  2624. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2625. algorithm for register allocation based on saturation and the
  2626. most-constrained-first heuristic. It is roughly equivalent to the
  2627. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2628. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2629. Sudoku, the algorithm represents colors with integers. The first $k$
  2630. colors corresponding to the $k$ registers in a given machine and the
  2631. rest of the integers corresponding to stack locations.
  2632. \begin{figure}[btp]
  2633. \centering
  2634. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2635. Algorithm: DSATUR
  2636. Input: a graph |$G$|
  2637. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2638. |$W \gets \mathit{vertices}(G)$|
  2639. while |$W \neq \emptyset$| do
  2640. pick a vertex |$u$| from |$W$| with the highest saturation,
  2641. breaking ties randomly
  2642. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2643. |$\mathrm{color}[u] \gets c$|
  2644. |$W \gets W - \{u\}$|
  2645. \end{lstlisting}
  2646. \caption{The saturation-based greedy graph coloring algorithm.}
  2647. \label{fig:satur-algo}
  2648. \end{figure}
  2649. With this algorithm in hand, let us return to the running example and
  2650. consider how to color the interference graph in
  2651. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2652. colored and they are unsaturated, so we annotate each of them with a
  2653. dash for their color and an empty set for the saturation.
  2654. \[
  2655. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2656. \node (v) at (0,0) {$v:-,\{\}$};
  2657. \node (w) at (3,0) {$w:-,\{\}$};
  2658. \node (x) at (6,0) {$x:-,\{\}$};
  2659. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2660. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2661. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2662. \draw (v) to (w);
  2663. \foreach \i in {w,x,y}
  2664. {
  2665. \foreach \j in {w,x,y}
  2666. {
  2667. \draw (\i) to (\j);
  2668. }
  2669. }
  2670. \draw (z) to (w);
  2671. \draw (z) to (y);
  2672. \draw (t1) to (z);
  2673. \end{tikzpicture}
  2674. \]
  2675. The algorithm says to select a maximally saturated vertex and color it
  2676. $0$. In this case we have a 7-way tie, so we arbitrarily pick
  2677. $t.1$. We then mark color $0$ as no longer available for $z$ because
  2678. it interferes with $t.1$.
  2679. \[
  2680. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2681. \node (v) at (0,0) {$v:-,\{\}$};
  2682. \node (w) at (3,0) {$w:-,\{\}$};
  2683. \node (x) at (6,0) {$x:-,\{\}$};
  2684. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2685. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2686. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2687. \draw (v) to (w);
  2688. \foreach \i in {w,x,y}
  2689. {
  2690. \foreach \j in {w,x,y}
  2691. {
  2692. \draw (\i) to (\j);
  2693. }
  2694. }
  2695. \draw (z) to (w);
  2696. \draw (z) to (y);
  2697. \draw (t1) to (z);
  2698. \end{tikzpicture}
  2699. \]
  2700. Next we repeat the process, selecting another maximally saturated
  2701. vertex, which is $z$, and color it with the first available number,
  2702. which is $1$.
  2703. \[
  2704. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2705. \node (v) at (0,0) {$v:-,\{\}$};
  2706. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2707. \node (x) at (6,0) {$x:-,\{\}$};
  2708. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2709. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2710. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2711. \draw (t1) to (z);
  2712. \draw (v) to (w);
  2713. \foreach \i in {w,x,y}
  2714. {
  2715. \foreach \j in {w,x,y}
  2716. {
  2717. \draw (\i) to (\j);
  2718. }
  2719. }
  2720. \draw (z) to (w);
  2721. \draw (z) to (y);
  2722. \end{tikzpicture}
  2723. \]
  2724. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2725. first available color, which is $0$.
  2726. \[
  2727. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2728. \node (v) at (0,0) {$v:-,\{\}$};
  2729. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2730. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2731. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2732. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2733. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2734. \draw (t1) to (z);
  2735. \draw (v) to (w);
  2736. \foreach \i in {w,x,y}
  2737. {
  2738. \foreach \j in {w,x,y}
  2739. {
  2740. \draw (\i) to (\j);
  2741. }
  2742. }
  2743. \draw (z) to (w);
  2744. \draw (z) to (y);
  2745. \end{tikzpicture}
  2746. \]
  2747. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2748. We cannot choose $0$ or $1$ because those numbers are in $w$'s
  2749. saturation set. Indeed, $w$ interferes with $y$ and $z$, whose colors
  2750. are $0$ and $1$ respectively.
  2751. \[
  2752. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2753. \node (v) at (0,0) {$v:-,\{2\}$};
  2754. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2755. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2756. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2757. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2758. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2759. \draw (t1) to (z);
  2760. \draw (v) to (w);
  2761. \foreach \i in {w,x,y}
  2762. {
  2763. \foreach \j in {w,x,y}
  2764. {
  2765. \draw (\i) to (\j);
  2766. }
  2767. }
  2768. \draw (z) to (w);
  2769. \draw (z) to (y);
  2770. \end{tikzpicture}
  2771. \]
  2772. Now $x$ has the highest saturation, so we color it $1$.
  2773. \[
  2774. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2775. \node (v) at (0,0) {$v:-,\{2\}$};
  2776. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2777. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2778. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2779. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2780. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2781. \draw (t1) to (z);
  2782. \draw (v) to (w);
  2783. \foreach \i in {w,x,y}
  2784. {
  2785. \foreach \j in {w,x,y}
  2786. {
  2787. \draw (\i) to (\j);
  2788. }
  2789. }
  2790. \draw (z) to (w);
  2791. \draw (z) to (y);
  2792. \end{tikzpicture}
  2793. \]
  2794. In the last step of the algorithm, we color $v$ with $0$.
  2795. \[
  2796. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2797. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2798. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2799. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2800. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2801. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2802. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2803. \draw (t1) to (z);
  2804. \draw (v) to (w);
  2805. \foreach \i in {w,x,y}
  2806. {
  2807. \foreach \j in {w,x,y}
  2808. {
  2809. \draw (\i) to (\j);
  2810. }
  2811. }
  2812. \draw (z) to (w);
  2813. \draw (z) to (y);
  2814. \end{tikzpicture}
  2815. \]
  2816. With the coloring complete, we finalize the assignment of variables to
  2817. registers and stack locations. Recall that if we have $k$ registers,
  2818. we map the first $k$ colors to registers and the rest to stack
  2819. locations. Suppose for the moment that we have just one register to
  2820. use for register allocation, \key{rcx}. Then the following is the
  2821. mapping of colors to registers and stack allocations.
  2822. \[
  2823. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2824. \]
  2825. Putting this mapping together with the above coloring of the
  2826. variables, we arrive at the following assignment of variables to
  2827. registers and stack locations.
  2828. \begin{gather*}
  2829. \{ v \mapsto \key{\%rcx}, \,
  2830. w \mapsto \key{-16(\%rbp)}, \,
  2831. x \mapsto \key{-8(\%rbp)}, \\
  2832. y \mapsto \key{\%rcx}, \,
  2833. z\mapsto \key{-8(\%rbp)},
  2834. t.1\mapsto \key{\%rcx} \}
  2835. \end{gather*}
  2836. Applying this assignment to our running example, on the left, yields
  2837. the program on the right.
  2838. % why frame size of 32? -JGS
  2839. \begin{center}
  2840. \begin{minipage}{0.3\textwidth}
  2841. \begin{lstlisting}
  2842. movq $1, v
  2843. movq $46, w
  2844. movq v, x
  2845. addq $7, x
  2846. movq x, y
  2847. addq $4, y
  2848. movq x, z
  2849. addq w, z
  2850. movq y, t.1
  2851. negq t.1
  2852. movq z, %rax
  2853. addq t.1, %rax
  2854. jmp conclusion
  2855. \end{lstlisting}
  2856. \end{minipage}
  2857. $\Rightarrow\qquad$
  2858. \begin{minipage}{0.45\textwidth}
  2859. \begin{lstlisting}
  2860. movq $1, %rcx
  2861. movq $46, -16(%rbp)
  2862. movq %rcx, -8(%rbp)
  2863. addq $7, -8(%rbp)
  2864. movq -8(%rbp), %rcx
  2865. addq $4, %rcx
  2866. movq -8(%rbp), -8(%rbp)
  2867. addq -16(%rbp), -8(%rbp)
  2868. movq %rcx, %rcx
  2869. negq %rcx
  2870. movq -8(%rbp), %rax
  2871. addq %rcx, %rax
  2872. jmp conclusion
  2873. \end{lstlisting}
  2874. \end{minipage}
  2875. \end{center}
  2876. The resulting program is almost an x86 program. The remaining step is
  2877. the patch instructions pass. In this example, the trivial move of
  2878. \code{-8(\%rbp)} to itself is deleted and the addition of
  2879. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2880. \code{rax} as follows.
  2881. \begin{lstlisting}
  2882. movq -16(%rbp), %rax
  2883. addq %rax, -8(%rbp)
  2884. \end{lstlisting}
  2885. An overview of all of the passes involved in register allocation is
  2886. shown in Figure~\ref{fig:reg-alloc-passes}.
  2887. \begin{figure}[tbp]
  2888. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2889. \node (R1) at (0,2) {\large $R_1$};
  2890. \node (R1-2) at (3,2) {\large $R_1$};
  2891. \node (R1-3) at (6,2) {\large $R_1$};
  2892. \node (C0-1) at (6,0) {\large $C_0$};
  2893. \node (C0-2) at (3,0) {\large $C_0$};
  2894. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2895. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2896. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2897. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2898. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2899. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2900. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2901. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2902. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2903. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2904. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2905. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2906. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2907. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2908. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2909. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2910. \end{tikzpicture}
  2911. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2912. \label{fig:reg-alloc-passes}
  2913. \end{figure}
  2914. \begin{exercise}\normalfont
  2915. Implement the pass \code{allocate-registers}, which should come
  2916. after the \code{build-interference} pass. The three new passes,
  2917. \code{uncover-live}, \code{build-interference}, and
  2918. \code{allocate-registers} replace the \code{assign-homes} pass of
  2919. Section~\ref{sec:assign-r1}.
  2920. We recommend that you create a helper function named
  2921. \code{color-graph} that takes an interference graph and a list of
  2922. all the variables in the program. This function should return a
  2923. mapping of variables to their colors (represented as natural
  2924. numbers). By creating this helper function, you will be able to
  2925. reuse it in Chapter~\ref{ch:functions} when you add support for
  2926. functions.
  2927. Once you have obtained the coloring from \code{color-graph}, you can
  2928. assign the variables to registers or stack locations and then reuse
  2929. code from the \code{assign-homes} pass from
  2930. Section~\ref{sec:assign-r1} to replace the variables with their
  2931. assigned location.
  2932. Test your updated compiler by creating new example programs that
  2933. exercise all of the register allocation algorithm, such as forcing
  2934. variables to be spilled to the stack.
  2935. \end{exercise}
  2936. \section{Print x86 and Conventions for Registers}
  2937. \label{sec:print-x86-reg-alloc}
  2938. Recall that the \code{print-x86} pass generates the prelude and
  2939. conclusion instructions for the \code{main} function.
  2940. %
  2941. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2942. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2943. reason for this is that our \code{main} function must adhere to the
  2944. x86 calling conventions that we described in
  2945. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2946. function needs to restore (in the conclusion) any callee-saved
  2947. registers that get used during register allocation. The simplest
  2948. approach is to save and restore all of the callee-saved registers. The
  2949. more efficient approach is to keep track of which callee-saved
  2950. registers were used and only save and restore them. Either way, make
  2951. sure to take this use of stack space into account when you are
  2952. calculating the size of the frame. Also, don't forget that the size of
  2953. the frame needs to be a multiple of 16 bytes.
  2954. \section{Challenge: Move Biasing}
  2955. \label{sec:move-biasing}
  2956. This section describes an optional enhancement to register allocation
  2957. for those students who are looking for an extra challenge or who have
  2958. a deeper interest in register allocation.
  2959. We return to the running example, but we remove the supposition that
  2960. we only have one register to use. So we have the following mapping of
  2961. color numbers to registers.
  2962. \[
  2963. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  2964. \]
  2965. Using the same assignment of variables to color numbers that was
  2966. produced by the register allocator described in the last section, we
  2967. get the following program.
  2968. \begin{minipage}{0.3\textwidth}
  2969. \begin{lstlisting}
  2970. movq $1, v
  2971. movq $46, w
  2972. movq v, x
  2973. addq $7, x
  2974. movq x, y
  2975. addq $4, y
  2976. movq x, z
  2977. addq w, z
  2978. movq y, t.1
  2979. negq t.1
  2980. movq z, %rax
  2981. addq t.1, %rax
  2982. jmp conclusion
  2983. \end{lstlisting}
  2984. \end{minipage}
  2985. $\Rightarrow\qquad$
  2986. \begin{minipage}{0.45\textwidth}
  2987. \begin{lstlisting}
  2988. movq $1, %rbx
  2989. movq $46, %rdx
  2990. movq %rbx, %rcx
  2991. addq $7, %rcx
  2992. movq %rcx, %rbx
  2993. addq $4, %rbx
  2994. movq %rcx, %rcx
  2995. addq %rdx, %rcx
  2996. movq %rbx, %rbx
  2997. negq %rbx
  2998. movq %rcx, %rax
  2999. addq %rbx, %rax
  3000. jmp conclusion
  3001. \end{lstlisting}
  3002. \end{minipage}
  3003. While this allocation is quite good, we could do better. For example,
  3004. the variables \key{v} and \key{x} ended up in different registers, but
  3005. if they had been placed in the same register, then the move from
  3006. \key{v} to \key{x} could be removed.
  3007. We say that two variables $p$ and $q$ are \emph{move related} if they
  3008. participate together in a \key{movq} instruction, that is, \key{movq}
  3009. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  3010. allocator chooses a color for a variable, it should prefer a color
  3011. that has already been used for a move-related variable (assuming that
  3012. they do not interfere). Of course, this preference should not override
  3013. the preference for registers over stack locations. This preference
  3014. should be used as a tie breaker when choosing between registers or
  3015. when choosing between stack locations.
  3016. We recommend representing the move relationships in a graph, similar
  3017. to how we represented interference. The following is the \emph{move
  3018. graph} for our running example.
  3019. \[
  3020. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3021. \node (v) at (0,0) {$v$};
  3022. \node (w) at (3,0) {$w$};
  3023. \node (x) at (6,0) {$x$};
  3024. \node (y) at (3,-1.5) {$y$};
  3025. \node (z) at (6,-1.5) {$z$};
  3026. \node (t1) at (9,-1.5) {$t.1$};
  3027. \draw[bend left=15] (t1) to (y);
  3028. \draw[bend left=15] (v) to (x);
  3029. \draw (x) to (y);
  3030. \draw (x) to (z);
  3031. \end{tikzpicture}
  3032. \]
  3033. Now we replay the graph coloring, pausing to see the coloring of $x$
  3034. and $v$. So we have the following coloring and the most saturated
  3035. vertex is $x$.
  3036. \[
  3037. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3038. \node (v) at (0,0) {$v:-,\{2\}$};
  3039. \node (w) at (3,0) {$w:2,\{0,1\}$};
  3040. \node (x) at (6,0) {$x:-,\{0,2\}$};
  3041. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3042. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3043. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3044. \draw (t1) to (z);
  3045. \draw (v) to (w);
  3046. \foreach \i in {w,x,y}
  3047. {
  3048. \foreach \j in {w,x,y}
  3049. {
  3050. \draw (\i) to (\j);
  3051. }
  3052. }
  3053. \draw (z) to (w);
  3054. \draw (z) to (y);
  3055. \end{tikzpicture}
  3056. \]
  3057. Last time we chose to color $x$ with $1$,
  3058. %
  3059. which so happens to be the color of $z$, and $x$ is move related to
  3060. $z$. This was lucky, and if the program had been a little different,
  3061. and say $z$ had been already assigned to $2$, then $x$ would still get
  3062. $1$ and our luck would have run out. With move biasing, we use the
  3063. fact that $x$ and $z$ are move related to influence the choice of
  3064. color for $x$, in this case choosing $1$ because that is the color of
  3065. $z$.
  3066. \[
  3067. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3068. \node (v) at (0,0) {$v:-,\{2\}$};
  3069. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3070. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  3071. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  3072. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3073. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3074. \draw (t1) to (z);
  3075. \draw (v) to (w);
  3076. \foreach \i in {w,x,y}
  3077. {
  3078. \foreach \j in {w,x,y}
  3079. {
  3080. \draw (\i) to (\j);
  3081. }
  3082. }
  3083. \draw (z) to (w);
  3084. \draw (z) to (y);
  3085. \end{tikzpicture}
  3086. \]
  3087. Next we consider coloring the variable $v$. We need to avoid choosing
  3088. $2$ because of the interference with $w$. Last time we chose the color
  3089. $0$ because it was the lowest, but this time we know that $v$ is move
  3090. related to $x$, so we choose the color $1$.
  3091. \[
  3092. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3093. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  3094. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3095. \node (x) at (6,0) {$x:1,\{0,2\}$};
  3096. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3097. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3098. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3099. \draw (t1) to (z);
  3100. \draw (v) to (w);
  3101. \foreach \i in {w,x,y}
  3102. {
  3103. \foreach \j in {w,x,y}
  3104. {
  3105. \draw (\i) to (\j);
  3106. }
  3107. }
  3108. \draw (z) to (w);
  3109. \draw (z) to (y);
  3110. \end{tikzpicture}
  3111. \]
  3112. We apply this register assignment to the running example, on the left,
  3113. to obtain the code on right.
  3114. \begin{minipage}{0.3\textwidth}
  3115. \begin{lstlisting}
  3116. movq $1, v
  3117. movq $46, w
  3118. movq v, x
  3119. addq $7, x
  3120. movq x, y
  3121. addq $4, y
  3122. movq x, z
  3123. addq w, z
  3124. movq y, t.1
  3125. negq t.1
  3126. movq z, %rax
  3127. addq t.1, %rax
  3128. jmp conclusion
  3129. \end{lstlisting}
  3130. \end{minipage}
  3131. $\Rightarrow\qquad$
  3132. \begin{minipage}{0.45\textwidth}
  3133. \begin{lstlisting}
  3134. movq $1, %rcx
  3135. movq $46, %rbx
  3136. movq %rcx, %rcx
  3137. addq $7, %rcx
  3138. movq %rcx, %rdx
  3139. addq $4, %rdx
  3140. movq %rcx, %rcx
  3141. addq %rbx, %rcx
  3142. movq %rdx, %rbx
  3143. negq %rbx
  3144. movq %rcx, %rax
  3145. addq %rbx, %rax
  3146. jmp conclusion
  3147. \end{lstlisting}
  3148. \end{minipage}
  3149. The \code{patch-instructions} then removes the trivial moves from
  3150. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3151. result.
  3152. \begin{minipage}{0.45\textwidth}
  3153. \begin{lstlisting}
  3154. movq $1 %rcx
  3155. movq $46 %rbx
  3156. addq $7 %rcx
  3157. movq %rcx %rdx
  3158. addq $4 %rdx
  3159. addq %rbx %rcx
  3160. movq %rdx %rbx
  3161. negq %rbx
  3162. movq %rcx %rax
  3163. addq %rbx %rax
  3164. jmp conclusion
  3165. \end{lstlisting}
  3166. \end{minipage}
  3167. \begin{exercise}\normalfont
  3168. Change your implementation of \code{allocate-registers} to take move
  3169. biasing into account. Make sure that your compiler still passes all of
  3170. the previous tests. Create two new tests that include at least one
  3171. opportunity for move biasing and visually inspect the output x86
  3172. programs to make sure that your move biasing is working properly.
  3173. \end{exercise}
  3174. \margincomment{\footnotesize To do: another neat challenge would be to do
  3175. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3176. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3177. \chapter{Booleans and Control Flow}
  3178. \label{ch:bool-types}
  3179. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3180. integers. In this chapter we add a second kind of value, the Booleans,
  3181. to create the $R_2$ language. The Boolean values \emph{true} and
  3182. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3183. Racket. The $R_2$ language includes several operations that involve
  3184. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3185. conditional \key{if} expression. With the addition of \key{if}
  3186. expressions, programs can have non-trivial control flow which which
  3187. significantly impacts the \code{explicate-control} and the liveness
  3188. analysis for register allocation. Also, because we now have two kinds
  3189. of values, we need to handle programs that apply an operation to the
  3190. wrong kind of value, such as \code{(not 1)}.
  3191. There are two language design options for such situations. One option
  3192. is to signal an error and the other is to provide a wider
  3193. interpretation of the operation. The Racket language uses a mixture of
  3194. these two options, depending on the operation and the kind of
  3195. value. For example, the result of \code{(not 1)} in Racket is
  3196. \code{\#f} because Racket treats non-zero integers as if they were
  3197. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3198. error in Racket stating that \code{car} expects a pair.
  3199. The Typed Racket language makes similar design choices as Racket,
  3200. except much of the error detection happens at compile time instead of
  3201. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3202. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3203. reports a compile-time error because Typed Racket expects the type of
  3204. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3205. For the $R_2$ language we choose to be more like Typed Racket in that
  3206. we shall perform type checking during compilation. In
  3207. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3208. is, how to compile a dynamically typed language like Racket. The
  3209. $R_2$ language is a subset of Typed Racket but by no means includes
  3210. all of Typed Racket. For many operations we take a narrower
  3211. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3212. This chapter is organized as follows. We begin by defining the syntax
  3213. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3214. then introduce the idea of type checking and build a type checker for
  3215. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3216. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3217. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3218. how our compiler passes need to change to accommodate Booleans and
  3219. conditional control flow.
  3220. \section{The $R_2$ Language}
  3221. \label{sec:r2-lang}
  3222. The concrete syntax of the $R_2$ language is defined in
  3223. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3224. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3225. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3226. and the conditional \code{if} expression. Also, we expand the
  3227. operators to include
  3228. \begin{enumerate}
  3229. \item subtraction on integers,
  3230. \item the logical operators \key{and}, \key{or} and \key{not},
  3231. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3232. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3233. comparing integers.
  3234. \end{enumerate}
  3235. \begin{figure}[tp]
  3236. \centering
  3237. \fbox{
  3238. \begin{minipage}{0.96\textwidth}
  3239. \[
  3240. \begin{array}{lcl}
  3241. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3242. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3243. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3244. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3245. &\mid& \itm{bool}
  3246. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3247. \mid (\key{not}\;\Exp) \\
  3248. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3249. R_2 &::=& \Exp
  3250. \end{array}
  3251. \]
  3252. \end{minipage}
  3253. }
  3254. \caption{The concrete syntax of $R_2$, extending $R_1$
  3255. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3256. \label{fig:r2-concrete-syntax}
  3257. \end{figure}
  3258. \begin{figure}[tp]
  3259. \centering
  3260. \fbox{
  3261. \begin{minipage}{0.96\textwidth}
  3262. \[
  3263. \begin{array}{lcl}
  3264. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3265. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3266. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3267. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3268. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3269. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3270. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3271. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3272. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3273. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3274. \end{array}
  3275. \]
  3276. \end{minipage}
  3277. }
  3278. \caption{The abstract syntax of $R_2$.}
  3279. \label{fig:r2-syntax}
  3280. \end{figure}
  3281. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3282. the parts that are the same as the interpreter for $R_1$
  3283. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3284. evaluate to the corresponding Boolean values. The conditional
  3285. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3286. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3287. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3288. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3289. you might expect, but note that the \code{and} operation is
  3290. short-circuiting. That is, given the expression
  3291. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3292. $e_1$ evaluates to \code{\#f}.
  3293. With the addition of the comparison operations, there are quite a few
  3294. primitive operations and the interpreter code for them could become
  3295. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3296. out the different parts of the code for primitive operations into the
  3297. \code{interp-op} function and the similar parts of the code into the
  3298. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3299. do not use \code{interp-op} for the \code{and} operation because of
  3300. the short-circuiting behavior in the order of evaluation of its
  3301. arguments.
  3302. \begin{figure}[tbp]
  3303. \begin{lstlisting}
  3304. (define (interp-op op)
  3305. (match op
  3306. ...
  3307. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3308. ['eq? (lambda (v1 v2)
  3309. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3310. (and (boolean? v1) (boolean? v2)))
  3311. (eq? v1 v2)]))]
  3312. ['< (lambda (v1 v2)
  3313. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3314. ['<= (lambda (v1 v2)
  3315. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3316. ['> (lambda (v1 v2)
  3317. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3318. ['>= (lambda (v1 v2)
  3319. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3320. [else (error 'interp-op "unknown operator")]))
  3321. (define (interp-exp env)
  3322. (lambda (e)
  3323. (define recur (interp-exp env))
  3324. (match e
  3325. ...
  3326. [(Bool b) b]
  3327. [(If cnd thn els)
  3328. (define b (recur cnd))
  3329. (match b
  3330. [#t (recur thn)]
  3331. [#f (recur els)])]
  3332. [(Prim 'and (list e1 e2))
  3333. (define v1 (recur e1))
  3334. (match v1
  3335. [#t (match (recur e2) [#t #t] [#f #f])]
  3336. [#f #f])]
  3337. [(Prim op args)
  3338. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3339. )))
  3340. (define (interp-R2 p)
  3341. (match p
  3342. [(Program info e)
  3343. ((interp-exp '()) e)]
  3344. ))
  3345. \end{lstlisting}
  3346. \caption{Interpreter for the $R_2$ language.}
  3347. \label{fig:interp-R2}
  3348. \end{figure}
  3349. \section{Type Checking $R_2$ Programs}
  3350. \label{sec:type-check-r2}
  3351. It is helpful to think about type checking in two complementary
  3352. ways. A type checker predicts the type of value that will be produced
  3353. by each expression in the program. For $R_2$, we have just two types,
  3354. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3355. \begin{lstlisting}
  3356. (+ 10 (- (+ 12 20)))
  3357. \end{lstlisting}
  3358. produces an \key{Integer} while
  3359. \begin{lstlisting}
  3360. (and (not #f) #t)
  3361. \end{lstlisting}
  3362. produces a \key{Boolean}.
  3363. Another way to think about type checking is that it enforces a set of
  3364. rules about which operators can be applied to which kinds of
  3365. values. For example, our type checker for $R_2$ will signal an error
  3366. for the below expression because, as we have seen above, the
  3367. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3368. checker enforces the rule that the argument of \code{not} must be a
  3369. \key{Boolean}.
  3370. \begin{lstlisting}
  3371. (not (+ 10 (- (+ 12 20))))
  3372. \end{lstlisting}
  3373. The type checker for $R_2$ is a structurally recursive function over
  3374. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3375. the \code{type-check-exp} function. Given an input expression
  3376. \code{e}, the type checker either returns a type (\key{Integer} or
  3377. \key{Boolean}) or it signals an error. The type of an integer literal
  3378. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3379. To handle variables, the type checker uses an environment that maps
  3380. variables to types. Consider the clause for \key{let}. We type check
  3381. the initializing expression to obtain its type \key{T} and then
  3382. associate type \code{T} with the variable \code{x} in the
  3383. environment. When the type checker encounters a use of variable
  3384. \code{x} in the body of the \key{let}, it can find its type in the
  3385. environment.
  3386. \begin{figure}[tbp]
  3387. \begin{lstlisting}
  3388. (define (type-check-exp env)
  3389. (lambda (e)
  3390. (match e
  3391. [(Var x) (dict-ref env x)]
  3392. [(Int n) 'Integer]
  3393. [(Bool b) 'Boolean]
  3394. [(Let x e body)
  3395. (define Te ((type-check-exp env) e))
  3396. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3397. Tb]
  3398. ...
  3399. [else
  3400. (error "type-check-exp couldn't match" e)])))
  3401. (define (type-check env)
  3402. (lambda (e)
  3403. (match e
  3404. [(Program info body)
  3405. (define Tb ((type-check-exp '()) body))
  3406. (unless (equal? Tb 'Integer)
  3407. (error "result of the program must be an integer, not " Tb))
  3408. (Program info body)]
  3409. )))
  3410. \end{lstlisting}
  3411. \caption{Skeleton of a type checker for the $R_2$ language.}
  3412. \label{fig:type-check-R2}
  3413. \end{figure}
  3414. \begin{exercise}\normalfont
  3415. Complete the implementation of \code{type-check-R2} and test it on 10
  3416. new example programs in $R_2$ that you choose based on how thoroughly
  3417. they test the type checking function. Half of the example programs
  3418. should have a type error to make sure that your type checker properly
  3419. rejects them. The other half of the example programs should not have
  3420. type errors. Your testing should check that the result of the type
  3421. checker agrees with the value returned by the interpreter, that is, if
  3422. the type checker returns \key{Integer}, then the interpreter should
  3423. return an integer. Likewise, if the type checker returns
  3424. \key{Boolean}, then the interpreter should return \code{\#t} or
  3425. \code{\#f}. Note that if your type checker does not signal an error
  3426. for a program, then interpreting that program should not encounter an
  3427. error. If it does, there is something wrong with your type checker.
  3428. \end{exercise}
  3429. \section{Shrink the $R_2$ Language}
  3430. \label{sec:shrink-r2}
  3431. The $R_2$ language includes several operators that are easily
  3432. expressible in terms of other operators. For example, subtraction is
  3433. expressible in terms of addition and negation.
  3434. \[
  3435. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3436. \]
  3437. Several of the comparison operations are expressible in terms of
  3438. less-than and logical negation.
  3439. \[
  3440. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3441. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3442. \]
  3443. The \key{let} is needed in the above translation to ensure that
  3444. expression $e_1$ is evaluated before $e_2$.
  3445. By performing these translations near the front-end of the compiler,
  3446. the later passes of the compiler do not need to deal with these
  3447. constructs, making those passes shorter. On the other hand, sometimes
  3448. these translations make it more difficult to generate the most
  3449. efficient code with respect to the number of instructions. However,
  3450. these differences typically do not affect the number of accesses to
  3451. memory, which is the primary factor that determines execution time on
  3452. modern computer architectures.
  3453. \begin{exercise}\normalfont
  3454. Implement the pass \code{shrink} that removes subtraction,
  3455. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3456. by translating them to other constructs in $R_2$. Create tests to
  3457. make sure that the behavior of all of these constructs stays the
  3458. same after translation.
  3459. \end{exercise}
  3460. \section{XOR, Comparisons, and Control Flow in x86}
  3461. \label{sec:x86-1}
  3462. To implement the new logical operations, the comparison operations,
  3463. and the \key{if} expression, we need to delve further into the x86
  3464. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3465. larger subset of x86 that includes instructions for logical
  3466. operations, comparisons, and jumps.
  3467. One small challenge is that x86 does not provide an instruction that
  3468. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3469. However, the \code{xorq} instruction can be used to encode \code{not}.
  3470. The \key{xorq} instruction takes two arguments, performs a pairwise
  3471. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3472. and writes the results into its second argument. Recall the truth
  3473. table for exclusive-or:
  3474. \begin{center}
  3475. \begin{tabular}{l|cc}
  3476. & 0 & 1 \\ \hline
  3477. 0 & 0 & 1 \\
  3478. 1 & 1 & 0
  3479. \end{tabular}
  3480. \end{center}
  3481. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3482. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3483. for the bit $1$, the result is the opposite of the second bit. Thus,
  3484. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3485. the first argument:
  3486. \[
  3487. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3488. \qquad\Rightarrow\qquad
  3489. \begin{array}{l}
  3490. \key{movq}~ \Arg\key{,} \Var\\
  3491. \key{xorq}~ \key{\$1,} \Var
  3492. \end{array}
  3493. \]
  3494. \begin{figure}[tp]
  3495. \fbox{
  3496. \begin{minipage}{0.96\textwidth}
  3497. \small
  3498. \[
  3499. \begin{array}{lcl}
  3500. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3501. \mid \BYTEREG{\code{'}\Reg} \\
  3502. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3503. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3504. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3505. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3506. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3507. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3508. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} } \\
  3509. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3510. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3511. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3512. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3513. &\mid& \JMP{\itm{label}}
  3514. \mid \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3515. % &\mid& (\key{label} \; \itm{label}) \\
  3516. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3517. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3518. \end{array}
  3519. \]
  3520. \end{minipage}
  3521. }
  3522. \caption{The abstract syntax of $x86_1$ (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3523. \label{fig:x86-1}
  3524. \end{figure}
  3525. Next we consider the x86 instructions that are relevant for compiling
  3526. the comparison operations. The \key{cmpq} instruction compares its two
  3527. arguments to determine whether one argument is less than, equal, or
  3528. greater than the other argument. The \key{cmpq} instruction is unusual
  3529. regarding the order of its arguments and where the result is
  3530. placed. The argument order is backwards: if you want to test whether
  3531. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3532. \key{cmpq} is placed in the special EFLAGS register. This register
  3533. cannot be accessed directly but it can be queried by a number of
  3534. instructions, including the \key{set} instruction. The \key{set}
  3535. instruction puts a \key{1} or \key{0} into its destination depending
  3536. on whether the comparison came out according to the condition code
  3537. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3538. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3539. The \key{set} instruction has an annoying quirk in that its
  3540. destination argument must be single byte register, such as \code{al},
  3541. which is part of the \code{rax} register. Thankfully, the
  3542. \key{movzbq} instruction can then be used to move from a single byte
  3543. register to a normal 64-bit register.
  3544. The x86 instructions for jumping are relevant to the compilation of
  3545. \key{if} expressions. The \key{Jmp} instruction updates the program
  3546. counter to point to the instruction after the indicated label. The
  3547. \key{JmpIf} instruction updates the program counter to point to the
  3548. instruction after the indicated label depending on whether the result
  3549. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3550. the \key{JmpIf} instruction falls through to the next instruction
  3551. \footnote{The abstract syntax for \key{JmpIf} differs from the
  3552. concrete syntax for x86 in that it separates the instruction name
  3553. from the condition code. For example, \code{(JmpIf le foo)}
  3554. corresponds to \code{jle foo}.}. Because the \key{JmpIf}
  3555. instruction relies on the EFLAGS register, it is common for the
  3556. \key{JmpIf} to be immediately preceded by a \key{cmpq} instruction to
  3557. set the EFLAGS register.
  3558. \section{The $C_1$ Intermediate Language}
  3559. \label{sec:c1}
  3560. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3561. we need to grow that intermediate language to handle the new features
  3562. in $R_2$: Booleans and conditional expressions.
  3563. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3564. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3565. particular, we add logical and comparison operators to the $\Exp$
  3566. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3567. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3568. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3569. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3570. sequence of statements may now end with a \code{goto} or a conditional
  3571. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3572. depending on the outcome of the comparison. In
  3573. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3574. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3575. and \key{goto}'s.
  3576. \begin{figure}[tbp]
  3577. \fbox{
  3578. \begin{minipage}{0.96\textwidth}
  3579. \small
  3580. \[
  3581. \begin{array}{lcl}
  3582. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3583. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3584. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3585. &::=& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3586. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3587. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail } \\
  3588. &\mid& \key{goto}~\itm{label}\key{;}\\
  3589. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3590. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)^{+} }
  3591. \end{array}
  3592. \]
  3593. \end{minipage}
  3594. }
  3595. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3596. \label{fig:c1-concrete-syntax}
  3597. \end{figure}
  3598. \begin{figure}[tp]
  3599. \fbox{
  3600. \begin{minipage}{0.96\textwidth}
  3601. \small
  3602. \[
  3603. \begin{array}{lcl}
  3604. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3605. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3606. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3607. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3608. &\mid& \UNIOP{\key{'not}}{\Atm}
  3609. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3610. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3611. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} } \\
  3612. &\mid& \GOTO{\itm{label}} \\
  3613. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3614. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3615. \end{array}
  3616. \]
  3617. \end{minipage}
  3618. }
  3619. \caption{The abstract syntax of $C_1$, extending $C_0$ with Booleans and conditionals.}
  3620. \label{fig:c1-syntax}
  3621. \end{figure}
  3622. \section{Explicate Control}
  3623. \label{sec:explicate-control-r2}
  3624. Recall that the purpose of \code{explicate-control} is to make the
  3625. order of evaluation explicit in the syntax of the program. With the
  3626. addition of \key{if} in $R_2$ this get more interesting.
  3627. As a motivating example, consider the following program that has an
  3628. \key{if} expression nested in the predicate of another \key{if}.
  3629. % s1_38.rkt
  3630. \begin{center}
  3631. \begin{minipage}{0.96\textwidth}
  3632. \begin{lstlisting}
  3633. (if (if (eq? (read) 1)
  3634. (eq? (read) 0)
  3635. (eq? (read) 2))
  3636. (+ 10 32)
  3637. (+ 700 77))
  3638. \end{lstlisting}
  3639. \end{minipage}
  3640. \end{center}
  3641. %
  3642. The naive way to compile \key{if} and \key{eq?} would be to handle
  3643. each of them in isolation, regardless of their context. Each
  3644. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3645. by a couple instructions to move the result from the EFLAGS register
  3646. into a general purpose register or stack location. Each \key{if} would
  3647. be translated into the combination of a \key{cmpq} and \key{JmpIf}.
  3648. However, if we take context into account we can do better and reduce
  3649. the use of \key{cmpq} and EFLAG-accessing instructions.
  3650. One idea is to try and reorganize the code at the level of $R_2$,
  3651. pushing the outer \key{if} inside the inner one. This would yield the
  3652. following code.
  3653. \begin{center}
  3654. \begin{minipage}{0.96\textwidth}
  3655. \begin{lstlisting}
  3656. (if (eq? (read) 1)
  3657. (if (eq? (read) 0)
  3658. (+ 10 32)
  3659. (+ 700 77))
  3660. (if (eq? (read) 2))
  3661. (+ 10 32)
  3662. (+ 700 77))
  3663. \end{lstlisting}
  3664. \end{minipage}
  3665. \end{center}
  3666. Unfortunately, this approach duplicates the two branches, and a
  3667. compiler must never duplicate code!
  3668. We need a way to perform the above transformation, but without
  3669. duplicating code. The solution is straightforward if we think at the
  3670. level of x86 assembly: we can label the code for each of the branches
  3671. and insert jumps in all the places that need to execute the
  3672. branches. Put another way, we need to move away from abstract syntax
  3673. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3674. use a standard program representation called a \emph{control flow
  3675. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3676. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3677. each edge represents a jump to another block. The \key{Program}
  3678. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3679. as an alist mapping labels to basic blocks. Each block is
  3680. represented by the $\Tail$ non-terminal.
  3681. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3682. \code{remove-complex-opera*} pass and then the
  3683. \code{explicate-control} pass on the example program. We walk through
  3684. the output program and then discuss the algorithm.
  3685. %
  3686. Following the order of evaluation in the output of
  3687. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3688. comparison to \code{1} from the predicate of the inner \key{if}. In
  3689. the output of \code{explicate-control}, in the \code{start} block,
  3690. this becomes a \code{(read)} followed by a conditional \key{goto} to
  3691. either \code{block61} or \code{block62}. Each of these contains the
  3692. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3693. 1)}, respectively. Regarding \code{block61}, we start with the
  3694. \code{(read)} and comparison to \code{0} and then have a conditional
  3695. goto, either to \code{block59} or \code{block60}, which indirectly
  3696. take us to \code{block55} and \code{block56}, the two branches of the
  3697. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3698. story for \code{block62} is similar.
  3699. \begin{figure}[tbp]
  3700. \begin{tabular}{lll}
  3701. \begin{minipage}{0.4\textwidth}
  3702. \begin{lstlisting}
  3703. (if (if (eq? (read) 1)
  3704. (eq? (read) 0)
  3705. (eq? (read) 2))
  3706. (+ 10 32)
  3707. (+ 700 77))
  3708. \end{lstlisting}
  3709. \hspace{40pt}$\Downarrow$
  3710. \begin{lstlisting}
  3711. (if (if (let ([tmp52 (read)])
  3712. (eq? tmp52 1))
  3713. (let ([tmp53 (read)])
  3714. (eq? tmp53 0))
  3715. (let ([tmp54 (read)])
  3716. (eq? tmp54 2)))
  3717. (+ 10 32)
  3718. (+ 700 77))
  3719. \end{lstlisting}
  3720. \end{minipage}
  3721. &
  3722. $\Rightarrow$
  3723. &
  3724. \begin{minipage}{0.55\textwidth}
  3725. \begin{lstlisting}
  3726. block62:
  3727. tmp54 = (read);
  3728. if (eq? tmp54 2) then
  3729. goto block59;
  3730. else
  3731. goto block60;
  3732. block61:
  3733. tmp53 = (read);
  3734. if (eq? tmp53 0) then
  3735. goto block57;
  3736. else
  3737. goto block58;
  3738. block60:
  3739. goto block56;
  3740. block59:
  3741. goto block55;
  3742. block58:
  3743. goto block56;
  3744. block57:
  3745. goto block55;
  3746. block56:
  3747. return (+ 700 77);
  3748. block55:
  3749. return (+ 10 32);
  3750. start:
  3751. tmp52 = (read);
  3752. if (eq? tmp52 1) then
  3753. goto block61;
  3754. else
  3755. goto block62;
  3756. \end{lstlisting}
  3757. \end{minipage}
  3758. \end{tabular}
  3759. \caption{Example translation from $R_2$ to $C_1$
  3760. via the \code{explicate-control}.}
  3761. \label{fig:explicate-control-s1-38}
  3762. \end{figure}
  3763. The nice thing about the output of \code{explicate-control} is that
  3764. there are no unnecessary uses of \code{eq?} and every use of
  3765. \code{eq?} is part of a conditional jump. The down-side of this output
  3766. is that it includes trivial blocks, such as \code{block57} through
  3767. \code{block60}, that only jump to another block. We discuss a solution
  3768. to this problem in Section~\ref{sec:opt-jumps}.
  3769. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3770. \code{explicate-control} for $R_1$ using two mutually recursive
  3771. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3772. former function translates expressions in tail position whereas the
  3773. later function translates expressions on the right-hand-side of a
  3774. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3775. new kind of context to deal with: the predicate position of the
  3776. \key{if}. We need another function, \code{explicate-pred}, that takes
  3777. an $R_2$ expression and two pieces of $C_1$ code (two $\Tail$'s) for
  3778. the then-branch and else-branch. The output of \code{explicate-pred}
  3779. is a $C_1$ $\Tail$ and a list of formerly \key{let}-bound variables.
  3780. Note that the three explicate functions need to construct a
  3781. control-flow graph, which we recommend they do via updates to a global
  3782. variable.
  3783. In the following paragraphs we consider the specific additions to the
  3784. \code{explicate-tail} and \code{explicate-assign} functions, and some
  3785. of cases for the \code{explicate-pred} function.
  3786. The \code{explicate-tail} function needs an additional case for
  3787. \key{if}. The branches of the \key{if} inherit the current context, so
  3788. they are in tail position. Let $B_1$ be the result of
  3789. \code{explicate-tail} on the ``then'' branch of the \key{if} and $B_2$
  3790. be the result of apply \code{explicate-tail} to the ``else''
  3791. branch. Then the \key{if} as a whole translates to the block $B_3$
  3792. which is the result of applying \code{explicate-pred} to the predicate
  3793. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3794. \[
  3795. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3796. \]
  3797. Next we consider the case for \key{if} in the \code{explicate-assign}
  3798. function. The context of the \key{if} is an assignment to some
  3799. variable $x$ and then the control continues to some block $B_1$. The
  3800. code that we generate for the ``then'' and ``else'' branches needs to
  3801. continue to $B_1$, so we add $B_1$ to the control flow graph with a
  3802. fresh label $\ell_1$. Again, the branches of the \key{if} inherit the
  3803. current context, so that are in assignment positions. Let $B_2$ be
  3804. the result of applying \code{explicate-assign} to the ``then'' branch,
  3805. variable $x$, and the block \GOTO{$\ell_1$}. Let $B_3$ be the result
  3806. of applying \code{explicate-assign} to the ``else'' branch, variable
  3807. $x$, and the block \GOTO{$\ell_1$}. The \key{if} translates to the
  3808. block $B_4$ which is the result of applying \code{explicate-pred} to
  3809. the predicate $\itm{cnd}$ and the blocks $B_2$ and $B_3$.
  3810. \[
  3811. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3812. \]
  3813. The function \code{explicate-pred} will need a case for every
  3814. expression that can have type \code{Boolean}. We detail a few cases
  3815. here and leave the rest for the reader. The input to this function is
  3816. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  3817. the enclosing \key{if}. Suppose the expression is the Boolean
  3818. \code{\#t}. Then we can perform a kind of partial evaluation and
  3819. translate it to the ``then'' branch $B_1$. Likewise, we translate
  3820. \code{\#f} to the ``else`` branch $B_2$.
  3821. \[
  3822. \key{\#t} \quad\Rightarrow\quad B_1,
  3823. \qquad\qquad\qquad
  3824. \key{\#f} \quad\Rightarrow\quad B_2
  3825. \]
  3826. Next, suppose the expression is a less-than comparison. We translate
  3827. it to a conditional \code{goto}. We need labels for the two branches
  3828. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  3829. obtain some labels $\ell_1$ and $\ell_2$. The translation of the
  3830. less-than comparison is as follows.
  3831. \[
  3832. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  3833. \begin{array}{l}
  3834. \key{if}~(\key{<}~e_1~e_2)~\key{then} \\
  3835. \qquad\key{goto}~\ell_1\key{;}\\
  3836. \key{else}\\
  3837. \qquad\key{goto}~\ell_2\key{;}
  3838. \end{array}
  3839. \]
  3840. The case for \key{if} in \code{explicate-pred} is particularly
  3841. illuminating as it deals with the challenges that we discussed above
  3842. regarding the example of the nested \key{if} expressions. Again, we
  3843. add the two branches $B_1$ and $B_2$ to the control flow graph and
  3844. obtain the labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  3845. branches of the current \key{if} inherit their context from the
  3846. current one, that is, predicate context. So we apply
  3847. \code{explicate-pred} to the ``then'' branch with the two blocks
  3848. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  3849. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  3850. apply \code{explicate-pred} to the predicate of hte \code{if} and the
  3851. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  3852. \[
  3853. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3854. \quad\Rightarrow\quad
  3855. B_5
  3856. \]
  3857. \begin{exercise}\normalfont
  3858. Implement the pass \code{explicate-control} by adding the cases for
  3859. \key{if} to the functions for tail and assignment contexts, and
  3860. implement \code{explicate-pred} for predicate contexts. Create test
  3861. cases that exercise all of the new cases in the code for this pass.
  3862. \end{exercise}
  3863. \section{Select Instructions}
  3864. \label{sec:select-r2}
  3865. Recall that the \code{select-instructions} pass lowers from our
  3866. $C$-like intermediate representation to the pseudo-x86 language, which
  3867. is suitable for conducting register allocation. The pass is
  3868. implemented using three auxiliary functions, one for each of the
  3869. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  3870. For $\Atm$, we have new cases for the Booleans. We take the usual
  3871. approach of encoding them as integers, with true as 1 and false as 0.
  3872. \[
  3873. \key{\#t} \Rightarrow \key{1}
  3874. \qquad
  3875. \key{\#f} \Rightarrow \key{0}
  3876. \]
  3877. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3878. be implemented in terms of \code{xorq} as we discussed at the
  3879. beginning of this section. Given an assignment
  3880. $\itm{var}$ \key{=} \key{(not} $\Arg$\key{);},
  3881. if the left-hand side $\itm{var}$ is
  3882. the same as $\Arg$, then just the \code{xorq} suffices.
  3883. \[
  3884. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  3885. \quad\Rightarrow\quad
  3886. \key{xorq}~\key{\$}1\key{,}~\Var
  3887. \]
  3888. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3889. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3890. $\Arg$. Then we have
  3891. \[
  3892. \Var~\key{=}~ \key{(not}\; \Arg\key{);}
  3893. \quad\Rightarrow\quad
  3894. \begin{array}{l}
  3895. \key{movq}~\Arg'\key{,}~\Var\\
  3896. \key{xorq}~\key{\$}1\key{,}~\Var
  3897. \end{array}
  3898. \]
  3899. Next consider the cases for \code{eq?} and less-than comparison.
  3900. Translating these operations to x86 is slightly involved due to the
  3901. unusual nature of the \key{cmpq} instruction discussed above. We
  3902. recommend translating an assignment from \code{eq?} into the following
  3903. sequence of three instructions. \\
  3904. \begin{tabular}{lll}
  3905. \begin{minipage}{0.4\textwidth}
  3906. \begin{lstlisting}
  3907. |$\Var$| = (eq? |$\Arg_1$| |$\Arg_2$|);
  3908. \end{lstlisting}
  3909. \end{minipage}
  3910. &
  3911. $\Rightarrow$
  3912. &
  3913. \begin{minipage}{0.4\textwidth}
  3914. \begin{lstlisting}
  3915. cmpq |$\Arg'_2$|, |$\Arg'_1$|
  3916. sete %al
  3917. movzbq %al, |$\Var$|
  3918. \end{lstlisting}
  3919. \end{minipage}
  3920. \end{tabular} \\
  3921. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  3922. and conditional \key{goto}. Both are straightforward to handle. A
  3923. \key{goto} becomes a jump instruction.
  3924. \[
  3925. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  3926. \]
  3927. A conditional \key{goto} becomes a compare instruction followed
  3928. by a conditional jump (for ``then'') and the fall-through is
  3929. to a regular jump (for ``else'').\\
  3930. \begin{tabular}{lll}
  3931. \begin{minipage}{0.4\textwidth}
  3932. \begin{lstlisting}
  3933. if (eq? |$\Arg_1$| |$\Arg_2$|) then
  3934. goto |$\ell_1$|;
  3935. else
  3936. goto |$\ell_2$|;
  3937. \end{lstlisting}
  3938. \end{minipage}
  3939. &
  3940. $\Rightarrow$
  3941. &
  3942. \begin{minipage}{0.4\textwidth}
  3943. \begin{lstlisting}
  3944. cmpq |$\Arg'_2$| |$\Arg'_1$|
  3945. je |$\ell_1$|
  3946. jmp |$\ell_2$|
  3947. \end{lstlisting}
  3948. \end{minipage}
  3949. \end{tabular} \\
  3950. \begin{exercise}\normalfont
  3951. Expand your \code{select-instructions} pass to handle the new features
  3952. of the $R_2$ language. Test the pass on all the examples you have
  3953. created and make sure that you have some test programs that use the
  3954. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3955. the output using the \code{interp-x86} interpreter
  3956. (Appendix~\ref{appendix:interp}).
  3957. \end{exercise}
  3958. \section{Register Allocation}
  3959. \label{sec:register-allocation-r2}
  3960. The changes required for $R_2$ affect liveness analysis, building the
  3961. interference graph, and assigning homes, but the graph coloring
  3962. algorithm itself does not change.
  3963. \subsection{Liveness Analysis}
  3964. \label{sec:liveness-analysis-r2}
  3965. Recall that for $R_1$ we implemented liveness analysis for a single
  3966. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3967. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3968. produces many basic blocks arranged in a control-flow graph. The first
  3969. question we need to consider is: what order should we process the
  3970. basic blocks? Recall that to perform liveness analysis, we need to
  3971. know the live-after set. If a basic block has no successor blocks
  3972. (i.e. no out-edges in the control flow graph), then it has an empty
  3973. live-after set and we can immediately apply liveness analysis to
  3974. it. If a basic block has some successors, then we need to complete
  3975. liveness analysis on those blocks first. Furthermore, we know that
  3976. the control flow graph does not contain any cycles because $R_2$ does
  3977. not include loops
  3978. %
  3979. \footnote{If we were to add loops to the language, then the CFG could
  3980. contain cycles and we would instead need to use the classic worklist
  3981. algorithm for computing the fixed point of the liveness
  3982. analysis~\citep{Aho:1986qf}.}.
  3983. %
  3984. Returning to the question of what order should we process the basic
  3985. blocks, the answer is reverse topological order. We recommend using
  3986. the \code{tsort} (topological sort) and \code{transpose} functions of
  3987. the Racket \code{graph} package to obtain this ordering.
  3988. The next question is how to compute the live-after set of a block
  3989. given the live-before sets of all its successor blocks. (There can be
  3990. more than one because of conditional jumps.) During compilation we do
  3991. not know which way a conditional jump will go, so we do not know which
  3992. of the successor's live-before set to use. The solution to this
  3993. challenge is based on the observation that there is no harm to the
  3994. correctness of the compiler if we classify more variables as live than
  3995. the ones that are truly live during a particular execution of the
  3996. block. Thus, we can take the union of the live-before sets from all
  3997. the successors to be the live-after set for the block. Once we have
  3998. computed the live-after set, we can proceed to perform liveness
  3999. analysis on the block just as we did in
  4000. Section~\ref{sec:liveness-analysis-r1}.
  4001. The helper functions for computing the variables in an instruction's
  4002. argument and for computing the variables read-from ($R$) or written-to
  4003. ($W$) by an instruction need to be updated to handle the new kinds of
  4004. arguments and instructions in x86$_1$.
  4005. \subsection{Build Interference}
  4006. \label{sec:build-interference-r2}
  4007. Many of the new instructions in x86$_1$ can be handled in the same way
  4008. as the instructions in x86$_0$. Thus, if your code was already quite
  4009. general, it will not need to be changed to handle the new
  4010. instructions. If you code is not general enough, I recommend that you
  4011. change your code to be more general. For example, you can factor out
  4012. the computing of the the read and write sets for each kind of
  4013. instruction into two auxiliary functions.
  4014. Note that the \key{movzbq} instruction requires some special care,
  4015. just like the \key{movq} instruction. See rule number 3 in
  4016. Section~\ref{sec:build-interference}.
  4017. %% \subsection{Assign Homes}
  4018. %% \label{sec:assign-homes-r2}
  4019. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4020. %% to be updated to handle the \key{if} statement, simply by recursively
  4021. %% processing the child nodes. Hopefully your code already handles the
  4022. %% other new instructions, but if not, you can generalize your code.
  4023. \begin{exercise}\normalfont
  4024. Update the \code{register-allocation} pass so that it works for $R_2$
  4025. and test your compiler using your previously created programs on the
  4026. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4027. \end{exercise}
  4028. \section{Patch Instructions}
  4029. The second argument of the \key{cmpq} instruction must not be an
  4030. immediate value (such as an integer). So if you are comparing two
  4031. immediates, we recommend inserting a \key{movq} instruction to put the
  4032. second argument in \key{rax}.
  4033. %
  4034. The second argument of the \key{movzbq} must be a register.
  4035. %
  4036. There are no special restrictions on the x86 instructions \key{JmpIf}
  4037. and \key{Jmp}.
  4038. \begin{exercise}\normalfont
  4039. Update \code{patch-instructions} to handle the new x86 instructions.
  4040. Test your compiler using your previously created programs on the
  4041. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4042. \end{exercise}
  4043. \section{An Example Translation}
  4044. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4045. $R_2$ translated to x86, showing the results of
  4046. \code{explicate-control}, \code{select-instructions}, and the final
  4047. x86 assembly code.
  4048. \begin{figure}[tbp]
  4049. \begin{tabular}{lll}
  4050. \begin{minipage}{0.5\textwidth}
  4051. % s1_20.rkt
  4052. \begin{lstlisting}
  4053. (if (eq? (read) 1) 42 0)
  4054. \end{lstlisting}
  4055. $\Downarrow$
  4056. \begin{lstlisting}
  4057. start:
  4058. tmp7951 = (read);
  4059. if (eq? tmp7951 1) then
  4060. goto block7952;
  4061. else
  4062. goto block7953;
  4063. block7952:
  4064. return 42;
  4065. block7953:
  4066. return 0;
  4067. \end{lstlisting}
  4068. $\Downarrow$
  4069. \begin{lstlisting}
  4070. start:
  4071. callq read_int
  4072. movq %rax, tmp7951
  4073. cmpq $1, tmp7951
  4074. je block7952
  4075. jmp block7953
  4076. block7953:
  4077. movq $0, %rax
  4078. jmp conclusion
  4079. block7952:
  4080. movq $42, %rax
  4081. jmp conclusion
  4082. \end{lstlisting}
  4083. \end{minipage}
  4084. &
  4085. $\Rightarrow\qquad$
  4086. \begin{minipage}{0.4\textwidth}
  4087. \begin{lstlisting}
  4088. start:
  4089. callq read_int
  4090. movq %rax, %rcx
  4091. cmpq $1, %rcx
  4092. je block7952
  4093. jmp block7953
  4094. block7953:
  4095. movq $0, %rax
  4096. jmp conclusion
  4097. block7952:
  4098. movq $42, %rax
  4099. jmp conclusion
  4100. .globl main
  4101. main:
  4102. pushq %rbp
  4103. movq %rsp, %rbp
  4104. pushq %r13
  4105. pushq %r12
  4106. pushq %rbx
  4107. pushq %r14
  4108. subq $0, %rsp
  4109. jmp start
  4110. conclusion:
  4111. addq $0, %rsp
  4112. popq %r14
  4113. popq %rbx
  4114. popq %r12
  4115. popq %r13
  4116. popq %rbp
  4117. retq
  4118. \end{lstlisting}
  4119. \end{minipage}
  4120. \end{tabular}
  4121. \caption{Example compilation of an \key{if} expression to x86.}
  4122. \label{fig:if-example-x86}
  4123. \end{figure}
  4124. \begin{figure}[p]
  4125. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4126. \node (R2) at (0,2) {\large $R_2$};
  4127. \node (R2-2) at (3,2) {\large $R_2$};
  4128. \node (R2-3) at (6,2) {\large $R_2$};
  4129. \node (R2-4) at (9,2) {\large $R_2$};
  4130. \node (R2-5) at (12,2) {\large $R_2$};
  4131. \node (C1-1) at (6,0) {\large $C_1$};
  4132. %\node (C1-2) at (3,0) {\large $C_1$};
  4133. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4134. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4135. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4136. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4137. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4138. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4139. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4140. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4141. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4142. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4143. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4144. %\path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4145. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4146. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4147. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4148. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4149. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4150. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4151. \end{tikzpicture}
  4152. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4153. \label{fig:R2-passes}
  4154. \end{figure}
  4155. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4156. compilation of $R_2$.
  4157. \section{Challenge: Optimize Jumps}
  4158. \label{sec:opt-jumps}
  4159. Recall that in the example output of \code{explicate-control} in
  4160. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4161. \code{block60} are trivial blocks, they do nothing but jump to another
  4162. block. The first goal of this challenge assignment is to remove those
  4163. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4164. \code{explicate-control} on the left and shows the result of bypassing
  4165. the trivial blocks on the right. Let us focus on \code{block61}. The
  4166. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4167. \code{block55}. The optimized code on the right of
  4168. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4169. \code{then} branch jumping directly to \code{block55}. The story is
  4170. similar for the \code{else} branch, as well as for the two branches in
  4171. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4172. have been optimized in this way, there are no longer any jumps to
  4173. blocks \code{block57} through \code{block60}, so they can be removed.
  4174. \begin{figure}[tbp]
  4175. \begin{tabular}{lll}
  4176. \begin{minipage}{0.4\textwidth}
  4177. \begin{lstlisting}
  4178. block62:
  4179. tmp54 = (read);
  4180. if (eq? tmp54 2) then
  4181. goto block59;
  4182. else
  4183. goto block60;
  4184. block61:
  4185. tmp53 = (read);
  4186. if (eq? tmp53 0) then
  4187. goto block57;
  4188. else
  4189. goto block58;
  4190. block60:
  4191. goto block56;
  4192. block59:
  4193. goto block55;
  4194. block58:
  4195. goto block56;
  4196. block57:
  4197. goto block55;
  4198. block56:
  4199. return (+ 700 77);
  4200. block55:
  4201. return (+ 10 32);
  4202. start:
  4203. tmp52 = (read);
  4204. if (eq? tmp52 1) then
  4205. goto block61;
  4206. else
  4207. goto block62;
  4208. \end{lstlisting}
  4209. \end{minipage}
  4210. &
  4211. $\Rightarrow$
  4212. &
  4213. \begin{minipage}{0.55\textwidth}
  4214. \begin{lstlisting}
  4215. block62:
  4216. tmp54 = (read);
  4217. if (eq? tmp54 2) then
  4218. goto block55;
  4219. else
  4220. goto block56;
  4221. block61:
  4222. tmp53 = (read);
  4223. if (eq? tmp53 0) then
  4224. goto block55;
  4225. else
  4226. goto block56;
  4227. block56:
  4228. return (+ 700 77);
  4229. block55:
  4230. return (+ 10 32);
  4231. start:
  4232. tmp52 = (read);
  4233. if (eq? tmp52 1) then
  4234. goto block61;
  4235. else
  4236. goto block62;
  4237. \end{lstlisting}
  4238. \end{minipage}
  4239. \end{tabular}
  4240. \caption{Optimize jumps by removing trivial blocks.}
  4241. \label{fig:optimize-jumps}
  4242. \end{figure}
  4243. The name of this pass is \code{optimize-jumps}. We recommend
  4244. implementing this pass in two phases. The first phrase builds a hash
  4245. table that maps labels to possibly improved labels. The second phase
  4246. changes the target of each \code{goto} to use the improved label. If
  4247. the label is for a trivial block, then the hash table should map the
  4248. label to the first non-trivial block that can be reached from this
  4249. label by jumping through trivial blocks. If the label is for a
  4250. non-trivial block, then the hash table should map the label to itself;
  4251. we do not want to change jumps to non-trivial blocks.
  4252. The first phase can be accomplished by constructing an empty hash
  4253. table, call it \code{short-cut}, and then iterating over the control
  4254. flow graph. Each time you encouter a block that is just a \code{goto},
  4255. then update the hash table, mapping the block's source to the target
  4256. of the \code{goto}. Also, the hash table may already have mapped some
  4257. labels to the block's source, to you must iterate through the hash
  4258. table and update all of those so that they instead map to the target
  4259. of the \code{goto}.
  4260. For the second phase, we recommend iterating through the $\Tail$ of
  4261. each block in the program, updating the target of every \code{goto}
  4262. according to the mapping in \code{short-cut}.
  4263. \begin{exercise}\normalfont
  4264. Implement the \code{optimize-jumps} pass and check that it remove
  4265. trivial blocks in a few example programs. Then check that your
  4266. compiler still passes all of your tests.
  4267. \end{exercise}
  4268. There is another opportunity for optimizing jumps that is apparent in
  4269. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4270. end with a jump to \code{block7953} and there are no other jumps to
  4271. \code{block7953} in the rest of the program. In this situation we can
  4272. avoid the runtime overhead of this jump by merging \code{block7953}
  4273. into the preceeding block, in this case the \code{start} block.
  4274. Figure~\ref{fig:remove-jumps} shows the output of
  4275. \code{select-instructions} on the left and the result of this
  4276. optimization on the right.
  4277. \begin{figure}[tbp]
  4278. \begin{tabular}{lll}
  4279. \begin{minipage}{0.5\textwidth}
  4280. % s1_20.rkt
  4281. \begin{lstlisting}
  4282. start:
  4283. callq read_int
  4284. movq %rax, tmp7951
  4285. cmpq $1, tmp7951
  4286. je block7952
  4287. jmp block7953
  4288. block7953:
  4289. movq $0, %rax
  4290. jmp conclusion
  4291. block7952:
  4292. movq $42, %rax
  4293. jmp conclusion
  4294. \end{lstlisting}
  4295. \end{minipage}
  4296. &
  4297. $\Rightarrow\qquad$
  4298. \begin{minipage}{0.4\textwidth}
  4299. \begin{lstlisting}
  4300. start:
  4301. callq read_int
  4302. movq %rax, tmp7951
  4303. cmpq $1, tmp7951
  4304. je block7952
  4305. movq $0, %rax
  4306. jmp conclusion
  4307. block7952:
  4308. movq $42, %rax
  4309. jmp conclusion
  4310. \end{lstlisting}
  4311. \end{minipage}
  4312. \end{tabular}
  4313. \caption{Merging basic blocks by removing unnecessary jumps.}
  4314. \label{fig:remove-jumps}
  4315. \end{figure}
  4316. \begin{exercise}\normalfont
  4317. Implement a pass named \code{remove-jumps} that merges basic blocks
  4318. into their preceeding basic block, when there is only one preceeding
  4319. block. Check that your pass accomplishes this goal on several test
  4320. programs and check that your compiler passes all of your tests.
  4321. \end{exercise}
  4322. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4323. \chapter{Tuples and Garbage Collection}
  4324. \label{ch:tuples}
  4325. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4326. things to discuss in this chapter. \\ --Jeremy}
  4327. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4328. all the IR grammars are spelled out! \\ --Jeremy}
  4329. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4330. but keep type annotations on vector creation and local variables, function
  4331. parameters, etc. \\ --Jeremy}
  4332. \margincomment{\scriptsize Be more explicit about how to deal with
  4333. the root stack. \\ --Jeremy}
  4334. In this chapter we study the implementation of mutable tuples (called
  4335. ``vectors'' in Racket). This language feature is the first to use the
  4336. computer's \emph{heap} because the lifetime of a Racket tuple is
  4337. indefinite, that is, a tuple lives forever from the programmer's
  4338. viewpoint. Of course, from an implementer's viewpoint, it is important
  4339. to reclaim the space associated with a tuple when it is no longer
  4340. needed, which is why we also study \emph{garbage collection}
  4341. techniques in this chapter.
  4342. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4343. interpreter and type checker. The $R_3$ language extends the $R_2$
  4344. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4345. \code{void} value. The reason for including the later is that the
  4346. \code{vector-set!} operation returns a value of type
  4347. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4348. called the \code{Unit} type in the programming languages
  4349. literature. Racket's \code{Void} type is inhabited by a single value
  4350. \code{void} which corresponds to \code{unit} or \code{()} in the
  4351. literature~\citep{Pierce:2002hj}.}.
  4352. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4353. copying live objects back and forth between two halves of the
  4354. heap. The garbage collector requires coordination with the compiler so
  4355. that it can see all of the \emph{root} pointers, that is, pointers in
  4356. registers or on the procedure call stack.
  4357. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4358. discuss all the necessary changes and additions to the compiler
  4359. passes, including a new compiler pass named \code{expose-allocation}.
  4360. \section{The $R_3$ Language}
  4361. \label{sec:r3}
  4362. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4363. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4364. $R_3$ language includes three new forms for creating a tuple, reading
  4365. an element of a tuple, and writing to an element of a tuple. The
  4366. program in Figure~\ref{fig:vector-eg} shows the usage of tuples in
  4367. Racket. We create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is
  4368. stored at index $2$ of the 3-tuple, demonstrating that tuples are
  4369. first-class values. The element at index $1$ of \code{t} is
  4370. \code{\#t}, so the ``then'' branch of the \key{if} is taken. The
  4371. element at index $0$ of \code{t} is $40$, to which we add $2$, the
  4372. element at index $0$ of the 1-tuple. So the result of the program is
  4373. $42$.
  4374. \begin{figure}[tbp]
  4375. \begin{lstlisting}
  4376. (let ([t (vector 40 #t (vector 2))])
  4377. (if (vector-ref t 1)
  4378. (+ (vector-ref t 0)
  4379. (vector-ref (vector-ref t 2) 0))
  4380. 44))
  4381. \end{lstlisting}
  4382. \caption{Example program that creates tuples and reads from them.}
  4383. \label{fig:vector-eg}
  4384. \end{figure}
  4385. \begin{figure}[tbp]
  4386. \centering
  4387. \fbox{
  4388. \begin{minipage}{0.96\textwidth}
  4389. \[
  4390. \begin{array}{lcl}
  4391. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4392. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4393. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4394. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4395. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4396. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4397. \mid (\key{and}\;\Exp\;\Exp)
  4398. \mid (\key{or}\;\Exp\;\Exp)
  4399. \mid (\key{not}\;\Exp) } \\
  4400. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4401. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4402. &\mid& (\key{vector}\;\Exp^{+})
  4403. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4404. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4405. &\mid& (\key{void}) \\
  4406. R_3 &::=& \Exp
  4407. \end{array}
  4408. \]
  4409. \end{minipage}
  4410. }
  4411. \caption{The concrete syntax of $R_3$, extending $R_2$
  4412. (Figure~\ref{fig:r2-concrete-syntax}).}
  4413. \label{fig:r3-concrete-syntax}
  4414. \end{figure}
  4415. \begin{figure}[tp]
  4416. \centering
  4417. \fbox{
  4418. \begin{minipage}{0.96\textwidth}
  4419. \[
  4420. \begin{array}{lcl}
  4421. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4422. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4423. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4424. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4425. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4426. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4427. &\mid& \gray{ \BOOL{\itm{bool}}
  4428. \mid \AND{\Exp}{\Exp} }\\
  4429. &\mid& \gray{ \OR{\Exp}{\Exp}
  4430. \mid \NOT{\Exp} } \\
  4431. &\mid& \gray{ \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp}
  4432. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4433. &\mid& \VECTOR{\Exp} \\
  4434. &\mid& \VECREF{\Exp}{\Int}\\
  4435. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4436. &\mid& \VOID{} \\
  4437. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4438. \end{array}
  4439. \]
  4440. \end{minipage}
  4441. }
  4442. \caption{The abstract syntax of $R_3$.}
  4443. \label{fig:r3-syntax}
  4444. \end{figure}
  4445. Tuples are our first encounter with heap-allocated data, which raises
  4446. several interesting issues. First, variable binding performs a
  4447. shallow-copy when dealing with tuples, which means that different
  4448. variables can refer to the same tuple, i.e., different variables can
  4449. be \emph{aliases} for the same thing. Consider the following example
  4450. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4451. the mutation through \code{t2} is visible when referencing the tuple
  4452. from \code{t1}, so the result of this program is \code{42}.
  4453. \begin{center}
  4454. \begin{minipage}{0.96\textwidth}
  4455. \begin{lstlisting}
  4456. (let ([t1 (vector 3 7)])
  4457. (let ([t2 t1])
  4458. (let ([_ (vector-set! t2 0 42)])
  4459. (vector-ref t1 0))))
  4460. \end{lstlisting}
  4461. \end{minipage}
  4462. \end{center}
  4463. The next issue concerns the lifetime of tuples. Of course, they are
  4464. created by the \code{vector} form, but when does their lifetime end?
  4465. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4466. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4467. is not tied to any notion of static scoping. For example, the
  4468. following program returns \code{3} even though the variable \code{t}
  4469. goes out of scope prior to accessing the vector.
  4470. \begin{center}
  4471. \begin{minipage}{0.96\textwidth}
  4472. \begin{lstlisting}
  4473. (vector-ref
  4474. (let ([t (vector 3 7)])
  4475. t)
  4476. 0)
  4477. \end{lstlisting}
  4478. \end{minipage}
  4479. \end{center}
  4480. From the perspective of programmer-observable behavior, tuples live
  4481. forever. Of course, if they really lived forever, then many programs
  4482. would run out of memory.\footnote{The $R_3$ language does not have
  4483. looping or recursive function, so it is nigh impossible to write a
  4484. program in $R_3$ that will run out of memory. However, we add
  4485. recursive functions in the next Chapter!} A Racket implementation
  4486. must therefore perform automatic garbage collection.
  4487. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4488. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4489. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4490. operations in Racket. One subtle point is that the \code{vector-set!}
  4491. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4492. can be passed around just like other values inside an $R_3$ program,
  4493. but there are no operations specific to the the \code{\#<void>} value
  4494. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4495. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4496. otherwise.
  4497. \begin{figure}[tbp]
  4498. \begin{lstlisting}
  4499. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4500. (define (interp-op op)
  4501. (match op
  4502. ...
  4503. ['vector vector]
  4504. ['vector-ref vector-ref]
  4505. ['vector-set! vector-set!]
  4506. [else (error 'interp-op "unknown operator")]))
  4507. (define (interp-R3 env)
  4508. (lambda (e)
  4509. (match e
  4510. ...
  4511. [else (error 'interp-R3 "unrecognized expression")]
  4512. )))
  4513. \end{lstlisting}
  4514. \caption{Interpreter for the $R_3$ language.}
  4515. \label{fig:interp-R3}
  4516. \end{figure}
  4517. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4518. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4519. need to know which variables are pointers into the heap, that is,
  4520. which variables are vectors. Also, when allocating a vector, we need
  4521. to know which elements of the vector are pointers. We can obtain this
  4522. information during type checking. The type checker in
  4523. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4524. expression, it also wraps every sub-expression $e$ with the form
  4525. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4526. % TODO: UPDATE? -Jeremy
  4527. Subsequently, in the \code{uncover-locals} pass
  4528. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4529. propagated to all variables (including the temporaries generated by
  4530. \code{remove-complex-opera*}).
  4531. \begin{figure}[tbp]
  4532. \begin{lstlisting}
  4533. (define (type-check-exp env)
  4534. (lambda (e)
  4535. (define recur (type-check-exp env))
  4536. (match e
  4537. ...
  4538. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4539. [(Prim 'vector es)
  4540. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4541. (recur e)))
  4542. (let ([t `(Vector ,@t*)])
  4543. (values (HasType (Prim 'vector e*) t) t))]
  4544. [(Prim 'vector-ref (list e (Int i)))
  4545. (define-values (e^ t) (recur e))
  4546. (match t
  4547. [`(Vector ,ts ...)
  4548. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4549. (error 'type-check-exp "invalid index ~a" i))
  4550. (let ([t (list-ref ts i)])
  4551. (values
  4552. (HasType (Prim 'vector-ref (list e^ (HasType (Int i) 'Integer))) t)
  4553. t))]
  4554. [else (error "expected a vector in vector-ref, not" t)])]
  4555. [(Prim 'eq? (list e1 e2))
  4556. (define-values (e1^ T1) (recur e1))
  4557. (define-values (e2^ T2) (recur e2))
  4558. (unless (equal? T1 T2)
  4559. (error "arguments of eq? must have the same type, but are not"
  4560. (list T1 T2)))
  4561. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4562. ...
  4563. )))
  4564. \end{lstlisting}
  4565. \caption{Type checker for the $R_3$ language.}
  4566. \label{fig:typecheck-R3}
  4567. \end{figure}
  4568. \section{Garbage Collection}
  4569. \label{sec:GC}
  4570. Here we study a relatively simple algorithm for garbage collection
  4571. that is the basis of state-of-the-art garbage
  4572. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4573. particular, we describe a two-space copying
  4574. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4575. perform the
  4576. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4577. coarse-grained depiction of what happens in a two-space collector,
  4578. showing two time steps, prior to garbage collection on the top and
  4579. after garbage collection on the bottom. In a two-space collector, the
  4580. heap is divided into two parts, the FromSpace and the
  4581. ToSpace. Initially, all allocations go to the FromSpace until there is
  4582. not enough room for the next allocation request. At that point, the
  4583. garbage collector goes to work to make more room.
  4584. The garbage collector must be careful not to reclaim tuples that will
  4585. be used by the program in the future. Of course, it is impossible in
  4586. general to predict what a program will do, but we can over approximate
  4587. the will-be-used tuples by preserving all tuples that could be
  4588. accessed by \emph{any} program given the current computer state. A
  4589. program could access any tuple whose address is in a register or on
  4590. the procedure call stack. These addresses are called the \emph{root
  4591. set}. In addition, a program could access any tuple that is
  4592. transitively reachable from the root set. Thus, it is safe for the
  4593. garbage collector to reclaim the tuples that are not reachable in this
  4594. way.
  4595. So the goal of the garbage collector is twofold:
  4596. \begin{enumerate}
  4597. \item preserve all tuple that are reachable from the root set via a
  4598. path of pointers, that is, the \emph{live} tuples, and
  4599. \item reclaim the memory of everything else, that is, the
  4600. \emph{garbage}.
  4601. \end{enumerate}
  4602. A copying collector accomplishes this by copying all of the live
  4603. objects from the FromSpace into the ToSpace and then performs a slight
  4604. of hand, treating the ToSpace as the new FromSpace and the old
  4605. FromSpace as the new ToSpace. In the example of
  4606. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4607. root set, one in a register and two on the stack. All of the live
  4608. objects have been copied to the ToSpace (the right-hand side of
  4609. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4610. pointer relationships. For example, the pointer in the register still
  4611. points to a 2-tuple whose first element is a 3-tuple and second
  4612. element is a 2-tuple. There are four tuples that are not reachable
  4613. from the root set and therefore do not get copied into the ToSpace.
  4614. (The situation in Figure~\ref{fig:copying-collector}, with a
  4615. cycle, cannot be created by a well-typed program in $R_3$. However,
  4616. creating cycles will be possible once we get to $R_6$. We design
  4617. the garbage collector to deal with cycles to begin with, so we will
  4618. not need to revisit this issue.)
  4619. \begin{figure}[tbp]
  4620. \centering
  4621. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4622. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4623. \caption{A copying collector in action.}
  4624. \label{fig:copying-collector}
  4625. \end{figure}
  4626. There are many alternatives to copying collectors (and their older
  4627. siblings, the generational collectors) when its comes to garbage
  4628. collection, such as mark-and-sweep and reference counting. The
  4629. strengths of copying collectors are that allocation is fast (just a
  4630. test and pointer increment), there is no fragmentation, cyclic garbage
  4631. is collected, and the time complexity of collection only depends on
  4632. the amount of live data, and not on the amount of
  4633. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4634. copying collectors is that they use a lot of space, though that
  4635. problem is ameliorated in generational collectors. Racket and Scheme
  4636. programs tend to allocate many small objects and generate a lot of
  4637. garbage, so copying and generational collectors are a good fit. Of
  4638. course, garbage collection is an active research topic, especially
  4639. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4640. continuously developing new techniques and revisiting old
  4641. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4642. \subsection{Graph Copying via Cheney's Algorithm}
  4643. \label{sec:cheney}
  4644. Let us take a closer look at how the copy works. The allocated objects
  4645. and pointers can be viewed as a graph and we need to copy the part of
  4646. the graph that is reachable from the root set. To make sure we copy
  4647. all of the reachable vertices in the graph, we need an exhaustive
  4648. graph traversal algorithm, such as depth-first search or breadth-first
  4649. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4650. take into account the possibility of cycles by marking which vertices
  4651. have already been visited, so as to ensure termination of the
  4652. algorithm. These search algorithms also use a data structure such as a
  4653. stack or queue as a to-do list to keep track of the vertices that need
  4654. to be visited. We shall use breadth-first search and a trick due to
  4655. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4656. copying tuples into the ToSpace.
  4657. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4658. copy progresses. The queue is represented by a chunk of contiguous
  4659. memory at the beginning of the ToSpace, using two pointers to track
  4660. the front and the back of the queue. The algorithm starts by copying
  4661. all tuples that are immediately reachable from the root set into the
  4662. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4663. old tuple to indicate that it has been visited. (We discuss the
  4664. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4665. inside the copied tuples in the queue still point back to the
  4666. FromSpace. Once the initial queue has been created, the algorithm
  4667. enters a loop in which it repeatedly processes the tuple at the front
  4668. of the queue and pops it off the queue. To process a tuple, the
  4669. algorithm copies all the tuple that are directly reachable from it to
  4670. the ToSpace, placing them at the back of the queue. The algorithm then
  4671. updates the pointers in the popped tuple so they point to the newly
  4672. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4673. step we copy the tuple whose second element is $42$ to the back of the
  4674. queue. The other pointer goes to a tuple that has already been copied,
  4675. so we do not need to copy it again, but we do need to update the
  4676. pointer to the new location. This can be accomplished by storing a
  4677. \emph{forwarding} pointer to the new location in the old tuple, back
  4678. when we initially copied the tuple into the ToSpace. This completes
  4679. one step of the algorithm. The algorithm continues in this way until
  4680. the front of the queue is empty, that is, until the front catches up
  4681. with the back.
  4682. \begin{figure}[tbp]
  4683. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4684. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4685. \label{fig:cheney}
  4686. \end{figure}
  4687. \subsection{Data Representation}
  4688. \label{sec:data-rep-gc}
  4689. The garbage collector places some requirements on the data
  4690. representations used by our compiler. First, the garbage collector
  4691. needs to distinguish between pointers and other kinds of data. There
  4692. are several ways to accomplish this.
  4693. \begin{enumerate}
  4694. \item Attached a tag to each object that identifies what type of
  4695. object it is~\citep{McCarthy:1960dz}.
  4696. \item Store different types of objects in different
  4697. regions~\citep{Steele:1977ab}.
  4698. \item Use type information from the program to either generate
  4699. type-specific code for collecting or to generate tables that can
  4700. guide the
  4701. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4702. \end{enumerate}
  4703. Dynamically typed languages, such as Lisp, need to tag objects
  4704. anyways, so option 1 is a natural choice for those languages.
  4705. However, $R_3$ is a statically typed language, so it would be
  4706. unfortunate to require tags on every object, especially small and
  4707. pervasive objects like integers and Booleans. Option 3 is the
  4708. best-performing choice for statically typed languages, but comes with
  4709. a relatively high implementation complexity. To keep this chapter to a
  4710. 2-week time budget, we recommend a combination of options 1 and 2,
  4711. with separate strategies used for the stack and the heap.
  4712. Regarding the stack, we recommend using a separate stack for
  4713. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4714. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4715. local variable needs to be spilled and is of type \code{(Vector
  4716. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4717. of the normal procedure call stack. Furthermore, we always spill
  4718. vector-typed variables if they are live during a call to the
  4719. collector, thereby ensuring that no pointers are in registers during a
  4720. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4721. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4722. layout using a root stack. The root stack contains the two pointers
  4723. from the regular stack and also the pointer in the second
  4724. register.
  4725. \begin{figure}[tbp]
  4726. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4727. \caption{Maintaining a root stack to facilitate garbage collection.}
  4728. \label{fig:shadow-stack}
  4729. \end{figure}
  4730. The problem of distinguishing between pointers and other kinds of data
  4731. also arises inside of each tuple. We solve this problem by attaching a
  4732. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4733. in on the tags for two of the tuples in the example from
  4734. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4735. in a big-endian way, from right-to-left, with bit location 0 (the
  4736. least significant bit) on the far right, which corresponds to the
  4737. directional of the x86 shifting instructions \key{salq} (shift
  4738. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4739. specifying which elements of the tuple are pointers, the part labeled
  4740. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4741. a pointer and a 0 bit indicates some other kind of data. The pointer
  4742. mask starts at bit location 7. We have limited tuples to a maximum
  4743. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4744. tag also contains two other pieces of information. The length of the
  4745. tuple (number of elements) is stored in bits location 1 through
  4746. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4747. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4748. has not yet been copied. If the bit has value 0 then the entire tag
  4749. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4750. always zero anyways because our tuples are 8-byte aligned.)
  4751. \begin{figure}[tbp]
  4752. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4753. \caption{Representation for tuples in the heap.}
  4754. \label{fig:tuple-rep}
  4755. \end{figure}
  4756. \subsection{Implementation of the Garbage Collector}
  4757. \label{sec:organize-gz}
  4758. The implementation of the garbage collector needs to do a lot of
  4759. bit-level data manipulation and we need to link it with our
  4760. compiler-generated x86 code. Thus, we recommend implementing the
  4761. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4762. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4763. interface to the garbage collector. The \code{initialize} function
  4764. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4765. function is meant to be called near the beginning of \code{main},
  4766. before the rest of the program executes. The \code{initialize}
  4767. function puts the address of the beginning of the FromSpace into the
  4768. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4769. points to the address that is 1-past the last element of the
  4770. FromSpace. (We use half-open intervals to represent chunks of
  4771. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4772. points to the first element of the root stack.
  4773. As long as there is room left in the FromSpace, your generated code
  4774. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4775. %
  4776. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4777. --Jeremy}
  4778. %
  4779. The amount of room left in FromSpace is the difference between the
  4780. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4781. function should be called when there is not enough room left in the
  4782. FromSpace for the next allocation. The \code{collect} function takes
  4783. a pointer to the current top of the root stack (one past the last item
  4784. that was pushed) and the number of bytes that need to be
  4785. allocated. The \code{collect} function performs the copying collection
  4786. and leaves the heap in a state such that the next allocation will
  4787. succeed.
  4788. \begin{figure}[tbp]
  4789. \begin{lstlisting}
  4790. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4791. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4792. int64_t* free_ptr;
  4793. int64_t* fromspace_begin;
  4794. int64_t* fromspace_end;
  4795. int64_t** rootstack_begin;
  4796. \end{lstlisting}
  4797. \caption{The compiler's interface to the garbage collector.}
  4798. \label{fig:gc-header}
  4799. \end{figure}
  4800. \begin{exercise}
  4801. In the file \code{runtime.c} you will find the implementation of
  4802. \code{initialize} and a partial implementation of \code{collect}.
  4803. The \code{collect} function calls another function, \code{cheney},
  4804. to perform the actual copy, and that function is left to the reader
  4805. to implement. The following is the prototype for \code{cheney}.
  4806. \begin{lstlisting}
  4807. static void cheney(int64_t** rootstack_ptr);
  4808. \end{lstlisting}
  4809. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4810. rootstack (which is an array of pointers). The \code{cheney} function
  4811. also communicates with \code{collect} through the global
  4812. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4813. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4814. the ToSpace:
  4815. \begin{lstlisting}
  4816. static int64_t* tospace_begin;
  4817. static int64_t* tospace_end;
  4818. \end{lstlisting}
  4819. The job of the \code{cheney} function is to copy all the live
  4820. objects (reachable from the root stack) into the ToSpace, update
  4821. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4822. update the root stack so that it points to the objects in the
  4823. ToSpace, and finally to swap the global pointers for the FromSpace
  4824. and ToSpace.
  4825. \end{exercise}
  4826. %% \section{Compiler Passes}
  4827. %% \label{sec:code-generation-gc}
  4828. The introduction of garbage collection has a non-trivial impact on our
  4829. compiler passes. We introduce one new compiler pass called
  4830. \code{expose-allocation} and make non-trivial changes to
  4831. \code{type-check}, \code{flatten}, \code{select-instructions},
  4832. \code{allocate-registers}, and \code{print-x86}. The following
  4833. program will serve as our running example. It creates two tuples, one
  4834. nested inside the other. Both tuples have length one. The example then
  4835. accesses the element in the inner tuple tuple via two vector
  4836. references.
  4837. % tests/s2_17.rkt
  4838. \begin{lstlisting}
  4839. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4840. \end{lstlisting}
  4841. Next we proceed to discuss the new \code{expose-allocation} pass.
  4842. \section{Expose Allocation}
  4843. \label{sec:expose-allocation}
  4844. The pass \code{expose-allocation} lowers the \code{vector} creation
  4845. form into a conditional call to the collector followed by the
  4846. allocation. We choose to place the \code{expose-allocation} pass
  4847. before \code{flatten} because \code{expose-allocation} introduces new
  4848. variables, which can be done locally with \code{let}, but \code{let}
  4849. is gone after \code{flatten}. In the following, we show the
  4850. transformation for the \code{vector} form into let-bindings for the
  4851. initializing expressions, by a conditional \code{collect}, an
  4852. \code{allocate}, and the initialization of the vector.
  4853. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4854. total bytes need to be allocated for the vector, which is 8 for the
  4855. tag plus \itm{len} times 8.)
  4856. \begin{lstlisting}
  4857. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4858. |$\Longrightarrow$|
  4859. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4860. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4861. (global-value fromspace_end))
  4862. (void)
  4863. (collect |\itm{bytes}|))])
  4864. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4865. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4866. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4867. |$v$|) ... )))) ...)
  4868. \end{lstlisting}
  4869. (In the above, we suppressed all of the \code{has-type} forms in the
  4870. output for the sake of readability.) The placement of the initializing
  4871. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4872. the sequence of \code{vector-set!}'s is important, as those expressions
  4873. may trigger garbage collection and we do not want an allocated but
  4874. uninitialized tuple to be present during a garbage collection.
  4875. The output of \code{expose-allocation} is a language that extends
  4876. $R_3$ with the three new forms that we use above in the translation of
  4877. \code{vector}.
  4878. \[
  4879. \begin{array}{lcl}
  4880. \Exp &::=& \cdots
  4881. \mid (\key{collect} \,\itm{int})
  4882. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4883. \mid (\key{global-value} \,\itm{name})
  4884. \end{array}
  4885. \]
  4886. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4887. %% the beginning of the program which will instruct the garbage collector
  4888. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4889. %% two arguments of \code{initialize} specify the initial allocated space
  4890. %% for the root stack and for the heap.
  4891. %
  4892. %% The \code{expose-allocation} pass annotates all of the local variables
  4893. %% in the \code{program} form with their type.
  4894. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4895. \code{expose-allocation} pass on our running example.
  4896. \begin{figure}[tbp]
  4897. % tests/s2_17.rkt
  4898. \begin{lstlisting}
  4899. (vector-ref
  4900. (vector-ref
  4901. (let ([vecinit7976
  4902. (let ([vecinit7972 42])
  4903. (let ([collectret7974
  4904. (if (< (+ free_ptr 16) fromspace_end)
  4905. (void)
  4906. (collect 16);
  4907. )])
  4908. (let ([alloc7971 (allocate 1 (Vector Integer))])
  4909. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  4910. alloc7971)
  4911. )
  4912. )
  4913. )
  4914. ])
  4915. (let ([collectret7978
  4916. (if (< (+ free_ptr 16) fromspace_end)
  4917. (void)
  4918. (collect 16);
  4919. )])
  4920. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  4921. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  4922. alloc7975)
  4923. )
  4924. )
  4925. )
  4926. 0)
  4927. 0)
  4928. \end{lstlisting}
  4929. \caption{Output of the \code{expose-allocation} pass, minus
  4930. all of the \code{HasType} forms.}
  4931. \label{fig:expose-alloc-output}
  4932. \end{figure}
  4933. %\clearpage
  4934. \section{Explicate Control and the $C_2$ language}
  4935. \label{sec:explicate-control-r3}
  4936. \begin{figure}[tp]
  4937. \fbox{
  4938. \begin{minipage}{0.96\textwidth}
  4939. \small
  4940. \[
  4941. \begin{array}{lcl}
  4942. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  4943. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4944. \Exp &::= & \gray{ \Atm \mid \READ{} \mid \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  4945. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  4946. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type})
  4947. \mid \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  4948. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  4949. &\mid& (\key{GlobalValue} \,\itm{name}) \mid (\key{Void}) \\
  4950. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} \mid \RETURN{\Exp} }
  4951. \mid (\key{Collect} \,\itm{int}) \\
  4952. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }\\
  4953. &\mid& \gray{ \GOTO{\itm{label}} }\\
  4954. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  4955. C_2 & ::= & \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)^{+}}}
  4956. \end{array}
  4957. \]
  4958. \end{minipage}
  4959. }
  4960. \caption{The abstract syntax of the $C_2$ language.
  4961. TODO: UPDATE}
  4962. \label{fig:c2-syntax}
  4963. \end{figure}
  4964. The output of \code{explicate-control} is a program in the
  4965. intermediate language $C_2$, whose syntax is defined in
  4966. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4967. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4968. \key{global-value} expressions and the \code{collect} statement. The
  4969. \code{explicate-control} pass can treat these new forms much like the
  4970. other forms.
  4971. \section{Uncover Locals}
  4972. \label{sec:uncover-locals-r3}
  4973. Recall that the \code{explicate-control} function collects all of the
  4974. local variables so that it can store them in the $\itm{info}$ field of
  4975. the \code{Program} structure. Also recall that we need to know the
  4976. types of all the local variables for purposes of identifying the root
  4977. set for the garbage collector. Thus, we create a pass named
  4978. \code{uncover-locals} to collect not just the variables but the
  4979. variables and their types in the form of an alist. Thanks
  4980. to the \code{HasType} nodes, the types are readily available in the
  4981. AST. Figure~\ref{fig:uncover-locals-r3} lists the output of the
  4982. \code{uncover-locals} pass on the running example.
  4983. \begin{figure}[tbp]
  4984. % tests/s2_17.rkt
  4985. \begin{lstlisting}
  4986. program:
  4987. locals:
  4988. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  4989. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  4990. collectret7974 : 'Void, initret7977 : 'Void,
  4991. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  4992. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  4993. alloc7971 : '(Vector Integer), tmp7981 : 'Integer, vecinit7972 : 'Integer,
  4994. initret7973 : 'Void,
  4995. block7991:
  4996. (collect 16);
  4997. goto block7989;
  4998. block7990:
  4999. collectret7974 = (void);
  5000. goto block7989;
  5001. block7989:
  5002. alloc7971 = (allocate 1 (Vector Integer));
  5003. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5004. vecinit7976 = alloc7971;
  5005. tmp7982 = free_ptr;
  5006. tmp7983 = (+ tmp7982 16);
  5007. tmp7984 = fromspace_end;
  5008. if (< tmp7983 tmp7984) then
  5009. goto block7987;
  5010. else
  5011. goto block7988;
  5012. block7988:
  5013. (collect 16);
  5014. goto block7986;
  5015. block7987:
  5016. collectret7978 = (void);
  5017. goto block7986;
  5018. block7986:
  5019. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5020. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5021. tmp7985 = (vector-ref alloc7975 0);
  5022. return (vector-ref tmp7985 0);
  5023. start:
  5024. vecinit7972 = 42;
  5025. tmp7979 = free_ptr;
  5026. tmp7980 = (+ tmp7979 16);
  5027. tmp7981 = fromspace_end;
  5028. if (< tmp7980 tmp7981) then
  5029. goto block7990;
  5030. else
  5031. goto block7991;
  5032. \end{lstlisting}
  5033. \caption{Output of \code{uncover-locals} for the running example.}
  5034. \label{fig:uncover-locals-r3}
  5035. \end{figure}
  5036. \clearpage
  5037. \section{Select Instructions}
  5038. \label{sec:select-instructions-gc}
  5039. %% void (rep as zero)
  5040. %% allocate
  5041. %% collect (callq collect)
  5042. %% vector-ref
  5043. %% vector-set!
  5044. %% global-value (postpone)
  5045. In this pass we generate x86 code for most of the new operations that
  5046. were needed to compile tuples, including \code{allocate},
  5047. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  5048. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  5049. The \code{vector-ref} and \code{vector-set!} forms translate into
  5050. \code{movq} instructions with the appropriate \key{deref}. (The
  5051. plus one is to get past the tag at the beginning of the tuple
  5052. representation.)
  5053. \begin{lstlisting}
  5054. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  5055. |$\Longrightarrow$|
  5056. (movq |$\itm{vec}'$| (reg r11))
  5057. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  5058. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  5059. |$\Longrightarrow$|
  5060. (movq |$\itm{vec}'$| (reg r11))
  5061. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  5062. (movq (int 0) |$\itm{lhs}$|)
  5063. \end{lstlisting}
  5064. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  5065. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  5066. register \code{r11} ensures that offsets are only performed with
  5067. register operands. This requires removing \code{r11} from
  5068. consideration by the register allocating.
  5069. We compile the \code{allocate} form to operations on the
  5070. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5071. is the next free address in the FromSpace, so we move it into the
  5072. \itm{lhs} and then move it forward by enough space for the tuple being
  5073. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5074. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5075. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5076. how the tag is organized. We recommend using the Racket operations
  5077. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  5078. The type annotation in the \code{vector} form is used to determine the
  5079. pointer mask region of the tag.
  5080. \begin{lstlisting}
  5081. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  5082. |$\Longrightarrow$|
  5083. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  5084. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  5085. (movq |$\itm{lhs}'$| (reg r11))
  5086. (movq (int |$\itm{tag}$|) (deref r11 0))
  5087. \end{lstlisting}
  5088. The \code{collect} form is compiled to a call to the \code{collect}
  5089. function in the runtime. The arguments to \code{collect} are the top
  5090. of the root stack and the number of bytes that need to be allocated.
  5091. We shall use a dedicated register, \code{r15}, to store the pointer to
  5092. the top of the root stack. So \code{r15} is not available for use by
  5093. the register allocator.
  5094. \begin{lstlisting}
  5095. (collect |$\itm{bytes}$|)
  5096. |$\Longrightarrow$|
  5097. (movq (reg r15) (reg rdi))
  5098. (movq |\itm{bytes}| (reg rsi))
  5099. (callq collect)
  5100. \end{lstlisting}
  5101. \begin{figure}[tp]
  5102. \fbox{
  5103. \begin{minipage}{0.96\textwidth}
  5104. \[
  5105. \begin{array}{lcl}
  5106. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5107. \mid (\key{deref}\,\Reg\,\Int) } \\
  5108. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  5109. \mid (\key{global-value}\; \itm{name}) \\
  5110. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5111. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  5112. (\key{subq} \; \Arg\; \Arg) \mid
  5113. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  5114. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  5115. (\key{pushq}\;\Arg) \mid
  5116. (\key{popq}\;\Arg) \mid
  5117. (\key{retq})} \\
  5118. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5119. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5120. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5121. \mid (\key{jmp} \; \itm{label})
  5122. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  5123. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  5124. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  5125. \end{array}
  5126. \]
  5127. \end{minipage}
  5128. }
  5129. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5130. \label{fig:x86-2}
  5131. \end{figure}
  5132. The syntax of the $x86_2$ language is defined in
  5133. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  5134. of the form for global variables.
  5135. %
  5136. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5137. \code{select-instructions} pass on the running example.
  5138. \begin{figure}[tbp]
  5139. \centering
  5140. \begin{minipage}{0.75\textwidth}
  5141. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5142. (program
  5143. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5144. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5145. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5146. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5147. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5148. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5149. ((block63 . (block ()
  5150. (movq (reg r15) (reg rdi))
  5151. (movq (int 16) (reg rsi))
  5152. (callq collect)
  5153. (jmp block61)))
  5154. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5155. (block61 . (block ()
  5156. (movq (global-value free_ptr) (var alloc43))
  5157. (addq (int 16) (global-value free_ptr))
  5158. (movq (var alloc43) (reg r11))
  5159. (movq (int 3) (deref r11 0))
  5160. (movq (var alloc43) (reg r11))
  5161. (movq (var vecinit44) (deref r11 8))
  5162. (movq (int 0) (var initret45))
  5163. (movq (var alloc43) (var vecinit48))
  5164. (movq (global-value free_ptr) (var tmp54))
  5165. (movq (var tmp54) (var tmp55))
  5166. (addq (int 16) (var tmp55))
  5167. (movq (global-value fromspace_end) (var tmp56))
  5168. (cmpq (var tmp56) (var tmp55))
  5169. (jmp-if l block59)
  5170. (jmp block60)))
  5171. (block60 . (block ()
  5172. (movq (reg r15) (reg rdi))
  5173. (movq (int 16) (reg rsi))
  5174. (callq collect)
  5175. (jmp block58))
  5176. (block59 . (block ()
  5177. (movq (int 0) (var collectret50))
  5178. (jmp block58)))
  5179. (block58 . (block ()
  5180. (movq (global-value free_ptr) (var alloc47))
  5181. (addq (int 16) (global-value free_ptr))
  5182. (movq (var alloc47) (reg r11))
  5183. (movq (int 131) (deref r11 0))
  5184. (movq (var alloc47) (reg r11))
  5185. (movq (var vecinit48) (deref r11 8))
  5186. (movq (int 0) (var initret49))
  5187. (movq (var alloc47) (reg r11))
  5188. (movq (deref r11 8) (var tmp57))
  5189. (movq (var tmp57) (reg r11))
  5190. (movq (deref r11 8) (reg rax))
  5191. (jmp conclusion)))
  5192. (start . (block ()
  5193. (movq (int 42) (var vecinit44))
  5194. (movq (global-value free_ptr) (var tmp51))
  5195. (movq (var tmp51) (var tmp52))
  5196. (addq (int 16) (var tmp52))
  5197. (movq (global-value fromspace_end) (var tmp53))
  5198. (cmpq (var tmp53) (var tmp52))
  5199. (jmp-if l block62)
  5200. (jmp block63))))))
  5201. \end{lstlisting}
  5202. \end{minipage}
  5203. \caption{Output of the \code{select-instructions} pass.}
  5204. \label{fig:select-instr-output-gc}
  5205. \end{figure}
  5206. \clearpage
  5207. \section{Register Allocation}
  5208. \label{sec:reg-alloc-gc}
  5209. As discussed earlier in this chapter, the garbage collector needs to
  5210. access all the pointers in the root set, that is, all variables that
  5211. are vectors. It will be the responsibility of the register allocator
  5212. to make sure that:
  5213. \begin{enumerate}
  5214. \item the root stack is used for spilling vector-typed variables, and
  5215. \item if a vector-typed variable is live during a call to the
  5216. collector, it must be spilled to ensure it is visible to the
  5217. collector.
  5218. \end{enumerate}
  5219. The later responsibility can be handled during construction of the
  5220. inference graph, by adding interference edges between the call-live
  5221. vector-typed variables and all the callee-saved registers. (They
  5222. already interfere with the caller-saved registers.) The type
  5223. information for variables is in the \code{program} form, so we
  5224. recommend adding another parameter to the \code{build-interference}
  5225. function to communicate this alist.
  5226. The spilling of vector-typed variables to the root stack can be
  5227. handled after graph coloring, when choosing how to assign the colors
  5228. (integers) to registers and stack locations. The \code{program} output
  5229. of this pass changes to also record the number of spills to the root
  5230. stack.
  5231. % build-interference
  5232. %
  5233. % callq
  5234. % extra parameter for var->type assoc. list
  5235. % update 'program' and 'if'
  5236. % allocate-registers
  5237. % allocate spilled vectors to the rootstack
  5238. % don't change color-graph
  5239. \section{Print x86}
  5240. \label{sec:print-x86-gc}
  5241. \margincomment{\scriptsize We need to show the translation to x86 and what
  5242. to do about global-value. \\ --Jeremy}
  5243. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5244. \code{print-x86} pass on the running example. In the prelude and
  5245. conclusion of the \code{main} function, we treat the root stack very
  5246. much like the regular stack in that we move the root stack pointer
  5247. (\code{r15}) to make room for all of the spills to the root stack,
  5248. except that the root stack grows up instead of down. For the running
  5249. example, there was just one spill so we increment \code{r15} by 8
  5250. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5251. One issue that deserves special care is that there may be a call to
  5252. \code{collect} prior to the initializing assignments for all the
  5253. variables in the root stack. We do not want the garbage collector to
  5254. accidentally think that some uninitialized variable is a pointer that
  5255. needs to be followed. Thus, we zero-out all locations on the root
  5256. stack in the prelude of \code{main}. In
  5257. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5258. %
  5259. \lstinline{movq $0, (%r15)}
  5260. %
  5261. accomplishes this task. The garbage collector tests each root to see
  5262. if it is null prior to dereferencing it.
  5263. \begin{figure}[htbp]
  5264. \begin{minipage}[t]{0.5\textwidth}
  5265. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5266. _block58:
  5267. movq _free_ptr(%rip), %rcx
  5268. addq $16, _free_ptr(%rip)
  5269. movq %rcx, %r11
  5270. movq $131, 0(%r11)
  5271. movq %rcx, %r11
  5272. movq -8(%r15), %rax
  5273. movq %rax, 8(%r11)
  5274. movq $0, %rdx
  5275. movq %rcx, %r11
  5276. movq 8(%r11), %rcx
  5277. movq %rcx, %r11
  5278. movq 8(%r11), %rax
  5279. jmp _conclusion
  5280. _block59:
  5281. movq $0, %rcx
  5282. jmp _block58
  5283. _block62:
  5284. movq $0, %rcx
  5285. jmp _block61
  5286. _block60:
  5287. movq %r15, %rdi
  5288. movq $16, %rsi
  5289. callq _collect
  5290. jmp _block58
  5291. _block63:
  5292. movq %r15, %rdi
  5293. movq $16, %rsi
  5294. callq _collect
  5295. jmp _block61
  5296. _start:
  5297. movq $42, %rbx
  5298. movq _free_ptr(%rip), %rdx
  5299. addq $16, %rdx
  5300. movq _fromspace_end(%rip), %rcx
  5301. cmpq %rcx, %rdx
  5302. jl _block62
  5303. jmp _block63
  5304. \end{lstlisting}
  5305. \end{minipage}
  5306. \begin{minipage}[t]{0.45\textwidth}
  5307. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5308. _block61:
  5309. movq _free_ptr(%rip), %rcx
  5310. addq $16, _free_ptr(%rip)
  5311. movq %rcx, %r11
  5312. movq $3, 0(%r11)
  5313. movq %rcx, %r11
  5314. movq %rbx, 8(%r11)
  5315. movq $0, %rdx
  5316. movq %rcx, -8(%r15)
  5317. movq _free_ptr(%rip), %rcx
  5318. addq $16, %rcx
  5319. movq _fromspace_end(%rip), %rdx
  5320. cmpq %rdx, %rcx
  5321. jl _block59
  5322. jmp _block60
  5323. .globl _main
  5324. _main:
  5325. pushq %rbp
  5326. movq %rsp, %rbp
  5327. pushq %r12
  5328. pushq %rbx
  5329. pushq %r13
  5330. pushq %r14
  5331. subq $0, %rsp
  5332. movq $16384, %rdi
  5333. movq $16, %rsi
  5334. callq _initialize
  5335. movq _rootstack_begin(%rip), %r15
  5336. movq $0, (%r15)
  5337. addq $8, %r15
  5338. jmp _start
  5339. _conclusion:
  5340. subq $8, %r15
  5341. addq $0, %rsp
  5342. popq %r14
  5343. popq %r13
  5344. popq %rbx
  5345. popq %r12
  5346. popq %rbp
  5347. retq
  5348. \end{lstlisting}
  5349. \end{minipage}
  5350. \caption{Output of the \code{print-x86} pass.}
  5351. \label{fig:print-x86-output-gc}
  5352. \end{figure}
  5353. \margincomment{\scriptsize Suggest an implementation strategy
  5354. in which the students first do the code gen and test that
  5355. without GC (just use a big heap), then after that is debugged,
  5356. implement the GC. \\ --Jeremy}
  5357. \begin{figure}[p]
  5358. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5359. \node (R3) at (0,2) {\large $R_3$};
  5360. \node (R3-2) at (3,2) {\large $R_3$};
  5361. \node (R3-3) at (6,2) {\large $R_3$};
  5362. \node (R3-4) at (9,2) {\large $R_3$};
  5363. \node (R3-5) at (12,2) {\large $R_3$};
  5364. \node (C2-4) at (3,0) {\large $C_2$};
  5365. \node (C2-3) at (6,0) {\large $C_2$};
  5366. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5367. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5368. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5369. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5370. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5371. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5372. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5373. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5374. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5375. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5376. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5377. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5378. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5379. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5380. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5381. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5382. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5383. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5384. \end{tikzpicture}
  5385. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5386. \label{fig:R3-passes}
  5387. \end{figure}
  5388. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5389. for the compilation of $R_3$.
  5390. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5391. \chapter{Functions}
  5392. \label{ch:functions}
  5393. This chapter studies the compilation of functions at the level of
  5394. abstraction of the C language. This corresponds to a subset of Typed
  5395. Racket in which only top-level function definitions are allowed. These
  5396. kind of functions are an important stepping stone to implementing
  5397. lexically-scoped functions in the form of \key{lambda} abstractions,
  5398. which is the topic of Chapter~\ref{ch:lambdas}.
  5399. \section{The $R_4$ Language}
  5400. The syntax for function definitions and function application is shown
  5401. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5402. Programs in $R_4$ start with zero or more function definitions. The
  5403. function names from these definitions are in-scope for the entire
  5404. program, including all other function definitions (so the ordering of
  5405. function definitions does not matter). The syntax for function
  5406. application does not include an explicit keyword, which is error prone
  5407. when using \code{match}. To alleviate this problem, we change the
  5408. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5409. during type checking.
  5410. Functions are first-class in the sense that a function pointer is data
  5411. and can be stored in memory or passed as a parameter to another
  5412. function. Thus, we introduce a function type, written
  5413. \begin{lstlisting}
  5414. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5415. \end{lstlisting}
  5416. for a function whose $n$ parameters have the types $\Type_1$ through
  5417. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5418. these functions (with respect to Racket functions) is that they are
  5419. not lexically scoped. That is, the only external entities that can be
  5420. referenced from inside a function body are other globally-defined
  5421. functions. The syntax of $R_4$ prevents functions from being nested
  5422. inside each other.
  5423. \begin{figure}[tp]
  5424. \centering
  5425. \fbox{
  5426. \begin{minipage}{0.96\textwidth}
  5427. \[
  5428. \begin{array}{lcl}
  5429. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5430. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5431. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5432. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5433. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5434. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5435. \mid (\key{and}\;\Exp\;\Exp)
  5436. \mid (\key{or}\;\Exp\;\Exp)
  5437. \mid (\key{not}\;\Exp)} \\
  5438. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5439. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5440. (\key{vector-ref}\;\Exp\;\Int)} \\
  5441. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5442. &\mid& (\Exp \; \Exp^{*}) \\
  5443. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5444. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5445. \end{array}
  5446. \]
  5447. \end{minipage}
  5448. }
  5449. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5450. with functions.}
  5451. \label{fig:r4-syntax}
  5452. \end{figure}
  5453. The program in Figure~\ref{fig:r4-function-example} is a
  5454. representative example of defining and using functions in $R_4$. We
  5455. define a function \code{map-vec} that applies some other function
  5456. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5457. vector containing the results. We also define a function \code{add1}
  5458. that does what its name suggests. The program then applies
  5459. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5460. \code{(vector 1 42)}, from which we return the \code{42}.
  5461. \begin{figure}[tbp]
  5462. \begin{lstlisting}
  5463. (program ()
  5464. (define (map-vec [f : (Integer -> Integer)]
  5465. [v : (Vector Integer Integer)])
  5466. : (Vector Integer Integer)
  5467. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5468. (define (add1 [x : Integer]) : Integer
  5469. (+ x 1))
  5470. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5471. )
  5472. \end{lstlisting}
  5473. \caption{Example of using functions in $R_4$.}
  5474. \label{fig:r4-function-example}
  5475. \end{figure}
  5476. The definitional interpreter for $R_4$ is in
  5477. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5478. responsible for setting up the mutual recursion between the top-level
  5479. function definitions. We use the classic back-patching approach that
  5480. uses mutable variables and makes two passes over the function
  5481. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5482. top-level environment using a mutable cons cell for each function
  5483. definition. Note that the \code{lambda} value for each function is
  5484. incomplete; it does not yet include the environment. Once the
  5485. top-level environment is constructed, we then iterate over it and
  5486. update the \code{lambda} value's to use the top-level environment.
  5487. \begin{figure}[tp]
  5488. \begin{lstlisting}
  5489. (define (interp-exp env)
  5490. (lambda (e)
  5491. (define recur (interp-exp env))
  5492. (match e
  5493. ...
  5494. [`(,fun ,args ...)
  5495. (define arg-vals (for/list ([e args]) (recur e)))
  5496. (define fun-val (recur fun))
  5497. (match fun-val
  5498. [`(lambda (,xs ...) ,body ,fun-env)
  5499. (define new-env (append (map cons xs arg-vals) fun-env))
  5500. ((interp-exp new-env) body)]
  5501. [else (error "interp-exp, expected function, not" fun-val)])]
  5502. [else (error 'interp-exp "unrecognized expression")]
  5503. )))
  5504. (define (interp-def d)
  5505. (match d
  5506. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5507. (mcons f `(lambda ,xs ,body ()))]
  5508. ))
  5509. (define (interp-R4 p)
  5510. (match p
  5511. [`(program ,ds ... ,body)
  5512. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5513. (for/list ([b top-level])
  5514. (set-mcdr! b (match (mcdr b)
  5515. [`(lambda ,xs ,body ())
  5516. `(lambda ,xs ,body ,top-level)])))
  5517. ((interp-exp top-level) body))]
  5518. ))
  5519. \end{lstlisting}
  5520. \caption{Interpreter for the $R_4$ language.}
  5521. \label{fig:interp-R4}
  5522. \end{figure}
  5523. \section{Functions in x86}
  5524. \label{sec:fun-x86}
  5525. \margincomment{\tiny Make sure callee-saved registers are discussed
  5526. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5527. \margincomment{\tiny Talk about the return address on the
  5528. stack and what callq and retq does.\\ --Jeremy }
  5529. The x86 architecture provides a few features to support the
  5530. implementation of functions. We have already seen that x86 provides
  5531. labels so that one can refer to the location of an instruction, as is
  5532. needed for jump instructions. Labels can also be used to mark the
  5533. beginning of the instructions for a function. Going further, we can
  5534. obtain the address of a label by using the \key{leaq} instruction and
  5535. \key{rip}-relative addressing. For example, the following puts the
  5536. address of the \code{add1} label into the \code{rbx} register.
  5537. \begin{lstlisting}
  5538. leaq add1(%rip), %rbx
  5539. \end{lstlisting}
  5540. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5541. instruction for jumping to a function whose location is given by a
  5542. label. Here we instead will be jumping to a function whose location is
  5543. given by an address, that is, we need to make an \emph{indirect
  5544. function call}. The x86 syntax is to give the register name prefixed
  5545. with an asterisk.
  5546. \begin{lstlisting}
  5547. callq *%rbx
  5548. \end{lstlisting}
  5549. \subsection{Calling Conventions}
  5550. The \code{callq} instruction provides partial support for implementing
  5551. functions, but it does not handle (1) parameter passing, (2) saving
  5552. and restoring frames on the procedure call stack, or (3) determining
  5553. how registers are shared by different functions. These issues require
  5554. coordination between the caller and the callee, which is often
  5555. assembly code written by different programmers or generated by
  5556. different compilers. As a result, people have developed
  5557. \emph{conventions} that govern how functions calls are performed.
  5558. Here we shall use the same conventions used by the \code{gcc}
  5559. compiler~\citep{Matz:2013aa}.
  5560. Regarding (1) parameter passing, the convention is to use the
  5561. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5562. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5563. than six arguments, then the convention is to use space on the frame
  5564. of the caller for the rest of the arguments. However, to ease the
  5565. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5566. we shall arrange to never have more than six arguments.
  5567. %
  5568. The register \code{rax} is for the return value of the function.
  5569. Regarding (2) frames and the procedure call stack, the convention is
  5570. that the stack grows down, with each function call using a chunk of
  5571. space called a frame. The caller sets the stack pointer, register
  5572. \code{rsp}, to the last data item in its frame. The callee must not
  5573. change anything in the caller's frame, that is, anything that is at or
  5574. above the stack pointer. The callee is free to use locations that are
  5575. below the stack pointer.
  5576. Regarding (3) the sharing of registers between different functions,
  5577. recall from Section~\ref{sec:calling-conventions} that the registers
  5578. are divided into two groups, the caller-saved registers and the
  5579. callee-saved registers. The caller should assume that all the
  5580. caller-saved registers get overwritten with arbitrary values by the
  5581. callee. Thus, the caller should either 1) not put values that are live
  5582. across a call in caller-saved registers, or 2) save and restore values
  5583. that are live across calls. We shall recommend option 1). On the flip
  5584. side, if the callee wants to use a callee-saved register, the callee
  5585. must save the contents of those registers on their stack frame and
  5586. then put them back prior to returning to the caller. The base
  5587. pointer, register \code{rbp}, is used as a point-of-reference within a
  5588. frame, so that each local variable can be accessed at a fixed offset
  5589. from the base pointer.
  5590. %
  5591. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5592. frames.
  5593. %% If we were to use stack arguments, they would be between the
  5594. %% caller locals and the callee return address.
  5595. \begin{figure}[tbp]
  5596. \centering
  5597. \begin{tabular}{r|r|l|l} \hline
  5598. Caller View & Callee View & Contents & Frame \\ \hline
  5599. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5600. 0(\key{\%rbp}) & & old \key{rbp} \\
  5601. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5602. \ldots & & \ldots \\
  5603. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5604. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5605. \ldots & & \ldots \\
  5606. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5607. %% & & \\
  5608. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5609. %% & \ldots & \ldots \\
  5610. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5611. \hline
  5612. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5613. & 0(\key{\%rbp}) & old \key{rbp} \\
  5614. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5615. & \ldots & \ldots \\
  5616. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5617. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5618. & \ldots & \ldots \\
  5619. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5620. \end{tabular}
  5621. \caption{Memory layout of caller and callee frames.}
  5622. \label{fig:call-frames}
  5623. \end{figure}
  5624. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5625. %% local variables and for storing the values of callee-saved registers
  5626. %% (we shall refer to all of these collectively as ``locals''), and that
  5627. %% at the beginning of a function we move the stack pointer \code{rsp}
  5628. %% down to make room for them.
  5629. %% We recommend storing the local variables
  5630. %% first and then the callee-saved registers, so that the local variables
  5631. %% can be accessed using \code{rbp} the same as before the addition of
  5632. %% functions.
  5633. %% To make additional room for passing arguments, we shall
  5634. %% move the stack pointer even further down. We count how many stack
  5635. %% arguments are needed for each function call that occurs inside the
  5636. %% body of the function and find their maximum. Adding this number to the
  5637. %% number of locals gives us how much the \code{rsp} should be moved at
  5638. %% the beginning of the function. In preparation for a function call, we
  5639. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5640. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5641. %% so on.
  5642. %% Upon calling the function, the stack arguments are retrieved by the
  5643. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5644. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5645. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5646. %% the layout of the caller and callee frames. Notice how important it is
  5647. %% that we correctly compute the maximum number of arguments needed for
  5648. %% function calls; if that number is too small then the arguments and
  5649. %% local variables will smash into each other!
  5650. \subsection{Efficient Tail Calls}
  5651. \label{sec:tail-call}
  5652. In general, the amount of stack space used by a program is determined
  5653. by the longest chain of nested function calls. That is, if function
  5654. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5655. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5656. $n$ can grow quite large in the case of recursive or mutually
  5657. recursive functions. However, in some cases we can arrange to use only
  5658. constant space, i.e. $O(1)$, instead of $O(n)$.
  5659. If a function call is the last action in a function body, then that
  5660. call is said to be a \emph{tail call}. In such situations, the frame
  5661. of the caller is no longer needed, so we can pop the caller's frame
  5662. before making the tail call. With this approach, a recursive function
  5663. that only makes tail calls will only use $O(1)$ stack space.
  5664. Functional languages like Racket typically rely heavily on recursive
  5665. functions, so they typically guarantee that all tail calls will be
  5666. optimized in this way.
  5667. However, some care is needed with regards to argument passing in tail
  5668. calls. As mentioned above, for arguments beyond the sixth, the
  5669. convention is to use space in the caller's frame for passing
  5670. arguments. But here we've popped the caller's frame and can no longer
  5671. use it. Another alternative is to use space in the callee's frame for
  5672. passing arguments. However, this option is also problematic because
  5673. the caller and callee's frame overlap in memory. As we begin to copy
  5674. the arguments from their sources in the caller's frame, the target
  5675. locations in the callee's frame might overlap with the sources for
  5676. later arguments! We solve this problem by not using the stack for
  5677. parameter passing but instead use the heap, as we describe in the
  5678. Section~\ref{sec:limit-functions-r4}.
  5679. As mentioned above, for a tail call we pop the caller's frame prior to
  5680. making the tail call. The instructions for popping a frame are the
  5681. instructions that we usually place in the conclusion of a
  5682. function. Thus, we also need to place such code immediately before
  5683. each tail call. These instructions include restoring the callee-saved
  5684. registers, so it is good that the argument passing registers are all
  5685. caller-saved registers.
  5686. One last note regarding which instruction to use to make the tail
  5687. call. When the callee is finished, it should not return to the current
  5688. function, but it should return to the function that called the current
  5689. one. Thus, the return address that is already on the stack is the
  5690. right one, and we should not use \key{callq} to make the tail call, as
  5691. that would unnecessarily overwrite the return address. Instead we can
  5692. simply use the \key{jmp} instruction. Like the indirect function call,
  5693. we write an indirect jump with a register prefixed with an asterisk.
  5694. We recommend using \code{rax} to hold the jump target because the
  5695. preceding ``conclusion'' overwrites just about everything else.
  5696. \begin{lstlisting}
  5697. jmp *%rax
  5698. \end{lstlisting}
  5699. %% Now that we have a good understanding of functions as they appear in
  5700. %% $R_4$ and the support for functions in x86, we need to plan the
  5701. %% changes to our compiler, that is, do we need any new passes and/or do
  5702. %% we need to change any existing passes? Also, do we need to add new
  5703. %% kinds of AST nodes to any of the intermediate languages?
  5704. \section{Shrink $R_4$}
  5705. \label{sec:shrink-r4}
  5706. The \code{shrink} pass performs a couple minor modifications to the
  5707. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5708. field to each function definition:
  5709. \begin{lstlisting}
  5710. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5711. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5712. \end{lstlisting}
  5713. and introduces an explicit \code{main} function.\\
  5714. \begin{tabular}{lll}
  5715. \begin{minipage}{0.45\textwidth}
  5716. \begin{lstlisting}
  5717. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5718. \end{lstlisting}
  5719. \end{minipage}
  5720. &
  5721. $\Rightarrow$
  5722. &
  5723. \begin{minipage}{0.45\textwidth}
  5724. \begin{lstlisting}
  5725. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5726. \end{lstlisting}
  5727. \end{minipage}
  5728. \end{tabular} \\
  5729. where $\itm{mainDef}$ is
  5730. \begin{lstlisting}
  5731. (define (main) : Integer () |$\Exp'$|)
  5732. \end{lstlisting}
  5733. \section{Reveal Functions}
  5734. \label{sec:reveal-functions-r4}
  5735. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5736. compilation because it conflates the use of function names and local
  5737. variables. This is a problem because we need to compile the use of a
  5738. function name differently than the use of a local variable; we need to
  5739. use \code{leaq} to convert the function name (a label in x86) to an
  5740. address in a register. Thus, it is a good idea to create a new pass
  5741. that changes function references from just a symbol $f$ to
  5742. \code{(fun-ref $f$)}. A good name for this pass is
  5743. \code{reveal-functions} and the output language, $F_1$, is defined in
  5744. Figure~\ref{fig:f1-syntax}.
  5745. \begin{figure}[tp]
  5746. \centering
  5747. \fbox{
  5748. \begin{minipage}{0.96\textwidth}
  5749. \[
  5750. \begin{array}{lcl}
  5751. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5752. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5753. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5754. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5755. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5756. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5757. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5758. (\key{vector-ref}\;\Exp\;\Int)} \\
  5759. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5760. (\key{app}\; \Exp \; \Exp^{*})} \\
  5761. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5762. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5763. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5764. \end{array}
  5765. \]
  5766. \end{minipage}
  5767. }
  5768. \caption{The $F_1$ language, an extension of $R_4$
  5769. (Figure~\ref{fig:r4-syntax}).}
  5770. \label{fig:f1-syntax}
  5771. \end{figure}
  5772. %% Distinguishing between calls in tail position and non-tail position
  5773. %% requires the pass to have some notion of context. We recommend using
  5774. %% two mutually recursive functions, one for processing expressions in
  5775. %% tail position and another for the rest.
  5776. Placing this pass after \code{uniquify} is a good idea, because it
  5777. will make sure that there are no local variables and functions that
  5778. share the same name. On the other hand, \code{reveal-functions} needs
  5779. to come before the \code{explicate-control} pass because that pass
  5780. will help us compile \code{fun-ref} into assignment statements.
  5781. \section{Limit Functions}
  5782. \label{sec:limit-functions-r4}
  5783. This pass transforms functions so that they have at most six
  5784. parameters and transforms all function calls so that they pass at most
  5785. six arguments. A simple strategy for imposing an argument limit of
  5786. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5787. into a vector, making that subsequent vector the $n$th argument.
  5788. \begin{tabular}{lll}
  5789. \begin{minipage}{0.2\textwidth}
  5790. \begin{lstlisting}
  5791. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5792. \end{lstlisting}
  5793. \end{minipage}
  5794. &
  5795. $\Rightarrow$
  5796. &
  5797. \begin{minipage}{0.4\textwidth}
  5798. \begin{lstlisting}
  5799. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5800. \end{lstlisting}
  5801. \end{minipage}
  5802. \end{tabular}
  5803. In the body of the function, all occurrences of the $i$th argument in
  5804. which $i>5$ must be replaced with a \code{vector-ref}.
  5805. \section{Remove Complex Operators and Operands}
  5806. \label{sec:rco-r4}
  5807. The primary decisions to make for this pass is whether to classify
  5808. \code{fun-ref} and \code{app} as either simple or complex
  5809. expressions. Recall that a simple expression will eventually end up as
  5810. just an ``immediate'' argument of an x86 instruction. Function
  5811. application will be translated to a sequence of instructions, so
  5812. \code{app} must be classified as complex expression. Regarding
  5813. \code{fun-ref}, as discussed above, the function label needs to
  5814. be converted to an address using the \code{leaq} instruction. Thus,
  5815. even though \code{fun-ref} seems rather simple, it needs to be
  5816. classified as a complex expression so that we generate an assignment
  5817. statement with a left-hand side that can serve as the target of the
  5818. \code{leaq}.
  5819. \section{Explicate Control and the $C_3$ language}
  5820. \label{sec:explicate-control-r4}
  5821. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5822. \key{explicate-control}. The three mutually recursive functions for
  5823. this pass, for assignment, tail, and predicate contexts, must all be
  5824. updated with cases for \code{fun-ref} and \code{app}. In
  5825. assignment and predicate contexts, \code{app} becomes \code{call},
  5826. whereas in tail position \code{app} becomes \code{tailcall}. We
  5827. recommend defining a new function for processing function definitions.
  5828. This code is similar to the case for \code{program} in $R_3$. The
  5829. top-level \code{explicate-control} function that handles the
  5830. \code{program} form of $R_4$ can then apply this new function to all
  5831. the function definitions.
  5832. \begin{figure}[tp]
  5833. \fbox{
  5834. \begin{minipage}{0.96\textwidth}
  5835. \[
  5836. \begin{array}{lcl}
  5837. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5838. \\
  5839. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5840. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5841. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5842. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5843. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5844. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5845. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5846. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5847. \mid (\key{collect} \,\itm{int}) }\\
  5848. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5849. &\mid& \gray{(\key{goto}\,\itm{label})
  5850. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5851. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5852. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5853. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5854. \end{array}
  5855. \]
  5856. \end{minipage}
  5857. }
  5858. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5859. \label{fig:c3-syntax}
  5860. \end{figure}
  5861. \section{Uncover Locals}
  5862. \label{sec:uncover-locals-r4}
  5863. The function for processing $\Tail$ should be updated with a case for
  5864. \code{tailcall}. We also recommend creating a new function for
  5865. processing function definitions. Each function definition in $C_3$ has
  5866. its own set of local variables, so the code for function definitions
  5867. should be similar to the case for the \code{program} form in $C_2$.
  5868. \section{Select Instructions}
  5869. \label{sec:select-r4}
  5870. The output of select instructions is a program in the x86$_3$
  5871. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5872. \begin{figure}[tp]
  5873. \fbox{
  5874. \begin{minipage}{0.96\textwidth}
  5875. \[
  5876. \begin{array}{lcl}
  5877. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5878. \mid (\key{deref}\,\Reg\,\Int) } \\
  5879. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  5880. \mid (\key{global-value}\; \itm{name}) } \\
  5881. &\mid& (\key{fun-ref}\; \itm{label})\\
  5882. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5883. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5884. (\key{subq} \; \Arg\; \Arg) \mid
  5885. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5886. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5887. (\key{pushq}\;\Arg) \mid
  5888. (\key{popq}\;\Arg) \mid
  5889. (\key{retq}) } \\
  5890. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5891. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5892. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5893. \mid (\key{jmp} \; \itm{label})
  5894. \mid (\key{j}\itm{cc} \; \itm{label})
  5895. \mid (\key{label} \; \itm{label}) } \\
  5896. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5897. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5898. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5899. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5900. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5901. \end{array}
  5902. \]
  5903. \end{minipage}
  5904. }
  5905. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5906. \label{fig:x86-3}
  5907. \end{figure}
  5908. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5909. as follows: \\
  5910. \begin{tabular}{lll}
  5911. \begin{minipage}{0.45\textwidth}
  5912. \begin{lstlisting}
  5913. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5914. \end{lstlisting}
  5915. \end{minipage}
  5916. &
  5917. $\Rightarrow$
  5918. &
  5919. \begin{minipage}{0.4\textwidth}
  5920. \begin{lstlisting}
  5921. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5922. \end{lstlisting}
  5923. \end{minipage}
  5924. \end{tabular} \\
  5925. Regarding function definitions, we need to remove their parameters and
  5926. instead perform parameter passing in terms of the conventions
  5927. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5928. in the argument passing registers, and inside the function we should
  5929. generate a \code{movq} instruction for each parameter, to move the
  5930. argument value from the appropriate register to a new local variable
  5931. with the same name as the old parameter.
  5932. Next, consider the compilation of function calls, which have the
  5933. following form upon input to \code{select-instructions}.
  5934. \begin{lstlisting}
  5935. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5936. \end{lstlisting}
  5937. In the mirror image of handling the parameters of function
  5938. definitions, the arguments \itm{args} need to be moved to the argument
  5939. passing registers.
  5940. %
  5941. Once the instructions for parameter passing have been generated, the
  5942. function call itself can be performed with an indirect function call,
  5943. for which I recommend creating the new instruction
  5944. \code{indirect-callq}. Of course, the return value from the function
  5945. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5946. \begin{lstlisting}
  5947. (indirect-callq |\itm{fun}|)
  5948. (movq (reg rax) |\itm{lhs}|)
  5949. \end{lstlisting}
  5950. Regarding tail calls, the parameter passing is the same as non-tail
  5951. calls: generate instructions to move the arguments into to the
  5952. argument passing registers. After that we need to pop the frame from
  5953. the procedure call stack. However, we do not yet know how big the
  5954. frame is; that gets determined during register allocation. So instead
  5955. of generating those instructions here, we invent a new instruction
  5956. that means ``pop the frame and then do an indirect jump'', which we
  5957. name \code{tail-jmp}.
  5958. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5959. using the label \code{start} for the initial block of a program, and
  5960. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5961. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5962. can be compiled to an assignment to \code{rax} followed by a jump to
  5963. \code{conclusion}. With the addition of function definitions, we will
  5964. have a starting block and conclusion for each function, but their
  5965. labels need to be unique. We recommend prepending the function's name
  5966. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5967. labels. (Alternatively, one could \code{gensym} labels for the start
  5968. and conclusion and store them in the $\itm{info}$ field of the
  5969. function definition.)
  5970. \section{Uncover Live}
  5971. %% The rest of the passes need only minor modifications to handle the new
  5972. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5973. %% \code{leaq}.
  5974. Inside \code{uncover-live}, when computing the $W$ set (written
  5975. variables) for an \code{indirect-callq} instruction, we recommend
  5976. including all the caller-saved registers, which will have the affect
  5977. of making sure that no caller-saved register actually needs to be
  5978. saved.
  5979. \section{Build Interference Graph}
  5980. With the addition of function definitions, we compute an interference
  5981. graph for each function (not just one for the whole program).
  5982. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5983. spill vector-typed variables that are live during a call to the
  5984. \code{collect}. With the addition of functions to our language, we
  5985. need to revisit this issue. Many functions will perform allocation and
  5986. therefore have calls to the collector inside of them. Thus, we should
  5987. not only spill a vector-typed variable when it is live during a call
  5988. to \code{collect}, but we should spill the variable if it is live
  5989. during any function call. Thus, in the \code{build-interference} pass,
  5990. we recommend adding interference edges between call-live vector-typed
  5991. variables and the callee-saved registers (in addition to the usual
  5992. addition of edges between call-live variables and the caller-saved
  5993. registers).
  5994. \section{Patch Instructions}
  5995. In \code{patch-instructions}, you should deal with the x86
  5996. idiosyncrasy that the destination argument of \code{leaq} must be a
  5997. register. Additionally, you should ensure that the argument of
  5998. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5999. code generation more convenient, because we will be trampling many
  6000. registers before the tail call (as explained below).
  6001. \section{Print x86}
  6002. For the \code{print-x86} pass, we recommend the following translations:
  6003. \begin{lstlisting}
  6004. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6005. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6006. \end{lstlisting}
  6007. Handling \code{tail-jmp} requires a bit more care. A straightforward
  6008. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  6009. is what we will want to do, but before the jump we need to pop the
  6010. current frame. So we need to restore the state of the registers to the
  6011. point they were at when the current function was called. This
  6012. sequence of instructions is the same as the code for the conclusion of
  6013. a function.
  6014. Note that your \code{print-x86} pass needs to add the code for saving
  6015. and restoring callee-saved registers, if you have not already
  6016. implemented that. This is necessary when generating code for function
  6017. definitions.
  6018. \section{An Example Translation}
  6019. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6020. function in $R_4$ to x86. The figure also includes the results of the
  6021. \code{explicate-control} and \code{select-instructions} passes. We
  6022. have omitted the \code{has-type} AST nodes for readability. Can you
  6023. see any ways to improve the translation?
  6024. \begin{figure}[tbp]
  6025. \begin{tabular}{ll}
  6026. \begin{minipage}{0.45\textwidth}
  6027. % s3_2.rkt
  6028. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6029. (program
  6030. (define (add [x : Integer]
  6031. [y : Integer])
  6032. : Integer (+ x y))
  6033. (add 40 2))
  6034. \end{lstlisting}
  6035. $\Downarrow$
  6036. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6037. (program ()
  6038. (define (add86 [x87 : Integer]
  6039. [y88 : Integer]) : Integer ()
  6040. ((add86start . (return (+ x87 y88)))))
  6041. (define (main) : Integer ()
  6042. ((mainstart .
  6043. (seq (assign tmp89 (fun-ref add86))
  6044. (tailcall tmp89 40 2))))))
  6045. \end{lstlisting}
  6046. \end{minipage}
  6047. &
  6048. $\Rightarrow$
  6049. \begin{minipage}{0.5\textwidth}
  6050. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6051. (program ()
  6052. (define (add86)
  6053. ((locals (x87 . Integer) (y88 . Integer))
  6054. (num-params . 2))
  6055. ((add86start .
  6056. (block ()
  6057. (movq (reg rcx) (var x87))
  6058. (movq (reg rdx) (var y88))
  6059. (movq (var x87) (reg rax))
  6060. (addq (var y88) (reg rax))
  6061. (jmp add86conclusion)))))
  6062. (define (main)
  6063. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6064. (num-params . 0))
  6065. ((mainstart .
  6066. (block ()
  6067. (leaq (fun-ref add86) (var tmp89))
  6068. (movq (int 40) (reg rcx))
  6069. (movq (int 2) (reg rdx))
  6070. (tail-jmp (var tmp89))))))
  6071. \end{lstlisting}
  6072. $\Downarrow$
  6073. \end{minipage}
  6074. \end{tabular}
  6075. \begin{tabular}{lll}
  6076. \begin{minipage}{0.3\textwidth}
  6077. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6078. _add90start:
  6079. movq %rcx, %rsi
  6080. movq %rdx, %rcx
  6081. movq %rsi, %rax
  6082. addq %rcx, %rax
  6083. jmp _add90conclusion
  6084. .globl _add90
  6085. .align 16
  6086. _add90:
  6087. pushq %rbp
  6088. movq %rsp, %rbp
  6089. pushq %r12
  6090. pushq %rbx
  6091. pushq %r13
  6092. pushq %r14
  6093. subq $0, %rsp
  6094. jmp _add90start
  6095. _add90conclusion:
  6096. addq $0, %rsp
  6097. popq %r14
  6098. popq %r13
  6099. popq %rbx
  6100. popq %r12
  6101. subq $0, %r15
  6102. popq %rbp
  6103. retq
  6104. \end{lstlisting}
  6105. \end{minipage}
  6106. &
  6107. \begin{minipage}{0.3\textwidth}
  6108. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6109. _mainstart:
  6110. leaq _add90(%rip), %rsi
  6111. movq $40, %rcx
  6112. movq $2, %rdx
  6113. movq %rsi, %rax
  6114. addq $0, %rsp
  6115. popq %r14
  6116. popq %r13
  6117. popq %rbx
  6118. popq %r12
  6119. subq $0, %r15
  6120. popq %rbp
  6121. jmp *%rax
  6122. .globl _main
  6123. .align 16
  6124. _main:
  6125. pushq %rbp
  6126. movq %rsp, %rbp
  6127. pushq %r12
  6128. pushq %rbx
  6129. pushq %r13
  6130. pushq %r14
  6131. subq $0, %rsp
  6132. movq $16384, %rdi
  6133. movq $16, %rsi
  6134. callq _initialize
  6135. movq _rootstack_begin(%rip), %r15
  6136. jmp _mainstart
  6137. \end{lstlisting}
  6138. \end{minipage}
  6139. &
  6140. \begin{minipage}{0.3\textwidth}
  6141. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6142. _mainconclusion:
  6143. addq $0, %rsp
  6144. popq %r14
  6145. popq %r13
  6146. popq %rbx
  6147. popq %r12
  6148. subq $0, %r15
  6149. popq %rbp
  6150. retq
  6151. \end{lstlisting}
  6152. \end{minipage}
  6153. \end{tabular}
  6154. \caption{Example compilation of a simple function to x86.}
  6155. \label{fig:add-fun}
  6156. \end{figure}
  6157. \begin{exercise}\normalfont
  6158. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6159. Create 5 new programs that use functions, including examples that pass
  6160. functions and return functions from other functions and including
  6161. recursive functions. Test your compiler on these new programs and all
  6162. of your previously created test programs.
  6163. \end{exercise}
  6164. \begin{figure}[p]
  6165. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6166. \node (R4) at (0,2) {\large $R_4$};
  6167. \node (R4-2) at (3,2) {\large $R_4$};
  6168. \node (R4-3) at (6,2) {\large $R_4$};
  6169. \node (F1-1) at (12,0) {\large $F_1$};
  6170. \node (F1-2) at (9,0) {\large $F_1$};
  6171. \node (F1-3) at (6,0) {\large $F_1$};
  6172. \node (F1-4) at (3,0) {\large $F_1$};
  6173. \node (C3-1) at (6,-2) {\large $C_3$};
  6174. \node (C3-2) at (3,-2) {\large $C_3$};
  6175. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6176. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6177. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6178. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6179. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6180. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6181. \path[->,bend left=15] (R4) edge [above] node
  6182. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6183. \path[->,bend left=15] (R4-2) edge [above] node
  6184. {\ttfamily\footnotesize uniquify} (R4-3);
  6185. \path[->,bend left=15] (R4-3) edge [right] node
  6186. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6187. \path[->,bend left=15] (F1-1) edge [below] node
  6188. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6189. \path[->,bend right=15] (F1-2) edge [above] node
  6190. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6191. \path[->,bend right=15] (F1-3) edge [above] node
  6192. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6193. \path[->,bend left=15] (F1-4) edge [right] node
  6194. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6195. \path[->,bend left=15] (C3-1) edge [below] node
  6196. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6197. \path[->,bend right=15] (C3-2) edge [left] node
  6198. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6199. \path[->,bend left=15] (x86-2) edge [left] node
  6200. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6201. \path[->,bend right=15] (x86-2-1) edge [below] node
  6202. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6203. \path[->,bend right=15] (x86-2-2) edge [left] node
  6204. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6205. \path[->,bend left=15] (x86-3) edge [above] node
  6206. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6207. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6208. \end{tikzpicture}
  6209. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6210. \label{fig:R4-passes}
  6211. \end{figure}
  6212. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6213. the compilation of $R_4$.
  6214. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6215. \chapter{Lexically Scoped Functions}
  6216. \label{ch:lambdas}
  6217. This chapter studies lexically scoped functions as they appear in
  6218. functional languages such as Racket. By lexical scoping we mean that a
  6219. function's body may refer to variables whose binding site is outside
  6220. of the function, in an enclosing scope.
  6221. %
  6222. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6223. anonymous function defined using the \key{lambda} form. The body of
  6224. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6225. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6226. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6227. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6228. returned from the function \code{f}. Below the definition of \code{f},
  6229. we have two calls to \code{f} with different arguments for \code{x},
  6230. first \code{5} then \code{3}. The functions returned from \code{f} are
  6231. bound to variables \code{g} and \code{h}. Even though these two
  6232. functions were created by the same \code{lambda}, they are really
  6233. different functions because they use different values for
  6234. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6235. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6236. the result of this program is \code{42}.
  6237. \begin{figure}[btp]
  6238. % s4_6.rkt
  6239. \begin{lstlisting}
  6240. (define (f [x : Integer]) : (Integer -> Integer)
  6241. (let ([y 4])
  6242. (lambda: ([z : Integer]) : Integer
  6243. (+ x (+ y z)))))
  6244. (let ([g (f 5)])
  6245. (let ([h (f 3)])
  6246. (+ (g 11) (h 15))))
  6247. \end{lstlisting}
  6248. \caption{Example of a lexically scoped function.}
  6249. \label{fig:lexical-scoping}
  6250. \end{figure}
  6251. \section{The $R_5$ Language}
  6252. The syntax for this language with anonymous functions and lexical
  6253. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6254. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6255. for function application. In this chapter we shall describe how to
  6256. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6257. into a combination of functions (as in $R_4$) and tuples (as in
  6258. $R_3$).
  6259. \begin{figure}[tp]
  6260. \centering
  6261. \fbox{
  6262. \begin{minipage}{0.96\textwidth}
  6263. \[
  6264. \begin{array}{lcl}
  6265. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6266. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6267. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6268. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6269. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6270. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6271. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6272. \mid (\key{and}\;\Exp\;\Exp)
  6273. \mid (\key{or}\;\Exp\;\Exp)
  6274. \mid (\key{not}\;\Exp) } \\
  6275. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6276. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6277. (\key{vector-ref}\;\Exp\;\Int)} \\
  6278. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6279. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6280. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6281. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6282. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6283. \end{array}
  6284. \]
  6285. \end{minipage}
  6286. }
  6287. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6288. with \key{lambda}.}
  6289. \label{fig:r5-syntax}
  6290. \end{figure}
  6291. To compile lexically-scoped functions to top-level function
  6292. definitions, the compiler will need to provide special treatment to
  6293. variable occurrences such as \code{x} and \code{y} in the body of the
  6294. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6295. of $R_4$ may not refer to variables defined outside the function. To
  6296. identify such variable occurrences, we review the standard notion of
  6297. free variable.
  6298. \begin{definition}
  6299. A variable is \emph{free with respect to an expression} $e$ if the
  6300. variable occurs inside $e$ but does not have an enclosing binding in
  6301. $e$.
  6302. \end{definition}
  6303. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6304. free with respect to the expression \code{(+ x (+ y z))}. On the
  6305. other hand, only \code{x} and \code{y} are free with respect to the
  6306. following expression because \code{z} is bound by the \code{lambda}.
  6307. \begin{lstlisting}
  6308. (lambda: ([z : Integer]) : Integer
  6309. (+ x (+ y z)))
  6310. \end{lstlisting}
  6311. Once we have identified the free variables of a \code{lambda}, we need
  6312. to arrange for some way to transport, at runtime, the values of those
  6313. variables from the point where the \code{lambda} was created to the
  6314. point where the \code{lambda} is applied. Referring again to
  6315. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6316. needs to be used in the application of \code{g} to \code{11}, but the
  6317. binding of \code{x} to \code{3} needs to be used in the application of
  6318. \code{h} to \code{15}. An efficient solution to the problem, due to
  6319. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6320. free variables together with the function pointer for the lambda's
  6321. code, an arrangement called a \emph{flat closure} (which we shorten to
  6322. just ``closure'') . Fortunately, we have all the ingredients to make
  6323. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6324. Chapter~\ref{ch:functions} gave us function pointers. The function
  6325. pointer shall reside at index $0$ and the values for free variables
  6326. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6327. the two closures created by the two calls to \code{f} in
  6328. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6329. the same \key{lambda}, they share the same function pointer but differ
  6330. in the values for the free variable \code{x}.
  6331. \begin{figure}[tbp]
  6332. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6333. \caption{Example closure representation for the \key{lambda}'s
  6334. in Figure~\ref{fig:lexical-scoping}.}
  6335. \label{fig:closures}
  6336. \end{figure}
  6337. \section{Interpreting $R_5$}
  6338. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6339. $R_5$. The clause for \key{lambda} saves the current environment
  6340. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6341. the environment from the \key{lambda}, the \code{lam-env}, when
  6342. interpreting the body of the \key{lambda}. The \code{lam-env}
  6343. environment is extended with the mapping of parameters to argument
  6344. values.
  6345. \begin{figure}[tbp]
  6346. \begin{lstlisting}
  6347. (define (interp-exp env)
  6348. (lambda (e)
  6349. (define recur (interp-exp env))
  6350. (match e
  6351. ...
  6352. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6353. `(lambda ,xs ,body ,env)]
  6354. [`(app ,fun ,args ...)
  6355. (define fun-val ((interp-exp env) fun))
  6356. (define arg-vals (map (interp-exp env) args))
  6357. (match fun-val
  6358. [`(lambda (,xs ...) ,body ,lam-env)
  6359. (define new-env (append (map cons xs arg-vals) lam-env))
  6360. ((interp-exp new-env) body)]
  6361. [else (error "interp-exp, expected function, not" fun-val)])]
  6362. [else (error 'interp-exp "unrecognized expression")]
  6363. )))
  6364. \end{lstlisting}
  6365. \caption{Interpreter for $R_5$.}
  6366. \label{fig:interp-R5}
  6367. \end{figure}
  6368. \section{Type Checking $R_5$}
  6369. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6370. \key{lambda} form. The body of the \key{lambda} is checked in an
  6371. environment that includes the current environment (because it is
  6372. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6373. require the body's type to match the declared return type.
  6374. \begin{figure}[tbp]
  6375. \begin{lstlisting}
  6376. (define (typecheck-R5 env)
  6377. (lambda (e)
  6378. (match e
  6379. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6380. (define new-env (append (map cons xs Ts) env))
  6381. (define bodyT ((typecheck-R5 new-env) body))
  6382. (cond [(equal? rT bodyT)
  6383. `(,@Ts -> ,rT)]
  6384. [else
  6385. (error "mismatch in return type" bodyT rT)])]
  6386. ...
  6387. )))
  6388. \end{lstlisting}
  6389. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6390. \label{fig:typecheck-R5}
  6391. \end{figure}
  6392. \section{Closure Conversion}
  6393. The compiling of lexically-scoped functions into top-level function
  6394. definitions is accomplished in the pass \code{convert-to-closures}
  6395. that comes after \code{reveal-functions} and before
  6396. \code{limit-functions}.
  6397. As usual, we shall implement the pass as a recursive function over the
  6398. AST. All of the action is in the clauses for \key{lambda} and
  6399. \key{app}. We transform a \key{lambda} expression into an expression
  6400. that creates a closure, that is, creates a vector whose first element
  6401. is a function pointer and the rest of the elements are the free
  6402. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6403. generated to identify the function.
  6404. \begin{tabular}{lll}
  6405. \begin{minipage}{0.4\textwidth}
  6406. \begin{lstlisting}
  6407. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6408. \end{lstlisting}
  6409. \end{minipage}
  6410. &
  6411. $\Rightarrow$
  6412. &
  6413. \begin{minipage}{0.4\textwidth}
  6414. \begin{lstlisting}
  6415. (vector |\itm{name}| |\itm{fvs}| ...)
  6416. \end{lstlisting}
  6417. \end{minipage}
  6418. \end{tabular} \\
  6419. %
  6420. In addition to transforming each \key{lambda} into a \key{vector}, we
  6421. must create a top-level function definition for each \key{lambda}, as
  6422. shown below.\\
  6423. \begin{minipage}{0.8\textwidth}
  6424. \begin{lstlisting}
  6425. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6426. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6427. ...
  6428. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6429. |\itm{body'}|)...))
  6430. \end{lstlisting}
  6431. \end{minipage}\\
  6432. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6433. parameters are the normal parameters of the \key{lambda}. The types
  6434. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6435. underscore is a dummy type because it is rather difficult to give a
  6436. type to the function in the closure's type, and it does not matter.
  6437. The sequence of \key{let} forms bind the free variables to their
  6438. values obtained from the closure.
  6439. We transform function application into code that retrieves the
  6440. function pointer from the closure and then calls the function, passing
  6441. in the closure as the first argument. We bind $e'$ to a temporary
  6442. variable to avoid code duplication.
  6443. \begin{tabular}{lll}
  6444. \begin{minipage}{0.3\textwidth}
  6445. \begin{lstlisting}
  6446. (app |$e$| |\itm{es}| ...)
  6447. \end{lstlisting}
  6448. \end{minipage}
  6449. &
  6450. $\Rightarrow$
  6451. &
  6452. \begin{minipage}{0.5\textwidth}
  6453. \begin{lstlisting}
  6454. (let ([|\itm{tmp}| |$e'$|])
  6455. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6456. \end{lstlisting}
  6457. \end{minipage}
  6458. \end{tabular} \\
  6459. There is also the question of what to do with top-level function
  6460. definitions. To maintain a uniform translation of function
  6461. application, we turn function references into closures.
  6462. \begin{tabular}{lll}
  6463. \begin{minipage}{0.3\textwidth}
  6464. \begin{lstlisting}
  6465. (fun-ref |$f$|)
  6466. \end{lstlisting}
  6467. \end{minipage}
  6468. &
  6469. $\Rightarrow$
  6470. &
  6471. \begin{minipage}{0.5\textwidth}
  6472. \begin{lstlisting}
  6473. (vector (fun-ref |$f$|))
  6474. \end{lstlisting}
  6475. \end{minipage}
  6476. \end{tabular} \\
  6477. %
  6478. The top-level function definitions need to be updated as well to take
  6479. an extra closure parameter.
  6480. \section{An Example Translation}
  6481. \label{sec:example-lambda}
  6482. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6483. conversion for the example program demonstrating lexical scoping that
  6484. we discussed at the beginning of this chapter.
  6485. \begin{figure}[h]
  6486. \begin{minipage}{0.8\textwidth}
  6487. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6488. (program
  6489. (define (f [x : Integer]) : (Integer -> Integer)
  6490. (let ([y 4])
  6491. (lambda: ([z : Integer]) : Integer
  6492. (+ x (+ y z)))))
  6493. (let ([g (f 5)])
  6494. (let ([h (f 3)])
  6495. (+ (g 11) (h 15)))))
  6496. \end{lstlisting}
  6497. $\Downarrow$
  6498. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6499. (program (type Integer)
  6500. (define (f (x : Integer)) : (Integer -> Integer)
  6501. (let ((y 4))
  6502. (lambda: ((z : Integer)) : Integer
  6503. (+ x (+ y z)))))
  6504. (let ((g (app (fun-ref f) 5)))
  6505. (let ((h (app (fun-ref f) 3)))
  6506. (+ (app g 11) (app h 15)))))
  6507. \end{lstlisting}
  6508. $\Downarrow$
  6509. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6510. (program (type Integer)
  6511. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6512. (let ((y 4))
  6513. (vector (fun-ref lam.1) x y)))
  6514. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6515. (let ((x (vector-ref clos.2 1)))
  6516. (let ((y (vector-ref clos.2 2)))
  6517. (+ x (+ y z)))))
  6518. (let ((g (let ((t.1 (vector (fun-ref f))))
  6519. (app (vector-ref t.1 0) t.1 5))))
  6520. (let ((h (let ((t.2 (vector (fun-ref f))))
  6521. (app (vector-ref t.2 0) t.2 3))))
  6522. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6523. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6524. \end{lstlisting}
  6525. \end{minipage}
  6526. \caption{Example of closure conversion.}
  6527. \label{fig:lexical-functions-example}
  6528. \end{figure}
  6529. \begin{figure}[p]
  6530. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6531. \node (R4) at (0,2) {\large $R_4$};
  6532. \node (R4-2) at (3,2) {\large $R_4$};
  6533. \node (R4-3) at (6,2) {\large $R_4$};
  6534. \node (F1-1) at (12,0) {\large $F_1$};
  6535. \node (F1-2) at (9,0) {\large $F_1$};
  6536. \node (F1-3) at (6,0) {\large $F_1$};
  6537. \node (F1-4) at (3,0) {\large $F_1$};
  6538. \node (F1-5) at (0,0) {\large $F_1$};
  6539. \node (C3-1) at (6,-2) {\large $C_3$};
  6540. \node (C3-2) at (3,-2) {\large $C_3$};
  6541. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6542. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6543. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6544. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6545. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6546. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6547. \path[->,bend left=15] (R4) edge [above] node
  6548. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6549. \path[->,bend left=15] (R4-2) edge [above] node
  6550. {\ttfamily\footnotesize uniquify} (R4-3);
  6551. \path[->] (R4-3) edge [right] node
  6552. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6553. \path[->,bend left=15] (F1-1) edge [below] node
  6554. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6555. \path[->,bend right=15] (F1-2) edge [above] node
  6556. {\ttfamily\footnotesize limit-functions} (F1-3);
  6557. \path[->,bend right=15] (F1-3) edge [above] node
  6558. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6559. \path[->,bend right=15] (F1-4) edge [above] node
  6560. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6561. \path[->] (F1-5) edge [left] node
  6562. {\ttfamily\footnotesize explicate-control} (C3-1);
  6563. \path[->,bend left=15] (C3-1) edge [below] node
  6564. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6565. \path[->,bend right=15] (C3-2) edge [left] node
  6566. {\ttfamily\footnotesize select-instr.} (x86-2);
  6567. \path[->,bend left=15] (x86-2) edge [left] node
  6568. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6569. \path[->,bend right=15] (x86-2-1) edge [below] node
  6570. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6571. \path[->,bend right=15] (x86-2-2) edge [left] node
  6572. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6573. \path[->,bend left=15] (x86-3) edge [above] node
  6574. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6575. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6576. \end{tikzpicture}
  6577. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6578. functions.}
  6579. \label{fig:R5-passes}
  6580. \end{figure}
  6581. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6582. for the compilation of $R_5$.
  6583. \begin{exercise}\normalfont
  6584. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6585. Create 5 new programs that use \key{lambda} functions and make use of
  6586. lexical scoping. Test your compiler on these new programs and all of
  6587. your previously created test programs.
  6588. \end{exercise}
  6589. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6590. \chapter{Dynamic Typing}
  6591. \label{ch:type-dynamic}
  6592. In this chapter we discuss the compilation of a dynamically typed
  6593. language, named $R_7$, that is a subset of the Racket
  6594. language. (Recall that in the previous chapters we have studied
  6595. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6596. languages, an expression may produce values of differing
  6597. type. Consider the following example with a conditional expression
  6598. that may return a Boolean or an integer depending on the input to the
  6599. program.
  6600. \begin{lstlisting}
  6601. (not (if (eq? (read) 1) #f 0))
  6602. \end{lstlisting}
  6603. Languages that allow expressions to produce different kinds of values
  6604. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6605. such as subtype polymorphism and parametric
  6606. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6607. talking about here does not have a special name, but it is the usual
  6608. kind that arises in dynamically typed languages.
  6609. Another characteristic of dynamically typed languages is that
  6610. primitive operations, such as \code{not}, are often defined to operate
  6611. on many different types of values. In fact, in Racket, the \code{not}
  6612. operator produces a result for any kind of value: given \code{\#f} it
  6613. returns \code{\#t} and given anything else it returns \code{\#f}.
  6614. Furthermore, even when primitive operations restrict their inputs to
  6615. values of a certain type, this restriction is enforced at runtime
  6616. instead of during compilation. For example, the following vector
  6617. reference results in a run-time contract violation.
  6618. \begin{lstlisting}
  6619. (vector-ref (vector 42) #t)
  6620. \end{lstlisting}
  6621. \begin{figure}[tp]
  6622. \centering
  6623. \fbox{
  6624. \begin{minipage}{0.97\textwidth}
  6625. \[
  6626. \begin{array}{rcl}
  6627. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6628. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6629. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6630. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6631. &\mid& \key{\#t} \mid \key{\#f}
  6632. \mid (\key{and}\;\Exp\;\Exp)
  6633. \mid (\key{or}\;\Exp\;\Exp)
  6634. \mid (\key{not}\;\Exp) \\
  6635. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6636. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6637. (\key{vector-ref}\;\Exp\;\Exp) \\
  6638. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6639. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6640. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6641. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6642. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6643. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6644. \end{array}
  6645. \]
  6646. \end{minipage}
  6647. }
  6648. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6649. \label{fig:r7-syntax}
  6650. \end{figure}
  6651. The syntax of $R_7$, our subset of Racket, is defined in
  6652. Figure~\ref{fig:r7-syntax}.
  6653. %
  6654. The definitional interpreter for $R_7$ is given in
  6655. Figure~\ref{fig:interp-R7}.
  6656. \begin{figure}[tbp]
  6657. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6658. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6659. (define (valid-op? op) (member op '(+ - and or not)))
  6660. (define (interp-r7 env)
  6661. (lambda (ast)
  6662. (define recur (interp-r7 env))
  6663. (match ast
  6664. [(? symbol?) (lookup ast env)]
  6665. [(? integer?) `(inject ,ast Integer)]
  6666. [#t `(inject #t Boolean)]
  6667. [#f `(inject #f Boolean)]
  6668. [`(read) `(inject ,(read-fixnum) Integer)]
  6669. [`(lambda (,xs ...) ,body)
  6670. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6671. [`(define (,f ,xs ...) ,body)
  6672. (mcons f `(lambda ,xs ,body))]
  6673. [`(program ,ds ... ,body)
  6674. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6675. (for/list ([b top-level])
  6676. (set-mcdr! b (match (mcdr b)
  6677. [`(lambda ,xs ,body)
  6678. `(inject (lambda ,xs ,body ,top-level)
  6679. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6680. ((interp-r7 top-level) body))]
  6681. [`(vector ,(app recur elts) ...)
  6682. (define tys (map get-tagged-type elts))
  6683. `(inject ,(apply vector elts) (Vector ,@tys))]
  6684. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6685. (match v1
  6686. [`(inject ,vec ,ty)
  6687. (vector-set! vec n v2)
  6688. `(inject (void) Void)])]
  6689. [`(vector-ref ,(app recur v) ,n)
  6690. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6691. [`(let ([,x ,(app recur v)]) ,body)
  6692. ((interp-r7 (cons (cons x v) env)) body)]
  6693. [`(,op ,es ...) #:when (valid-op? op)
  6694. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6695. [`(eq? ,(app recur l) ,(app recur r))
  6696. `(inject ,(equal? l r) Boolean)]
  6697. [`(if ,(app recur q) ,t ,f)
  6698. (match q
  6699. [`(inject #f Boolean) (recur f)]
  6700. [else (recur t)])]
  6701. [`(,(app recur f-val) ,(app recur vs) ...)
  6702. (match f-val
  6703. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6704. (define new-env (append (map cons xs vs) lam-env))
  6705. ((interp-r7 new-env) body)]
  6706. [else (error "interp-r7, expected function, not" f-val)])])))
  6707. \end{lstlisting}
  6708. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6709. \label{fig:interp-R7}
  6710. \end{figure}
  6711. Let us consider how we might compile $R_7$ to x86, thinking about the
  6712. first example above. Our bit-level representation of the Boolean
  6713. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6714. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6715. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6716. general, cannot be determined at compile time, but depends on the
  6717. runtime type of its input, as in the example above that depends on the
  6718. result of \code{(read)}.
  6719. The way around this problem is to include information about a value's
  6720. runtime type in the value itself, so that this information can be
  6721. inspected by operators such as \code{not}. In particular, we shall
  6722. steal the 3 right-most bits from our 64-bit values to encode the
  6723. runtime type. We shall use $001$ to identify integers, $100$ for
  6724. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6725. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6726. define the following auxiliary function.
  6727. \begin{align*}
  6728. \itm{tagof}(\key{Integer}) &= 001 \\
  6729. \itm{tagof}(\key{Boolean}) &= 100 \\
  6730. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6731. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6732. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6733. \itm{tagof}(\key{Void}) &= 101
  6734. \end{align*}
  6735. (We shall say more about the new \key{Vectorof} type shortly.)
  6736. This stealing of 3 bits comes at some
  6737. price: our integers are reduced to ranging from $-2^{60}$ to
  6738. $2^{60}$. The stealing does not adversely affect vectors and
  6739. procedures because those values are addresses, and our addresses are
  6740. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6741. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6742. bits with the tag and we can simply zero-out the tag to recover the
  6743. original address.
  6744. In some sense, these tagged values are a new kind of value. Indeed,
  6745. we can extend our \emph{typed} language with tagged values by adding a
  6746. new type to classify them, called \key{Any}, and with operations for
  6747. creating and using tagged values, yielding the $R_6$ language that we
  6748. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6749. fundamental support for polymorphism and runtime types that we need to
  6750. support dynamic typing.
  6751. There is an interesting interaction between tagged values and garbage
  6752. collection. A variable of type \code{Any} might refer to a vector and
  6753. therefore it might be a root that needs to be inspected and copied
  6754. during garbage collection. Thus, we need to treat variables of type
  6755. \code{Any} in a similar way to variables of type \code{Vector} for
  6756. purposes of register allocation, which we discuss in
  6757. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6758. variable of type \code{Any} is spilled, it must be spilled to the root
  6759. stack. But this means that the garbage collector needs to be able to
  6760. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6761. value that points to a tuple, and (3) a tagged value that is not a
  6762. tuple. We enable this differentiation by choosing not to use the tag
  6763. $000$. Instead, that bit pattern is reserved for identifying plain old
  6764. pointers to tuples. On the other hand, if one of the first three bits
  6765. is set, then we have a tagged value, and inspecting the tag can
  6766. differentiation between vectors ($010$) and the other kinds of values.
  6767. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6768. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6769. extend our compiler to handle the new features of $R_6$
  6770. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6771. \ref{sec:register-allocation-r6}).
  6772. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6773. \label{sec:r6-lang}
  6774. \begin{figure}[tp]
  6775. \centering
  6776. \fbox{
  6777. \begin{minipage}{0.97\textwidth}
  6778. \[
  6779. \begin{array}{lcl}
  6780. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6781. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6782. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6783. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6784. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6785. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6786. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6787. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6788. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6789. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6790. \mid (\key{and}\;\Exp\;\Exp)
  6791. \mid (\key{or}\;\Exp\;\Exp)
  6792. \mid (\key{not}\;\Exp)} \\
  6793. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6794. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6795. (\key{vector-ref}\;\Exp\;\Int)} \\
  6796. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6797. &\mid& \gray{(\Exp \; \Exp^{*})
  6798. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6799. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6800. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6801. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6802. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6803. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6804. \end{array}
  6805. \]
  6806. \end{minipage}
  6807. }
  6808. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6809. with \key{Any}.}
  6810. \label{fig:r6-syntax}
  6811. \end{figure}
  6812. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6813. $(\key{inject}\; e\; T)$ form converts the value produced by
  6814. expression $e$ of type $T$ into a tagged value. The
  6815. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6816. expression $e$ into a value of type $T$ or else halts the program if
  6817. the type tag is equivalent to $T$. We treat
  6818. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6819. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6820. Note that in both \key{inject} and
  6821. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6822. which simplifies the implementation and corresponds with what is
  6823. needed for compiling untyped Racket. The type predicates,
  6824. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6825. if the tag corresponds to the predicate, and return \key{\#t}
  6826. otherwise.
  6827. %
  6828. Selections from the type checker for $R_6$ are shown in
  6829. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6830. Figure~\ref{fig:interp-R6}.
  6831. \begin{figure}[btp]
  6832. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6833. (define (flat-ty? ty) ...)
  6834. (define (typecheck-R6 env)
  6835. (lambda (e)
  6836. (define recur (typecheck-R6 env))
  6837. (match e
  6838. [`(inject ,e ,ty)
  6839. (unless (flat-ty? ty)
  6840. (error "may only inject a value of flat type, not ~a" ty))
  6841. (define-values (new-e e-ty) (recur e))
  6842. (cond
  6843. [(equal? e-ty ty)
  6844. (values `(inject ,new-e ,ty) 'Any)]
  6845. [else
  6846. (error "inject expected ~a to have type ~a" e ty)])]
  6847. [`(project ,e ,ty)
  6848. (unless (flat-ty? ty)
  6849. (error "may only project to a flat type, not ~a" ty))
  6850. (define-values (new-e e-ty) (recur e))
  6851. (cond
  6852. [(equal? e-ty 'Any)
  6853. (values `(project ,new-e ,ty) ty)]
  6854. [else
  6855. (error "project expected ~a to have type Any" e)])]
  6856. [`(vector-ref ,e ,i)
  6857. (define-values (new-e e-ty) (recur e))
  6858. (match e-ty
  6859. [`(Vector ,ts ...) ...]
  6860. [`(Vectorof ,ty)
  6861. (unless (exact-nonnegative-integer? i)
  6862. (error 'type-check "invalid index ~a" i))
  6863. (values `(vector-ref ,new-e ,i) ty)]
  6864. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6865. ...
  6866. )))
  6867. \end{lstlisting}
  6868. \caption{Type checker for parts of the $R_6$ language.}
  6869. \label{fig:typecheck-R6}
  6870. \end{figure}
  6871. % to do: add rules for vector-ref, etc. for Vectorof
  6872. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6873. \begin{figure}[btp]
  6874. \begin{lstlisting}
  6875. (define primitives (set 'boolean? ...))
  6876. (define (interp-op op)
  6877. (match op
  6878. ['boolean? (lambda (v)
  6879. (match v
  6880. [`(tagged ,v1 Boolean) #t]
  6881. [else #f]))]
  6882. ...))
  6883. ;; Equivalence of flat types
  6884. (define (tyeq? t1 t2)
  6885. (match `(,t1 ,t2)
  6886. [`((Vectorof Any) (Vector ,t2s ...))
  6887. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6888. [`((Vector ,t1s ...) (Vectorof Any))
  6889. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6890. [else (equal? t1 t2)]))
  6891. (define (interp-R6 env)
  6892. (lambda (ast)
  6893. (match ast
  6894. [`(inject ,e ,t)
  6895. `(tagged ,((interp-R6 env) e) ,t)]
  6896. [`(project ,e ,t2)
  6897. (define v ((interp-R6 env) e))
  6898. (match v
  6899. [`(tagged ,v1 ,t1)
  6900. (cond [(tyeq? t1 t2)
  6901. v1]
  6902. [else
  6903. (error "in project, type mismatch" t1 t2)])]
  6904. [else
  6905. (error "in project, expected tagged value" v)])]
  6906. ...)))
  6907. \end{lstlisting}
  6908. \caption{Interpreter for $R_6$.}
  6909. \label{fig:interp-R6}
  6910. \end{figure}
  6911. %\clearpage
  6912. \section{Shrinking $R_6$}
  6913. \label{sec:shrink-r6}
  6914. In the \code{shrink} pass we recommend compiling \code{project} into
  6915. an explicit \code{if} expression that uses three new operations:
  6916. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6917. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6918. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6919. value from a tagged value. Finally, the \code{exit} operation ends the
  6920. execution of the program by invoking the operating system's
  6921. \code{exit} function. So the translation for \code{project} is as
  6922. follows. (We have omitted the \code{has-type} AST nodes to make this
  6923. output more readable.)
  6924. \begin{tabular}{lll}
  6925. \begin{minipage}{0.3\textwidth}
  6926. \begin{lstlisting}
  6927. (project |$e$| |$\Type$|)
  6928. \end{lstlisting}
  6929. \end{minipage}
  6930. &
  6931. $\Rightarrow$
  6932. &
  6933. \begin{minipage}{0.5\textwidth}
  6934. \begin{lstlisting}
  6935. (let ([|$\itm{tmp}$| |$e'$|])
  6936. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6937. (value-of-any |$\itm{tmp}$|)
  6938. (exit)))
  6939. \end{lstlisting}
  6940. \end{minipage}
  6941. \end{tabular} \\
  6942. Similarly, we recommend translating the type predicates
  6943. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6944. \section{Instruction Selection for $R_6$}
  6945. \label{sec:select-r6}
  6946. \paragraph{Inject}
  6947. We recommend compiling an \key{inject} as follows if the type is
  6948. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6949. destination to the left by the number of bits specified its source
  6950. argument (in this case $3$, the length of the tag) and it preserves
  6951. the sign of the integer. We use the \key{orq} instruction to combine
  6952. the tag and the value to form the tagged value. \\
  6953. \begin{tabular}{lll}
  6954. \begin{minipage}{0.4\textwidth}
  6955. \begin{lstlisting}
  6956. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6957. \end{lstlisting}
  6958. \end{minipage}
  6959. &
  6960. $\Rightarrow$
  6961. &
  6962. \begin{minipage}{0.5\textwidth}
  6963. \begin{lstlisting}
  6964. (movq |$e'$| |\itm{lhs}'|)
  6965. (salq (int 3) |\itm{lhs}'|)
  6966. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6967. \end{lstlisting}
  6968. \end{minipage}
  6969. \end{tabular} \\
  6970. The instruction selection for vectors and procedures is different
  6971. because their is no need to shift them to the left. The rightmost 3
  6972. bits are already zeros as described above. So we just combine the
  6973. value and the tag using \key{orq}. \\
  6974. \begin{tabular}{lll}
  6975. \begin{minipage}{0.4\textwidth}
  6976. \begin{lstlisting}
  6977. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6978. \end{lstlisting}
  6979. \end{minipage}
  6980. &
  6981. $\Rightarrow$
  6982. &
  6983. \begin{minipage}{0.5\textwidth}
  6984. \begin{lstlisting}
  6985. (movq |$e'$| |\itm{lhs}'|)
  6986. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6987. \end{lstlisting}
  6988. \end{minipage}
  6989. \end{tabular}
  6990. \paragraph{Tag of Any}
  6991. Recall that the \code{tag-of-any} operation extracts the type tag from
  6992. a value of type \code{Any}. The type tag is the bottom three bits, so
  6993. we obtain the tag by taking the bitwise-and of the value with $111$
  6994. ($7$ in decimal).
  6995. \begin{tabular}{lll}
  6996. \begin{minipage}{0.4\textwidth}
  6997. \begin{lstlisting}
  6998. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6999. \end{lstlisting}
  7000. \end{minipage}
  7001. &
  7002. $\Rightarrow$
  7003. &
  7004. \begin{minipage}{0.5\textwidth}
  7005. \begin{lstlisting}
  7006. (movq |$e'$| |\itm{lhs}'|)
  7007. (andq (int 7) |\itm{lhs}'|)
  7008. \end{lstlisting}
  7009. \end{minipage}
  7010. \end{tabular}
  7011. \paragraph{Value of Any}
  7012. Like \key{inject}, the instructions for \key{value-of-any} are
  7013. different depending on whether the type $T$ is a pointer (vector or
  7014. procedure) or not (Integer or Boolean). The following shows the
  7015. instruction selection for Integer and Boolean. We produce an untagged
  7016. value by shifting it to the right by 3 bits.
  7017. %
  7018. \\
  7019. \begin{tabular}{lll}
  7020. \begin{minipage}{0.4\textwidth}
  7021. \begin{lstlisting}
  7022. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7023. \end{lstlisting}
  7024. \end{minipage}
  7025. &
  7026. $\Rightarrow$
  7027. &
  7028. \begin{minipage}{0.5\textwidth}
  7029. \begin{lstlisting}
  7030. (movq |$e'$| |\itm{lhs}'|)
  7031. (sarq (int 3) |\itm{lhs}'|)
  7032. \end{lstlisting}
  7033. \end{minipage}
  7034. \end{tabular} \\
  7035. %
  7036. In the case for vectors and procedures, there is no need to
  7037. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7038. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7039. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7040. \code{movq} into the destination $\itm{lhs}$. We then generate
  7041. \code{andq} with the tagged value to get the desired result. \\
  7042. %
  7043. \begin{tabular}{lll}
  7044. \begin{minipage}{0.4\textwidth}
  7045. \begin{lstlisting}
  7046. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7047. \end{lstlisting}
  7048. \end{minipage}
  7049. &
  7050. $\Rightarrow$
  7051. &
  7052. \begin{minipage}{0.5\textwidth}
  7053. \begin{lstlisting}
  7054. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7055. (andq |$e'$| |\itm{lhs}'|)
  7056. \end{lstlisting}
  7057. \end{minipage}
  7058. \end{tabular}
  7059. %% \paragraph{Type Predicates} We leave it to the reader to
  7060. %% devise a sequence of instructions to implement the type predicates
  7061. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7062. \section{Register Allocation for $R_6$}
  7063. \label{sec:register-allocation-r6}
  7064. As mentioned above, a variable of type \code{Any} might refer to a
  7065. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7066. of type \code{Any} in the same way that it treats variables of type
  7067. \code{Vector} for purposes of garbage collection. In particular,
  7068. \begin{itemize}
  7069. \item If a variable of type \code{Any} is live during a function call,
  7070. then it must be spilled. One way to accomplish this is to augment
  7071. the pass \code{build-interference} to mark all variables that are
  7072. live after a \code{callq} as interfering with all the registers.
  7073. \item If a variable of type \code{Any} is spilled, it must be spilled
  7074. to the root stack instead of the normal procedure call stack.
  7075. \end{itemize}
  7076. \begin{exercise}\normalfont
  7077. Expand your compiler to handle $R_6$ as discussed in the last few
  7078. sections. Create 5 new programs that use the \code{Any} type and the
  7079. new operations (\code{inject}, \code{project}, \code{boolean?},
  7080. etc.). Test your compiler on these new programs and all of your
  7081. previously created test programs.
  7082. \end{exercise}
  7083. \section{Compiling $R_7$ to $R_6$}
  7084. \label{sec:compile-r7}
  7085. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7086. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7087. given a subexpression $e$ of $R_7$, the pass will produce an
  7088. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7089. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7090. the Boolean \code{\#t}, which must be injected to produce an
  7091. expression of type \key{Any}.
  7092. %
  7093. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7094. addition, is representative of compilation for many operations: the
  7095. arguments have type \key{Any} and must be projected to \key{Integer}
  7096. before the addition can be performed.
  7097. The compilation of \key{lambda} (third row of
  7098. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7099. produce type annotations: we simply use \key{Any}.
  7100. %
  7101. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7102. has to account for some differences in behavior between $R_7$ and
  7103. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7104. kind of values can be used in various places. For example, the
  7105. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7106. the arguments need not be of the same type (but in that case, the
  7107. result will be \code{\#f}).
  7108. \begin{figure}[btp]
  7109. \centering
  7110. \begin{tabular}{|lll|} \hline
  7111. \begin{minipage}{0.25\textwidth}
  7112. \begin{lstlisting}
  7113. #t
  7114. \end{lstlisting}
  7115. \end{minipage}
  7116. &
  7117. $\Rightarrow$
  7118. &
  7119. \begin{minipage}{0.6\textwidth}
  7120. \begin{lstlisting}
  7121. (inject #t Boolean)
  7122. \end{lstlisting}
  7123. \end{minipage}
  7124. \\[2ex]\hline
  7125. \begin{minipage}{0.25\textwidth}
  7126. \begin{lstlisting}
  7127. (+ |$e_1$| |$e_2$|)
  7128. \end{lstlisting}
  7129. \end{minipage}
  7130. &
  7131. $\Rightarrow$
  7132. &
  7133. \begin{minipage}{0.6\textwidth}
  7134. \begin{lstlisting}
  7135. (inject
  7136. (+ (project |$e'_1$| Integer)
  7137. (project |$e'_2$| Integer))
  7138. Integer)
  7139. \end{lstlisting}
  7140. \end{minipage}
  7141. \\[2ex]\hline
  7142. \begin{minipage}{0.25\textwidth}
  7143. \begin{lstlisting}
  7144. (lambda (|$x_1 \ldots$|) |$e$|)
  7145. \end{lstlisting}
  7146. \end{minipage}
  7147. &
  7148. $\Rightarrow$
  7149. &
  7150. \begin{minipage}{0.6\textwidth}
  7151. \begin{lstlisting}
  7152. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7153. (Any|$\ldots$|Any -> Any))
  7154. \end{lstlisting}
  7155. \end{minipage}
  7156. \\[2ex]\hline
  7157. \begin{minipage}{0.25\textwidth}
  7158. \begin{lstlisting}
  7159. (app |$e_0$| |$e_1 \ldots e_n$|)
  7160. \end{lstlisting}
  7161. \end{minipage}
  7162. &
  7163. $\Rightarrow$
  7164. &
  7165. \begin{minipage}{0.6\textwidth}
  7166. \begin{lstlisting}
  7167. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7168. |$e'_1 \ldots e'_n$|)
  7169. \end{lstlisting}
  7170. \end{minipage}
  7171. \\[2ex]\hline
  7172. \begin{minipage}{0.25\textwidth}
  7173. \begin{lstlisting}
  7174. (vector-ref |$e_1$| |$e_2$|)
  7175. \end{lstlisting}
  7176. \end{minipage}
  7177. &
  7178. $\Rightarrow$
  7179. &
  7180. \begin{minipage}{0.6\textwidth}
  7181. \begin{lstlisting}
  7182. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7183. (let ([tmp2 (project |$e'_2$| Integer)])
  7184. (vector-ref tmp1 tmp2)))
  7185. \end{lstlisting}
  7186. \end{minipage}
  7187. \\[2ex]\hline
  7188. \begin{minipage}{0.25\textwidth}
  7189. \begin{lstlisting}
  7190. (if |$e_1$| |$e_2$| |$e_3$|)
  7191. \end{lstlisting}
  7192. \end{minipage}
  7193. &
  7194. $\Rightarrow$
  7195. &
  7196. \begin{minipage}{0.6\textwidth}
  7197. \begin{lstlisting}
  7198. (if (eq? |$e'_1$| (inject #f Boolean))
  7199. |$e'_3$|
  7200. |$e'_2$|)
  7201. \end{lstlisting}
  7202. \end{minipage}
  7203. \\[2ex]\hline
  7204. \begin{minipage}{0.25\textwidth}
  7205. \begin{lstlisting}
  7206. (eq? |$e_1$| |$e_2$|)
  7207. \end{lstlisting}
  7208. \end{minipage}
  7209. &
  7210. $\Rightarrow$
  7211. &
  7212. \begin{minipage}{0.6\textwidth}
  7213. \begin{lstlisting}
  7214. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7215. \end{lstlisting}
  7216. \end{minipage}
  7217. \\[2ex]\hline
  7218. \end{tabular}
  7219. \caption{Compiling $R_7$ to $R_6$.}
  7220. \label{fig:compile-r7-r6}
  7221. \end{figure}
  7222. \begin{exercise}\normalfont
  7223. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7224. Create tests for $R_7$ by adapting all of your previous test programs
  7225. by removing type annotations. Add 5 more tests programs that
  7226. specifically rely on the language being dynamically typed. That is,
  7227. they should not be legal programs in a statically typed language, but
  7228. nevertheless, they should be valid $R_7$ programs that run to
  7229. completion without error.
  7230. \end{exercise}
  7231. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7232. \chapter{Gradual Typing}
  7233. \label{ch:gradual-typing}
  7234. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7235. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7236. \chapter{Parametric Polymorphism}
  7237. \label{ch:parametric-polymorphism}
  7238. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7239. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7240. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7241. \chapter{High-level Optimization}
  7242. \label{ch:high-level-optimization}
  7243. This chapter will present a procedure inlining pass based on the
  7244. algorithm of \citet{Waddell:1997fk}.
  7245. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7246. \chapter{Appendix}
  7247. \section{Interpreters}
  7248. \label{appendix:interp}
  7249. We provide several interpreters in the \key{interp.rkt} file. The
  7250. \key{interp-scheme} function takes an AST in one of the Racket-like
  7251. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7252. the program, returning the result value. The \key{interp-C} function
  7253. interprets an AST for a program in one of the C-like languages ($C_0,
  7254. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7255. for an x86 program.
  7256. \section{Utility Functions}
  7257. \label{appendix:utilities}
  7258. The utility function described in this section can be found in the
  7259. \key{utilities.rkt} file.
  7260. The \key{read-program} function takes a file path and parses that file
  7261. (it must be a Racket program) into an abstract syntax tree with a
  7262. \key{Program} node at the top.
  7263. The \key{parse-program} function takes an S-expression representation
  7264. of an AST and converts it into the struct-based representation.
  7265. The \key{assert} function displays the error message \key{msg} if the
  7266. Boolean \key{bool} is false.
  7267. \begin{lstlisting}
  7268. (define (assert msg bool) ...)
  7269. \end{lstlisting}
  7270. % remove discussion of lookup? -Jeremy
  7271. The \key{lookup} function takes a key and an alist, and returns the
  7272. first value that is associated with the given key, if there is one. If
  7273. not, an error is triggered. The alist may contain both immutable
  7274. pairs (built with \key{cons}) and mutable pairs (built with
  7275. \key{mcons}).
  7276. The \key{map2} function ...
  7277. %% \subsection{Graphs}
  7278. %% \begin{itemize}
  7279. %% \item The \code{make-graph} function takes a list of vertices
  7280. %% (symbols) and returns a graph.
  7281. %% \item The \code{add-edge} function takes a graph and two vertices and
  7282. %% adds an edge to the graph that connects the two vertices. The graph
  7283. %% is updated in-place. There is no return value for this function.
  7284. %% \item The \code{adjacent} function takes a graph and a vertex and
  7285. %% returns the set of vertices that are adjacent to the given
  7286. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7287. %% used with functions from the \code{racket/set} module.
  7288. %% \item The \code{vertices} function takes a graph and returns the list
  7289. %% of vertices in the graph.
  7290. %% \end{itemize}
  7291. \subsection{Testing}
  7292. The \key{interp-tests} function takes a compiler name (a string), a
  7293. description of the passes, an interpreter for the source language, a
  7294. test family name (a string), and a list of test numbers, and runs the
  7295. compiler passes and the interpreters to check whether the passes
  7296. correct. The description of the passes is a list with one entry per
  7297. pass. An entry is a list with three things: a string giving the name
  7298. of the pass, the function that implements the pass (a translator from
  7299. AST to AST), and a function that implements the interpreter (a
  7300. function from AST to result value) for the language of the output of
  7301. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7302. good choice. The \key{interp-tests} function assumes that the
  7303. subdirectory \key{tests} has a collection of Scheme programs whose names
  7304. all start with the family name, followed by an underscore and then the
  7305. test number, ending in \key{.scm}. Also, for each Scheme program there
  7306. is a file with the same number except that it ends with \key{.in} that
  7307. provides the input for the Scheme program.
  7308. \begin{lstlisting}
  7309. (define (interp-tests name passes test-family test-nums) ...)
  7310. \end{lstlisting}
  7311. The compiler-tests function takes a compiler name (a string) a
  7312. description of the passes (as described above for
  7313. \code{interp-tests}), a test family name (a string), and a list of
  7314. test numbers (see the comment for interp-tests), and runs the compiler
  7315. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7316. machine code. It runs the machine code and checks that the output is
  7317. 42.
  7318. \begin{lstlisting}
  7319. (define (compiler-tests name passes test-family test-nums) ...)
  7320. \end{lstlisting}
  7321. The compile-file function takes a description of the compiler passes
  7322. (see the comment for \key{interp-tests}) and returns a function that,
  7323. given a program file name (a string ending in \key{.scm}), applies all
  7324. of the passes and writes the output to a file whose name is the same
  7325. as the program file name but with \key{.scm} replaced with \key{.s}.
  7326. \begin{lstlisting}
  7327. (define (compile-file passes)
  7328. (lambda (prog-file-name) ...))
  7329. \end{lstlisting}
  7330. \section{x86 Instruction Set Quick-Reference}
  7331. \label{sec:x86-quick-reference}
  7332. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7333. do. We write $A \to B$ to mean that the value of $A$ is written into
  7334. location $B$. Address offsets are given in bytes. The instruction
  7335. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7336. registers (such as $\%rax$), or memory references (such as
  7337. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7338. reference per instruction. Other operands must be immediates or
  7339. registers.
  7340. \begin{table}[tbp]
  7341. \centering
  7342. \begin{tabular}{l|l}
  7343. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7344. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7345. \texttt{negq} $A$ & $- A \to A$ \\
  7346. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7347. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7348. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7349. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7350. \texttt{retq} & Pops the return address and jumps to it \\
  7351. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7352. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7353. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7354. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7355. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7356. matches the condition code of the instruction, otherwise go to the
  7357. next instructions. The condition codes are \key{e} for ``equal'',
  7358. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7359. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7360. \texttt{jl} $L$ & \\
  7361. \texttt{jle} $L$ & \\
  7362. \texttt{jg} $L$ & \\
  7363. \texttt{jge} $L$ & \\
  7364. \texttt{jmp} $L$ & Jump to label $L$ \\
  7365. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7366. \texttt{movzbq} $A$, $B$ &
  7367. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7368. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7369. and the extra bytes of $B$ are set to zero.} \\
  7370. & \\
  7371. & \\
  7372. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7373. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7374. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7375. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7376. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7377. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7378. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7379. description of the condition codes. $A$ must be a single byte register
  7380. (e.g., \texttt{al} or \texttt{cl}).} \\
  7381. \texttt{setl} $A$ & \\
  7382. \texttt{setle} $A$ & \\
  7383. \texttt{setg} $A$ & \\
  7384. \texttt{setge} $A$ &
  7385. \end{tabular}
  7386. \vspace{5pt}
  7387. \caption{Quick-reference for the x86 instructions used in this book.}
  7388. \label{tab:x86-instr}
  7389. \end{table}
  7390. \bibliographystyle{plainnat}
  7391. \bibliography{all}
  7392. \end{document}
  7393. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7394. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7395. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7396. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7397. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7398. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7399. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7400. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7401. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7402. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7403. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7404. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7405. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7406. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7407. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7408. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7409. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7410. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7411. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7412. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7413. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7414. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7415. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7416. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7417. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7418. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7419. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7420. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7421. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7422. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7423. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7424. % LocalWords: struct symtab