book.tex 360 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560
  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. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  76. deletekeywords={read},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge An Incremental Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses on programming languages by Professor Daniel
  151. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, he returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Professor Dybvig continued
  162. development of Chez Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Friedman's ideas was to split the compiler into many small
  166. ``passes'' so that the code for each pass would be easy to understood
  167. in isolation. (In contrast, most compilers of the time were organized
  168. into only a few monolithic passes for reasons of compile-time
  169. efficiency.) Dybvig, with later help from his students Dipanwita
  170. Sarkar and Andrew Keep, developed infrastructure to support this
  171. approach and evolved the course, first to use smaller micro-passes and
  172. then into even smaller
  173. nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student in this
  174. compiler course in the early 2000's as part of his Ph.D. studies at
  175. Indiana University. Needless to say, I enjoyed the course immensely!
  176. During that time, another graduate student named Abdulaziz Ghuloum
  177. observed that the front-to-back organization of the course made it
  178. difficult for students to understand the rationale for the compiler
  179. design. Ghuloum proposed an incremental approach in which the students
  180. build the compiler in stages; they start by implementing a complete
  181. compiler for a very small subset of the input language and in each
  182. subsequent stage they add a language feature and add or modify passes
  183. to handle the new feature~\citep{Ghuloum:2006bh}. In this way, the
  184. students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  190. on the surface but there is a large overlap in the compiler techniques
  191. required for the two languages. Thus, I was able to teach much of the
  192. same content from the Indiana compiler course. I very much enjoyed
  193. teaching the course organized in this way, and even better, many of
  194. the students learned a lot and got excited about compilers.
  195. I returned to teach at Indiana University in 2013. In my absence the
  196. compiler course had switched from the front-to-back organization to a
  197. back-to-front organization. Seeing how well the incremental approach
  198. worked at Colorado, I started porting and adapting the structure of
  199. the Colorado course back into the land of Scheme. In the meantime
  200. Indiana University had moved on from Scheme to Racket, so the course
  201. is now about compiling a subset of Racket (and Typed Racket) to the
  202. x86 assembly language. The compiler is implemented in
  203. Racket~\citep{plt-tr}.
  204. This is the textbook for the incremental version of the compiler
  205. course at Indiana University (Spring 2016 - present) and it is the
  206. first open textbook for an Indiana compiler course. With this book I
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study compilers at Indiana University. Many of
  209. the compiler design decisions in this book are drawn from the
  210. assignment descriptions of \cite{Dybvig:2010aa}. I have captured what
  211. I think are the most important topics from \cite{Dybvig:2010aa} but
  212. have omitted topics that are less interesting conceptually. I have
  213. also made simplifications to reduce complexity. In this way, this
  214. book leans more towards pedagogy than towards the efficiency of the
  215. generated code. Also, the book differs in places where we I the
  216. opportunity to make the topics more fun, such as in relating register
  217. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  218. \section*{Prerequisites}
  219. The material in this book is challenging but rewarding. It is meant to
  220. prepare students for a lifelong career in programming languages.
  221. The book uses the Racket language both for the implementation of the
  222. compiler and for the language that is compiled, so a student should be
  223. proficient with Racket (or Scheme) prior to reading this book. There
  224. are many excellent resources for learning Scheme and
  225. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  226. It is helpful but not necessary for the student to have prior exposure
  227. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  228. from a computer systems
  229. course~\citep{Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %
  232. We follow the System V calling
  233. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  234. assembly code that we generate will work properly with our runtime
  235. system (written in C) when it is compiled using the GNU C compiler
  236. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  237. adjustments are needed for MacOS which we note as they arise.)
  238. %
  239. When running on the Microsoft Windows operating system, the GNU C
  240. compiler follows the Microsoft x64 calling
  241. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  242. code that we generate will \emph{not} work properly with our runtime
  243. system on Windows. One option to consider for using a Windows computer
  244. is to run a virtual machine with Linux as the guest operating system.
  245. %\section*{Structure of book}
  246. % You might want to add short description about each chapter in this book.
  247. %\section*{About the companion website}
  248. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  249. %\begin{itemize}
  250. % \item A link to (freely downlodable) latest version of this document.
  251. % \item Link to download LaTeX source for this document.
  252. % \item Miscellaneous material (e.g. suggested readings etc).
  253. %\end{itemize}
  254. \section*{Acknowledgments}
  255. Many people have contributed to the ideas, techniques, and
  256. organization of this book and have taught courses based on it. We
  257. especially thank John Clements, Bor-Yuh Evan Chang, Kent Dybvig,
  258. Daniel P. Friedman, Ronald Garcia, Abdulaziz Ghuloum, Andrew Keep, Jay
  259. McCarthy, Nate Nystrom, Dipanwita Sarkar, Oscar Waddell, and Michael
  260. Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.
  276. \index{concrete syntax}
  277. \index{abstract syntax}
  278. \index{abstract syntax tree}
  279. \index{AST}
  280. \index{program}
  281. \index{parse}
  282. %
  283. The translation from concrete syntax to abstract syntax is a process
  284. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  285. and implementation of parsing in this book. A parser is provided in
  286. the supporting materials for translating from concrete syntax to
  287. abstract syntax for the languages used in this book.
  288. ASTs can be represented in many different ways inside the compiler,
  289. depending on the programming language used to write the compiler.
  290. %
  291. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  292. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  293. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  294. and pattern matching to inspect individual nodes in an AST
  295. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  296. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  297. chapter provides an brief introduction to these ideas.
  298. \index{struct}
  299. \section{Abstract Syntax Trees and Racket Structures}
  300. \label{sec:ast}
  301. Compilers use abstract syntax trees to represent programs because
  302. compilers often need to ask questions like: for a given part of a
  303. program, what kind of language feature is it? What are the sub-parts
  304. of this part of the program? Consider the program on the left and its
  305. AST on the right. This program is an addition and it has two
  306. sub-parts, a read operation and a negation. The negation has another
  307. sub-part, the integer constant \code{8}. By using a tree to represent
  308. the program, we can easily follow the links to go from one part of a
  309. program to its sub-parts.
  310. \begin{center}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{lstlisting}
  313. (+ (read) (- 8))
  314. \end{lstlisting}
  315. \end{minipage}
  316. \begin{minipage}{0.4\textwidth}
  317. \begin{equation}
  318. \begin{tikzpicture}
  319. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  320. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  321. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  322. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  323. \draw[->] (plus) to (read);
  324. \draw[->] (plus) to (minus);
  325. \draw[->] (minus) to (8);
  326. \end{tikzpicture}
  327. \label{eq:arith-prog}
  328. \end{equation}
  329. \end{minipage}
  330. \end{center}
  331. We use the standard terminology for trees to describe ASTs: each
  332. circle above is called a \emph{node}. The arrows connect a node to its
  333. \emph{children} (which are also nodes). The top-most node is the
  334. \emph{root}. Every node except for the root has a \emph{parent} (the
  335. node it is the child of). If a node has no children, it is a
  336. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  337. \index{node}
  338. \index{children}
  339. \index{root}
  340. \index{parent}
  341. \index{leaf}
  342. \index{internal node}
  343. %% Recall that an \emph{symbolic expression} (S-expression) is either
  344. %% \begin{enumerate}
  345. %% \item an atom, or
  346. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  347. %% where $e_1$ and $e_2$ are each an S-expression.
  348. %% \end{enumerate}
  349. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  350. %% null value \code{'()}, etc. We can create an S-expression in Racket
  351. %% simply by writing a backquote (called a quasi-quote in Racket)
  352. %% followed by the textual representation of the S-expression. It is
  353. %% quite common to use S-expressions to represent a list, such as $a, b
  354. %% ,c$ in the following way:
  355. %% \begin{lstlisting}
  356. %% `(a . (b . (c . ())))
  357. %% \end{lstlisting}
  358. %% Each element of the list is in the first slot of a pair, and the
  359. %% second slot is either the rest of the list or the null value, to mark
  360. %% the end of the list. Such lists are so common that Racket provides
  361. %% special notation for them that removes the need for the periods
  362. %% and so many parenthesis:
  363. %% \begin{lstlisting}
  364. %% `(a b c)
  365. %% \end{lstlisting}
  366. %% The following expression creates an S-expression that represents AST
  367. %% \eqref{eq:arith-prog}.
  368. %% \begin{lstlisting}
  369. %% `(+ (read) (- 8))
  370. %% \end{lstlisting}
  371. %% When using S-expressions to represent ASTs, the convention is to
  372. %% represent each AST node as a list and to put the operation symbol at
  373. %% the front of the list. The rest of the list contains the children. So
  374. %% in the above case, the root AST node has operation \code{`+} and its
  375. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  376. %% diagram \eqref{eq:arith-prog}.
  377. %% To build larger S-expressions one often needs to splice together
  378. %% several smaller S-expressions. Racket provides the comma operator to
  379. %% splice an S-expression into a larger one. For example, instead of
  380. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  381. %% we could have first created an S-expression for AST
  382. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  383. %% S-expression.
  384. %% \begin{lstlisting}
  385. %% (define ast1.4 `(- 8))
  386. %% (define ast1.1 `(+ (read) ,ast1.4))
  387. %% \end{lstlisting}
  388. %% In general, the Racket expression that follows the comma (splice)
  389. %% can be any expression that produces an S-expression.
  390. We define a Racket \code{struct} for each kind of node. For this
  391. chapter we require just two kinds of nodes: one for integer constants
  392. and one for primitive operations. The following is the \code{struct}
  393. definition for integer constants.
  394. \begin{lstlisting}
  395. (struct Int (value))
  396. \end{lstlisting}
  397. An integer node includes just one thing: the integer value.
  398. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  399. \begin{lstlisting}
  400. (define eight (Int 8))
  401. \end{lstlisting}
  402. We say that the value created by \code{(Int 8)} is an
  403. \emph{instance} of the \code{Int} structure.
  404. The following is the \code{struct} definition for primitives operations.
  405. \begin{lstlisting}
  406. (struct Prim (op arg*))
  407. \end{lstlisting}
  408. A primitive operation node includes an operator symbol \code{op}
  409. and a list of children \code{arg*}. For example, to create
  410. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  411. \begin{lstlisting}
  412. (define neg-eight (Prim '- (list eight)))
  413. \end{lstlisting}
  414. Primitive operations may have zero or more children. The \code{read}
  415. operator has zero children:
  416. \begin{lstlisting}
  417. (define rd (Prim 'read '()))
  418. \end{lstlisting}
  419. whereas the addition operator has two children:
  420. \begin{lstlisting}
  421. (define ast1.1 (Prim '+ (list rd neg-eight)))
  422. \end{lstlisting}
  423. We have made a design choice regarding the \code{Prim} structure.
  424. Instead of using one structure for many different operations
  425. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  426. structure for each operation, as follows.
  427. \begin{lstlisting}
  428. (struct Read ())
  429. (struct Add (left right))
  430. (struct Neg (value))
  431. \end{lstlisting}
  432. The reason we choose to use just one structure is that in many parts
  433. of the compiler the code for the different primitive operators is the
  434. same, so we might as well just write that code once, which is enabled
  435. by using a single structure.
  436. When compiling a program such as \eqref{eq:arith-prog}, we need to
  437. know that the operation associated with the root node is addition and
  438. we need to be able to access its two children. Racket provides pattern
  439. matching over structures to support these kinds of queries, as we
  440. see in Section~\ref{sec:pattern-matching}.
  441. In this book, we often write down the concrete syntax of a program
  442. even when we really have in mind the AST because the concrete syntax
  443. is more concise. We recommend that, in your mind, you always think of
  444. programs as abstract syntax trees.
  445. \section{Grammars}
  446. \label{sec:grammar}
  447. \index{integer}
  448. \index{literal}
  449. \index{constant}
  450. A programming language can be thought of as a \emph{set} of programs.
  451. The set is typically infinite (one can always create larger and larger
  452. programs), so one cannot simply describe a language by listing all of
  453. the programs in the language. Instead we write down a set of rules, a
  454. \emph{grammar}, for building programs. Grammars are often used to
  455. define the concrete syntax of a language, but they can also be used to
  456. describe the abstract syntax. We write our rules in a variant of
  457. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  458. \index{Backus-Naur Form}\index{BNF}
  459. As an example, we describe a small language, named $R_0$, that consists of
  460. integers and arithmetic operations.
  461. \index{grammar}
  462. The first grammar rule for the abstract syntax of $R_0$ says that an
  463. instance of the \code{Int} structure is an expression:
  464. \begin{equation}
  465. \Exp ::= \INT{\Int} \label{eq:arith-int}
  466. \end{equation}
  467. %
  468. Each rule has a left-hand-side and a right-hand-side. The way to read
  469. a rule is that if you have all the program parts on the
  470. right-hand-side, then you can create an AST node and categorize it
  471. according to the left-hand-side.
  472. %
  473. A name such as $\Exp$ that is
  474. defined by the grammar rules is a \emph{non-terminal}.
  475. \index{non-terminal}
  476. %
  477. The name $\Int$ is a also a non-terminal, but instead of defining it
  478. with a grammar rule, we define it with the following explanation. We
  479. make the simplifying design decision that all of the languages in this
  480. book only handle machine-representable integers. On most modern
  481. machines this corresponds to integers represented with 64-bits, i.e.,
  482. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  483. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  484. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  485. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  486. that the sequence of decimals represent an integer in range $-2^{62}$
  487. to $2^{62}-1$.
  488. The second grammar rule is the \texttt{read} operation that receives
  489. an input integer from the user of the program.
  490. \begin{equation}
  491. \Exp ::= \READ{} \label{eq:arith-read}
  492. \end{equation}
  493. The third rule says that, given an $\Exp$ node, you can build another
  494. $\Exp$ node by negating it.
  495. \begin{equation}
  496. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  497. \end{equation}
  498. Symbols in typewriter font such as \key{-} and \key{read} are
  499. \emph{terminal} symbols and must literally appear in the program for
  500. the rule to be applicable.
  501. \index{terminal}
  502. We can apply the rules to build ASTs in the $R_0$
  503. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  504. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  505. an $\Exp$.
  506. \begin{center}
  507. \begin{minipage}{0.4\textwidth}
  508. \begin{lstlisting}
  509. (Prim '- (list (Int 8)))
  510. \end{lstlisting}
  511. \end{minipage}
  512. \begin{minipage}{0.25\textwidth}
  513. \begin{equation}
  514. \begin{tikzpicture}
  515. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  516. \node[draw, circle] (8) at (0, -1.2) {$8$};
  517. \draw[->] (minus) to (8);
  518. \end{tikzpicture}
  519. \label{eq:arith-neg8}
  520. \end{equation}
  521. \end{minipage}
  522. \end{center}
  523. The next grammar rule defines addition expressions:
  524. \begin{equation}
  525. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  526. \end{equation}
  527. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  528. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  529. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  530. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  531. to show that
  532. \begin{lstlisting}
  533. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  534. \end{lstlisting}
  535. is an $\Exp$ in the $R_0$ language.
  536. If you have an AST for which the above rules do not apply, then the
  537. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  538. is not in $R_0$ because there are no rules for \code{+} with only one
  539. argument, nor for \key{-} with two arguments. Whenever we define a
  540. language with a grammar, the language only includes those programs
  541. that are justified by the rules.
  542. The last grammar rule for $R_0$ states that there is a \code{Program}
  543. node to mark the top of the whole program:
  544. \[
  545. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  546. \]
  547. The \code{Program} structure is defined as follows
  548. \begin{lstlisting}
  549. (struct Program (info body))
  550. \end{lstlisting}
  551. where \code{body} is an expression. In later chapters, the \code{info}
  552. part will be used to store auxiliary information but for now it is
  553. just the empty list.
  554. It is common to have many grammar rules with the same left-hand side
  555. but different right-hand sides, such as the rules for $\Exp$ in the
  556. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  557. combine several right-hand-sides into a single rule.
  558. We collect all of the grammar rules for the abstract syntax of $R_0$
  559. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  560. defined in Figure~\ref{fig:r0-concrete-syntax}.
  561. The \code{read-program} function provided in \code{utilities.rkt} of
  562. the support materials reads a program in from a file (the sequence of
  563. characters in the concrete syntax of Racket) and parses it into an
  564. abstract syntax tree. See the description of \code{read-program} in
  565. Appendix~\ref{appendix:utilities} for more details.
  566. \begin{figure}[tp]
  567. \fbox{
  568. \begin{minipage}{0.96\textwidth}
  569. \[
  570. \begin{array}{rcl}
  571. \begin{array}{rcl}
  572. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  573. R_0 &::=& \Exp
  574. \end{array}
  575. \end{array}
  576. \]
  577. \end{minipage}
  578. }
  579. \caption{The concrete syntax of $R_0$.}
  580. \label{fig:r0-concrete-syntax}
  581. \end{figure}
  582. \begin{figure}[tp]
  583. \fbox{
  584. \begin{minipage}{0.96\textwidth}
  585. \[
  586. \begin{array}{rcl}
  587. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  588. &\mid& \ADD{\Exp}{\Exp} \\
  589. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  590. \end{array}
  591. \]
  592. \end{minipage}
  593. }
  594. \caption{The abstract syntax of $R_0$.}
  595. \label{fig:r0-syntax}
  596. \end{figure}
  597. \section{Pattern Matching}
  598. \label{sec:pattern-matching}
  599. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  600. the parts of an AST node. Racket provides the \texttt{match} form to
  601. access the parts of a structure. Consider the following example and
  602. the output on the right. \index{match} \index{pattern matching}
  603. \begin{center}
  604. \begin{minipage}{0.5\textwidth}
  605. \begin{lstlisting}
  606. (match ast1.1
  607. [(Prim op (list child1 child2))
  608. (print op)])
  609. \end{lstlisting}
  610. \end{minipage}
  611. \vrule
  612. \begin{minipage}{0.25\textwidth}
  613. \begin{lstlisting}
  614. '+
  615. \end{lstlisting}
  616. \end{minipage}
  617. \end{center}
  618. In the above example, the \texttt{match} form takes the AST
  619. \eqref{eq:arith-prog} and binds its parts to the three pattern
  620. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  621. general, a match clause consists of a \emph{pattern} and a
  622. \emph{body}.
  623. \index{pattern}
  624. Patterns are recursively defined to be either a pattern
  625. variable, a structure name followed by a pattern for each of the
  626. structure's arguments, or an S-expression (symbols, lists, etc.).
  627. (See Chapter 12 of The Racket
  628. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  629. and Chapter 9 of The Racket
  630. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  631. for a complete description of \code{match}.)
  632. %
  633. The body of a match clause may contain arbitrary Racket code. The
  634. pattern variables can be used in the scope of the body.
  635. A \code{match} form may contain several clauses, as in the following
  636. function \code{leaf?} that recognizes when an $R_0$ node is
  637. a leaf. The \code{match} proceeds through the clauses in order,
  638. checking whether the pattern can match the input AST. The
  639. body of the first clause that matches is executed. The output of
  640. \code{leaf?} for several ASTs is shown on the right.
  641. \begin{center}
  642. \begin{minipage}{0.6\textwidth}
  643. \begin{lstlisting}
  644. (define (leaf? arith)
  645. (match arith
  646. [(Int n) #t]
  647. [(Prim 'read '()) #t]
  648. [(Prim '- (list c1)) #f]
  649. [(Prim '+ (list c1 c2)) #f]))
  650. (leaf? (Prim 'read '()))
  651. (leaf? (Prim '- (list (Int 8))))
  652. (leaf? (Int 8))
  653. \end{lstlisting}
  654. \end{minipage}
  655. \vrule
  656. \begin{minipage}{0.25\textwidth}
  657. \begin{lstlisting}
  658. #t
  659. #f
  660. #t
  661. \end{lstlisting}
  662. \end{minipage}
  663. \end{center}
  664. When writing a \code{match}, we refer to the grammar definition to
  665. identify which non-terminal we are expecting to match against, then we
  666. make sure that 1) we have one clause for each alternative of that
  667. non-terminal and 2) that the pattern in each clause corresponds to the
  668. corresponding right-hand side of a grammar rule. For the \code{match}
  669. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  670. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  671. alternatives, so the \code{match} has 4 clauses. The pattern in each
  672. clause corresponds to the right-hand side of a grammar rule. For
  673. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  674. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  675. patterns, replace non-terminals such as $\Exp$ with pattern variables
  676. of your choice (e.g. \code{c1} and \code{c2}).
  677. \section{Recursion}
  678. \label{sec:recursion}
  679. \index{recursive function}
  680. Programs are inherently recursive. For example, an $R_0$ expression is
  681. often made of smaller expressions. Thus, the natural way to process an
  682. entire program is with a recursive function. As a first example of
  683. such a recursive function, we define \texttt{exp?} below, which takes
  684. an arbitrary value and determines whether or not it is an $R_0$
  685. expression.
  686. %
  687. When a recursive function is defined using a sequence of match clauses
  688. that correspond to a grammar, and the body of each clause makes a
  689. recursive call on each child node, then we say the function is defined
  690. by \emph{structural recursion}\footnote{This principle of structuring
  691. code according to the data definition is advocated in the book
  692. \emph{How to Design Programs}
  693. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  694. define a second function, named \code{R0?}, that determines whether a
  695. value is an $R_0$ program. In general we can expect to write one
  696. recursive function to handle each non-terminal in a grammar.
  697. \index{structural recursion}
  698. %
  699. \begin{center}
  700. \begin{minipage}{0.7\textwidth}
  701. \begin{lstlisting}
  702. (define (exp? ast)
  703. (match ast
  704. [(Int n) #t]
  705. [(Prim 'read '()) #t]
  706. [(Prim '- (list e)) (exp? e)]
  707. [(Prim '+ (list e1 e2))
  708. (and (exp? e1) (exp? e2))]
  709. [else #f]))
  710. (define (R0? ast)
  711. (match ast
  712. [(Program '() e) (exp? e)]
  713. [else #f]))
  714. (R0? (Program '() ast1.1)
  715. (R0? (Program '()
  716. (Prim '- (list (Prim 'read '())
  717. (Prim '+ (list (Num 8)))))))
  718. \end{lstlisting}
  719. \end{minipage}
  720. \vrule
  721. \begin{minipage}{0.25\textwidth}
  722. \begin{lstlisting}
  723. #t
  724. #f
  725. \end{lstlisting}
  726. \end{minipage}
  727. \end{center}
  728. You may be tempted to merge the two functions into one, like this:
  729. \begin{center}
  730. \begin{minipage}{0.5\textwidth}
  731. \begin{lstlisting}
  732. (define (R0? ast)
  733. (match ast
  734. [(Int n) #t]
  735. [(Prim 'read '()) #t]
  736. [(Prim '- (list e)) (R0? e)]
  737. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  738. [(Program '() e) (R0? e)]
  739. [else #f]))
  740. \end{lstlisting}
  741. \end{minipage}
  742. \end{center}
  743. %
  744. Sometimes such a trick will save a few lines of code, especially when
  745. it comes to the \code{Program} wrapper. Yet this style is generally
  746. \emph{not} recommended because it can get you into trouble.
  747. %
  748. For example, the above function is subtly wrong:
  749. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  750. will return true, when it should return false.
  751. %% NOTE FIXME - must check for consistency on this issue throughout.
  752. \section{Interpreters}
  753. \label{sec:interp-R0}
  754. \index{interpreter}
  755. The meaning, or semantics, of a program is typically defined in the
  756. specification of the language. For example, the Scheme language is
  757. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  758. defined in its reference manual~\citep{plt-tr}. In this book we use an
  759. interpreter to define the meaning of each language that we consider,
  760. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  761. interpreter that is designated (by some people) as the definition of a
  762. language is called a \emph{definitional interpreter}.
  763. \index{definitional interpreter}
  764. We warm up by creating a definitional interpreter for the $R_0$ language, which
  765. serves as a second example of structural recursion. The
  766. \texttt{interp-R0} function is defined in
  767. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  768. input program followed by a call to the \lstinline{interp-exp} helper
  769. function, which in turn has one match clause per grammar rule for
  770. $R_0$ expressions.
  771. \begin{figure}[tp]
  772. \begin{lstlisting}
  773. (define (interp-exp e)
  774. (match e
  775. [(Int n) n]
  776. [(Prim 'read '())
  777. (define r (read))
  778. (cond [(fixnum? r) r]
  779. [else (error 'interp-R0 "expected an integer" r)])]
  780. [(Prim '- (list e))
  781. (define v (interp-exp e))
  782. (fx- 0 v)]
  783. [(Prim '+ (list e1 e2))
  784. (define v1 (interp-exp e1))
  785. (define v2 (interp-exp e2))
  786. (fx+ v1 v2)]
  787. ))
  788. (define (interp-R0 p)
  789. (match p
  790. [(Program '() e) (interp-exp e)]
  791. ))
  792. \end{lstlisting}
  793. \caption{Interpreter for the $R_0$ language.}
  794. \label{fig:interp-R0}
  795. \end{figure}
  796. Let us consider the result of interpreting a few $R_0$ programs. The
  797. following program adds two integers.
  798. \begin{lstlisting}
  799. (+ 10 32)
  800. \end{lstlisting}
  801. The result is \key{42}. We wrote the above program in concrete syntax,
  802. whereas the parsed abstract syntax is:
  803. \begin{lstlisting}
  804. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  805. \end{lstlisting}
  806. The next example demonstrates that expressions may be nested within
  807. each other, in this case nesting several additions and negations.
  808. \begin{lstlisting}
  809. (+ 10 (- (+ 12 20)))
  810. \end{lstlisting}
  811. What is the result of the above program?
  812. As mentioned previously, the $R_0$ language does not support
  813. arbitrarily-large integers, but only $63$-bit integers, so we
  814. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  815. in Racket.
  816. Suppose
  817. \[
  818. n = 999999999999999999
  819. \]
  820. which indeed fits in $63$-bits. What happens when we run the
  821. following program in our interpreter?
  822. \begin{lstlisting}
  823. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  824. \end{lstlisting}
  825. It produces an error:
  826. \begin{lstlisting}
  827. fx+: result is not a fixnum
  828. \end{lstlisting}
  829. We establish the convention that if running the definitional
  830. interpreter on a program produces an error, then the meaning of that
  831. program is \emph{unspecified}. That means a compiler for the language
  832. is under no obligations regarding that program; it may or may not
  833. produce an executable, and if it does, that executable can do
  834. anything. This convention applies to the languages defined in this
  835. book, as a way to simplify the student's task of implementing them,
  836. but this convention is not applicable to all programming languages.
  837. \index{unspecified behavior}
  838. Moving on to the last feature of the $R_0$ language, the \key{read}
  839. operation prompts the user of the program for an integer. Recall that
  840. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  841. \code{8}. So if we run
  842. \begin{lstlisting}
  843. (interp-R0 (Program '() ast1.1))
  844. \end{lstlisting}
  845. and if the input is \code{50}, then we get the answer to life, the
  846. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  847. Guide to the Galaxy} by Douglas Adams.}
  848. We include the \key{read} operation in $R_0$ so a clever student
  849. cannot implement a compiler for $R_0$ that simply runs the interpreter
  850. during compilation to obtain the output and then generates the trivial
  851. code to produce the output. (Yes, a clever student did this in the
  852. first instance of this course.)
  853. The job of a compiler is to translate a program in one language into a
  854. program in another language so that the output program behaves the
  855. same way as the input program does according to its definitional
  856. interpreter. This idea is depicted in the following diagram. Suppose
  857. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  858. interpreter for each language. Suppose that the compiler translates
  859. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  860. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  861. respective interpreters with input $i$ should yield the same output
  862. $o$.
  863. \begin{equation} \label{eq:compile-correct}
  864. \begin{tikzpicture}[baseline=(current bounding box.center)]
  865. \node (p1) at (0, 0) {$P_1$};
  866. \node (p2) at (3, 0) {$P_2$};
  867. \node (o) at (3, -2.5) {$o$};
  868. \path[->] (p1) edge [above] node {compile} (p2);
  869. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  870. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  871. \end{tikzpicture}
  872. \end{equation}
  873. In the next section we see our first example of a compiler.
  874. \section{Example Compiler: a Partial Evaluator}
  875. \label{sec:partial-evaluation}
  876. In this section we consider a compiler that translates $R_0$ programs
  877. into $R_0$ programs that may be more efficient, that is, this compiler
  878. is an optimizer. This optimizer eagerly computes the parts of the
  879. program that do not depend on any inputs, a process known as
  880. \emph{partial evaluation}~\cite{Jones:1993uq}.
  881. \index{partial evaluation}
  882. For example, given the following program
  883. \begin{lstlisting}
  884. (+ (read) (- (+ 5 3)))
  885. \end{lstlisting}
  886. our compiler will translate it into the program
  887. \begin{lstlisting}
  888. (+ (read) -8)
  889. \end{lstlisting}
  890. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  891. evaluator for the $R_0$ language. The output of the partial evaluator
  892. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  893. recursion over $\Exp$ is captured in the \code{pe-exp} function
  894. whereas the code for partially evaluating the negation and addition
  895. operations is factored into two separate helper functions:
  896. \code{pe-neg} and \code{pe-add}. The input to these helper
  897. functions is the output of partially evaluating the children.
  898. \begin{figure}[tp]
  899. \begin{lstlisting}
  900. (define (pe-neg r)
  901. (match r
  902. [(Int n) (Int (fx- 0 n))]
  903. [else (Prim '- (list r))]))
  904. (define (pe-add r1 r2)
  905. (match* (r1 r2)
  906. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  907. [(_ _) (Prim '+ (list r1 r2))]))
  908. (define (pe-exp e)
  909. (match e
  910. [(Int n) (Int n)]
  911. [(Prim 'read '()) (Prim 'read '())]
  912. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  913. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  914. ))
  915. (define (pe-R0 p)
  916. (match p
  917. [(Program '() e) (Program '() (pe-exp e))]
  918. ))
  919. \end{lstlisting}
  920. \caption{A partial evaluator for $R_0$ expressions.}
  921. \label{fig:pe-arith}
  922. \end{figure}
  923. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  924. arguments are integers and if they are, perform the appropriate
  925. arithmetic. Otherwise, they create an AST node for the operation
  926. (either negation or addition).
  927. To gain some confidence that the partial evaluator is correct, we can
  928. test whether it produces programs that get the same result as the
  929. input programs. That is, we can test whether it satisfies Diagram
  930. \eqref{eq:compile-correct}. The following code runs the partial
  931. evaluator on several examples and tests the output program. The
  932. \texttt{parse-program} and \texttt{assert} functions are defined in
  933. Appendix~\ref{appendix:utilities}.\\
  934. \begin{minipage}{1.0\textwidth}
  935. \begin{lstlisting}
  936. (define (test-pe p)
  937. (assert "testing pe-R0"
  938. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  939. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  940. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  941. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  942. \end{lstlisting}
  943. \end{minipage}
  944. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  945. \chapter{Integers and Variables}
  946. \label{ch:int-exp}
  947. This chapter is about compiling the subset of Racket that includes
  948. integer arithmetic and local variable binding, which we name $R_1$, to
  949. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  950. to x86-64 simply as x86. The chapter begins with a description of the
  951. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  952. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  953. discuss only what is needed for compiling $R_1$. We introduce more of
  954. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  955. reflect on their differences and come up with a plan to break down the
  956. translation from $R_1$ to x86 into a handful of steps
  957. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  958. chapter give detailed hints regarding each step
  959. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  960. to give enough hints that the well-prepared reader, together with a
  961. few friends, can implement a compiler from $R_1$ to x86 in a couple
  962. weeks while at the same time leaving room for some fun and creativity.
  963. To give the reader a feeling for the scale of this first compiler, the
  964. instructor solution for the $R_1$ compiler is less than 500 lines of
  965. code.
  966. \section{The $R_1$ Language}
  967. \label{sec:s0}
  968. \index{variable}
  969. The $R_1$ language extends the $R_0$ language with variable
  970. definitions. The concrete syntax of the $R_1$ language is defined by
  971. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  972. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  973. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  974. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  975. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  976. \key{Program} struct to mark the top of the program.
  977. %% The $\itm{info}$
  978. %% field of the \key{Program} structure contains an \emph{association
  979. %% list} (a list of key-value pairs) that is used to communicate
  980. %% auxiliary data from one compiler pass the next.
  981. Despite the simplicity of the $R_1$ language, it is rich enough to
  982. exhibit several compilation techniques.
  983. \begin{figure}[tp]
  984. \centering
  985. \fbox{
  986. \begin{minipage}{0.96\textwidth}
  987. \[
  988. \begin{array}{rcl}
  989. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  990. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  991. R_1 &::=& \Exp
  992. \end{array}
  993. \]
  994. \end{minipage}
  995. }
  996. \caption{The concrete syntax of $R_1$.}
  997. \label{fig:r1-concrete-syntax}
  998. \end{figure}
  999. \begin{figure}[tp]
  1000. \centering
  1001. \fbox{
  1002. \begin{minipage}{0.96\textwidth}
  1003. \[
  1004. \begin{array}{rcl}
  1005. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1006. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1007. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1008. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1009. \end{array}
  1010. \]
  1011. \end{minipage}
  1012. }
  1013. \caption{The abstract syntax of $R_1$.}
  1014. \label{fig:r1-syntax}
  1015. \end{figure}
  1016. Let us dive further into the syntax and semantics of the $R_1$
  1017. language. The \key{Let} feature defines a variable for use within its
  1018. body and initializes the variable with the value of an expression.
  1019. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1020. The concrete syntax for \key{Let} is
  1021. \begin{lstlisting}
  1022. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1023. \end{lstlisting}
  1024. For example, the following program initializes \code{x} to $32$ and then
  1025. evaluates the body \code{(+ 10 x)}, producing $42$.
  1026. \begin{lstlisting}
  1027. (let ([x (+ 12 20)]) (+ 10 x))
  1028. \end{lstlisting}
  1029. When there are multiple \key{let}'s for the same variable, the closest
  1030. enclosing \key{let} is used. That is, variable definitions overshadow
  1031. prior definitions. Consider the following program with two \key{let}'s
  1032. that define variables named \code{x}. Can you figure out the result?
  1033. \begin{lstlisting}
  1034. (let ([x 32]) (+ (let ([x 10]) x) x))
  1035. \end{lstlisting}
  1036. For the purposes of depicting which variable uses correspond to which
  1037. definitions, the following shows the \code{x}'s annotated with
  1038. subscripts to distinguish them. Double check that your answer for the
  1039. above is the same as your answer for this annotated version of the
  1040. program.
  1041. \begin{lstlisting}
  1042. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1043. \end{lstlisting}
  1044. The initializing expression is always evaluated before the body of the
  1045. \key{let}, so in the following, the \key{read} for \code{x} is
  1046. performed before the \key{read} for \code{y}. Given the input
  1047. $52$ then $10$, the following produces $42$ (not $-42$).
  1048. \begin{lstlisting}
  1049. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1050. \end{lstlisting}
  1051. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1052. \small
  1053. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1054. An \emph{association list} (alist) is a list of key-value pairs.
  1055. For example, we can map people to their ages with an alist.
  1056. \index{alist}\index{association list}
  1057. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1058. (define ages
  1059. '((jane . 25) (sam . 24) (kate . 45)))
  1060. \end{lstlisting}
  1061. The \emph{dictionary} interface is for mapping keys to values.
  1062. Every alist implements this interface. \index{dictionary} The package
  1063. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1064. provides many functions for working with dictionaries. Here
  1065. are a few of them:
  1066. \begin{description}
  1067. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1068. returns the value associated with the given $\itm{key}$.
  1069. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1070. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1071. but otherwise is the same as $\itm{dict}$.
  1072. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1073. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1074. of keys and values in $\itm{dict}$. For example, the following
  1075. creates a new alist in which the ages are incremented.
  1076. \end{description}
  1077. \vspace{-10pt}
  1078. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1079. (for/list ([(k v) (in-dict ages)])
  1080. (cons k (add1 v)))
  1081. \end{lstlisting}
  1082. \end{tcolorbox}
  1083. \end{wrapfigure}
  1084. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1085. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1086. \key{match} clauses for variables and for \key{let}. For \key{let},
  1087. we need a way to communicate the value of a variable to all the uses
  1088. of a variable. To accomplish this, we maintain a mapping from
  1089. variables to values. Throughout the compiler we often need to map
  1090. variables to information about them. We refer to these mappings as
  1091. \emph{environments}\index{environment}
  1092. \footnote{Another common term for environment in the compiler
  1093. literature is \emph{symbol table}\index{symbol table}.}.
  1094. For simplicity, we use an
  1095. association list (alist) to represent the environment. The sidebar to
  1096. the right gives a brief introduction to alists and the
  1097. \code{racket/dict} package. The \code{interp-R1} function takes the
  1098. current environment, \code{env}, as an extra parameter. When the
  1099. interpreter encounters a variable, it finds the corresponding value
  1100. using the \code{dict-ref} function. When the interpreter encounters a
  1101. \key{Let}, it evaluates the initializing expression, extends the
  1102. environment with the result value bound to the variable, using
  1103. \code{dict-set}, then evaluates the body of the \key{Let}.
  1104. \begin{figure}[tp]
  1105. \begin{lstlisting}
  1106. (define (interp-exp env)
  1107. (lambda (e)
  1108. (match e
  1109. [(Int n) n]
  1110. [(Prim 'read '())
  1111. (define r (read))
  1112. (cond [(fixnum? r) r]
  1113. [else (error 'interp-R1 "expected an integer" r)])]
  1114. [(Prim '- (list e))
  1115. (define v ((interp-exp env) e))
  1116. (fx- 0 v)]
  1117. [(Prim '+ (list e1 e2))
  1118. (define v1 ((interp-exp env) e1))
  1119. (define v2 ((interp-exp env) e2))
  1120. (fx+ v1 v2)]
  1121. [(Var x) (dict-ref env x)]
  1122. [(Let x e body)
  1123. (define new-env (dict-set env x ((interp-exp env) e)))
  1124. ((interp-exp new-env) body)]
  1125. )))
  1126. (define (interp-R1 p)
  1127. (match p
  1128. [(Program '() e) ((interp-exp '()) e)]
  1129. ))
  1130. \end{lstlisting}
  1131. \caption{Interpreter for the $R_1$ language.}
  1132. \label{fig:interp-R1}
  1133. \end{figure}
  1134. The goal for this chapter is to implement a compiler that translates
  1135. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1136. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1137. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1138. is, they both output the same integer $n$. We depict this correctness
  1139. criteria in the following diagram.
  1140. \[
  1141. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1142. \node (p1) at (0, 0) {$P_1$};
  1143. \node (p2) at (4, 0) {$P_2$};
  1144. \node (o) at (4, -2) {$n$};
  1145. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1146. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1147. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1148. \end{tikzpicture}
  1149. \]
  1150. In the next section we introduce enough of the x86 assembly
  1151. language to compile $R_1$.
  1152. \section{The x86$_0$ Assembly Language}
  1153. \label{sec:x86}
  1154. \index{x86}
  1155. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1156. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1157. %
  1158. An x86 program begins with a \code{main} label followed by a sequence
  1159. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1160. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1161. instructions.\index{instruction}
  1162. %
  1163. An x86 program is stored in the computer's memory and the computer has
  1164. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1165. that points to the address of the next
  1166. instruction to be executed. For most instructions, once the
  1167. instruction is executed, the program counter is incremented to point
  1168. to the immediately following instruction in memory. Most x86
  1169. instructions take two operands, where each operand is either an
  1170. integer constant (called \emph{immediate value}\index{immediate value}),
  1171. a \emph{register}\index{register}, or a memory location.
  1172. A register is a special kind of variable. Each
  1173. one holds a 64-bit value; there are 16 registers in the computer and
  1174. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1175. as a mapping of 64-bit addresses to 64-bit values%
  1176. \footnote{This simple story suffices for describing how sequential
  1177. programs access memory but is not sufficient for multi-threaded
  1178. programs. However, multi-threaded execution is beyond the scope of
  1179. this book.}.
  1180. %
  1181. We use the AT\&T syntax expected by the GNU assembler, which comes
  1182. with the \key{gcc} compiler that we use for compiling assembly code to
  1183. machine code.
  1184. %
  1185. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1186. the x86 instructions used in this book.
  1187. % to do: finish treatment of imulq
  1188. % it's needed for vector's in R6/R7
  1189. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1190. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1191. && \key{r8} \mid \key{r9} \mid \key{r10}
  1192. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1193. \mid \key{r14} \mid \key{r15}}
  1194. \begin{figure}[tp]
  1195. \fbox{
  1196. \begin{minipage}{0.96\textwidth}
  1197. \[
  1198. \begin{array}{lcl}
  1199. \Reg &::=& \allregisters{} \\
  1200. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1201. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1202. \key{subq} \; \Arg\key{,} \Arg \mid
  1203. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1204. && \key{callq} \; \mathit{label} \mid
  1205. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1206. && \itm{label}\key{:}\; \Instr \\
  1207. x86_0 &::= & \key{.globl main}\\
  1208. & & \key{main:} \; \Instr\ldots
  1209. \end{array}
  1210. \]
  1211. \end{minipage}
  1212. }
  1213. \caption{The syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1214. \label{fig:x86-0-concrete}
  1215. \end{figure}
  1216. An immediate value is written using the notation \key{\$}$n$ where $n$
  1217. is an integer.
  1218. %
  1219. A register is written with a \key{\%} followed by the register name,
  1220. such as \key{\%rax}.
  1221. %
  1222. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1223. which obtains the address stored in register $r$ and then adds $n$
  1224. bytes to the address. The resulting address is used to either load or
  1225. store to memory depending on whether it occurs as a source or
  1226. destination argument of an instruction.
  1227. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1228. source $s$ and destination $d$, applies the arithmetic operation, then
  1229. writes the result back to the destination $d$.
  1230. %
  1231. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1232. stores the result in $d$.
  1233. %
  1234. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1235. specified by the label and $\key{retq}$ returns from a procedure to
  1236. its caller. The abstract syntax for \code{callq} includes an extra
  1237. integer field that represents the arity (number of parameters) of the
  1238. function being called.
  1239. %
  1240. We discuss procedure calls in more detail later in this
  1241. chapter and in Chapter~\ref{ch:functions}. The
  1242. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1243. the address of the instruction after the specified label.
  1244. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1245. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1246. \key{main} procedure is externally visible, which is necessary so
  1247. that the operating system can call it. The label \key{main:}
  1248. indicates the beginning of the \key{main} procedure which is where
  1249. the operating system starts executing this program. The instruction
  1250. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1251. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1252. $10$ in \key{rax} and puts the result, $42$, back into
  1253. \key{rax}.
  1254. %
  1255. The last instruction, \key{retq}, finishes the \key{main} function by
  1256. returning the integer in \key{rax} to the operating system. The
  1257. operating system interprets this integer as the program's exit
  1258. code. By convention, an exit code of 0 indicates that a program
  1259. completed successfully, and all other exit codes indicate various
  1260. errors. Nevertheless, we return the result of the program as the exit
  1261. code.
  1262. %\begin{wrapfigure}{r}{2.25in}
  1263. \begin{figure}[tbp]
  1264. \begin{lstlisting}
  1265. .globl main
  1266. main:
  1267. movq $10, %rax
  1268. addq $32, %rax
  1269. retq
  1270. \end{lstlisting}
  1271. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1272. \label{fig:p0-x86}
  1273. %\end{wrapfigure}
  1274. \end{figure}
  1275. Unfortunately, x86 varies in a couple ways depending on what operating
  1276. system it is assembled in. The code examples shown here are correct on
  1277. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1278. labels like \key{main} must be prefixed with an underscore, as in
  1279. \key{\_main}.
  1280. We exhibit the use of memory for storing intermediate results in the
  1281. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1282. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1283. memory called the \emph{procedure call stack} (or \emph{stack} for
  1284. short). \index{stack}\index{procedure call stack} The stack consists
  1285. of a separate \emph{frame}\index{frame} for each procedure call. The
  1286. memory layout for an individual frame is shown in
  1287. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1288. \emph{stack pointer}\index{stack pointer} and points to the item at
  1289. the top of the stack. The stack grows downward in memory, so we
  1290. increase the size of the stack by subtracting from the stack pointer.
  1291. In the context of a procedure call, the \emph{return
  1292. address}\index{return address} is the instruction after the call
  1293. instruction on the caller side. The function call inststruction,
  1294. \code{callq}, pushes the return address onto the stack. The register
  1295. \key{rbp} is the \emph{base pointer}\index{base pointer} and is used
  1296. to access variables associated with the current procedure call. The
  1297. base pointer of the caller is pushed onto the stack after the return
  1298. address. We number the variables from $1$ to $n$. Variable $1$ is
  1299. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1300. $-16\key{(\%rbp)}$, etc.
  1301. \begin{figure}[tbp]
  1302. \begin{lstlisting}
  1303. start:
  1304. movq $10, -8(%rbp)
  1305. negq -8(%rbp)
  1306. movq -8(%rbp), %rax
  1307. addq $52, %rax
  1308. jmp conclusion
  1309. .globl main
  1310. main:
  1311. pushq %rbp
  1312. movq %rsp, %rbp
  1313. subq $16, %rsp
  1314. jmp start
  1315. conclusion:
  1316. addq $16, %rsp
  1317. popq %rbp
  1318. retq
  1319. \end{lstlisting}
  1320. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1321. \label{fig:p1-x86}
  1322. \end{figure}
  1323. \begin{figure}[tbp]
  1324. \centering
  1325. \begin{tabular}{|r|l|} \hline
  1326. Position & Contents \\ \hline
  1327. 8(\key{\%rbp}) & return address \\
  1328. 0(\key{\%rbp}) & old \key{rbp} \\
  1329. -8(\key{\%rbp}) & variable $1$ \\
  1330. -16(\key{\%rbp}) & variable $2$ \\
  1331. \ldots & \ldots \\
  1332. 0(\key{\%rsp}) & variable $n$\\ \hline
  1333. \end{tabular}
  1334. \caption{Memory layout of a frame.}
  1335. \label{fig:frame}
  1336. \end{figure}
  1337. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1338. control is transfered from the operating system to the \code{main}
  1339. function. The operating system issues a \code{callq main} instruction
  1340. which pushes its return address on the stack and then jumps to
  1341. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1342. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1343. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1344. alignment (because the \code{callq} pushed the return address). The
  1345. first three instructions are the typical \emph{prelude}\index{prelude}
  1346. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1347. pointer for the caller onto the stack and subtracts $8$ from the stack
  1348. pointer. At this point the stack pointer is back to being 16-byte
  1349. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1350. base pointer so that it points the location of the old base
  1351. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1352. pointer down to make enough room for storing variables. This program
  1353. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1354. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1355. we are ready to make calls to other functions. The last instruction of
  1356. the prelude is \code{jmp start}, which transfers control to the
  1357. instructions that were generated from the Racket expression \code{(+
  1358. 10 32)}.
  1359. The four instructions under the label \code{start} carry out the work
  1360. of computing \code{(+ 52 (- 10)))}.
  1361. %
  1362. The first instruction \code{movq \$10, -8(\%rbp)} stores $10$ in
  1363. variable $1$.
  1364. %
  1365. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1366. %
  1367. The following instruction moves the $-10$ from variable $1$ into the
  1368. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1369. the value in \code{rax}, updating its contents to $42$.
  1370. The three instructions under the label \code{conclusion} are the
  1371. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1372. two instructions are necessary to get the state of the machine back to
  1373. where it was at the beginning of the procedure. The instruction
  1374. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1375. old base pointer. The amount added here needs to match the amount that
  1376. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1377. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1378. pointer. The last instruction, \key{retq}, jumps back to the
  1379. procedure that called this one and adds 8 to the stack pointer, which
  1380. returns the stack pointer to where it was prior to the procedure call.
  1381. The compiler needs a convenient representation for manipulating x86
  1382. programs, so we define an abstract syntax for x86 in
  1383. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1384. a subscript $0$ because later we introduce extended versions of this
  1385. assembly language. The main difference compared to the concrete syntax
  1386. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1387. labeled instructions to appear anywhere, but instead organizes
  1388. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1389. and associates a label with every block, which is why the \key{CFG} struct
  1390. (for control-flow graph) includes an alist mapping labels to
  1391. blocks. The reason for this organization becomes apparent in
  1392. Chapter~\ref{ch:bool-types} when we introduce conditional
  1393. branching. The \code{Block} structure includes an $\itm{info}$ field
  1394. that is not needed for this chapter, but will become useful in
  1395. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1396. field should just contain an empty list.
  1397. \begin{figure}[tp]
  1398. \fbox{
  1399. \begin{minipage}{0.96\textwidth}
  1400. \small
  1401. \[
  1402. \begin{array}{lcl}
  1403. \Reg &::=& \allregisters{} \\
  1404. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1405. \mid \DEREF{\Reg}{\Int} \\
  1406. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1407. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1408. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1409. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1410. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1411. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1412. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1413. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1414. \end{array}
  1415. \]
  1416. \end{minipage}
  1417. }
  1418. \caption{The abstract syntax of x86$_0$ assembly.}
  1419. \label{fig:x86-0-ast}
  1420. \end{figure}
  1421. \section{Planning the trip to x86 via the $C_0$ language}
  1422. \label{sec:plan-s0-x86}
  1423. To compile one language to another it helps to focus on the
  1424. differences between the two languages because the compiler will need
  1425. to bridge those differences. What are the differences between $R_1$
  1426. and x86 assembly? Here are some of the most important ones:
  1427. \begin{enumerate}
  1428. \item[(a)] x86 arithmetic instructions typically have two arguments
  1429. and update the second argument in place. In contrast, $R_1$
  1430. arithmetic operations take two arguments and produce a new value.
  1431. An x86 instruction may have at most one memory-accessing argument.
  1432. Furthermore, some instructions place special restrictions on their
  1433. arguments.
  1434. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1435. whereas x86 instructions restrict their arguments to be integers
  1436. constants, registers, and memory locations.
  1437. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1438. sequence of instructions and jumps to labeled positions, whereas in
  1439. $R_1$ the order of evaluation is a left-to-right depth-first
  1440. traversal of the abstract syntax tree.
  1441. \item[(d)] An $R_1$ program can have any number of variables whereas
  1442. x86 has 16 registers and the procedure calls stack.
  1443. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1444. same name. The registers and memory locations of x86 all have unique
  1445. names or addresses.
  1446. \end{enumerate}
  1447. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1448. the problem into several steps, dealing with the above differences one
  1449. at a time. Each of these steps is called a \emph{pass} of the
  1450. compiler.\index{pass}\index{compiler pass}
  1451. %
  1452. This terminology comes from each step traverses (i.e. passes over) the
  1453. AST of the program.
  1454. %
  1455. We begin by sketching how we might implement each pass, and give them
  1456. names. We then figure out an ordering of the passes and the
  1457. input/output language for each pass. The very first pass has $R_1$ as
  1458. its input language and the last pass has x86 as its output
  1459. language. In between we can choose whichever language is most
  1460. convenient for expressing the output of each pass, whether that be
  1461. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1462. Finally, to implement each pass we write one recursive function per
  1463. non-terminal in the grammar of the input language of the pass.
  1464. \index{intermediate language}
  1465. \begin{description}
  1466. \item[Pass \key{select-instructions}] To handle the difference between
  1467. $R_1$ operations and x86 instructions we convert each $R_1$
  1468. operation to a short sequence of instructions that accomplishes the
  1469. same task.
  1470. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1471. subexpression (i.e. operator and operand, and hence the name
  1472. \key{opera*}) is an \emph{atomic} expression (a variable or
  1473. integer), we introduce temporary variables to hold the results
  1474. of subexpressions.\index{atomic expression}
  1475. \item[Pass \key{explicate-control}] To make the execution order of the
  1476. program explicit, we convert from the abstract syntax tree
  1477. representation into a control-flow graph in which each node
  1478. contains a sequence of statements and the edges between nodes say
  1479. where to go at the end of the sequence.
  1480. \item[Pass \key{assign-homes}] To handle the difference between the
  1481. variables in $R_1$ versus the registers and stack locations in x86,
  1482. we map each variable to a register or stack location.
  1483. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1484. by renaming every variable to a unique name, so that shadowing no
  1485. longer occurs.
  1486. \end{description}
  1487. The next question is: in what order should we apply these passes? This
  1488. question can be challenging because it is difficult to know ahead of
  1489. time which orders will be better (easier to implement, produce more
  1490. efficient code, etc.) so oftentimes trial-and-error is
  1491. involved. Nevertheless, we can try to plan ahead and make educated
  1492. choices regarding the ordering.
  1493. Let us consider the ordering of \key{uniquify} and
  1494. \key{remove-complex-opera*}. The assignment of subexpressions to
  1495. temporary variables involves introducing new variables and moving
  1496. subexpressions, which might change the shadowing of variables and
  1497. inadvertently change the behavior of the program. But if we apply
  1498. \key{uniquify} first, this will not be an issue. Of course, this means
  1499. that in \key{remove-complex-opera*}, we need to ensure that the
  1500. temporary variables that it creates are unique.
  1501. What should be the ordering of \key{explicate-control} with respect to
  1502. \key{uniquify}? The \key{uniquify} pass should come first because
  1503. \key{explicate-control} changes all the \key{let}-bound variables to
  1504. become local variables whose scope is the entire program, which would
  1505. confuse variables with the same name.
  1506. %
  1507. Likewise, we place \key{explicate-control} after
  1508. \key{remove-complex-opera*} because \key{explicate-control} removes
  1509. the \key{let} form, but it is convenient to use \key{let} in the
  1510. output of \key{remove-complex-opera*}.
  1511. %
  1512. Regarding \key{assign-homes}, it is helpful to place
  1513. \key{explicate-control} first because \key{explicate-control} changes
  1514. \key{let}-bound variables into program-scope variables. This means
  1515. that the \key{assign-homes} pass can read off the variables from the
  1516. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1517. entire program in search of \key{let}-bound variables.
  1518. Last, we need to decide on the ordering of \key{select-instructions}
  1519. and \key{assign-homes}. These two passes are intertwined, creating a
  1520. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1521. have already determined which instructions will be used, because x86
  1522. instructions have restrictions about which of their arguments can be
  1523. registers versus stack locations. One might want to give preferential
  1524. treatment to variables that occur in register-argument positions. On
  1525. the other hand, it may turn out to be impossible to make sure that all
  1526. such variables are assigned to registers, and then one must redo the
  1527. selection of instructions. Some compilers handle this problem by
  1528. iteratively repeating these two passes until a good solution is found.
  1529. We use a simpler approach in which \key{select-instructions}
  1530. comes first, followed by the \key{assign-homes}, then a third
  1531. pass named \key{patch-instructions} that uses a reserved register to
  1532. patch-up outstanding problems regarding instructions with too many
  1533. memory accesses. The disadvantage of this approach is some programs
  1534. may not execute as efficiently as they would if we used the iterative
  1535. approach and used all of the registers for variables.
  1536. \begin{figure}[tbp]
  1537. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1538. \node (R1) at (0,2) {\large $R_1$};
  1539. \node (R1-2) at (3,2) {\large $R_1$};
  1540. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1541. %\node (C0-1) at (6,0) {\large $C_0$};
  1542. \node (C0-2) at (3,0) {\large $C_0$};
  1543. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1544. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1545. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1546. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1547. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1548. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1549. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1550. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1551. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1552. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1553. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1554. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1555. \end{tikzpicture}
  1556. \caption{Overview of the passes for compiling $R_1$. }
  1557. \label{fig:R1-passes}
  1558. \end{figure}
  1559. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1560. passes in the form of a graph. Each pass is an edge and the
  1561. input/output language of each pass is a node in the graph. The output
  1562. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1563. are still in the $R_1$ language, but the output of the pass
  1564. \key{explicate-control} is in a different language $C_0$ that is
  1565. designed to make the order of evaluation explicit in its syntax, which
  1566. we introduce in the next section. The \key{select-instruction} pass
  1567. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1568. \key{patch-instructions} passes input and output variants of x86
  1569. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1570. \key{print-x86}, which converts from the abstract syntax of
  1571. $\text{x86}_0$ to the concrete syntax of x86.
  1572. In the next sections we discuss the $C_0$ language and the
  1573. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1574. remainder of this chapter gives hints regarding the implementation of
  1575. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1576. \subsection{The $C_0$ Intermediate Language}
  1577. The output of \key{explicate-control} is similar to the $C$
  1578. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1579. categories for expressions and statements, so we name it $C_0$. The
  1580. concrete syntax for $C_0$ is defined in
  1581. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1582. is defined in Figure~\ref{fig:c0-syntax}.
  1583. %
  1584. The $C_0$ language supports the same operators as $R_1$ but the
  1585. arguments of operators are restricted to atomic expressions (variables
  1586. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1587. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1588. executed in sequence using the \key{Seq} form. A sequence of
  1589. statements always ends with \key{Return}, a guarantee that is baked
  1590. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1591. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1592. which refers to an expression that is the last one to execute within a
  1593. function. (An expression in tail position may contain subexpressions,
  1594. and those may or may not be in tail position depending on the kind of
  1595. expression.)
  1596. A $C_0$ program consists of a control-flow graph (represented as an
  1597. alist mapping labels to tails). This is more general than
  1598. necessary for the present chapter, as we do not yet need to introduce
  1599. \key{goto} for jumping to labels, but it saves us from having to
  1600. change the syntax of the program construct in
  1601. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1602. \key{start}, and the whole program is its tail.
  1603. %
  1604. The $\itm{info}$ field of the \key{Program} form, after the
  1605. \key{explicate-control} pass, contains a mapping from the symbol
  1606. \key{locals} to a list of variables, that is, a list of all the
  1607. variables used in the program. At the start of the program, these
  1608. variables are uninitialized; they become initialized on their first
  1609. assignment.
  1610. \begin{figure}[tbp]
  1611. \fbox{
  1612. \begin{minipage}{0.96\textwidth}
  1613. \[
  1614. \begin{array}{lcl}
  1615. \Atm &::=& \Int \mid \Var \\
  1616. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1617. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1618. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1619. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1620. \end{array}
  1621. \]
  1622. \end{minipage}
  1623. }
  1624. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1625. \label{fig:c0-concrete-syntax}
  1626. \end{figure}
  1627. \begin{figure}[tbp]
  1628. \fbox{
  1629. \begin{minipage}{0.96\textwidth}
  1630. \[
  1631. \begin{array}{lcl}
  1632. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1633. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1634. &\mid& \ADD{\Atm}{\Atm}\\
  1635. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1636. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1637. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1638. \end{array}
  1639. \]
  1640. \end{minipage}
  1641. }
  1642. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1643. \label{fig:c0-syntax}
  1644. \end{figure}
  1645. \subsection{The dialects of x86}
  1646. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1647. the pass \key{select-instructions}. It extends x86$_0$ with an
  1648. unbounded number of program-scope variables and has looser rules
  1649. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1650. output of \key{print-x86}, is the concrete syntax for x86.
  1651. \section{Uniquify Variables}
  1652. \label{sec:uniquify-s0}
  1653. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1654. programs in which every \key{let} uses a unique variable name. For
  1655. example, the \code{uniquify} pass should translate the program on the
  1656. left into the program on the right. \\
  1657. \begin{tabular}{lll}
  1658. \begin{minipage}{0.4\textwidth}
  1659. \begin{lstlisting}
  1660. (let ([x 32])
  1661. (+ (let ([x 10]) x) x))
  1662. \end{lstlisting}
  1663. \end{minipage}
  1664. &
  1665. $\Rightarrow$
  1666. &
  1667. \begin{minipage}{0.4\textwidth}
  1668. \begin{lstlisting}
  1669. (let ([x.1 32])
  1670. (+ (let ([x.2 10]) x.2) x.1))
  1671. \end{lstlisting}
  1672. \end{minipage}
  1673. \end{tabular} \\
  1674. %
  1675. The following is another example translation, this time of a program
  1676. with a \key{let} nested inside the initializing expression of another
  1677. \key{let}.\\
  1678. \begin{tabular}{lll}
  1679. \begin{minipage}{0.4\textwidth}
  1680. \begin{lstlisting}
  1681. (let ([x (let ([x 4])
  1682. (+ x 1))])
  1683. (+ x 2))
  1684. \end{lstlisting}
  1685. \end{minipage}
  1686. &
  1687. $\Rightarrow$
  1688. &
  1689. \begin{minipage}{0.4\textwidth}
  1690. \begin{lstlisting}
  1691. (let ([x.2 (let ([x.1 4])
  1692. (+ x.1 1))])
  1693. (+ x.2 2))
  1694. \end{lstlisting}
  1695. \end{minipage}
  1696. \end{tabular}
  1697. We recommend implementing \code{uniquify} by creating a function named
  1698. \code{uniquify-exp} that is structurally recursive function and mostly
  1699. just copies the input program. However, when encountering a \key{let},
  1700. it should generate a unique name for the variable (the Racket function
  1701. \code{gensym} is handy for this) and associate the old name with the
  1702. new unique name in an alist. The \code{uniquify-exp}
  1703. function will need to access this alist when it gets to a
  1704. variable reference, so we add another parameter to \code{uniquify-exp}
  1705. for the alist.
  1706. The skeleton of the \code{uniquify-exp} function is shown in
  1707. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1708. convenient to partially apply it to a symbol table and then apply it
  1709. to different expressions, as in the last clause for primitive
  1710. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1711. form is useful for applying a function to each element of a list to produce
  1712. a new list.
  1713. \index{for/list}
  1714. \begin{exercise}
  1715. \normalfont % I don't like the italics for exercises. -Jeremy
  1716. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1717. implement the clauses for variables and for the \key{let} form.
  1718. \end{exercise}
  1719. \begin{figure}[tbp]
  1720. \begin{lstlisting}
  1721. (define (uniquify-exp symtab)
  1722. (lambda (e)
  1723. (match e
  1724. [(Var x) ___]
  1725. [(Int n) (Int n)]
  1726. [(Let x e body) ___]
  1727. [(Prim op es)
  1728. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1729. )))
  1730. (define (uniquify p)
  1731. (match p
  1732. [(Program '() e)
  1733. (Program '() ((uniquify-exp '()) e))]
  1734. )))
  1735. \end{lstlisting}
  1736. \caption{Skeleton for the \key{uniquify} pass.}
  1737. \label{fig:uniquify-s0}
  1738. \end{figure}
  1739. \begin{exercise}
  1740. \normalfont % I don't like the italics for exercises. -Jeremy
  1741. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1742. and checking whether the output programs produce the same result as
  1743. the input programs. The $R_1$ programs should be designed to test the
  1744. most interesting parts of the \key{uniquify} pass, that is, the
  1745. programs should include \key{let} forms, variables, and variables that
  1746. overshadow each other. The five programs should be in a subdirectory
  1747. named \key{tests} and they should have the same file name except for a
  1748. different integer at the end of the name, followed by the ending
  1749. \key{.rkt}. Use the \key{interp-tests} function
  1750. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1751. your \key{uniquify} pass on the example programs. See the
  1752. \key{run-tests.rkt} script in the support code for an example of how
  1753. to use \key{interp-tests}. The support code is in a \code{github}
  1754. repository at the following URL:
  1755. \begin{center}\footnotesize
  1756. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1757. \end{center}
  1758. \end{exercise}
  1759. \section{Remove Complex Operands}
  1760. \label{sec:remove-complex-opera-R1}
  1761. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1762. $R_1$ programs in which the arguments of operations are atomic
  1763. expressions. Put another way, this pass removes complex
  1764. operands\index{complex operand}, such as the expression \code{(- 10)}
  1765. in the program below. This is accomplished by introducing a new
  1766. \key{let}-bound variable, binding the complex operand to the new
  1767. variable, and then using the new variable in place of the complex
  1768. operand, as shown in the output of \code{remove-complex-opera*} on the
  1769. right.\\
  1770. \begin{tabular}{lll}
  1771. \begin{minipage}{0.4\textwidth}
  1772. % s0_19.rkt
  1773. \begin{lstlisting}
  1774. (+ 52 (- 10))
  1775. \end{lstlisting}
  1776. \end{minipage}
  1777. &
  1778. $\Rightarrow$
  1779. &
  1780. \begin{minipage}{0.4\textwidth}
  1781. \begin{lstlisting}
  1782. (let ([tmp.1 (- 10)])
  1783. (+ 52 tmp.1))
  1784. \end{lstlisting}
  1785. \end{minipage}
  1786. \end{tabular}
  1787. \begin{figure}[tp]
  1788. \centering
  1789. \fbox{
  1790. \begin{minipage}{0.96\textwidth}
  1791. \[
  1792. \begin{array}{rcl}
  1793. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1794. \Exp &::=& \Atm \mid \READ{} \\
  1795. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1796. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1797. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1798. \end{array}
  1799. \]
  1800. \end{minipage}
  1801. }
  1802. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1803. \label{fig:r1-anf-syntax}
  1804. \end{figure}
  1805. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1806. this pass, language $R_1^{\dagger}$. The main difference is that
  1807. operator arguments are required to be atomic expressions. In the
  1808. literature, this is called \emph{administrative normal form}, or ANF
  1809. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1810. \index{administrative normal form}
  1811. \index{ANF}
  1812. We recommend implementing this pass with two mutually recursive
  1813. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1814. \code{rco-atom} to subexpressions that are required to be atomic and
  1815. to apply \code{rco-exp} to subexpressions that can be atomic or
  1816. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1817. $R_1$ expression as input. The \code{rco-exp} function returns an
  1818. expression. The \code{rco-atom} function returns two things: an
  1819. atomic expression and alist mapping temporary variables to complex
  1820. subexpressions. You can return multiple things from a function using
  1821. Racket's \key{values} form and you can receive multiple things from a
  1822. function call using the \key{define-values} form. If you are not
  1823. familiar with these features, review the Racket documentation. Also,
  1824. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1825. form is useful for applying a function to each
  1826. element of a list, in the case where the function returns multiple
  1827. values.
  1828. \index{for/lists}
  1829. The following shows the output of \code{rco-atom} on the expression
  1830. \code{(- 10)} (using concrete syntax to be concise).
  1831. \begin{tabular}{lll}
  1832. \begin{minipage}{0.4\textwidth}
  1833. \begin{lstlisting}
  1834. (- 10)
  1835. \end{lstlisting}
  1836. \end{minipage}
  1837. &
  1838. $\Rightarrow$
  1839. &
  1840. \begin{minipage}{0.4\textwidth}
  1841. \begin{lstlisting}
  1842. tmp.1
  1843. ((tmp.1 . (- 10)))
  1844. \end{lstlisting}
  1845. \end{minipage}
  1846. \end{tabular}
  1847. Take special care of programs such as the next one that \key{let}-bind
  1848. variables with integers or other variables. You should leave them
  1849. unchanged, as shown in to the program on the right \\
  1850. \begin{tabular}{lll}
  1851. \begin{minipage}{0.4\textwidth}
  1852. % s0_20.rkt
  1853. \begin{lstlisting}
  1854. (let ([a 42])
  1855. (let ([b a])
  1856. b))
  1857. \end{lstlisting}
  1858. \end{minipage}
  1859. &
  1860. $\Rightarrow$
  1861. &
  1862. \begin{minipage}{0.4\textwidth}
  1863. \begin{lstlisting}
  1864. (let ([a 42])
  1865. (let ([b a])
  1866. b))
  1867. \end{lstlisting}
  1868. \end{minipage}
  1869. \end{tabular} \\
  1870. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1871. produce the following output.\\
  1872. \begin{minipage}{0.4\textwidth}
  1873. \begin{lstlisting}
  1874. (let ([tmp.1 42])
  1875. (let ([a tmp.1])
  1876. (let ([tmp.2 a])
  1877. (let ([b tmp.2])
  1878. b))))
  1879. \end{lstlisting}
  1880. \end{minipage}
  1881. \begin{exercise}
  1882. \normalfont Implement the \code{remove-complex-opera*} pass.
  1883. Test the new pass on all of the example programs that you created to test the
  1884. \key{uniquify} pass and create three new example programs that are
  1885. designed to exercise the interesting code in the
  1886. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1887. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1888. your passes on the example programs.
  1889. \end{exercise}
  1890. \section{Explicate Control}
  1891. \label{sec:explicate-control-r1}
  1892. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1893. programs that make the order of execution explicit in their
  1894. syntax. For now this amounts to flattening \key{let} constructs into a
  1895. sequence of assignment statements. For example, consider the following
  1896. $R_1$ program.\\
  1897. % s0_11.rkt
  1898. \begin{minipage}{0.96\textwidth}
  1899. \begin{lstlisting}
  1900. (let ([y (let ([x 20])
  1901. (+ x (let ([x 22]) x)))])
  1902. y)
  1903. \end{lstlisting}
  1904. \end{minipage}\\
  1905. %
  1906. The output of the previous pass and of \code{explicate-control} is
  1907. shown below. Recall that the right-hand-side of a \key{let} executes
  1908. before its body, so the order of evaluation for this program is to
  1909. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1910. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1911. output of \code{explicate-control} makes this ordering explicit.\\
  1912. \begin{tabular}{lll}
  1913. \begin{minipage}{0.4\textwidth}
  1914. \begin{lstlisting}
  1915. (let ([y (let ([x.1 20])
  1916. (let ([x.2 22])
  1917. (+ x.1 x.2)))])
  1918. y)
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. &
  1922. $\Rightarrow$
  1923. &
  1924. \begin{minipage}{0.4\textwidth}
  1925. \begin{lstlisting}
  1926. start:
  1927. x.1 = 20;
  1928. x.2 = 22;
  1929. y = (+ x.1 x.2);
  1930. return y;
  1931. \end{lstlisting}
  1932. \end{minipage}
  1933. \end{tabular}
  1934. We recommend implementing \code{explicate-control} using two mutually
  1935. recursive functions: \code{explicate-tail} and
  1936. \code{explicate-assign}. The first function should be applied to
  1937. expressions in tail position whereas the second should be applied to
  1938. expressions that occur on the right-hand-side of a \key{let}.
  1939. %
  1940. The \code{explicate-tail} function takes an $R_1$ expression as input
  1941. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}).
  1942. %
  1943. The \code{explicate-assign} function takes an $R_1$ expression, the
  1944. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1945. should come after the assignment (e.g., the code generated for the
  1946. body of the \key{let}) and returns a $\Tail$. The
  1947. \code{explicate-assign} function is in accumulator-passing style in
  1948. that its third parameter is some $C_0$ code that it adds to and
  1949. returns. The reader might be tempted to instead organize
  1950. \code{explicate-assign} in a more direct fashion, without the third
  1951. parameter and perhaps using \code{append} to combine statements. We
  1952. warn against that alternative because the accumulator-passing style is
  1953. key to how we generate high-quality code for conditional expressions
  1954. in Chapter~\ref{ch:bool-types}.
  1955. The top-level \code{explicate-control} function should invoke
  1956. \code{explicate-tail} on the body of the \key{Program} AST node.
  1957. \section{Select Instructions}
  1958. \label{sec:select-r1}
  1959. \index{instruction selection}
  1960. In the \code{select-instructions} pass we begin the work of
  1961. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1962. this pass is a variant of x86 that still uses variables, so we add an
  1963. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1964. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1965. \code{select-instructions} in terms of three auxiliary functions, one
  1966. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1967. The cases for $\Atm$ are straightforward, variables stay
  1968. the same and integer constants are changed to immediates:
  1969. $\INT{n}$ changes to $\IMM{n}$.
  1970. Next we consider the cases for $\Stmt$, starting with arithmetic
  1971. operations. For example, in $C_0$ an addition operation can take the
  1972. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1973. need to use the \key{addq} instruction which does an in-place
  1974. update. So we must first move \code{10} to \code{x}. \\
  1975. \begin{tabular}{lll}
  1976. \begin{minipage}{0.4\textwidth}
  1977. \begin{lstlisting}
  1978. x = (+ 10 32);
  1979. \end{lstlisting}
  1980. \end{minipage}
  1981. &
  1982. $\Rightarrow$
  1983. &
  1984. \begin{minipage}{0.4\textwidth}
  1985. \begin{lstlisting}
  1986. movq $10, x
  1987. addq $32, x
  1988. \end{lstlisting}
  1989. \end{minipage}
  1990. \end{tabular} \\
  1991. %
  1992. There are cases that require special care to avoid generating
  1993. needlessly complicated code. If one of the arguments of the addition
  1994. is the same as the left-hand side of the assignment, then there is no
  1995. need for the extra move instruction. For example, the following
  1996. assignment statement can be translated into a single \key{addq}
  1997. instruction.\\
  1998. \begin{tabular}{lll}
  1999. \begin{minipage}{0.4\textwidth}
  2000. \begin{lstlisting}
  2001. x = (+ 10 x);
  2002. \end{lstlisting}
  2003. \end{minipage}
  2004. &
  2005. $\Rightarrow$
  2006. &
  2007. \begin{minipage}{0.4\textwidth}
  2008. \begin{lstlisting}
  2009. addq $10, x
  2010. \end{lstlisting}
  2011. \end{minipage}
  2012. \end{tabular} \\
  2013. The \key{read} operation does not have a direct counterpart in x86
  2014. assembly, so we have instead implemented this functionality in the C
  2015. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2016. in the file \code{runtime.c}. In general, we refer to all of the
  2017. functionality in this file as the \emph{runtime system}\index{runtime system},
  2018. or simply the \emph{runtime} for short. When compiling your generated x86
  2019. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2020. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2021. the executable. For our purposes of code generation, all you need to
  2022. do is translate an assignment of \key{read} into some variable
  2023. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2024. function followed by a move from \code{rax} to the left-hand side.
  2025. The move from \code{rax} is needed because the return value from
  2026. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2027. \begin{tabular}{lll}
  2028. \begin{minipage}{0.3\textwidth}
  2029. \begin{lstlisting}
  2030. |$\itm{var}$| = (read);
  2031. \end{lstlisting}
  2032. \end{minipage}
  2033. &
  2034. $\Rightarrow$
  2035. &
  2036. \begin{minipage}{0.3\textwidth}
  2037. \begin{lstlisting}
  2038. callq read_int
  2039. movq %rax, |$\itm{var}$|
  2040. \end{lstlisting}
  2041. \end{minipage}
  2042. \end{tabular} \\
  2043. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2044. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2045. assignment to the \key{rax} register followed by a jump to the
  2046. conclusion of the program (so the conclusion needs to be labeled).
  2047. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2048. recursively and append the resulting instructions.
  2049. \begin{exercise}
  2050. \normalfont
  2051. Implement the \key{select-instructions} pass and test it on all of the
  2052. example programs that you created for the previous passes and create
  2053. three new example programs that are designed to exercise all of the
  2054. interesting code in this pass. Use the \key{interp-tests} function
  2055. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2056. your passes on the example programs.
  2057. \end{exercise}
  2058. \section{Assign Homes}
  2059. \label{sec:assign-r1}
  2060. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2061. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2062. Thus, the \key{assign-homes} pass is responsible for placing all of
  2063. the program variables in registers or on the stack. For runtime
  2064. efficiency, it is better to place variables in registers, but as there
  2065. are only 16 registers, some programs must necessarily resort to
  2066. placing some variables on the stack. In this chapter we focus on the
  2067. mechanics of placing variables on the stack. We study an algorithm for
  2068. placing variables in registers in
  2069. Chapter~\ref{ch:register-allocation-r1}.
  2070. Consider again the following $R_1$ program.
  2071. % s0_20.rkt
  2072. \begin{lstlisting}
  2073. (let ([a 42])
  2074. (let ([b a])
  2075. b))
  2076. \end{lstlisting}
  2077. For reference, we repeat the output of \code{select-instructions} on
  2078. the left and show the output of \code{assign-homes} on the right.
  2079. %
  2080. %% Recall that \key{explicate-control} associated the list of
  2081. %% variables with the \code{locals} symbol in the program's $\itm{info}$
  2082. %% field, so \code{assign-homes} has convenient access to the them.
  2083. %
  2084. In this example, we assign variable \code{a} to stack location
  2085. \code{-8(\%rbp)} and variable \code{b} to location
  2086. \code{-16(\%rbp)}.\\
  2087. \begin{tabular}{l}
  2088. \begin{minipage}{0.4\textwidth}
  2089. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2090. locals-types:
  2091. a : 'Integer, b : 'Integer
  2092. start:
  2093. movq $42, a
  2094. movq a, b
  2095. movq b, %rax
  2096. jmp conclusion
  2097. \end{lstlisting}
  2098. \end{minipage}
  2099. {$\Rightarrow$}
  2100. \begin{minipage}{0.4\textwidth}
  2101. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2102. stack-space: 16
  2103. start:
  2104. movq $42, -8(%rbp)
  2105. movq -8(%rbp), -16(%rbp)
  2106. movq -16(%rbp), %rax
  2107. jmp conclusion
  2108. \end{lstlisting}
  2109. \end{minipage}
  2110. \end{tabular} \\
  2111. In the output of \code{select-instructions}, there is a entry for
  2112. \code{locals-types} in the $\itm{info}$ of the \code{Program} node,
  2113. which is needed here so that we have the list of variables that should
  2114. be assigned to homes. The the support code computes the
  2115. \code{locals-types} entry. In particular, \code{type-check-C0}
  2116. installs it in the $\itm{info}$ field of the \code{Program} node.
  2117. When using \code{interp-tests} or \code{compiler-tests} (see Appendix,
  2118. Section~\ref{appendix:utilities}), specify \code{type-check-C0} as the
  2119. type checker to use after \code{explicate-control}.
  2120. In the process of assigning variables to stack locations, it is
  2121. convenient for you to compute and store the size of the frame (in
  2122. bytes) in the $\itm{info}$ field of the \key{Program} node, with the
  2123. key \code{stack-space}, which is needed later to generate the
  2124. conclusion of the \code{main} procedure. The x86-64 standard requires
  2125. the frame size to be a multiple of 16 bytes. \index{frame}
  2126. \begin{exercise}
  2127. \normalfont Implement the \key{assign-homes} pass and test it on all
  2128. of the example programs that you created for the previous passes pass.
  2129. We recommend that \key{assign-homes} take an extra parameter that is a
  2130. mapping of variable names to homes (stack locations for now). Use the
  2131. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2132. \key{utilities.rkt} to test your passes on the example programs.
  2133. \end{exercise}
  2134. \section{Patch Instructions}
  2135. \label{sec:patch-s0}
  2136. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2137. programs to $\text{x86}_0$ programs by making sure that each
  2138. instruction adheres to the restrictions of the x86 assembly language.
  2139. In particular, at most one argument of an instruction may be a memory
  2140. reference.
  2141. We return to the following running example.
  2142. % s0_20.rkt
  2143. \begin{lstlisting}
  2144. (let ([a 42])
  2145. (let ([b a])
  2146. b))
  2147. \end{lstlisting}
  2148. After the \key{assign-homes} pass, the above program has been translated to
  2149. the following. \\
  2150. \begin{minipage}{0.5\textwidth}
  2151. \begin{lstlisting}
  2152. stack-space: 16
  2153. start:
  2154. movq $42, -8(%rbp)
  2155. movq -8(%rbp), -16(%rbp)
  2156. movq -16(%rbp), %rax
  2157. jmp conclusion
  2158. \end{lstlisting}
  2159. \end{minipage}\\
  2160. The second \key{movq} instruction is problematic because both
  2161. arguments are stack locations. We suggest fixing this problem by
  2162. moving from the source location to the register \key{rax} and then
  2163. from \key{rax} to the destination location, as follows.
  2164. \begin{lstlisting}
  2165. movq -8(%rbp), %rax
  2166. movq %rax, -16(%rbp)
  2167. \end{lstlisting}
  2168. \begin{exercise}
  2169. \normalfont
  2170. Implement the \key{patch-instructions} pass and test it on all of the
  2171. example programs that you created for the previous passes and create
  2172. three new example programs that are designed to exercise all of the
  2173. interesting code in this pass. Use the \key{interp-tests} function
  2174. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2175. your passes on the example programs.
  2176. \end{exercise}
  2177. \section{Print x86}
  2178. \label{sec:print-x86}
  2179. The last step of the compiler from $R_1$ to x86 is to convert the
  2180. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2181. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2182. \key{format} and \key{string-append} functions are useful in this
  2183. regard. The main work that this step needs to perform is to create the
  2184. \key{main} function and the standard instructions for its prelude and
  2185. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2186. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2187. variables, so we suggest computing it in the \key{assign-homes} pass
  2188. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2189. of the \key{program} node.
  2190. %% Your compiled code should print the result of the program's execution
  2191. %% by using the \code{print\_int} function provided in
  2192. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2193. %% far, this final result should be stored in the \key{rax} register.
  2194. %% We'll talk more about how to perform function calls with arguments in
  2195. %% general later on, but for now, place the following after the compiled
  2196. %% code for the $R_1$ program but before the conclusion:
  2197. %% \begin{lstlisting}
  2198. %% movq %rax, %rdi
  2199. %% callq print_int
  2200. %% \end{lstlisting}
  2201. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2202. %% stores the first argument to be passed into \key{print\_int}.
  2203. If you want your program to run on Mac OS X, your code needs to
  2204. determine whether or not it is running on a Mac, and prefix
  2205. underscores to labels like \key{main}. You can determine the platform
  2206. with the Racket call \code{(system-type 'os)}, which returns
  2207. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2208. %% In addition to
  2209. %% placing underscores on \key{main}, you need to put them in front of
  2210. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2211. %% \_print\_int}).
  2212. \begin{exercise}
  2213. \normalfont Implement the \key{print-x86} pass and test it on all of
  2214. the example programs that you created for the previous passes. Use the
  2215. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2216. \key{utilities.rkt} to test your complete compiler on the example
  2217. programs. See the \key{run-tests.rkt} script in the student support
  2218. code for an example of how to use \key{compiler-tests}. Also, remember
  2219. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2220. \key{gcc}.
  2221. \end{exercise}
  2222. \section{Challenge: Partial Evaluator for $R_1$}
  2223. \label{sec:pe-R1}
  2224. \index{partial evaluation}
  2225. This section describes optional challenge exercises that involve
  2226. adapting and improving the partial evaluator for $R_0$ that was
  2227. introduced in Section~\ref{sec:partial-evaluation}.
  2228. \begin{exercise}\label{ex:pe-R1}
  2229. \normalfont
  2230. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2231. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2232. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2233. and variables to the $R_0$ language, so you will need to add cases for
  2234. them in the \code{pe-exp} function. Also, note that the \key{program}
  2235. form changes slightly to include an $\itm{info}$ field. Once
  2236. complete, add the partial evaluation pass to the front of your
  2237. compiler and make sure that your compiler still passes all of the
  2238. tests.
  2239. \end{exercise}
  2240. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2241. \begin{exercise}
  2242. \normalfont
  2243. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2244. \code{pe-add} auxiliary functions with functions that know more about
  2245. arithmetic. For example, your partial evaluator should translate
  2246. \begin{lstlisting}
  2247. (+ 1 (+ (read) 1))
  2248. \end{lstlisting}
  2249. into
  2250. \begin{lstlisting}
  2251. (+ 2 (read))
  2252. \end{lstlisting}
  2253. To accomplish this, the \code{pe-exp} function should produce output
  2254. in the form of the $\itm{residual}$ non-terminal of the following
  2255. grammar.
  2256. \[
  2257. \begin{array}{lcl}
  2258. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2259. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2260. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2261. \end{array}
  2262. \]
  2263. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2264. that their inputs are $\itm{residual}$ expressions and they should
  2265. return $\itm{residual}$ expressions. Once the improvements are
  2266. complete, make sure that your compiler still passes all of the tests.
  2267. After all, fast code is useless if it produces incorrect results!
  2268. \end{exercise}
  2269. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2270. \chapter{Register Allocation}
  2271. \label{ch:register-allocation-r1}
  2272. \index{register allocation}
  2273. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2274. make our life easier. However, we can improve the performance of the
  2275. generated code if we instead place some variables into registers. The
  2276. CPU can access a register in a single cycle, whereas accessing the
  2277. stack takes many cycles if the relevant data is in cache or many more
  2278. to access main memory if the data is not in cache.
  2279. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2280. serves as a running example. We show the source program and also the
  2281. output of instruction selection. At that point the program is almost
  2282. x86 assembly but not quite; it still contains variables instead of
  2283. stack locations or registers.
  2284. \begin{figure}
  2285. \begin{minipage}{0.45\textwidth}
  2286. Example $R_1$ program:
  2287. % s0_28.rkt
  2288. \begin{lstlisting}
  2289. (let ([v 1])
  2290. (let ([w 42])
  2291. (let ([x (+ v 7)])
  2292. (let ([y x])
  2293. (let ([z (+ x w)])
  2294. (+ z (- y)))))))
  2295. \end{lstlisting}
  2296. \end{minipage}
  2297. \begin{minipage}{0.45\textwidth}
  2298. After instruction selection:
  2299. \begin{lstlisting}
  2300. locals-types:
  2301. x : Integer, y : Integer,
  2302. z : Integer, t : Integer,
  2303. v : Integer, w : Integer
  2304. start:
  2305. movq $1, v
  2306. movq $42, w
  2307. movq v, x
  2308. addq $7, x
  2309. movq x, y
  2310. movq x, z
  2311. addq w, z
  2312. movq y, t
  2313. negq t
  2314. movq z, %rax
  2315. addq t, %rax
  2316. jmp conclusion
  2317. \end{lstlisting}
  2318. \end{minipage}
  2319. \caption{A running example program for register allocation.}
  2320. \label{fig:reg-eg}
  2321. \end{figure}
  2322. The goal of register allocation is to fit as many variables into
  2323. registers as possible. A program sometimes has more variables than
  2324. registers, so we cannot map each variable to a different
  2325. register. Fortunately, it is common for different variables to be
  2326. needed during different periods of time during program execution, and
  2327. in such cases several variables can be mapped to the same register.
  2328. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2329. After the variable \code{x} is moved to \code{z} it is no longer
  2330. needed. Variable \code{y}, on the other hand, is used only after this
  2331. point, so \code{x} and \code{y} could share the same register. The
  2332. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2333. where a variable is needed. Once we have that information, we compute
  2334. which variables are needed at the same time, i.e., which ones
  2335. \emph{interfere} with each other, and represent this relation as an
  2336. undirected graph whose vertices are variables and edges indicate when
  2337. two variables interfere (Section~\ref{sec:build-interference}). We
  2338. then model register allocation as a graph coloring problem, which we
  2339. discuss in Section~\ref{sec:graph-coloring}.
  2340. In the event that we run out of registers despite these efforts, we
  2341. place the remaining variables on the stack, similar to what we did in
  2342. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2343. for assigning a variable to a stack location. The process of spilling
  2344. variables is handled as part of the graph coloring process described
  2345. in \ref{sec:graph-coloring}.
  2346. We make the simplifying assumption that each variable is assigned to
  2347. one location (a register or stack address). A more sophisticated
  2348. approach is to assign a variable to one or more locations in different
  2349. regions of the program. For example, if a variable is used many times
  2350. in short sequence and then only used again after many other
  2351. instructions, it could be more efficient to assign the variable to a
  2352. register during the intial sequence and then move it to the stack for
  2353. the rest of its lifetime. We refer the interested reader to
  2354. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2355. about this approach.
  2356. % discuss prioritizing variables based on how much they are used.
  2357. \section{Registers and Calling Conventions}
  2358. \label{sec:calling-conventions}
  2359. \index{calling conventions}
  2360. As we perform register allocation, we need to be aware of the
  2361. \emph{calling conventions} \index{calling conventions} that govern how
  2362. functions calls are performed in x86. Function calls require
  2363. coordination between the caller and the callee, which is often
  2364. assembly code written by different programmers or generated by
  2365. different compilers. Here we follow the System V calling conventions
  2366. that are used by the \code{gcc} compiler on Linux and
  2367. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2368. %
  2369. Even though $R_1$ does not include programmer-defined functions, our
  2370. generated code will 1) include a \code{main} function that the
  2371. operating system will call to initiate execution, and 2) make calls to
  2372. the \code{read\_int} function in our runtime system.
  2373. The calling conventions include rules about how functions share the
  2374. use of registers. In particular, the caller is responsible for freeing
  2375. up some registers prior to the function call for use by the callee.
  2376. These are called the \emph{caller-saved registers}
  2377. \index{caller-saved registers}
  2378. and they are
  2379. \begin{lstlisting}
  2380. rax rcx rdx rsi rdi r8 r9 r10 r11
  2381. \end{lstlisting}
  2382. On the other hand, the callee is responsible for preserving the values
  2383. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2384. which are
  2385. \begin{lstlisting}
  2386. rsp rbp rbx r12 r13 r14 r15
  2387. \end{lstlisting}
  2388. We can think about this caller/callee convention from two points of
  2389. view, the caller view and the callee view:
  2390. \begin{itemize}
  2391. \item The caller should assume that all the caller-saved registers get
  2392. overwritten with arbitrary values by the callee. On the other hand,
  2393. the caller can safely assume that all the callee-saved registers
  2394. contain the same values after the call that they did before the
  2395. call.
  2396. \item The callee can freely use any of the caller-saved registers.
  2397. However, if the callee wants to use a callee-saved register, the
  2398. callee must arrange to put the original value back in the register
  2399. prior to returning to the caller, which is usually accomplished by
  2400. saving the value to the stack in the prelude of the function and
  2401. restoring the value in the conclusion of the function.
  2402. \end{itemize}
  2403. In x86, registers are also used for passing arguments to a function
  2404. and for the return value. In particular, the first six arguments of a
  2405. function are passed in the following six registers, in the order
  2406. given.
  2407. \begin{lstlisting}
  2408. rdi rsi rdx rcx r8 r9
  2409. \end{lstlisting}
  2410. If there are more than six arguments, then the convention is to use
  2411. space on the frame of the caller for the rest of the
  2412. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2413. need more than six arguments. For now, the only function we care about
  2414. is \code{read\_int} and it takes zero argument.
  2415. %
  2416. The register \code{rax} is for the return value of a function.
  2417. The next question is how these calling conventions impact register
  2418. allocation. Consider the $R_1$ program in
  2419. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2420. example from the caller point of view and then from the callee point
  2421. of view.
  2422. The program makes two calls to the \code{read} function. Also, the
  2423. variable \code{x} is in-use during the second call to \code{read}, so
  2424. we need to make sure that the value in \code{x} does not get
  2425. accidentally wiped out by the call to \code{read}. One obvious
  2426. approach is to save all the values in caller-saved registers to the
  2427. stack prior to each function call, and restore them after each
  2428. call. That way, if the register allocator chooses to assign \code{x}
  2429. to a caller-saved register, its value will be preserved accross the
  2430. call to \code{read}. However, the disadvantage of this approach is
  2431. that saving and restoring to the stack is relatively slow. If \code{x}
  2432. is not used many times, it may be better to assign \code{x} to a stack
  2433. location in the first place. Or better yet, if we can arrange for
  2434. \code{x} to be placed in a callee-saved register, then it won't need
  2435. to be saved and restored during function calls.
  2436. The approach that we recommend for variables that are in-use during a
  2437. function call is to either assign them to callee-saved registers or to
  2438. spill them to the stack. On the other hand, for variables that are not
  2439. in-use during a function call, we try the following alternatives in
  2440. order 1) look for an available caller-saved register (to leave room
  2441. for other variables in the callee-saved register), 2) look for a
  2442. callee-saved register, and 3) spill the variable to the stack.
  2443. It is straightforward to implement this approach in a graph coloring
  2444. register allocator. First, we know which variables are in-use during
  2445. every function call because we compute that information for every
  2446. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2447. build the interference graph (Section~\ref{sec:build-interference}),
  2448. we can place an edge between each of these variables and the
  2449. caller-saved registers in the interference graph. This will prevent
  2450. the graph coloring algorithm from assigning those variables to
  2451. caller-saved registers.
  2452. Returning to the example in
  2453. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2454. generated x86 code on the right-hand side, focusing on the
  2455. \code{start} block. Notice that variable \code{x} is assigned to
  2456. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2457. place during the second call to \code{read\_int}. Next, notice that
  2458. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2459. because there are no function calls in the remainder of the block.
  2460. Next we analyze the example from the callee point of view, focusing on
  2461. the prelude and conclusion of the \code{main} function. As usual the
  2462. prelude begins with saving the \code{rbp} register to the stack and
  2463. setting the \code{rbp} to the current stack pointer. We now know why
  2464. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2465. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2466. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2467. variable (\code{x}). There are several more callee-saved register that
  2468. are not saved in the prelude because they were not assigned to
  2469. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2470. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2471. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2472. from the stack with a \code{popq} instruction.
  2473. \index{prelude}\index{conclusion}
  2474. \begin{figure}[tp]
  2475. \begin{minipage}{0.45\textwidth}
  2476. Example $R_1$ program:
  2477. %s0_14.rkt
  2478. \begin{lstlisting}
  2479. (let ([x (read)])
  2480. (let ([y (read)])
  2481. (+ (+ x y) 42)))
  2482. \end{lstlisting}
  2483. \end{minipage}
  2484. \begin{minipage}{0.45\textwidth}
  2485. Generated x86 assembly:
  2486. \begin{lstlisting}
  2487. start:
  2488. callq read_int
  2489. movq %rax, %rbx
  2490. callq read_int
  2491. movq %rax, %rcx
  2492. addq %rcx, %rbx
  2493. movq %rbx, %rax
  2494. addq $42, %rax
  2495. jmp _conclusion
  2496. .globl main
  2497. main:
  2498. pushq %rbp
  2499. movq %rsp, %rbp
  2500. pushq %rbx
  2501. subq $8, %rsp
  2502. jmp start
  2503. conclusion:
  2504. addq $8, %rsp
  2505. popq %rbx
  2506. popq %rbp
  2507. retq
  2508. \end{lstlisting}
  2509. \end{minipage}
  2510. \caption{An example with function calls.}
  2511. \label{fig:example-calling-conventions}
  2512. \end{figure}
  2513. \clearpage
  2514. \section{Liveness Analysis}
  2515. \label{sec:liveness-analysis-r1}
  2516. \index{liveness analysis}
  2517. A variable or register is \emph{live} at a program point if its
  2518. current value is used at some later point in the program. We
  2519. refer to variables and registers collectively as \emph{locations}.
  2520. %
  2521. Consider the following code fragment in which there are two writes to
  2522. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2523. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2524. movq $5, a
  2525. movq $30, b
  2526. movq a, c
  2527. movq $10, b
  2528. addq b, c
  2529. \end{lstlisting}
  2530. The answer is no because the integer \code{30} written to \code{b} on
  2531. line 2 is never used. The variable \code{b} is read on line 5 and
  2532. there is an intervening write to \code{b} on line 4, so the read on
  2533. line 5 receives the value written on line 4, not line 2.
  2534. \begin{wrapfigure}[18]{l}[1.0in]{0.6\textwidth}
  2535. \small
  2536. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2537. A \emph{set} is an unordered collection of elements without duplicates.
  2538. \index{set}
  2539. \begin{description}
  2540. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2541. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2542. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2543. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2544. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2545. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2546. \end{description}
  2547. \end{tcolorbox}
  2548. \end{wrapfigure}
  2549. The live locations can be computed by traversing the instruction
  2550. sequence back to front (i.e., backwards in execution order). Let
  2551. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2552. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2553. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2554. locations before instruction $I_k$. The live locations after an
  2555. instruction are always the same as the live locations before the next
  2556. instruction. \index{live-after} \index{live-before}
  2557. \begin{equation} \label{eq:live-after-before-next}
  2558. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2559. \end{equation}
  2560. To start things off, there are no live locations after the last
  2561. instruction\footnote{Technically, the \code{rax} register is live
  2562. but we do not use it for register allocation.}, so
  2563. \begin{equation}\label{eq:live-last-empty}
  2564. L_{\mathsf{after}}(n) = \emptyset
  2565. \end{equation}
  2566. We then apply the following rule repeatedly, traversing the
  2567. instruction sequence back to front.
  2568. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2569. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2570. \end{equation}
  2571. where $W(k)$ are the locations written to by instruction $I_k$ and
  2572. $R(k)$ are the locations read by instruction $I_k$.
  2573. Let us walk through the above example, applying these formulas
  2574. starting with the instruction on line 5. We collect the answers in the
  2575. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2576. instruction is $\emptyset$ because it is the last instruction
  2577. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2578. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2579. variables \code{b} and \code{c}
  2580. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2581. \[
  2582. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2583. \]
  2584. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2585. the live-before set from line 5 to be the live-after set for this
  2586. instruction (formula~\ref{eq:live-after-before-next}).
  2587. \[
  2588. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2589. \]
  2590. This move instruction writes to \code{b} and does not read from any
  2591. variables, so we have the following live-before set
  2592. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2593. \[
  2594. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2595. \]
  2596. The live-before for instruction \code{movq a, c}
  2597. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2598. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2599. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2600. variable that is not live and does not read from a variable.
  2601. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2602. because it writes to variable \code{a}.
  2603. \begin{center}
  2604. \begin{minipage}{0.45\textwidth}
  2605. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2606. movq $5, a
  2607. movq $30, b
  2608. movq a, c
  2609. movq $10, b
  2610. addq b, c
  2611. \end{lstlisting}
  2612. \end{minipage}
  2613. \vrule\hspace{10pt}
  2614. \begin{minipage}{0.45\textwidth}
  2615. \begin{align*}
  2616. L_{\mathsf{before}}(1)= \emptyset,
  2617. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2618. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2619. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2620. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2621. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2622. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2623. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2624. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2625. L_{\mathsf{after}}(5)= \emptyset
  2626. \end{align*}
  2627. \end{minipage}
  2628. \end{center}
  2629. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2630. the running example program, with the live-before and live-after sets
  2631. shown between each instruction to make the figure easy to read.
  2632. \begin{figure}[tp]
  2633. \hspace{20pt}
  2634. \begin{minipage}{0.45\textwidth}
  2635. \begin{lstlisting}
  2636. |$\{\}$|
  2637. movq $1, v
  2638. |$\{\ttm{v}\}$|
  2639. movq $42, w
  2640. |$\{\ttm{v},\ttm{w}\}$|
  2641. movq v, x
  2642. |$\{\ttm{w},\ttm{x}\}$|
  2643. addq $7, x
  2644. |$\{\ttm{w},\ttm{x}\}$|
  2645. movq x, y
  2646. |$\{\ttm{w},\ttm{x},\ttm{y}\}$|
  2647. movq x, z
  2648. |$\{\ttm{w},\ttm{y},\ttm{z}\}$|
  2649. addq w, z
  2650. |$\{\ttm{y},\ttm{z}\}$|
  2651. movq y, t
  2652. |$\{\ttm{t},\ttm{z}\}$|
  2653. negq t
  2654. |$\{\ttm{t},\ttm{z}\}$|
  2655. movq z, %rax
  2656. |$\{\ttm{rax},\ttm{t}\}$|
  2657. addq t, %rax
  2658. |$\{\}$|
  2659. jmp conclusion
  2660. |$\{\}$|
  2661. \end{lstlisting}
  2662. \end{minipage}
  2663. \caption{The running example annotated with live-after sets.}
  2664. \label{fig:live-eg}
  2665. \end{figure}
  2666. \begin{exercise}\normalfont
  2667. Implement the compiler pass named \code{uncover-live} that computes
  2668. the live-after sets. We recommend storing the live-after sets (a list
  2669. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2670. structure.
  2671. %
  2672. We recommend organizing your code to use a helper function that takes
  2673. a list of instructions and an initial live-after set (typically empty)
  2674. and returns the list of live-after sets.
  2675. %
  2676. We recommend creating helper functions to 1) compute the set of
  2677. locations that appear in an argument (of an instruction), 2) compute
  2678. the locations read by an instruction which corresponds to the $R$
  2679. function discussed above, and 3) the locations written by an
  2680. instruction which corresponds to $W$. The \code{callq} instruction
  2681. should include all of the caller-saved registers in its write-set $W$
  2682. because the calling convention says that those registers may be
  2683. written to during the function call. Likewise, the \code{callq}
  2684. instruction should include the appropriate number of argument passing
  2685. registers in its read-set $R$, depending on the arity of the function
  2686. being called. (This is why the abstract syntax for \code{callq}
  2687. includes the arity.)
  2688. \end{exercise}
  2689. \section{Building the Interference Graph}
  2690. \label{sec:build-interference}
  2691. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2692. \small
  2693. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2694. A \emph{graph} is a collection of vertices and edges where each
  2695. edge connects two vertices. A graph is \emph{directed} if each
  2696. edge points from a source to a target. Otherwise the graph is
  2697. \emph{undirected}.
  2698. \index{graph}\index{directed graph}\index{undirected graph}
  2699. \begin{description}
  2700. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2701. directed graph from a list of edges. Each edge is a list
  2702. containing the source and target vertex.
  2703. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2704. undirected graph from a list of edges. Each edge is represented by
  2705. a list containing two vertices.
  2706. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2707. inserts a vertex into the graph.
  2708. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2709. inserts an edge between the two vertices into the graph.
  2710. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2711. returns a sequence of all the neighbors of the given vertex.
  2712. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2713. returns a sequence of all the vertices in the graph.
  2714. \end{description}
  2715. \end{tcolorbox}
  2716. \end{wrapfigure}
  2717. Based on the liveness analysis, we know where each variable is needed.
  2718. However, during register allocation, we need to answer questions of
  2719. the specific form: are variables $u$ and $v$ live at the same time?
  2720. (And therefore cannot be assigned to the same register.) To make this
  2721. question easier to answer, we create an explicit data structure, an
  2722. \emph{interference graph}\index{interference graph}. An interference
  2723. graph is an undirected graph that has an edge between two variables if
  2724. they are live at the same time, that is, if they interfere with each
  2725. other.
  2726. The most obvious way to compute the interference graph is to look at
  2727. the set of live location between each statement in the program and add
  2728. an edge to the graph for every pair of variables in the same set.
  2729. This approach is less than ideal for two reasons. First, it can be
  2730. expensive because it takes $O(n^2)$ time to look at every pair in a
  2731. set of $n$ live locations. Second, there is a special case in which
  2732. two locations that are live at the same time do not actually interfere
  2733. with each other: when they both contain the same value because we have
  2734. assigned one to the other.
  2735. A better way to compute the interference graph is to focus on the
  2736. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2737. instruction to overwrite something in a live location. So for each
  2738. instruction, we create an edge between the locations being written to
  2739. and all the other live locations. (Except that one should not create
  2740. self edges.) Recall that for a \key{callq} instruction, we consider
  2741. all of the caller-saved registers as being written to, so an edge will
  2742. be added between every live variable and every caller-saved
  2743. register. For \key{movq}, we deal with the above-mentioned special
  2744. case by not adding an edge between a live variable $v$ and destination
  2745. $d$ if $v$ matches the source of the move. So we have the following
  2746. two rules.
  2747. \begin{enumerate}
  2748. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2749. $d$, then add the edge $(d,v)$ for every $v \in
  2750. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2751. \item For any other instruction $I_k$, for every $d \in W(k)$
  2752. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2753. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2754. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2755. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2756. %% \item If instruction $I_k$ is of the form \key{callq}
  2757. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2758. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2759. \end{enumerate}
  2760. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2761. the above rules to each instruction. We highlight a few of the
  2762. instructions and then refer the reader to
  2763. Figure~\ref{fig:interference-results} for all the interference
  2764. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2765. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2766. interference edges because the one live variable \code{v} is also the
  2767. destination of this instruction.
  2768. %
  2769. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2770. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2771. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2772. %
  2773. Next we skip forward to the instruction \lstinline{movq x, y}.
  2774. \begin{figure}[tbp]
  2775. \begin{quote}
  2776. \begin{tabular}{ll}
  2777. \lstinline!movq $1, v!& no interference by rule 3,\\
  2778. \lstinline!movq $42, w!& $w$ interferes with $v$ by rule 3,\\
  2779. \lstinline!movq v, x!& $x$ interferes with $w$ by rule 3,\\
  2780. \lstinline!addq $7, x!& $x$ interferes with $w$ by rule 1,\\
  2781. \lstinline!movq x, y!& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2782. \lstinline!movq x, z!& $z$ interferes with $w$ and $y$ by rule 3,\\
  2783. \lstinline!addq w, z!& $z$ interferes with $y$ by rule 1, \\
  2784. \lstinline!movq y, t!& $t$ interferes with $z$ by rule 3, \\
  2785. \lstinline!negq t!& $t$ interferes with $z$ by rule 1, \\
  2786. \lstinline!movq z, %rax! & no interference (ignore rax), \\
  2787. \lstinline!addq t, %rax! & no interference (ignore rax). \\
  2788. \lstinline!jmp conclusion!& no interference.
  2789. \end{tabular}
  2790. \end{quote}
  2791. \caption{Interference results for the running example.}
  2792. \label{fig:interference-results}
  2793. \end{figure}
  2794. The resulting interference graph is shown in
  2795. Figure~\ref{fig:interfere}.
  2796. \begin{figure}[tbp]
  2797. \large
  2798. \[
  2799. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2800. \node (rax) at (0,0) {$\ttm{rax}$};
  2801. \node (t1) at (0,2) {$\ttm{t}$};
  2802. \node (z) at (3,2) {$\ttm{z}$};
  2803. \node (x) at (6,2) {$\ttm{x}$};
  2804. \node (y) at (3,0) {$\ttm{y}$};
  2805. \node (w) at (6,0) {$\ttm{w}$};
  2806. \node (v) at (9,0) {$\ttm{v}$};
  2807. \draw (t1) to (rax);
  2808. \draw (t1) to (z);
  2809. \draw (z) to (y);
  2810. \draw (z) to (w);
  2811. \draw (x) to (w);
  2812. \draw (y) to (w);
  2813. \draw (v) to (w);
  2814. \end{tikzpicture}
  2815. \]
  2816. \caption{The interference graph of the example program.}
  2817. \label{fig:interfere}
  2818. \end{figure}
  2819. %% Our next concern is to choose a data structure for representing the
  2820. %% interference graph. There are many choices for how to represent a
  2821. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2822. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2823. %% data structure is to study the algorithm that uses the data structure,
  2824. %% determine what operations need to be performed, and then choose the
  2825. %% data structure that provide the most efficient implementations of
  2826. %% those operations. Often times the choice of data structure can have an
  2827. %% effect on the time complexity of the algorithm, as it does here. If
  2828. %% you skim the next section, you will see that the register allocation
  2829. %% algorithm needs to ask the graph for all of its vertices and, given a
  2830. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2831. %% correct choice of graph representation is that of an adjacency
  2832. %% list. There are helper functions in \code{utilities.rkt} for
  2833. %% representing graphs using the adjacency list representation:
  2834. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2835. %% (Appendix~\ref{appendix:utilities}).
  2836. %% %
  2837. %% \margincomment{\footnotesize To do: change to use the
  2838. %% Racket graph library. \\ --Jeremy}
  2839. %% %
  2840. %% In particular, those functions use a hash table to map each vertex to
  2841. %% the set of adjacent vertices, and the sets are represented using
  2842. %% Racket's \key{set}, which is also a hash table.
  2843. \begin{exercise}\normalfont
  2844. Implement the compiler pass named \code{build-interference} according
  2845. to the algorithm suggested above. We recommend using the \code{graph}
  2846. package to create and inspect the interference graph. The output
  2847. graph of this pass should be stored in the $\itm{info}$ field of the
  2848. program, under the key \code{conflicts}.
  2849. \end{exercise}
  2850. \section{Graph Coloring via Sudoku}
  2851. \label{sec:graph-coloring}
  2852. \index{graph coloring}
  2853. \index{Sudoku}
  2854. \index{color}
  2855. We come to the main event, mapping variables to registers (or to stack
  2856. locations in the event that we run out of registers). We need to make
  2857. sure that two variables do not get mapped to the same register if the
  2858. two variables interfere with each other. Thinking about the
  2859. interference graph, this means that adjacent vertices must be mapped
  2860. to different registers. If we think of registers as colors, the
  2861. register allocation problem becomes the widely-studied graph coloring
  2862. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2863. The reader may be more familiar with the graph coloring problem than he
  2864. or she realizes; the popular game of Sudoku is an instance of the
  2865. graph coloring problem. The following describes how to build a graph
  2866. out of an initial Sudoku board.
  2867. \begin{itemize}
  2868. \item There is one vertex in the graph for each Sudoku square.
  2869. \item There is an edge between two vertices if the corresponding squares
  2870. are in the same row, in the same column, or if the squares are in
  2871. the same $3\times 3$ region.
  2872. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2873. \item Based on the initial assignment of numbers to squares in the
  2874. Sudoku board, assign the corresponding colors to the corresponding
  2875. vertices in the graph.
  2876. \end{itemize}
  2877. If you can color the remaining vertices in the graph with the nine
  2878. colors, then you have also solved the corresponding game of Sudoku.
  2879. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2880. the corresponding graph with colored vertices. We map the Sudoku
  2881. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2882. sampling of the vertices (the colored ones) because showing edges for
  2883. all of the vertices would make the graph unreadable.
  2884. \begin{figure}[tbp]
  2885. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2886. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2887. \caption{A Sudoku game board and the corresponding colored graph.}
  2888. \label{fig:sudoku-graph}
  2889. \end{figure}
  2890. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2891. strategies to come up with an algorithm for allocating registers. For
  2892. example, one of the basic techniques for Sudoku is called Pencil
  2893. Marks. The idea is to use a process of elimination to determine what
  2894. numbers no longer make sense for a square and write down those
  2895. numbers in the square (writing very small). For example, if the number
  2896. $1$ is assigned to a square, then by process of elimination, you can
  2897. write the pencil mark $1$ in all the squares in the same row, column,
  2898. and region. Many Sudoku computer games provide automatic support for
  2899. Pencil Marks.
  2900. %
  2901. The Pencil Marks technique corresponds to the notion of
  2902. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2903. The saturation of a
  2904. vertex, in Sudoku terms, is the set of numbers that are no longer
  2905. available. In graph terminology, we have the following definition:
  2906. \begin{equation*}
  2907. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2908. \text{ and } \mathrm{color}(v) = c \}
  2909. \end{equation*}
  2910. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2911. edge with $u$.
  2912. Using the Pencil Marks technique leads to a simple strategy for
  2913. filling in numbers: if there is a square with only one possible number
  2914. left, then choose that number! But what if there are no squares with
  2915. only one possibility left? One brute-force approach is to try them
  2916. all: choose the first and if it ultimately leads to a solution,
  2917. great. If not, backtrack and choose the next possibility. One good
  2918. thing about Pencil Marks is that it reduces the degree of branching in
  2919. the search tree. Nevertheless, backtracking can be horribly time
  2920. consuming. One way to reduce the amount of backtracking is to use the
  2921. most-constrained-first heuristic. That is, when choosing a square,
  2922. always choose one with the fewest possibilities left (the vertex with
  2923. the highest saturation). The idea is that choosing highly constrained
  2924. squares earlier rather than later is better because later on there may
  2925. not be any possibilities left for those squares.
  2926. However, register allocation is easier than Sudoku because the
  2927. register allocator can map variables to stack locations when the
  2928. registers run out. Thus, it makes sense to drop backtracking in favor
  2929. of greedy search, that is, make the best choice at the time and keep
  2930. going. We still wish to minimize the number of colors needed, so
  2931. keeping the most-constrained-first heuristic is a good idea.
  2932. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2933. algorithm for register allocation based on saturation and the
  2934. most-constrained-first heuristic. It is roughly equivalent to the
  2935. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2936. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2937. Sudoku, the algorithm represents colors with integers. The integers
  2938. $0$ through $k-1$ correspond to the $k$ registers that we use for
  2939. register allocation. The integers $k$ and larger correspond to stack
  2940. locations. The registers that are not used for register allocation,
  2941. such as \code{rax}, are assigned to negative integers. In particular,
  2942. we assign $-1$ to \code{rax}.
  2943. \begin{figure}[btp]
  2944. \centering
  2945. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2946. Algorithm: DSATUR
  2947. Input: a graph |$G$|
  2948. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2949. |$W \gets \mathrm{vertices}(G)$|
  2950. while |$W \neq \emptyset$| do
  2951. pick a vertex |$u$| from |$W$| with the highest saturation,
  2952. breaking ties randomly
  2953. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2954. |$\mathrm{color}[u] \gets c$|
  2955. |$W \gets W - \{u\}$|
  2956. \end{lstlisting}
  2957. \caption{The saturation-based greedy graph coloring algorithm.}
  2958. \label{fig:satur-algo}
  2959. \end{figure}
  2960. With this algorithm in hand, let us return to the running example and
  2961. consider how to color the interference graph in
  2962. Figure~\ref{fig:interfere}.
  2963. %
  2964. We color the vertices for registers with their own color. For example,
  2965. \code{rax} is assigned the color $-1$. We then update the saturation
  2966. for their neighboring vertices. In this case, the saturation for
  2967. \code{t} includes $-1$. The remaining vertices are not yet colored,
  2968. so they annotated with a dash, and their saturation sets are empty.
  2969. \[
  2970. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2971. \node (rax) at (0,0) {$\ttm{rax}:-1,\{\}$};
  2972. \node (t1) at (0,2) {$\ttm{t}:-,\{-1\}$};
  2973. \node (z) at (3,2) {$\ttm{z}:-,\{\}$};
  2974. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2975. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2976. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2977. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2978. \draw (t1) to (rax);
  2979. \draw (t1) to (z);
  2980. \draw (z) to (y);
  2981. \draw (z) to (w);
  2982. \draw (x) to (w);
  2983. \draw (y) to (w);
  2984. \draw (v) to (w);
  2985. \end{tikzpicture}
  2986. \]
  2987. The algorithm says to select a maximally saturated vertex. So we pick
  2988. $\ttm{t}$ and color it with the first available integer, which is
  2989. $0$. We mark $0$ as no longer available for $\ttm{z}$ and $\ttm{rax}$
  2990. because they interfere with $\ttm{t}$.
  2991. \[
  2992. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2993. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2994. \node (t1) at (0,2) {$\ttm{t}:0,\{-1\}$};
  2995. \node (z) at (3,2) {$\ttm{z}:-,\{0\}$};
  2996. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2997. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2998. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2999. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3000. \draw (t1) to (rax);
  3001. \draw (t1) to (z);
  3002. \draw (z) to (y);
  3003. \draw (z) to (w);
  3004. \draw (x) to (w);
  3005. \draw (y) to (w);
  3006. \draw (v) to (w);
  3007. \end{tikzpicture}
  3008. \]
  3009. We repeat the process, selecting another maximally saturated
  3010. vertex, which is \code{z}, and color it with the first available
  3011. number, which is $1$. We add $1$ to the saturations for the
  3012. neighboring vertices \code{t}, \code{y}, and \code{w}.
  3013. \[
  3014. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3015. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3016. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3017. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3018. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3019. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3020. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3021. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3022. \draw (t1) to (rax);
  3023. \draw (t1) to (z);
  3024. \draw (z) to (y);
  3025. \draw (z) to (w);
  3026. \draw (x) to (w);
  3027. \draw (y) to (w);
  3028. \draw (v) to (w);
  3029. \end{tikzpicture}
  3030. \]
  3031. The most saturated vertices are now \code{w} and \code{y}. We color
  3032. \code{w} with the first available color, which is $0$.
  3033. \[
  3034. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3035. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3036. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3037. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3038. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3039. \node (y) at (3,0) {$\ttm{y}:-,\{0,1\}$};
  3040. \node (w) at (6,0) {$\ttm{w}:0,\{1\}$};
  3041. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3042. \draw (t1) to (rax);
  3043. \draw (t1) to (z);
  3044. \draw (z) to (y);
  3045. \draw (z) to (w);
  3046. \draw (x) to (w);
  3047. \draw (y) to (w);
  3048. \draw (v) to (w);
  3049. \end{tikzpicture}
  3050. \]
  3051. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3052. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3053. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3054. and \code{z}, whose colors are $0$ and $1$ respectively.
  3055. \[
  3056. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3057. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3058. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3059. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3060. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3061. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3062. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3063. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3064. \draw (t1) to (rax);
  3065. \draw (t1) to (z);
  3066. \draw (z) to (y);
  3067. \draw (z) to (w);
  3068. \draw (x) to (w);
  3069. \draw (y) to (w);
  3070. \draw (v) to (w);
  3071. \end{tikzpicture}
  3072. \]
  3073. Now \code{x} and \code{v} are the most saturated, so we color \code{v} it $1$.
  3074. \[
  3075. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3076. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3077. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3078. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3079. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3080. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3081. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3082. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3083. \draw (t1) to (rax);
  3084. \draw (t1) to (z);
  3085. \draw (z) to (y);
  3086. \draw (z) to (w);
  3087. \draw (x) to (w);
  3088. \draw (y) to (w);
  3089. \draw (v) to (w);
  3090. \end{tikzpicture}
  3091. \]
  3092. In the last step of the algorithm, we color \code{x} with $1$.
  3093. \[
  3094. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3095. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3096. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,\}$};
  3097. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3098. \node (x) at (6,2) {$\ttm{x}:1,\{0\}$};
  3099. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3100. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3101. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3102. \draw (t1) to (rax);
  3103. \draw (t1) to (z);
  3104. \draw (z) to (y);
  3105. \draw (z) to (w);
  3106. \draw (x) to (w);
  3107. \draw (y) to (w);
  3108. \draw (v) to (w);
  3109. \end{tikzpicture}
  3110. \]
  3111. With the coloring complete, we finalize the assignment of variables to
  3112. registers and stack locations. Recall that if we have $k$ registers to
  3113. use for allocation, we map the first $k$ colors to registers and the
  3114. rest to stack locations. Suppose for the moment that we have just one
  3115. register to use for register allocation, \key{rcx}. Then the following
  3116. is the mapping of colors to registers and stack allocations.
  3117. \[
  3118. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3119. \]
  3120. Putting this mapping together with the above coloring of the
  3121. variables, we arrive at the following assignment of variables to
  3122. registers and stack locations.
  3123. \begin{gather*}
  3124. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3125. \ttm{w} \mapsto \key{\%rcx}, \,
  3126. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3127. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3128. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3129. \ttm{t} \mapsto \key{\%rcx} \}
  3130. \end{gather*}
  3131. Applying this assignment to our running example, on the left, yields
  3132. the program on the right.
  3133. % why frame size of 32? -JGS
  3134. \begin{center}
  3135. \begin{minipage}{0.3\textwidth}
  3136. \begin{lstlisting}
  3137. movq $1, v
  3138. movq $42, w
  3139. movq v, x
  3140. addq $7, x
  3141. movq x, y
  3142. movq x, z
  3143. addq w, z
  3144. movq y, t
  3145. negq t
  3146. movq z, %rax
  3147. addq t, %rax
  3148. jmp conclusion
  3149. \end{lstlisting}
  3150. \end{minipage}
  3151. $\Rightarrow\qquad$
  3152. \begin{minipage}{0.45\textwidth}
  3153. \begin{lstlisting}
  3154. movq $1, %rcx
  3155. movq $42, %rcx
  3156. movq %rcx, -8(%rbp)
  3157. addq $7, -8(%rbp)
  3158. movq -8(%rbp), -16(%rbp)
  3159. movq -8(%rbp), -8(%rbp)
  3160. addq %rcx, -8(%rbp)
  3161. movq -16(%rbp), %rcx
  3162. negq %rcx
  3163. movq -8(%rbp), %rax
  3164. addq %rcx, %rax
  3165. jmp conclusion
  3166. \end{lstlisting}
  3167. \end{minipage}
  3168. \end{center}
  3169. The resulting program is almost an x86 program. The remaining step is
  3170. the patch instructions pass. In this example, the trivial move of
  3171. \code{-8(\%rbp)} to itself is deleted and the addition of
  3172. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3173. \code{rax} as follows.
  3174. \begin{lstlisting}
  3175. movq -8(%rbp), %rax
  3176. addq %rax, -16(%rbp)
  3177. \end{lstlisting}
  3178. An overview of all of the passes involved in register allocation is
  3179. shown in Figure~\ref{fig:reg-alloc-passes}.
  3180. \begin{figure}[tbp]
  3181. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3182. \node (R1) at (0,2) {\large $R_1$};
  3183. \node (R1-2) at (3,2) {\large $R_1$};
  3184. \node (R1-3) at (6,2) {\large $R_1$};
  3185. \node (C0-1) at (3,0) {\large $C_0$};
  3186. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3187. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3188. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3189. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3190. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3191. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3192. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3193. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3194. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3195. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3196. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3197. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3198. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3199. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3200. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3201. \end{tikzpicture}
  3202. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3203. \label{fig:reg-alloc-passes}
  3204. \end{figure}
  3205. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  3206. \small
  3207. \begin{tcolorbox}[title=Priority Queue]
  3208. A \emph{priority queue} is a collection of items in which the
  3209. removal of items is governed by priority. In a ``min'' queue,
  3210. lower priority items are removed first. An implementation is in
  3211. \code{priority\_queue.rkt} of the support code. \index{priority
  3212. queue} \index{minimum priority queue}
  3213. \begin{description}
  3214. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3215. priority queue that uses the $\itm{cmp}$ predicate to determine
  3216. whether its first argument has lower or equal priority to its
  3217. second argument.
  3218. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3219. items in the queue.
  3220. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3221. the item into the queue and returns a handle for the item in the
  3222. queue.
  3223. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3224. the lowest priority.
  3225. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3226. notifices the queue the the priority has decreased for the item
  3227. associated with the given handle.
  3228. \end{description}
  3229. \end{tcolorbox}
  3230. \end{wrapfigure}
  3231. We recommend creating a helper function named \code{color-graph} that
  3232. takes an interference graph and a list of all the variables in the
  3233. program. This function should return a mapping of variables to their
  3234. colors (represented as natural numbers). By creating this helper
  3235. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3236. when you add support for functions. To prioritize the process of
  3237. highly saturated nodes inside your \code{color-graph} function, we
  3238. recommend using the priority queue data structure (see the side bar on
  3239. the right). Note that you will also need to maintain a mapping from
  3240. variables to their ``handles'' in the priority queue so that you can
  3241. notify the priority queue when their saturation changes.
  3242. Once you have obtained the coloring from \code{color-graph}, you can
  3243. assign the variables to registers or stack locations and then reuse
  3244. code from the \code{assign-homes} pass from
  3245. Section~\ref{sec:assign-r1} to replace the variables with their
  3246. assigned location.
  3247. \begin{exercise}\normalfont
  3248. Implement the compiler pass \code{allocate-registers}, which should come
  3249. after the \code{build-interference} pass. The three new passes,
  3250. \code{uncover-live}, \code{build-interference}, and
  3251. \code{allocate-registers} replace the \code{assign-homes} pass of
  3252. Section~\ref{sec:assign-r1}.
  3253. Test your updated compiler by creating new example programs that
  3254. exercise all of the register allocation algorithm, such as forcing
  3255. variables to be spilled to the stack.
  3256. \end{exercise}
  3257. \section{Print x86 and Conventions for Registers}
  3258. \label{sec:print-x86-reg-alloc}
  3259. \index{calling conventions}
  3260. \index{prelude}\index{conclusion}
  3261. Recall that the \code{print-x86} pass generates the prelude and
  3262. conclusion instructions for the \code{main} function.
  3263. %
  3264. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3265. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3266. reason for this is that our \code{main} function must adhere to the
  3267. x86 calling conventions that we described in
  3268. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3269. allocator assigned variables to other callee-saved registers
  3270. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3271. saved to the stack in the prelude and restored in the conclusion. The
  3272. simplest approach is to save and restore all of the callee-saved
  3273. registers. The more efficient approach is to keep track of which
  3274. callee-saved registers were used and only save and restore
  3275. them. Either way, make sure to take this use of stack space into
  3276. account when you are calculating the size of the frame and adjusting
  3277. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3278. frame needs to be a multiple of 16 bytes!
  3279. \section{Challenge: Move Biasing}
  3280. \label{sec:move-biasing}
  3281. \index{move biasing}
  3282. This section describes an optional enhancement to register allocation
  3283. for those students who are looking for an extra challenge or who have
  3284. a deeper interest in register allocation.
  3285. We return to the running example, but we remove the supposition that
  3286. we only have one register to use. So we have the following mapping of
  3287. color numbers to registers.
  3288. \[
  3289. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3290. \]
  3291. Using the same assignment of variables to color numbers that was
  3292. produced by the register allocator described in the last section, we
  3293. get the following program.
  3294. \begin{minipage}{0.3\textwidth}
  3295. \begin{lstlisting}
  3296. movq $1, v
  3297. movq $42, w
  3298. movq v, x
  3299. addq $7, x
  3300. movq x, y
  3301. movq x, z
  3302. addq w, z
  3303. movq y, t
  3304. negq t
  3305. movq z, %rax
  3306. addq t, %rax
  3307. jmp conclusion
  3308. \end{lstlisting}
  3309. \end{minipage}
  3310. $\Rightarrow\qquad$
  3311. \begin{minipage}{0.45\textwidth}
  3312. \begin{lstlisting}
  3313. movq $1, %rcx
  3314. movq $42, $rbx
  3315. movq %rcx, %rcx
  3316. addq $7, %rcx
  3317. movq %rcx, %rdx
  3318. movq %rcx, %rcx
  3319. addq %rbx, %rcx
  3320. movq %rdx, %rbx
  3321. negq %rbx
  3322. movq %rcx, %rax
  3323. addq %rbx, %rax
  3324. jmp conclusion
  3325. \end{lstlisting}
  3326. \end{minipage}
  3327. In the above output code there are two \key{movq} instructions that
  3328. can be removed because their source and target are the same. However,
  3329. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3330. register, we could instead remove three \key{movq} instructions. We
  3331. can accomplish this by taking into account which variables appear in
  3332. \key{movq} instructions with which other variables.
  3333. We say that two variables $p$ and $q$ are \emph{move
  3334. related}\index{move related} if they participate together in a
  3335. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3336. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3337. for a variable, it should prefer a color that has already been used
  3338. for a move-related variable (assuming that they do not interfere). Of
  3339. course, this preference should not override the preference for
  3340. registers over stack locations. This preference should be used as a
  3341. tie breaker when choosing between registers or when choosing between
  3342. stack locations.
  3343. We recommend representing the move relationships in a graph, similar
  3344. to how we represented interference. The following is the \emph{move
  3345. graph} for our running example.
  3346. \[
  3347. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3348. \node (rax) at (0,0) {$\ttm{rax}$};
  3349. \node (t) at (0,2) {$\ttm{t}$};
  3350. \node (z) at (3,2) {$\ttm{z}$};
  3351. \node (x) at (6,2) {$\ttm{x}$};
  3352. \node (y) at (3,0) {$\ttm{y}$};
  3353. \node (w) at (6,0) {$\ttm{w}$};
  3354. \node (v) at (9,0) {$\ttm{v}$};
  3355. \draw (v) to (x);
  3356. \draw (x) to (y);
  3357. \draw (x) to (z);
  3358. \draw (y) to (t);
  3359. \end{tikzpicture}
  3360. \]
  3361. Now we replay the graph coloring, pausing to see the coloring of
  3362. \code{y}. Recall the following configuration. The most saturated vertices
  3363. were \code{w} and \code{y}.
  3364. \[
  3365. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3366. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3367. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3368. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3369. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3370. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3371. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3372. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3373. \draw (t1) to (rax);
  3374. \draw (t1) to (z);
  3375. \draw (z) to (y);
  3376. \draw (z) to (w);
  3377. \draw (x) to (w);
  3378. \draw (y) to (w);
  3379. \draw (v) to (w);
  3380. \end{tikzpicture}
  3381. \]
  3382. %
  3383. Last time we chose to color \code{w} with $0$. But this time we see
  3384. that \code{w} is not move related to any vertex, but \code{y} is move
  3385. related to \code{t}. So we choose to color \code{y} the same color,
  3386. $0$.
  3387. \[
  3388. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3389. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3390. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3391. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3392. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3393. \node (y) at (3,0) {$\ttm{y}:0,\{1\}$};
  3394. \node (w) at (6,0) {$\ttm{w}:-,\{0,1\}$};
  3395. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3396. \draw (t1) to (rax);
  3397. \draw (t1) to (z);
  3398. \draw (z) to (y);
  3399. \draw (z) to (w);
  3400. \draw (x) to (w);
  3401. \draw (y) to (w);
  3402. \draw (v) to (w);
  3403. \end{tikzpicture}
  3404. \]
  3405. Now \code{w} is the most saturated, so we color it $2$.
  3406. \[
  3407. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3408. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3409. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3410. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3411. \node (x) at (6,2) {$\ttm{x}:-,\{2\}$};
  3412. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3413. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3414. \node (v) at (9,0) {$\ttm{v}:-,\{2\}$};
  3415. \draw (t1) to (rax);
  3416. \draw (t1) to (z);
  3417. \draw (z) to (y);
  3418. \draw (z) to (w);
  3419. \draw (x) to (w);
  3420. \draw (y) to (w);
  3421. \draw (v) to (w);
  3422. \end{tikzpicture}
  3423. \]
  3424. At this point, vertices \code{x} and \code{v} are most saturated, but
  3425. \code{x} is move related to \code{y} and \code{z}, so we color
  3426. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3427. \[
  3428. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3429. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3430. \node (t) at (0,2) {$\ttm{t}:0,\{1\}$};
  3431. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3432. \node (x) at (6,2) {$\ttm{x}:0,\{2\}$};
  3433. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3434. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3435. \node (v) at (9,0) {$\ttm{v}:0,\{2\}$};
  3436. \draw (t1) to (rax);
  3437. \draw (t) to (z);
  3438. \draw (z) to (y);
  3439. \draw (z) to (w);
  3440. \draw (x) to (w);
  3441. \draw (y) to (w);
  3442. \draw (v) to (w);
  3443. \end{tikzpicture}
  3444. \]
  3445. So we have the following assignment of variables to registers.
  3446. \begin{gather*}
  3447. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3448. \ttm{w} \mapsto \key{\%rdx}, \,
  3449. \ttm{x} \mapsto \key{\%rbx}, \,
  3450. \ttm{y} \mapsto \key{\%rbx}, \,
  3451. \ttm{z} \mapsto \key{\%rcx}, \,
  3452. \ttm{t} \mapsto \key{\%rbx} \}
  3453. \end{gather*}
  3454. We apply this register assignment to the running example, on the left,
  3455. to obtain the code on right.
  3456. \begin{minipage}{0.3\textwidth}
  3457. \begin{lstlisting}
  3458. movq $1, v
  3459. movq $42, w
  3460. movq v, x
  3461. addq $7, x
  3462. movq x, y
  3463. movq x, z
  3464. addq w, z
  3465. movq y, t
  3466. negq t
  3467. movq z, %rax
  3468. addq t, %rax
  3469. jmp conclusion
  3470. \end{lstlisting}
  3471. \end{minipage}
  3472. $\Rightarrow\qquad$
  3473. \begin{minipage}{0.45\textwidth}
  3474. \begin{lstlisting}
  3475. movq $1, %rbx
  3476. movq $42, %rdx
  3477. movq %rbx, %rbx
  3478. addq $7, %rbx
  3479. movq %rbx, %rbx
  3480. movq %rbx, %rcx
  3481. addq %rdx, %rcx
  3482. movq %rbx, %rbx
  3483. negq %rbx
  3484. movq %rcx, %rax
  3485. addq %rbx, %rax
  3486. jmp conclusion
  3487. \end{lstlisting}
  3488. \end{minipage}
  3489. The \code{patch-instructions} then removes the three trivial moves
  3490. from \key{rbx} to \key{rbx} to obtain the following result.
  3491. \begin{minipage}{0.45\textwidth}
  3492. \begin{lstlisting}
  3493. movq $1, %rbx
  3494. movq $42, %rdx
  3495. addq $7, %rbx
  3496. movq %rbx, %rcx
  3497. addq %rdx, %rcx
  3498. negq %rbx
  3499. movq %rcx, %rax
  3500. addq %rbx, %rax
  3501. jmp conclusion
  3502. \end{lstlisting}
  3503. \end{minipage}
  3504. \begin{exercise}\normalfont
  3505. Change your implementation of \code{allocate-registers} to take move
  3506. biasing into account. Make sure that your compiler still passes all of
  3507. the previous tests. Create two new tests that include at least one
  3508. opportunity for move biasing and visually inspect the output x86
  3509. programs to make sure that your move biasing is working properly.
  3510. \end{exercise}
  3511. \margincomment{\footnotesize To do: another neat challenge would be to do
  3512. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3513. \section{Output of the Running Example}
  3514. \label{sec:reg-alloc-output}
  3515. \index{prelude}\index{conclusion}
  3516. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3517. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3518. and move biasing. To demonstrate both the use of registers and the
  3519. stack, we have limited the register allocator to use just two
  3520. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3521. \code{main} function, we push \code{rbx} onto the stack because it is
  3522. a callee-saved register and it was assigned to variable by the
  3523. register allocator. We substract \code{8} from the \code{rsp} at the
  3524. end of the prelude to reserve space for the one spilled variable.
  3525. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3526. Moving on the the \code{start} block, we see how the registers were
  3527. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3528. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3529. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3530. that the prelude saved the callee-save register \code{rbx} onto the
  3531. stack. The spilled variables must be placed lower on the stack than
  3532. the saved callee-save registers, so in this case \code{w} is placed at
  3533. \code{-16(\%rbp)}.
  3534. In the \code{conclusion}, we undo the work that was done in the
  3535. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3536. spilled variables), then we pop the old values of \code{rbx} and
  3537. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3538. return control to the operating system.
  3539. \begin{figure}[tbp]
  3540. % s0_28.rkt
  3541. % (use-minimal-set-of-registers! #t)
  3542. % and only rbx rcx
  3543. % tmp 0 rbx
  3544. % z 1 rcx
  3545. % y 0 rbx
  3546. % w 2 16(%rbp)
  3547. % v 0 rbx
  3548. % x 0 rbx
  3549. \begin{lstlisting}
  3550. start:
  3551. movq $1, %rbx
  3552. movq $42, -16(%rbp)
  3553. addq $7, %rbx
  3554. movq %rbx, %rcx
  3555. addq -16(%rbp), %rcx
  3556. negq %rbx
  3557. movq %rcx, %rax
  3558. addq %rbx, %rax
  3559. jmp conclusion
  3560. .globl main
  3561. main:
  3562. pushq %rbp
  3563. movq %rsp, %rbp
  3564. pushq %rbx
  3565. subq $8, %rsp
  3566. jmp start
  3567. conclusion:
  3568. addq $8, %rsp
  3569. popq %rbx
  3570. popq %rbp
  3571. retq
  3572. \end{lstlisting}
  3573. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3574. \label{fig:running-example-x86}
  3575. \end{figure}
  3576. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3577. \chapter{Booleans and Control Flow}
  3578. \label{ch:bool-types}
  3579. \index{Boolean}
  3580. \index{control flow}
  3581. \index{conditional expression}
  3582. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3583. integers. In this chapter we add a second kind of value, the Booleans,
  3584. to create the $R_2$ language. The Boolean values \emph{true} and
  3585. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3586. Racket. The $R_2$ language includes several operations that involve
  3587. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3588. conditional \key{if} expression. With the addition of \key{if}
  3589. expressions, programs can have non-trivial control flow which which
  3590. significantly impacts the \code{explicate-control} and the liveness
  3591. analysis for register allocation. Also, because we now have two kinds
  3592. of values, we need to handle programs that apply an operation to the
  3593. wrong kind of value, such as \code{(not 1)}.
  3594. There are two language design options for such situations. One option
  3595. is to signal an error and the other is to provide a wider
  3596. interpretation of the operation. The Racket language uses a mixture of
  3597. these two options, depending on the operation and the kind of
  3598. value. For example, the result of \code{(not 1)} in Racket is
  3599. \code{\#f} because Racket treats non-zero integers as if they were
  3600. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3601. error in Racket stating that \code{car} expects a pair.
  3602. The Typed Racket language makes similar design choices as Racket,
  3603. except much of the error detection happens at compile time instead of
  3604. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3605. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3606. reports a compile-time error because Typed Racket expects the type of
  3607. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3608. For the $R_2$ language we choose to be more like Typed Racket in that
  3609. we perform type checking during compilation. In
  3610. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3611. is, how to compile a dynamically typed language like Racket. The
  3612. $R_2$ language is a subset of Typed Racket but by no means includes
  3613. all of Typed Racket. For many operations we take a narrower
  3614. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3615. This chapter is organized as follows. We begin by defining the syntax
  3616. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3617. then introduce the idea of type checking and build a type checker for
  3618. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3619. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3620. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3621. how our compiler passes need to change to accommodate Booleans and
  3622. conditional control flow.
  3623. \section{The $R_2$ Language}
  3624. \label{sec:r2-lang}
  3625. The concrete syntax of the $R_2$ language is defined in
  3626. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3627. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3628. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3629. and the conditional \code{if} expression. Also, we expand the
  3630. operators to include
  3631. \begin{enumerate}
  3632. \item subtraction on integers,
  3633. \item the logical operators \key{and}, \key{or} and \key{not},
  3634. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3635. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3636. comparing integers.
  3637. \end{enumerate}
  3638. We reorganize the abstract syntax for the primitive operations in
  3639. Figure~\ref{fig:r2-syntax}, using only one grammar rule for all of
  3640. them. This means that the grammar no longer checks whether the arity
  3641. of an operators matches the number of arguments. That responsibility
  3642. is moved to the type checker for $R_2$, which we introduce in
  3643. Section~\ref{sec:type-check-r2}.
  3644. \begin{figure}[tp]
  3645. \centering
  3646. \fbox{
  3647. \begin{minipage}{0.96\textwidth}
  3648. \[
  3649. \begin{array}{lcl}
  3650. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3651. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3652. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3653. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3654. &\mid& \itm{bool}
  3655. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3656. \mid (\key{not}\;\Exp) \\
  3657. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3658. R_2 &::=& \Exp
  3659. \end{array}
  3660. \]
  3661. \end{minipage}
  3662. }
  3663. \caption{The concrete syntax of $R_2$, extending $R_1$
  3664. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3665. \label{fig:r2-concrete-syntax}
  3666. \end{figure}
  3667. \begin{figure}[tp]
  3668. \centering
  3669. \fbox{
  3670. \begin{minipage}{0.96\textwidth}
  3671. \[
  3672. \begin{array}{lcl}
  3673. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3674. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3675. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3676. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3677. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3678. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3679. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3680. R_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3681. \end{array}
  3682. \]
  3683. \end{minipage}
  3684. }
  3685. \caption{The abstract syntax of $R_2$.}
  3686. \label{fig:r2-syntax}
  3687. \end{figure}
  3688. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3689. the parts that are the same as the interpreter for $R_1$
  3690. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3691. evaluate to the corresponding Boolean values. The conditional
  3692. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3693. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3694. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3695. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3696. you might expect, but note that the \code{and} operation is
  3697. short-circuiting. That is, given the expression
  3698. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3699. $e_1$ evaluates to \code{\#f}.
  3700. With the increase in the number of primitive operations, the
  3701. interpreter code for them could become repetitive without some
  3702. care. In Figure~\ref{fig:interp-R2} we factor out the different parts
  3703. of the code for primitive operations into the \code{interp-op}
  3704. function and the similar parts of the code into the match clause for
  3705. \code{Prim} shown in Figure~\ref{fig:interp-R2}. We do not use
  3706. \code{interp-op} for the \code{and} operation because of the
  3707. short-circuiting behavior in the order of evaluation of its arguments.
  3708. \begin{figure}[tbp]
  3709. \begin{lstlisting}
  3710. (define (interp-op op)
  3711. (match op
  3712. ...
  3713. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3714. ['eq? (lambda (v1 v2)
  3715. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3716. (and (boolean? v1) (boolean? v2)))
  3717. (eq? v1 v2)]))]
  3718. ['< (lambda (v1 v2)
  3719. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3720. ['<= (lambda (v1 v2)
  3721. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3722. ['> (lambda (v1 v2)
  3723. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3724. ['>= (lambda (v1 v2)
  3725. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3726. [else (error 'interp-op "unknown operator")]))
  3727. (define (interp-exp env)
  3728. (lambda (e)
  3729. (define recur (interp-exp env))
  3730. (match e
  3731. ...
  3732. [(Bool b) b]
  3733. [(If cnd thn els)
  3734. (define b (recur cnd))
  3735. (match b
  3736. [#t (recur thn)]
  3737. [#f (recur els)])]
  3738. [(Prim 'and (list e1 e2))
  3739. (define v1 (recur e1))
  3740. (match v1
  3741. [#t (match (recur e2) [#t #t] [#f #f])]
  3742. [#f #f])]
  3743. [(Prim op args)
  3744. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3745. )))
  3746. (define (interp-R2 p)
  3747. (match p
  3748. [(Program info e)
  3749. ((interp-exp '()) e)]
  3750. ))
  3751. \end{lstlisting}
  3752. \caption{Interpreter for the $R_2$ language.}
  3753. \label{fig:interp-R2}
  3754. \end{figure}
  3755. \section{Type Checking $R_2$ Programs}
  3756. \label{sec:type-check-r2}
  3757. \index{type checking}
  3758. \index{semantic analysis}
  3759. It is helpful to think about type checking in two complementary
  3760. ways. A type checker predicts the type of value that will be produced
  3761. by each expression in the program. For $R_2$, we have just two types,
  3762. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3763. \begin{lstlisting}
  3764. (+ 10 (- (+ 12 20)))
  3765. \end{lstlisting}
  3766. produces an \key{Integer} while
  3767. \begin{lstlisting}
  3768. (and (not #f) #t)
  3769. \end{lstlisting}
  3770. produces a \key{Boolean}.
  3771. Another way to think about type checking is that it enforces a set of
  3772. rules about which operators can be applied to which kinds of
  3773. values. For example, our type checker for $R_2$ will signal an error
  3774. for the below expression because, as we have seen above, the
  3775. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3776. checker enforces the rule that the argument of \code{not} must be a
  3777. \key{Boolean}.
  3778. \begin{lstlisting}
  3779. (not (+ 10 (- (+ 12 20))))
  3780. \end{lstlisting}
  3781. The type checker for $R_2$ is a structurally recursive function over
  3782. the AST. Figure~\ref{fig:type-check-R2} defines the
  3783. \code{type-check-exp} function. The code for the type checker is in
  3784. the file \code{type-check-R2.rkt} of the support code.
  3785. %
  3786. Given an input expression \code{e}, the type checker either returns a
  3787. type (\key{Integer} or \key{Boolean}) or it signals an error. The
  3788. type of an integer literal is \code{Integer} and the type of a Boolean
  3789. literal is \code{Boolean}. To handle variables, the type checker uses
  3790. the environment \code{env} to map variables to types. Consider the
  3791. clause for \key{let}. We type check the initializing expression to
  3792. obtain its type \key{T} and then associate type \code{T} with the
  3793. variable \code{x} in the environment used to type check the body of
  3794. the \key{let}. Thus, when the type checker encounters a use of
  3795. variable \code{x}, it can find its type in the environment.
  3796. \begin{figure}[tbp]
  3797. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3798. (define (type-check-exp env)
  3799. (lambda (e)
  3800. (match e
  3801. [(Var x)
  3802. (let ([t (dict-ref env x)])
  3803. (values (Var x) t))]
  3804. [(Int n) (values (Int n) 'Integer)]
  3805. [(Bool b) (values (Bool b) 'Boolean)]
  3806. [(Let x e body)
  3807. (define-values (e^ Te) ((type-check-exp env) e))
  3808. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  3809. (values (Let x e^ b) Tb)]
  3810. [(If cnd thn els)
  3811. (define-values (c Tc) ((type-check-exp env) cnd))
  3812. (define-values (t Tt) ((type-check-exp env) thn))
  3813. (define-values (e Te) ((type-check-exp env) els))
  3814. (unless (type-equal? Tc 'Boolean)
  3815. (error 'type-check-exp "condition should be Boolean, not ~a" Tc))
  3816. (unless (type-equal? Tt Te)
  3817. (error 'type-check-exp "types of branches not equal, ~a != ~a" Tt Te))
  3818. (values (If c t e) Te)]
  3819. [(Prim 'eq? (list e1 e2))
  3820. (define-values (e1^ T1) ((type-check-exp env) e1))
  3821. (define-values (e2^ T2) ((type-check-exp env) e2))
  3822. (unless (type-equal? T1 T2)
  3823. (error 'type-check-exp "argument types of eq?: ~a != ~a" T1 T2))
  3824. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  3825. [(Prim op es)
  3826. (define-values (new-es ts)
  3827. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  3828. (define t-ret (type-check-op op ts))
  3829. (values (Prim op new-es) t-ret)]
  3830. [else
  3831. (error 'type-check-exp "couldn't match" e)])))
  3832. (define (type-check-R2 e)
  3833. (match e
  3834. [(Program info body)
  3835. (define-values (body^ Tb) ((type-check-exp '()) body))
  3836. (unless (type-equal? Tb 'Integer)
  3837. (error 'type-check-R2 "result type must be Integer, not ~a" Tb))
  3838. (Program info body^)]
  3839. [else (error 'type-check-R2 "couldn't match ~a" e)]))
  3840. \end{lstlisting}
  3841. \caption{Type checker for the $R_2$ language.}
  3842. \label{fig:type-check-R2}
  3843. \end{figure}
  3844. Figure~\ref{fig:type-check-aux-R2} defines three auxilliary functions
  3845. that are used in the type checker. The \code{operator-types} function
  3846. defines a dictionary that maps the operator names to their parameter
  3847. and return types. The \code{type-equal?} function determines whether
  3848. two types are equal, which for now simply dispatches to \code{equal?}
  3849. (deep equality). The \code{type-check-op} function looks up the
  3850. operator in the \code{operator-types} dictionary and then checks
  3851. whether the argument types are equal to the parameter types. The
  3852. result is the return type of the operator.
  3853. \begin{figure}[tbp]
  3854. \begin{lstlisting}
  3855. (define (operator-types)
  3856. '((+ . ((Integer Integer) . Integer))
  3857. (- . ((Integer Integer) . Integer))
  3858. (and . ((Boolean Boolean) . Boolean))
  3859. (or . ((Boolean Boolean) . Boolean))
  3860. (< . ((Integer Integer) . Boolean))
  3861. (<= . ((Integer Integer) . Boolean))
  3862. (> . ((Integer Integer) . Boolean))
  3863. (>= . ((Integer Integer) . Boolean))
  3864. (- . ((Integer) . Integer))
  3865. (not . ((Boolean) . Boolean))
  3866. (read . (() . Integer))
  3867. ))
  3868. (define (type-equal? t1 t2)
  3869. (equal? t1 t2))
  3870. (define (type-check-op op arg-types)
  3871. (match (dict-ref (operator-types) op)
  3872. [`(,param-types . ,return-type)
  3873. (for ([at arg-types] [pt param-types])
  3874. (unless (type-equal? at pt)
  3875. (error 'type-check-op
  3876. "argument and parameter mismatch, ~a != ~a" at pt)))
  3877. return-type]
  3878. [else
  3879. (error 'type-check-op "unrecognized operator ~a" op)]))
  3880. \end{lstlisting}
  3881. \caption{Auxilliary functions for type checking.}
  3882. \label{fig:type-check-aux-R2}
  3883. \end{figure}
  3884. \begin{exercise}\normalfont
  3885. Create 10 new example programs in $R_2$. Half of the example programs
  3886. should have a type error. For those programs, to signal that a type
  3887. error is expected, create an empty file with the same base name but
  3888. with file extension \code{.tyerr}. For example, if the test
  3889. \code{r2\_14.rkt} is expected to error, then create an empty file
  3890. named \code{r2\_14.tyerr}. The other half of the example programs
  3891. should not have type errors. Note that if the type checker does not
  3892. signal an error for a program, then interpreting that program should
  3893. not encounter an error.
  3894. \end{exercise}
  3895. \section{Shrink the $R_2$ Language}
  3896. \label{sec:shrink-r2}
  3897. The $R_2$ language includes several operators that are easily
  3898. expressible in terms of other operators. For example, subtraction is
  3899. expressible in terms of addition and negation.
  3900. \[
  3901. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3902. \]
  3903. Several of the comparison operations are expressible in terms of
  3904. less-than and logical negation.
  3905. \[
  3906. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3907. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3908. \]
  3909. The \key{let} is needed in the above translation to ensure that
  3910. expression $e_1$ is evaluated before $e_2$.
  3911. By performing these translations near the front-end of the compiler,
  3912. the later passes of the compiler do not need to deal with these
  3913. constructs, making those passes shorter. On the other hand, sometimes
  3914. these translations make it more difficult to generate the most
  3915. efficient code with respect to the number of instructions. However,
  3916. these differences typically do not affect the number of accesses to
  3917. memory, which is the primary factor that determines execution time on
  3918. modern computer architectures.
  3919. \begin{exercise}\normalfont
  3920. Implement the pass \code{shrink} that removes subtraction,
  3921. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3922. by translating them to other constructs in $R_2$. Create tests to
  3923. make sure that the behavior of all of these constructs stays the
  3924. same after translation.
  3925. \end{exercise}
  3926. \section{The x86$_1$ Language}
  3927. \label{sec:x86-1}
  3928. \index{x86}
  3929. To implement the new logical operations, the comparison operations,
  3930. and the \key{if} expression, we need to delve further into the x86
  3931. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3932. the concrete and abstract syntax for a larger subset of x86 that
  3933. includes instructions for logical operations, comparisons, and
  3934. conditional jumps.
  3935. One small challenge is that x86 does not provide an instruction that
  3936. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3937. However, the \code{xorq} instruction can be used to encode \code{not}.
  3938. The \key{xorq} instruction takes two arguments, performs a pairwise
  3939. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3940. and writes the results into its second argument. Recall the truth
  3941. table for exclusive-or:
  3942. \begin{center}
  3943. \begin{tabular}{l|cc}
  3944. & 0 & 1 \\ \hline
  3945. 0 & 0 & 1 \\
  3946. 1 & 1 & 0
  3947. \end{tabular}
  3948. \end{center}
  3949. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3950. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3951. for the bit $1$, the result is the opposite of the second bit. Thus,
  3952. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3953. the first argument:
  3954. \[
  3955. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3956. \qquad\Rightarrow\qquad
  3957. \begin{array}{l}
  3958. \key{movq}~ \Arg\key{,} \Var\\
  3959. \key{xorq}~ \key{\$1,} \Var
  3960. \end{array}
  3961. \]
  3962. \begin{figure}[tp]
  3963. \fbox{
  3964. \begin{minipage}{0.96\textwidth}
  3965. \[
  3966. \begin{array}{lcl}
  3967. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3968. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3969. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3970. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3971. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3972. \key{subq} \; \Arg\key{,} \Arg \mid
  3973. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3974. && \gray{ \key{callq} \; \itm{label} \mid
  3975. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3976. && \gray{ \itm{label}\key{:}\; \Instr }
  3977. \mid \key{xorq}~\Arg\key{,}~\Arg
  3978. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3979. && \key{set}cc~\Arg
  3980. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3981. \mid \key{j}cc~\itm{label}
  3982. \\
  3983. x86_1 &::= & \gray{ \key{.globl main} }\\
  3984. & & \gray{ \key{main:} \; \Instr\ldots }
  3985. \end{array}
  3986. \]
  3987. \end{minipage}
  3988. }
  3989. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3990. \label{fig:x86-1-concrete}
  3991. \end{figure}
  3992. \begin{figure}[tp]
  3993. \fbox{
  3994. \begin{minipage}{0.96\textwidth}
  3995. \small
  3996. \[
  3997. \begin{array}{lcl}
  3998. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3999. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4000. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4001. \mid \BYTEREG{\itm{bytereg}} \\
  4002. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4003. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  4004. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  4005. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4006. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  4007. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4008. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4009. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  4010. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  4011. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  4012. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  4013. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4014. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  4015. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  4016. \end{array}
  4017. \]
  4018. \end{minipage}
  4019. }
  4020. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  4021. \label{fig:x86-1}
  4022. \end{figure}
  4023. Next we consider the x86 instructions that are relevant for compiling
  4024. the comparison operations. The \key{cmpq} instruction compares its two
  4025. arguments to determine whether one argument is less than, equal, or
  4026. greater than the other argument. The \key{cmpq} instruction is unusual
  4027. regarding the order of its arguments and where the result is
  4028. placed. The argument order is backwards: if you want to test whether
  4029. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4030. \key{cmpq} is placed in the special EFLAGS register. This register
  4031. cannot be accessed directly but it can be queried by a number of
  4032. instructions, including the \key{set} instruction. The \key{set}
  4033. instruction puts a \key{1} or \key{0} into its destination depending
  4034. on whether the comparison came out according to the condition code
  4035. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4036. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4037. The \key{set} instruction has an annoying quirk in that its
  4038. destination argument must be single byte register, such as \code{al}
  4039. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4040. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4041. then be used to move from a single byte register to a normal 64-bit
  4042. register.
  4043. The x86 instruction for conditional jump are relevant to the
  4044. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4045. updates the program counter to point to the instruction after the
  4046. indicated label depending on whether the result in the EFLAGS register
  4047. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4048. instruction falls through to the next instruction. The abstract
  4049. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4050. that it separates the instruction name from the condition code. For
  4051. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4052. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4053. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4054. instruction to set the EFLAGS register.
  4055. \section{The $C_1$ Intermediate Language}
  4056. \label{sec:c1}
  4057. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  4058. we need to grow that intermediate language to handle the new features
  4059. in $R_2$: Booleans and conditional expressions.
  4060. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  4061. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  4062. particular, we add logical and comparison operators to the $\Exp$
  4063. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  4064. non-terminal. Regarding control flow, $C_1$ differs considerably from
  4065. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  4066. conditional \key{goto} in the grammar for $\Tail$. This means that a
  4067. sequence of statements may now end with a \code{goto} or a conditional
  4068. \code{goto}. The conditional \code{goto} jumps to one of two labels
  4069. depending on the outcome of the comparison. In
  4070. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  4071. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  4072. and \key{goto}'s.
  4073. \begin{figure}[tbp]
  4074. \fbox{
  4075. \begin{minipage}{0.96\textwidth}
  4076. \small
  4077. \[
  4078. \begin{array}{lcl}
  4079. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  4080. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4081. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  4082. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  4083. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  4084. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  4085. \mid \key{goto}~\itm{label}\key{;}\\
  4086. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  4087. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  4088. \end{array}
  4089. \]
  4090. \end{minipage}
  4091. }
  4092. \caption{The concrete syntax of the $C_1$ intermediate language.}
  4093. \label{fig:c1-concrete-syntax}
  4094. \end{figure}
  4095. \begin{figure}[tp]
  4096. \fbox{
  4097. \begin{minipage}{0.96\textwidth}
  4098. \small
  4099. \[
  4100. \begin{array}{lcl}
  4101. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4102. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4103. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4104. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4105. &\mid& \UNIOP{\key{'not}}{\Atm}
  4106. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4107. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4108. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4109. \mid \GOTO{\itm{label}} \\
  4110. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4111. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4112. \end{array}
  4113. \]
  4114. \end{minipage}
  4115. }
  4116. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  4117. (Figure~\ref{fig:c0-syntax}).}
  4118. \label{fig:c1-syntax}
  4119. \end{figure}
  4120. \clearpage
  4121. \section{Remove Complex Operands}
  4122. \label{sec:remove-complex-opera-R2}
  4123. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4124. \code{rco-atom} functions according to the definition of the output
  4125. language for this pass, $R_2^{\dagger}$, the administrative normal
  4126. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4127. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4128. three sub-expressions of an \code{If} are allowed to be complex
  4129. expressions in the output of \code{remove-complex-opera*}, but the
  4130. operands of \code{not} and the comparisons must be atoms. Regarding
  4131. the \code{If} form, it is particularly important to \textbf{not}
  4132. replace its condition with a temporary variable because that would
  4133. interfere with the generation of high-quality output in the
  4134. \code{explicate-control} pass.
  4135. \begin{figure}[tp]
  4136. \centering
  4137. \fbox{
  4138. \begin{minipage}{0.96\textwidth}
  4139. \[
  4140. \begin{array}{rcl}
  4141. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4142. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4143. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4144. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4145. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4146. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4147. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4148. \end{array}
  4149. \]
  4150. \end{minipage}
  4151. }
  4152. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4153. \label{fig:r2-anf-syntax}
  4154. \end{figure}
  4155. \section{Explicate Control}
  4156. \label{sec:explicate-control-r2}
  4157. Recall that the purpose of \code{explicate-control} is to make the
  4158. order of evaluation explicit in the syntax of the program. With the
  4159. addition of \key{if} in $R_2$ this get more interesting.
  4160. As a motivating example, consider the following program that has an
  4161. \key{if} expression nested in the predicate of another \key{if}.
  4162. % s1_41.rkt
  4163. \begin{center}
  4164. \begin{minipage}{0.96\textwidth}
  4165. \begin{lstlisting}
  4166. (let ([x (read)])
  4167. (let ([y (read)])
  4168. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4169. (+ y 2)
  4170. (+ y 10))))
  4171. \end{lstlisting}
  4172. \end{minipage}
  4173. \end{center}
  4174. %
  4175. The naive way to compile \key{if} and the comparison would be to
  4176. handle each of them in isolation, regardless of their context. Each
  4177. comparison would be translated into a \key{cmpq} instruction followed
  4178. by a couple instructions to move the result from the EFLAGS register
  4179. into a general purpose register or stack location. Each \key{if} would
  4180. be translated into the combination of a \key{cmpq} and a conditional
  4181. jump. The generated code for the inner \key{if} in the above example
  4182. would be as follows.
  4183. \begin{center}
  4184. \begin{minipage}{0.96\textwidth}
  4185. \begin{lstlisting}
  4186. ...
  4187. cmpq $1, x ;; (< x 1)
  4188. setl %al
  4189. movzbq %al, tmp
  4190. cmpq $1, tmp ;; (if (< x 1) ...)
  4191. je then_branch_1
  4192. jmp else_branch_1
  4193. ...
  4194. \end{lstlisting}
  4195. \end{minipage}
  4196. \end{center}
  4197. However, if we take context into account we can do better and reduce
  4198. the use of \key{cmpq} and EFLAG-accessing instructions.
  4199. One idea is to try and reorganize the code at the level of $R_2$,
  4200. pushing the outer \key{if} inside the inner one. This would yield the
  4201. following code.
  4202. \begin{center}
  4203. \begin{minipage}{0.96\textwidth}
  4204. \begin{lstlisting}
  4205. (let ([x (read)])
  4206. (let ([y (read)])
  4207. (if (< x 1)
  4208. (if (eq? x 0)
  4209. (+ y 2)
  4210. (+ y 10))
  4211. (if (eq? x 2)
  4212. (+ y 2)
  4213. (+ y 10)))))
  4214. \end{lstlisting}
  4215. \end{minipage}
  4216. \end{center}
  4217. Unfortunately, this approach duplicates the two branches, and a
  4218. compiler must never duplicate code!
  4219. We need a way to perform the above transformation, but without
  4220. duplicating code. That is, we need a way for different parts of a
  4221. program to refer to the same piece of code, that is, to \emph{share}
  4222. code. At the level of x86 assembly this is straightforward because we
  4223. can label the code for each of the branches and insert jumps in all
  4224. the places that need to execute the branches. At the higher level of
  4225. our intermediate languages, we need to move away from abstract syntax
  4226. \emph{trees} and instead use \emph{graphs}. In particular, we use a
  4227. standard program representation called a \emph{control flow graph}
  4228. (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4229. \index{control-flow graph} Each vertex is a labeled sequence of code,
  4230. called a \emph{basic block}, and each edge represents a jump to
  4231. another block. The \key{Program} construct of $C_0$ and $C_1$ contains
  4232. a control flow graph represented as an alist mapping labels to basic
  4233. blocks. Each basic block is represented by the $\Tail$ non-terminal.
  4234. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4235. \code{remove-complex-opera*} pass and then the
  4236. \code{explicate-control} pass on the example program. We walk through
  4237. the output program and then discuss the algorithm.
  4238. %
  4239. Following the order of evaluation in the output of
  4240. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4241. and then the less-than-comparison to \code{1} in the predicate of the
  4242. inner \key{if}. In the output of \code{explicate-control}, in the
  4243. block labeled \code{start}, this becomes two assignment statements
  4244. followed by a conditional \key{goto} to label \code{block40} or
  4245. \code{block41}. The blocks associated with those labels contain the
  4246. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4247. respectively. Regarding the block labeled with \code{block40}, we
  4248. start with the comparison to \code{0} and then have a conditional
  4249. goto, either to label \code{block38} or label \code{block39}, which
  4250. are the two branches of the outer \key{if}, i.e., \code{(+ y 2)} and
  4251. \code{(+ y 10)}. The story for the block labeled \code{block41} is
  4252. similar.
  4253. \begin{figure}[tbp]
  4254. \begin{tabular}{lll}
  4255. \begin{minipage}{0.4\textwidth}
  4256. % s1_41.rkt
  4257. \begin{lstlisting}
  4258. (let ([x (read)])
  4259. (let ([y (read)])
  4260. (if (if (< x 1)
  4261. (eq? x 0)
  4262. (eq? x 2))
  4263. (+ y 2)
  4264. (+ y 10))))
  4265. \end{lstlisting}
  4266. \hspace{40pt}$\Downarrow$
  4267. \begin{lstlisting}
  4268. (let ([x (read)])
  4269. (let ([y (read)])
  4270. (if (if (< x 1)
  4271. (eq? x 0)
  4272. (eq? x 2))
  4273. (+ y 2)
  4274. (+ y 10))))
  4275. \end{lstlisting}
  4276. \end{minipage}
  4277. &
  4278. $\Rightarrow$
  4279. &
  4280. \begin{minipage}{0.55\textwidth}
  4281. \begin{lstlisting}
  4282. start:
  4283. x = (read);
  4284. y = (read);
  4285. if (< x 1)
  4286. goto block40;
  4287. else
  4288. goto block41;
  4289. block40:
  4290. if (eq? x 0)
  4291. goto block38;
  4292. else
  4293. goto block39;
  4294. block41:
  4295. if (eq? x 2)
  4296. goto block38;
  4297. else
  4298. goto block39;
  4299. block38:
  4300. return (+ y 2);
  4301. block39:
  4302. return (+ y 10);
  4303. \end{lstlisting}
  4304. \end{minipage}
  4305. \end{tabular}
  4306. \caption{Translation from $R_2$ to $C_1$
  4307. via the \code{explicate-control}.}
  4308. \label{fig:explicate-control-s1-38}
  4309. \end{figure}
  4310. The nice thing about the output of \code{explicate-control} is that
  4311. there are no unnecessary comparisons and every comparison is part of a
  4312. conditional jump.
  4313. %% The down-side of this output is that it includes
  4314. %% trivial blocks, such as the blocks labeled \code{block92} through
  4315. %% \code{block95}, that only jump to another block. We discuss a solution
  4316. %% to this problem in Section~\ref{sec:opt-jumps}.
  4317. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4318. \code{explicate-control} for $R_1$ using two mutually recursive
  4319. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4320. former function translates expressions in tail position whereas the
  4321. later function translates expressions on the right-hand-side of a
  4322. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4323. new kind of context to deal with: the predicate position of the
  4324. \key{if}. We need another function, \code{explicate-pred}, that takes
  4325. an $R_2$ expression and two blocks for the then-branch and
  4326. else-branch. The output of \code{explicate-pred} is a block.
  4327. %
  4328. %% Note that the three explicate functions need to construct a
  4329. %% control-flow graph, which we recommend they do via updates to a global
  4330. %% variable.
  4331. %
  4332. In the following paragraphs we discuss specific cases in the
  4333. \code{explicate-pred} function as well as the additions to the
  4334. \code{explicate-tail} and \code{explicate-assign} functions.
  4335. The function \code{explicate-pred} will need a case for every
  4336. expression that can have type \code{Boolean}. We detail a few cases
  4337. here and leave the rest for the reader. The input to this function is
  4338. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4339. the enclosing \key{if}, though some care will be needed regarding how
  4340. we represent the blocks. Suppose the expression is the Boolean
  4341. \code{\#t}. Then we can perform a kind of partial evaluation
  4342. \index{partial evaluation} and translate it to the ``then'' branch
  4343. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4344. \[
  4345. \key{\#t} \quad\Rightarrow\quad B_1,
  4346. \qquad\qquad\qquad
  4347. \key{\#f} \quad\Rightarrow\quad B_2
  4348. \]
  4349. These two cases demonstrate that we sometimes discard one of the
  4350. blocks that are input to \code{explicate-pred}. We will need to
  4351. arrange for the blocks that we actually use to appear in the resulting
  4352. control-flow graph, but not the discarded blocks.
  4353. The case for \key{if} in \code{explicate-pred} is particularly
  4354. illuminating as it deals with the challenges that we discussed above
  4355. regarding the example of the nested \key{if} expressions. The
  4356. ``then'' and ``else'' branches of the current \key{if} inherit their
  4357. context from the current one, that is, predicate context. So we
  4358. recursively apply \code{explicate-pred} to the ``then'' and ``else''
  4359. branches. For both of those recursive calls, we shall pass the blocks
  4360. $B_1$ and $B_2$. Thus, $B_1$ may get used twice, once inside each
  4361. recursive call, and likewise for $B_2$. As discussed above, to avoid
  4362. duplicating code, we need to add these blocks to the control-flow
  4363. graph so that we can instead refer to them by name and execute them
  4364. with a \key{goto}. However, as we saw in the cases above for \key{\#t}
  4365. and \key{\#f}, the blocks $B_1$ or $B_2$ may not get used at all and
  4366. we don't want to prematurely add them to the control-flow graph if
  4367. they end up being discarded.
  4368. The solution to this conundrum is to use \emph{lazy evaluation} to
  4369. delay adding the blocks to the control-flow graph until the points
  4370. where we know they will be used~\citep{Friedman:1976aa}.\index{lazy
  4371. evaluation} Racket provides support for lazy evaluation with the
  4372. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4373. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4374. \index{delay} creates a \emph{promise}\index{promise} in which the
  4375. evaluation of the expressions is postponed. When \key{(force}
  4376. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4377. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4378. $e_n$ is cached in the promise and returned. If \code{force} is
  4379. applied again to the same promise, then the cached result is returned.
  4380. We use lazy evaluation for the input and output blocks of the
  4381. functions \code{explicate-pred} and \code{explicate-assign} and for
  4382. the output block of \code{explicate-tail}. So instead of taking and
  4383. returns blocks, they take and return promised blocks. Furthermore,
  4384. when we come to a situation in which we a block might be used more
  4385. than once, as in the case for \code{if} above, we can transform the
  4386. promise into a new promise that will add the block to the control-flow
  4387. graph and return a \code{goto}. The following auxiliary function
  4388. accomplishes this task. It begins with \code{delay} to create a
  4389. promise. When forced, it will in turn force the input block. If that
  4390. block is already a \code{goto} (because it was already added to the
  4391. control-flow graph), then we return that \code{goto}. Otherwise we add
  4392. the block to the control-flow graph with another auxiliary function
  4393. named \code{add-node} that returns the new label, and then return the
  4394. \code{goto}.
  4395. \begin{lstlisting}
  4396. (define (block->goto block)
  4397. (delay
  4398. (define b (force block))
  4399. (match b
  4400. [(Goto label) (Goto label)]
  4401. [else (Goto (add-node b))]
  4402. )))
  4403. \end{lstlisting}
  4404. Getting back to the case for \code{if} in \code{explicate-pred}, we
  4405. make the recursive calls to \code{explicate-pred} on the ``then'' and
  4406. ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4407. and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4408. results from the two recursive calls. We complete the case for
  4409. \code{if} by recursively apply \code{explicate-pred} to the condition
  4410. of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4411. the result $B_5$.
  4412. \[
  4413. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4414. \quad\Rightarrow\quad
  4415. B_5
  4416. \]
  4417. Next, consider the case for a less-than comparison in
  4418. \code{explicate-pred}. We translate it to an \code{if} statement,
  4419. whose two branches are required to be \code{goto}'s. So we apply
  4420. \code{block->goto} to $B_1$ and $B_2$ to obtain two promised goto's,
  4421. which we can \code{force} to obtain the two actual goto's $G_1$ and
  4422. $G_2$. The translation of the less-than comparison is as follows.
  4423. \[
  4424. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4425. \begin{array}{l}
  4426. \key{if}~(\key{<}~e_1~e_2) \; G_1\\
  4427. \key{else} \; G_2
  4428. \end{array}
  4429. \]
  4430. The \code{explicate-tail} function needs to be updated to use lazy
  4431. evaluation and it needs an additional case for \key{if}. Each of the
  4432. cases that return an AST node need use \code{delay} to instead return
  4433. a promise of an AST node. Recall that \code{explicate-tail} has an
  4434. accumulator parameter that is a block, which now becomes a promise of
  4435. a block, which we refer to as $B_0$.
  4436. In the case for \code{if} in \code{explicate-tail}, the two branches
  4437. inherit the current context, so they are in tail position. Thus, the
  4438. recursive calls on the ``then'' and ``else'' branch should be calls to
  4439. \code{explicate-tail}.
  4440. %
  4441. We need to pass $B_0$ as the accumulator argument for both of these
  4442. recursive calls, but we need to be careful not to duplicate $B_0$.
  4443. Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4444. to the control-flow graph and obtain a promised goto $G_0$.
  4445. %
  4446. Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4447. branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4448. on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4449. \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4450. $B_2$. Then the \key{if} as a whole translates to $B_3$.
  4451. \[
  4452. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4453. \]
  4454. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4455. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4456. %% should not be confused with the labels for the blocks that appear in
  4457. %% the generated code. We initially construct unlabeled blocks; we only
  4458. %% attach labels to blocks when we add them to the control-flow graph, as
  4459. %% we see in the next case.
  4460. Next consider the case for \key{if} in the \code{explicate-assign}
  4461. function. The context of the \key{if} is an assignment to some
  4462. variable $x$ and then the control continues to some promised block
  4463. $B_1$. The code that we generate for both the ``then'' and ``else''
  4464. branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4465. apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4466. branches of the \key{if} inherit the current context, so they are in
  4467. assignment positions. Let $B_2$ be the result of applying
  4468. \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4469. $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4470. the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4471. the result of applying \code{explicate-pred} to the predicate
  4472. $\itm{cnd}$ and the blocks $B_2$ and $B_3$. The \key{if} as a whole
  4473. translates to the block $B_4$.
  4474. \[
  4475. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4476. \]
  4477. This completes the description of \code{explicate-control} for $R_2$.
  4478. The way in which the \code{shrink} pass transforms logical operations
  4479. such as \code{and} and \code{or} can impact the quality of code
  4480. generated by \code{explicate-control}. For example, consider the
  4481. following program.
  4482. % s1_21.rkt
  4483. \begin{lstlisting}
  4484. (if (and (eq? (read) 0) (eq? (read) 1))
  4485. 0
  4486. 42)
  4487. \end{lstlisting}
  4488. The \code{and} operation should transform into something that the
  4489. \code{explicat-pred} function can still analyze and descend through to
  4490. reach the underlying \code{eq?} conditions. Ideally, your
  4491. \code{explicate-control} pass should generate code similar to the
  4492. following for the above program.
  4493. \begin{center}
  4494. \begin{lstlisting}
  4495. start:
  4496. tmp1 = (read);
  4497. if (eq? tmp1 0)
  4498. goto block40;
  4499. else
  4500. goto block39;
  4501. block40:
  4502. tmp2 = (read);
  4503. if (eq? tmp2 1)
  4504. goto block38;
  4505. else
  4506. goto block39;
  4507. block38:
  4508. return 0;
  4509. block39:
  4510. return 42;
  4511. \end{lstlisting}
  4512. \end{center}
  4513. \begin{exercise}\normalfont
  4514. Implement the pass \code{explicate-control} by adding the cases for
  4515. \key{if} to the functions for tail and assignment contexts, and
  4516. implement \code{explicate-pred} for predicate contexts. Create test
  4517. cases that exercise all of the new cases in the code for this pass.
  4518. \end{exercise}
  4519. \section{Select Instructions}
  4520. \label{sec:select-r2}
  4521. \index{instruction selection}
  4522. Recall that the \code{select-instructions} pass lowers from our
  4523. $C$-like intermediate representation to the pseudo-x86 language, which
  4524. is suitable for conducting register allocation. The pass is
  4525. implemented using three auxiliary functions, one for each of the
  4526. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4527. For $\Atm$, we have new cases for the Booleans. We take the usual
  4528. approach of encoding them as integers, with true as 1 and false as 0.
  4529. \[
  4530. \key{\#t} \Rightarrow \key{1}
  4531. \qquad
  4532. \key{\#f} \Rightarrow \key{0}
  4533. \]
  4534. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4535. be implemented in terms of \code{xorq} as we discussed at the
  4536. beginning of this section. Given an assignment
  4537. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4538. if the left-hand side $\itm{var}$ is
  4539. the same as $\Atm$, then just the \code{xorq} suffices.
  4540. \[
  4541. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4542. \quad\Rightarrow\quad
  4543. \key{xorq}~\key{\$}1\key{,}~\Var
  4544. \]
  4545. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4546. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4547. x86. Then we have
  4548. \[
  4549. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4550. \quad\Rightarrow\quad
  4551. \begin{array}{l}
  4552. \key{movq}~\Arg\key{,}~\Var\\
  4553. \key{xorq}~\key{\$}1\key{,}~\Var
  4554. \end{array}
  4555. \]
  4556. Next consider the cases for \code{eq?} and less-than comparison.
  4557. Translating these operations to x86 is slightly involved due to the
  4558. unusual nature of the \key{cmpq} instruction discussed above. We
  4559. recommend translating an assignment from \code{eq?} into the following
  4560. sequence of three instructions. \\
  4561. \begin{tabular}{lll}
  4562. \begin{minipage}{0.4\textwidth}
  4563. \begin{lstlisting}
  4564. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4565. \end{lstlisting}
  4566. \end{minipage}
  4567. &
  4568. $\Rightarrow$
  4569. &
  4570. \begin{minipage}{0.4\textwidth}
  4571. \begin{lstlisting}
  4572. cmpq |$\Arg_2$|, |$\Arg_1$|
  4573. sete %al
  4574. movzbq %al, |$\Var$|
  4575. \end{lstlisting}
  4576. \end{minipage}
  4577. \end{tabular} \\
  4578. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4579. and conditional \key{goto}. Both are straightforward to handle. A
  4580. \key{goto} becomes a jump instruction.
  4581. \[
  4582. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4583. \]
  4584. A conditional \key{goto} becomes a compare instruction followed
  4585. by a conditional jump (for ``then'') and the fall-through is
  4586. to a regular jump (for ``else'').\\
  4587. \begin{tabular}{lll}
  4588. \begin{minipage}{0.4\textwidth}
  4589. \begin{lstlisting}
  4590. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4591. goto |$\ell_1$|;
  4592. else
  4593. goto |$\ell_2$|;
  4594. \end{lstlisting}
  4595. \end{minipage}
  4596. &
  4597. $\Rightarrow$
  4598. &
  4599. \begin{minipage}{0.4\textwidth}
  4600. \begin{lstlisting}
  4601. cmpq |$\Arg_2$|, |$\Arg_1$|
  4602. je |$\ell_1$|
  4603. jmp |$\ell_2$|
  4604. \end{lstlisting}
  4605. \end{minipage}
  4606. \end{tabular} \\
  4607. \begin{exercise}\normalfont
  4608. Expand your \code{select-instructions} pass to handle the new features
  4609. of the $R_2$ language. Test the pass on all the examples you have
  4610. created and make sure that you have some test programs that use the
  4611. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4612. the output using the \code{interp-x86} interpreter
  4613. (Appendix~\ref{appendix:interp}).
  4614. \end{exercise}
  4615. \section{Register Allocation}
  4616. \label{sec:register-allocation-r2}
  4617. \index{register allocation}
  4618. The changes required for $R_2$ affect liveness analysis, building the
  4619. interference graph, and assigning homes, but the graph coloring
  4620. algorithm itself does not change.
  4621. \subsection{Liveness Analysis}
  4622. \label{sec:liveness-analysis-r2}
  4623. \index{liveness analysis}
  4624. Recall that for $R_1$ we implemented liveness analysis for a single
  4625. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4626. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4627. produces many basic blocks arranged in a control-flow graph. The first
  4628. question we need to consider is: what order should we process the
  4629. basic blocks? Recall that to perform liveness analysis, we need to
  4630. know the live-after set. If a basic block has no successor blocks
  4631. (i.e. no out-edges in the control flow graph), then it has an empty
  4632. live-after set and we can immediately apply liveness analysis to
  4633. it. If a basic block has some successors, then we need to complete
  4634. liveness analysis on those blocks first. Furthermore, we know that
  4635. the control flow graph does not contain any cycles because $R_2$ does
  4636. not include loops
  4637. %
  4638. \footnote{If we were to add loops to the language, then the CFG could
  4639. contain cycles and we would instead need to use the classic worklist
  4640. algorithm for computing the fixed point of the liveness
  4641. analysis~\citep{Aho:1986qf}.}.
  4642. %
  4643. Returning to the question of what order should we process the basic
  4644. blocks, the answer is reverse topological order. We recommend using
  4645. the \code{tsort} (topological sort) and \code{transpose} functions of
  4646. the Racket \code{graph} package to obtain this ordering.
  4647. \index{topological order}
  4648. \index{topological sort}
  4649. The next question is how to compute the live-after set of a block
  4650. given the live-before sets of all its successor blocks. (There can be
  4651. more than one because of conditional jumps.) During compilation we do
  4652. not know which way a conditional jump will go, so we do not know which
  4653. of the successor's live-before set to use. The solution to this
  4654. challenge is based on the observation that there is no harm to the
  4655. correctness of the compiler if we classify more variables as live than
  4656. the ones that are truly live during a particular execution of the
  4657. block. Thus, we can take the union of the live-before sets from all
  4658. the successors to be the live-after set for the block. Once we have
  4659. computed the live-after set, we can proceed to perform liveness
  4660. analysis on the block just as we did in
  4661. Section~\ref{sec:liveness-analysis-r1}.
  4662. The helper functions for computing the variables in an instruction's
  4663. argument and for computing the variables read-from ($R$) or written-to
  4664. ($W$) by an instruction need to be updated to handle the new kinds of
  4665. arguments and instructions in x86$_1$.
  4666. \subsection{Build Interference}
  4667. \label{sec:build-interference-r2}
  4668. Many of the new instructions in x86$_1$ can be handled in the same way
  4669. as the instructions in x86$_0$. Thus, if your code was already quite
  4670. general, it will not need to be changed to handle the new
  4671. instructions. If you code is not general enough, I recommend that you
  4672. change your code to be more general. For example, you can factor out
  4673. the computing of the the read and write sets for each kind of
  4674. instruction into two auxiliary functions.
  4675. Note that the \key{movzbq} instruction requires some special care,
  4676. just like the \key{movq} instruction. See rule number 3 in
  4677. Section~\ref{sec:build-interference}.
  4678. %% \subsection{Assign Homes}
  4679. %% \label{sec:assign-homes-r2}
  4680. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4681. %% to be updated to handle the \key{if} statement, simply by recursively
  4682. %% processing the child nodes. Hopefully your code already handles the
  4683. %% other new instructions, but if not, you can generalize your code.
  4684. \begin{exercise}\normalfont
  4685. Update the \code{register-allocation} pass so that it works for $R_2$
  4686. and test your compiler using your previously created programs on the
  4687. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4688. \end{exercise}
  4689. \section{Patch Instructions}
  4690. The second argument of the \key{cmpq} instruction must not be an
  4691. immediate value (such as an integer). So if you are comparing two
  4692. immediates, we recommend inserting a \key{movq} instruction to put the
  4693. second argument in \key{rax}.
  4694. %
  4695. The second argument of the \key{movzbq} must be a register.
  4696. %
  4697. There are no special restrictions on the x86 instructions \key{JmpIf}
  4698. and \key{Jmp}.
  4699. \begin{exercise}\normalfont
  4700. Update \code{patch-instructions} to handle the new x86 instructions.
  4701. Test your compiler using your previously created programs on the
  4702. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4703. \end{exercise}
  4704. \section{An Example Translation}
  4705. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4706. $R_2$ translated to x86, showing the results of
  4707. \code{explicate-control}, \code{select-instructions}, and the final
  4708. x86 assembly code.
  4709. \begin{figure}[tbp]
  4710. \begin{tabular}{lll}
  4711. \begin{minipage}{0.5\textwidth}
  4712. % s1_20.rkt
  4713. \begin{lstlisting}
  4714. (if (eq? (read) 1) 42 0)
  4715. \end{lstlisting}
  4716. $\Downarrow$
  4717. \begin{lstlisting}
  4718. start:
  4719. tmp7951 = (read);
  4720. if (eq? tmp7951 1) then
  4721. goto block7952;
  4722. else
  4723. goto block7953;
  4724. block7952:
  4725. return 42;
  4726. block7953:
  4727. return 0;
  4728. \end{lstlisting}
  4729. $\Downarrow$
  4730. \begin{lstlisting}
  4731. start:
  4732. callq read_int
  4733. movq %rax, tmp7951
  4734. cmpq $1, tmp7951
  4735. je block7952
  4736. jmp block7953
  4737. block7953:
  4738. movq $0, %rax
  4739. jmp conclusion
  4740. block7952:
  4741. movq $42, %rax
  4742. jmp conclusion
  4743. \end{lstlisting}
  4744. \end{minipage}
  4745. &
  4746. $\Rightarrow\qquad$
  4747. \begin{minipage}{0.4\textwidth}
  4748. \begin{lstlisting}
  4749. start:
  4750. callq read_int
  4751. movq %rax, %rcx
  4752. cmpq $1, %rcx
  4753. je block7952
  4754. jmp block7953
  4755. block7953:
  4756. movq $0, %rax
  4757. jmp conclusion
  4758. block7952:
  4759. movq $42, %rax
  4760. jmp conclusion
  4761. .globl main
  4762. main:
  4763. pushq %rbp
  4764. movq %rsp, %rbp
  4765. pushq %r13
  4766. pushq %r12
  4767. pushq %rbx
  4768. pushq %r14
  4769. subq $0, %rsp
  4770. jmp start
  4771. conclusion:
  4772. addq $0, %rsp
  4773. popq %r14
  4774. popq %rbx
  4775. popq %r12
  4776. popq %r13
  4777. popq %rbp
  4778. retq
  4779. \end{lstlisting}
  4780. \end{minipage}
  4781. \end{tabular}
  4782. \caption{Example compilation of an \key{if} expression to x86.}
  4783. \label{fig:if-example-x86}
  4784. \end{figure}
  4785. \begin{figure}[p]
  4786. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4787. \node (R2) at (0,2) {\large $R_2$};
  4788. \node (R2-2) at (3,2) {\large $R_2$};
  4789. \node (R2-3) at (6,2) {\large $R_2$};
  4790. \node (R2-4) at (9,2) {\large $R_2$};
  4791. \node (R2-5) at (9,0) {\large $R_2$};
  4792. \node (C1-1) at (3,-2) {\large $C_1$};
  4793. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4794. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4795. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4796. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4797. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4798. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4799. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R2-2);
  4800. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4801. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4802. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4803. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4804. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4805. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4806. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4807. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4808. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4809. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4810. \end{tikzpicture}
  4811. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4812. \label{fig:R2-passes}
  4813. \end{figure}
  4814. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4815. compilation of $R_2$.
  4816. \section{Challenge: Optimize and Remove Jumps}
  4817. \label{sec:opt-jumps}
  4818. Recall that in the example output of \code{explicate-control} in
  4819. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4820. \code{block60} are trivial blocks, they do nothing but jump to another
  4821. block. The first goal of this challenge assignment is to remove those
  4822. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4823. \code{explicate-control} on the left and shows the result of bypassing
  4824. the trivial blocks on the right. Let us focus on \code{block61}. The
  4825. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4826. \code{block55}. The optimized code on the right of
  4827. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4828. \code{then} branch jumping directly to \code{block55}. The story is
  4829. similar for the \code{else} branch, as well as for the two branches in
  4830. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4831. have been optimized in this way, there are no longer any jumps to
  4832. blocks \code{block57} through \code{block60}, so they can be removed.
  4833. \begin{figure}[tbp]
  4834. \begin{tabular}{lll}
  4835. \begin{minipage}{0.4\textwidth}
  4836. \begin{lstlisting}
  4837. block62:
  4838. tmp54 = (read);
  4839. if (eq? tmp54 2) then
  4840. goto block59;
  4841. else
  4842. goto block60;
  4843. block61:
  4844. tmp53 = (read);
  4845. if (eq? tmp53 0) then
  4846. goto block57;
  4847. else
  4848. goto block58;
  4849. block60:
  4850. goto block56;
  4851. block59:
  4852. goto block55;
  4853. block58:
  4854. goto block56;
  4855. block57:
  4856. goto block55;
  4857. block56:
  4858. return (+ 700 77);
  4859. block55:
  4860. return (+ 10 32);
  4861. start:
  4862. tmp52 = (read);
  4863. if (eq? tmp52 1) then
  4864. goto block61;
  4865. else
  4866. goto block62;
  4867. \end{lstlisting}
  4868. \end{minipage}
  4869. &
  4870. $\Rightarrow$
  4871. &
  4872. \begin{minipage}{0.55\textwidth}
  4873. \begin{lstlisting}
  4874. block62:
  4875. tmp54 = (read);
  4876. if (eq? tmp54 2) then
  4877. goto block55;
  4878. else
  4879. goto block56;
  4880. block61:
  4881. tmp53 = (read);
  4882. if (eq? tmp53 0) then
  4883. goto block55;
  4884. else
  4885. goto block56;
  4886. block56:
  4887. return (+ 700 77);
  4888. block55:
  4889. return (+ 10 32);
  4890. start:
  4891. tmp52 = (read);
  4892. if (eq? tmp52 1) then
  4893. goto block61;
  4894. else
  4895. goto block62;
  4896. \end{lstlisting}
  4897. \end{minipage}
  4898. \end{tabular}
  4899. \caption{Optimize jumps by removing trivial blocks.}
  4900. \label{fig:optimize-jumps}
  4901. \end{figure}
  4902. The name of this pass is \code{optimize-jumps}. We recommend
  4903. implementing this pass in two phases. The first phrase builds a hash
  4904. table that maps labels to possibly improved labels. The second phase
  4905. changes the target of each \code{goto} to use the improved label. If
  4906. the label is for a trivial block, then the hash table should map the
  4907. label to the first non-trivial block that can be reached from this
  4908. label by jumping through trivial blocks. If the label is for a
  4909. non-trivial block, then the hash table should map the label to itself;
  4910. we do not want to change jumps to non-trivial blocks.
  4911. The first phase can be accomplished by constructing an empty hash
  4912. table, call it \code{short-cut}, and then iterating over the control
  4913. flow graph. Each time you encouter a block that is just a \code{goto},
  4914. then update the hash table, mapping the block's source to the target
  4915. of the \code{goto}. Also, the hash table may already have mapped some
  4916. labels to the block's source, to you must iterate through the hash
  4917. table and update all of those so that they instead map to the target
  4918. of the \code{goto}.
  4919. For the second phase, we recommend iterating through the $\Tail$ of
  4920. each block in the program, updating the target of every \code{goto}
  4921. according to the mapping in \code{short-cut}.
  4922. \begin{exercise}\normalfont
  4923. Implement the \code{optimize-jumps} pass as a transformation from
  4924. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4925. Check that \code{optimize-jumps} removes trivial blocks in a few
  4926. example programs. Then check that your compiler still passes all of
  4927. your tests.
  4928. \end{exercise}
  4929. There is another opportunity for optimizing jumps that is apparent in
  4930. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4931. end with a jump to \code{block7953} and there are no other jumps to
  4932. \code{block7953} in the rest of the program. In this situation we can
  4933. avoid the runtime overhead of this jump by merging \code{block7953}
  4934. into the preceeding block, in this case the \code{start} block.
  4935. Figure~\ref{fig:remove-jumps} shows the output of
  4936. \code{select-instructions} on the left and the result of this
  4937. optimization on the right.
  4938. \begin{figure}[tbp]
  4939. \begin{tabular}{lll}
  4940. \begin{minipage}{0.5\textwidth}
  4941. % s1_20.rkt
  4942. \begin{lstlisting}
  4943. start:
  4944. callq read_int
  4945. movq %rax, tmp7951
  4946. cmpq $1, tmp7951
  4947. je block7952
  4948. jmp block7953
  4949. block7953:
  4950. movq $0, %rax
  4951. jmp conclusion
  4952. block7952:
  4953. movq $42, %rax
  4954. jmp conclusion
  4955. \end{lstlisting}
  4956. \end{minipage}
  4957. &
  4958. $\Rightarrow\qquad$
  4959. \begin{minipage}{0.4\textwidth}
  4960. \begin{lstlisting}
  4961. start:
  4962. callq read_int
  4963. movq %rax, tmp7951
  4964. cmpq $1, tmp7951
  4965. je block7952
  4966. movq $0, %rax
  4967. jmp conclusion
  4968. block7952:
  4969. movq $42, %rax
  4970. jmp conclusion
  4971. \end{lstlisting}
  4972. \end{minipage}
  4973. \end{tabular}
  4974. \caption{Merging basic blocks by removing unnecessary jumps.}
  4975. \label{fig:remove-jumps}
  4976. \end{figure}
  4977. \begin{exercise}\normalfont
  4978. Implement a pass named \code{remove-jumps} that merges basic blocks
  4979. into their preceeding basic block, when there is only one preceeding
  4980. block. The pass should translate from psuedo $x86_1$ to pseudo
  4981. $x86_1$ and it should come immediately after
  4982. \code{select-instructions}. Check that \code{remove-jumps}
  4983. accomplishes the goal of merging basic blocks on several test
  4984. programs and check that your compiler passes all of your tests.
  4985. \end{exercise}
  4986. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4987. \chapter{Tuples and Garbage Collection}
  4988. \label{ch:tuples}
  4989. \index{tuple}
  4990. \index{vector}
  4991. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4992. add simple structures. \\ --Jeremy}
  4993. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4994. things to discuss in this chapter. \\ --Jeremy}
  4995. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4996. all the IR grammars are spelled out! \\ --Jeremy}
  4997. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4998. but keep type annotations on vector creation and local variables, function
  4999. parameters, etc. \\ --Jeremy}
  5000. \margincomment{\scriptsize Be more explicit about how to deal with
  5001. the root stack. \\ --Jeremy}
  5002. In this chapter we study the implementation of mutable tuples (called
  5003. ``vectors'' in Racket). This language feature is the first to use the
  5004. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  5005. indefinite, that is, a tuple lives forever from the programmer's
  5006. viewpoint. Of course, from an implementer's viewpoint, it is important
  5007. to reclaim the space associated with a tuple when it is no longer
  5008. needed, which is why we also study \emph{garbage collection}
  5009. \emph{garbage collection}
  5010. techniques in this chapter.
  5011. Section~\ref{sec:r3} introduces the $R_3$ language including its
  5012. interpreter and type checker. The $R_3$ language extends the $R_2$
  5013. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5014. \code{void} value. The reason for including the later is that the
  5015. \code{vector-set!} operation returns a value of type
  5016. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5017. called the \code{Unit} type in the programming languages
  5018. literature. Racket's \code{Void} type is inhabited by a single value
  5019. \code{void} which corresponds to \code{unit} or \code{()} in the
  5020. literature~\citep{Pierce:2002hj}.}.
  5021. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5022. copying live objects back and forth between two halves of the
  5023. heap. The garbage collector requires coordination with the compiler so
  5024. that it can see all of the \emph{root} pointers, that is, pointers in
  5025. registers or on the procedure call stack.
  5026. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5027. discuss all the necessary changes and additions to the compiler
  5028. passes, including a new compiler pass named \code{expose-allocation}.
  5029. \section{The $R_3$ Language}
  5030. \label{sec:r3}
  5031. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  5032. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  5033. $R_3$ language includes three new forms: \code{vector} for creating a
  5034. tuple, \code{vector-ref} for reading an element of a tuple, and
  5035. \code{vector-set!} for writing to an element of a tuple. The program
  5036. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5037. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5038. the 3-tuple, demonstrating that tuples are first-class values. The
  5039. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5040. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5041. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5042. 1-tuple. So the result of the program is \code{42}.
  5043. \begin{figure}[tbp]
  5044. \centering
  5045. \fbox{
  5046. \begin{minipage}{0.96\textwidth}
  5047. \[
  5048. \begin{array}{lcl}
  5049. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5050. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  5051. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5052. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5053. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5054. \mid (\key{and}\;\Exp\;\Exp)
  5055. \mid (\key{or}\;\Exp\;\Exp)
  5056. \mid (\key{not}\;\Exp) } \\
  5057. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5058. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5059. &\mid& (\key{vector}\;\Exp\ldots)
  5060. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  5061. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)
  5062. \mid (\key{vector-length}\;\Exp) \\
  5063. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  5064. R_3 &::=& \Exp
  5065. \end{array}
  5066. \]
  5067. \end{minipage}
  5068. }
  5069. \caption{The concrete syntax of $R_3$, extending $R_2$
  5070. (Figure~\ref{fig:r2-concrete-syntax}).}
  5071. \label{fig:r3-concrete-syntax}
  5072. \end{figure}
  5073. \begin{figure}[tbp]
  5074. \begin{lstlisting}
  5075. (let ([t (vector 40 #t (vector 2))])
  5076. (if (vector-ref t 1)
  5077. (+ (vector-ref t 0)
  5078. (vector-ref (vector-ref t 2) 0))
  5079. 44))
  5080. \end{lstlisting}
  5081. \caption{Example program that creates tuples and reads from them.}
  5082. \label{fig:vector-eg}
  5083. \end{figure}
  5084. \begin{figure}[tp]
  5085. \centering
  5086. \fbox{
  5087. \begin{minipage}{0.96\textwidth}
  5088. \[
  5089. \begin{array}{lcl}
  5090. \itm{op} &::=& \ldots
  5091. \mid \code{vector} \mid \code{vector-ref} \mid \code{vector-set!}
  5092. \mid \code{vector-length} \\
  5093. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5094. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5095. \mid \BOOL{\itm{bool}}
  5096. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5097. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5098. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  5099. \end{array}
  5100. \]
  5101. \end{minipage}
  5102. }
  5103. \caption{The abstract syntax of $R_3$.}
  5104. \label{fig:r3-syntax}
  5105. \end{figure}
  5106. \index{allocate}
  5107. \index{heap allocate}
  5108. Tuples are our first encounter with heap-allocated data, which raises
  5109. several interesting issues. First, variable binding performs a
  5110. shallow-copy when dealing with tuples, which means that different
  5111. variables can refer to the same tuple, that is, different variables
  5112. can be \emph{aliases} for the same entity. Consider the following
  5113. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5114. Thus, the mutation through \code{t2} is visible when referencing the
  5115. tuple from \code{t1}, so the result of this program is \code{42}.
  5116. \index{alias}\index{mutation}
  5117. \begin{center}
  5118. \begin{minipage}{0.96\textwidth}
  5119. \begin{lstlisting}
  5120. (let ([t1 (vector 3 7)])
  5121. (let ([t2 t1])
  5122. (let ([_ (vector-set! t2 0 42)])
  5123. (vector-ref t1 0))))
  5124. \end{lstlisting}
  5125. \end{minipage}
  5126. \end{center}
  5127. The next issue concerns the lifetime of tuples. Of course, they are
  5128. created by the \code{vector} form, but when does their lifetime end?
  5129. Notice that $R_3$ does not include an operation for deleting
  5130. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5131. of static scoping. For example, the following program returns
  5132. \code{42} even though the variable \code{w} goes out of scope prior to
  5133. the \code{vector-ref} that reads from the vector it was bound to.
  5134. \begin{center}
  5135. \begin{minipage}{0.96\textwidth}
  5136. \begin{lstlisting}
  5137. (let ([v (vector (vector 44))])
  5138. (let ([x (let ([w (vector 42)])
  5139. (let ([_ (vector-set! v 0 w)])
  5140. 0))])
  5141. (+ x (vector-ref (vector-ref v 0) 0))))
  5142. \end{lstlisting}
  5143. \end{minipage}
  5144. \end{center}
  5145. From the perspective of programmer-observable behavior, tuples live
  5146. forever. Of course, if they really lived forever, then many programs
  5147. would run out of memory.\footnote{The $R_3$ language does not have
  5148. looping or recursive functions, so it is nigh impossible to write a
  5149. program in $R_3$ that will run out of memory. However, we add
  5150. recursive functions in the next Chapter!} A Racket implementation
  5151. must therefore perform automatic garbage collection.
  5152. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5153. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  5154. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  5155. operations in Racket. One subtle point is that the \code{vector-set!}
  5156. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  5157. can be passed around just like other values inside an $R_3$ program
  5158. and a \code{\#<void>} value can be compared for equality with another
  5159. \code{\#<void>} value. However, there are no other operations specific
  5160. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  5161. the \code{void?} predicate that returns \code{\#t} when applied to
  5162. \code{\#<void>} and \code{\#f} otherwise.
  5163. \begin{figure}[tbp]
  5164. \begin{lstlisting}
  5165. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  5166. (define (interp-op op)
  5167. (match op
  5168. ...
  5169. ['vector vector]
  5170. ['vector-ref vector-ref]
  5171. ['vector-set! vector-set!]
  5172. [else (error 'interp-op "unknown operator")]))
  5173. (define (interp-exp env)
  5174. (lambda (e)
  5175. (define recur (interp-exp env))
  5176. (match e
  5177. ...
  5178. )))
  5179. (define (interp-R3 p)
  5180. (match p
  5181. [(Program '() e)
  5182. ((interp-exp '()) e)]
  5183. ))
  5184. \end{lstlisting}
  5185. \caption{Interpreter for the $R_3$ language.}
  5186. \label{fig:interp-R3}
  5187. \end{figure}
  5188. Figure~\ref{fig:type-check-R3} shows the type checker for $R_3$, which
  5189. deserves some explanation. As we see in Section~\ref{sec:GC}, we
  5190. need to know which variables contain pointers into the heap, that is,
  5191. which variables contain vectors. Also, when allocating a vector, we
  5192. need to know which elements of the vector are pointers. We can obtain
  5193. this information during type checking. The type checker in
  5194. Figure~\ref{fig:type-check-R3} not only computes the type of an
  5195. expression, it also wraps every sub-expression $e$ with the form
  5196. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  5197. Subsequently, in the \code{uncover-locals} pass
  5198. (Section~\ref{sec:uncover-locals-r3}) this type information is
  5199. propagated to all variables (including the temporaries generated by
  5200. \code{remove-complex-opera*}).
  5201. To create the s-expression for the \code{Vector} type in
  5202. Figure~\ref{fig:type-check-R3}, we use the
  5203. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5204. operator} \code{,@} to insert the list \code{t*} without its usual
  5205. start and end parentheses. \index{unquote-slicing}
  5206. \begin{figure}[tp]
  5207. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5208. (define (type-check-exp env)
  5209. (lambda (e)
  5210. (define recur (type-check-exp env))
  5211. (match e
  5212. ...
  5213. [(Void) (values (HasType (Void) 'Void) 'Void)]
  5214. [(Prim 'vector es)
  5215. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5216. (let ([t `(Vector ,@t*)])
  5217. (values (HasType (Prim 'vector e*) t) t))]
  5218. [(Prim 'vector-ref (list e (Int i)))
  5219. (define-values (e^ t) (recur e))
  5220. (match t
  5221. [`(Vector ,ts ...)
  5222. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5223. (error 'type-check-exp "invalid index ~a" i))
  5224. (let ([t (list-ref ts i)])
  5225. (values
  5226. (HasType (Prim 'vector-ref
  5227. (list e^ (HasType (Int i) 'Integer)))
  5228. t)
  5229. t))]
  5230. [else (error "expected a vector in vector-ref, not" t)])]
  5231. [(Prim 'vector-set! (list e (Int i) arg) )
  5232. (define-values (e-vec t-vec) (recur e))
  5233. (define-values (e-arg^ t-arg) (recur arg))
  5234. (match t-vec
  5235. [`(Vector ,ts ...)
  5236. (unless (and (exact-nonnegative-integer? i)
  5237. (i . < . (length ts)))
  5238. (error 'type-check-exp "invalid index ~a" i))
  5239. (unless (type-equal? (list-ref ts i) t-arg)
  5240. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  5241. (list-ref ts i) t-arg))
  5242. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5243. [else (error 'type-check-exp
  5244. "expected a vector in vector-set!, not ~a"
  5245. t-vec)])]
  5246. [(Prim 'vector-length (list e))
  5247. (define-values (e^ t) (recur e))
  5248. (match t
  5249. [`(Vector ,ts ...)
  5250. (values (Prim 'vector-length (list e^)) 'Integer)]
  5251. [else (error 'type-check-exp
  5252. "expected a vector in vector-lenfth, not ~a" t)])]
  5253. [(Prim 'eq? (list e1 e2))
  5254. (define-values (e1^ T1) (recur e1))
  5255. (define-values (e2^ T2) (recur e2))
  5256. (unless (equal? T1 T2)
  5257. (error "arguments of eq? must have the same type, but are not"
  5258. (list T1 T2)))
  5259. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  5260. ...
  5261. )))
  5262. \end{lstlisting}
  5263. \caption{Type checker for the $R_3$ language.}
  5264. \label{fig:type-check-R3}
  5265. \end{figure}
  5266. \section{Garbage Collection}
  5267. \label{sec:GC}
  5268. Here we study a relatively simple algorithm for garbage collection
  5269. that is the basis of state-of-the-art garbage
  5270. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5271. particular, we describe a two-space copying
  5272. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5273. perform the
  5274. copy~\citep{Cheney:1970aa}.
  5275. \index{copying collector}
  5276. \index{two-space copying collector}
  5277. Figure~\ref{fig:copying-collector} gives a
  5278. coarse-grained depiction of what happens in a two-space collector,
  5279. showing two time steps, prior to garbage collection (on the top) and
  5280. after garbage collection (on the bottom). In a two-space collector,
  5281. the heap is divided into two parts named the FromSpace and the
  5282. ToSpace. Initially, all allocations go to the FromSpace until there is
  5283. not enough room for the next allocation request. At that point, the
  5284. garbage collector goes to work to make more room.
  5285. \index{ToSpace}
  5286. \index{FromSpace}
  5287. The garbage collector must be careful not to reclaim tuples that will
  5288. be used by the program in the future. Of course, it is impossible in
  5289. general to predict what a program will do, but we can over approximate
  5290. the will-be-used tuples by preserving all tuples that could be
  5291. accessed by \emph{any} program given the current computer state. A
  5292. program could access any tuple whose address is in a register or on
  5293. the procedure call stack. These addresses are called the \emph{root
  5294. set}\index{root set}. In addition, a program could access any tuple that is
  5295. transitively reachable from the root set. Thus, it is safe for the
  5296. garbage collector to reclaim the tuples that are not reachable in this
  5297. way.
  5298. So the goal of the garbage collector is twofold:
  5299. \begin{enumerate}
  5300. \item preserve all tuple that are reachable from the root set via a
  5301. path of pointers, that is, the \emph{live} tuples, and
  5302. \item reclaim the memory of everything else, that is, the
  5303. \emph{garbage}.
  5304. \end{enumerate}
  5305. A copying collector accomplishes this by copying all of the live
  5306. objects from the FromSpace into the ToSpace and then performs a slight
  5307. of hand, treating the ToSpace as the new FromSpace and the old
  5308. FromSpace as the new ToSpace. In the example of
  5309. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5310. root set, one in a register and two on the stack. All of the live
  5311. objects have been copied to the ToSpace (the right-hand side of
  5312. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5313. pointer relationships. For example, the pointer in the register still
  5314. points to a 2-tuple whose first element is a 3-tuple and whose second
  5315. element is a 2-tuple. There are four tuples that are not reachable
  5316. from the root set and therefore do not get copied into the ToSpace.
  5317. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5318. created by a well-typed program in $R_3$ because it contains a
  5319. cycle. However, creating cycles will be possible once we get to $R_6$.
  5320. We design the garbage collector to deal with cycles to begin with so
  5321. we will not need to revisit this issue.
  5322. \begin{figure}[tbp]
  5323. \centering
  5324. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5325. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5326. \caption{A copying collector in action.}
  5327. \label{fig:copying-collector}
  5328. \end{figure}
  5329. There are many alternatives to copying collectors (and their bigger
  5330. siblings, the generational collectors) when its comes to garbage
  5331. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5332. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5333. collectors are that allocation is fast (just a comparison and pointer
  5334. increment), there is no fragmentation, cyclic garbage is collected,
  5335. and the time complexity of collection only depends on the amount of
  5336. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5337. main disadvantages of a two-space copying collector is that it uses a
  5338. lot of space and takes a long time to perform the copy, though these
  5339. problems are ameliorated in generational collectors. Racket and
  5340. Scheme programs tend to allocate many small objects and generate a lot
  5341. of garbage, so copying and generational collectors are a good fit.
  5342. Garbage collection is an active research topic, especially concurrent
  5343. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5344. developing new techniques and revisiting old
  5345. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5346. meet every year at the International Symposium on Memory Management to
  5347. present these findings.
  5348. \subsection{Graph Copying via Cheney's Algorithm}
  5349. \label{sec:cheney}
  5350. \index{Cheney's algorithm}
  5351. Let us take a closer look at the copying of the live objects. The
  5352. allocated objects and pointers can be viewed as a graph and we need to
  5353. copy the part of the graph that is reachable from the root set. To
  5354. make sure we copy all of the reachable vertices in the graph, we need
  5355. an exhaustive graph traversal algorithm, such as depth-first search or
  5356. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5357. such algorithms take into account the possibility of cycles by marking
  5358. which vertices have already been visited, so as to ensure termination
  5359. of the algorithm. These search algorithms also use a data structure
  5360. such as a stack or queue as a to-do list to keep track of the vertices
  5361. that need to be visited. We use breadth-first search and a trick
  5362. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5363. and copying tuples into the ToSpace.
  5364. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5365. copy progresses. The queue is represented by a chunk of contiguous
  5366. memory at the beginning of the ToSpace, using two pointers to track
  5367. the front and the back of the queue. The algorithm starts by copying
  5368. all tuples that are immediately reachable from the root set into the
  5369. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5370. old tuple to indicate that it has been visited. We discuss how this
  5371. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5372. pointers inside the copied tuples in the queue still point back to the
  5373. FromSpace. Once the initial queue has been created, the algorithm
  5374. enters a loop in which it repeatedly processes the tuple at the front
  5375. of the queue and pops it off the queue. To process a tuple, the
  5376. algorithm copies all the tuple that are directly reachable from it to
  5377. the ToSpace, placing them at the back of the queue. The algorithm then
  5378. updates the pointers in the popped tuple so they point to the newly
  5379. copied tuples.
  5380. \begin{figure}[tbp]
  5381. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5382. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5383. \label{fig:cheney}
  5384. \end{figure}
  5385. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5386. tuple whose second element is $42$ to the back of the queue. The other
  5387. pointer goes to a tuple that has already been copied, so we do not
  5388. need to copy it again, but we do need to update the pointer to the new
  5389. location. This can be accomplished by storing a \emph{forwarding
  5390. pointer} to the new location in the old tuple, back when we initially
  5391. copied the tuple into the ToSpace. This completes one step of the
  5392. algorithm. The algorithm continues in this way until the front of the
  5393. queue is empty, that is, until the front catches up with the back.
  5394. \subsection{Data Representation}
  5395. \label{sec:data-rep-gc}
  5396. The garbage collector places some requirements on the data
  5397. representations used by our compiler. First, the garbage collector
  5398. needs to distinguish between pointers and other kinds of data. There
  5399. are several ways to accomplish this.
  5400. \begin{enumerate}
  5401. \item Attached a tag to each object that identifies what type of
  5402. object it is~\citep{McCarthy:1960dz}.
  5403. \item Store different types of objects in different
  5404. regions~\citep{Steele:1977ab}.
  5405. \item Use type information from the program to either generate
  5406. type-specific code for collecting or to generate tables that can
  5407. guide the
  5408. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5409. \end{enumerate}
  5410. Dynamically typed languages, such as Lisp, need to tag objects
  5411. anyways, so option 1 is a natural choice for those languages.
  5412. However, $R_3$ is a statically typed language, so it would be
  5413. unfortunate to require tags on every object, especially small and
  5414. pervasive objects like integers and Booleans. Option 3 is the
  5415. best-performing choice for statically typed languages, but comes with
  5416. a relatively high implementation complexity. To keep this chapter
  5417. within a 2-week time budget, we recommend a combination of options 1
  5418. and 2, using separate strategies for the stack and the heap.
  5419. Regarding the stack, we recommend using a separate stack for pointers,
  5420. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5421. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5422. is, when a local variable needs to be spilled and is of type
  5423. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5424. stack instead of the normal procedure call stack. Furthermore, we
  5425. always spill vector-typed variables if they are live during a call to
  5426. the collector, thereby ensuring that no pointers are in registers
  5427. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5428. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5429. the data layout using a root stack. The root stack contains the two
  5430. pointers from the regular stack and also the pointer in the second
  5431. register.
  5432. \begin{figure}[tbp]
  5433. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5434. \caption{Maintaining a root stack to facilitate garbage collection.}
  5435. \label{fig:shadow-stack}
  5436. \end{figure}
  5437. The problem of distinguishing between pointers and other kinds of data
  5438. also arises inside of each tuple on the heap. We solve this problem by
  5439. attaching a tag, an extra 64-bits, to each
  5440. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5441. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5442. that we have drawn the bits in a big-endian way, from right-to-left,
  5443. with bit location 0 (the least significant bit) on the far right,
  5444. which corresponds to the direction of the x86 shifting instructions
  5445. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5446. is dedicated to specifying which elements of the tuple are pointers,
  5447. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5448. indicates there is a pointer and a 0 bit indicates some other kind of
  5449. data. The pointer mask starts at bit location 7. We have limited
  5450. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5451. the pointer mask. The tag also contains two other pieces of
  5452. information. The length of the tuple (number of elements) is stored in
  5453. bits location 1 through 6. Finally, the bit at location 0 indicates
  5454. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5455. value 1, then this tuple has not yet been copied. If the bit has
  5456. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5457. of a pointer are always zero anyways because our tuples are 8-byte
  5458. aligned.)
  5459. \begin{figure}[tbp]
  5460. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5461. \caption{Representation of tuples in the heap.}
  5462. \label{fig:tuple-rep}
  5463. \end{figure}
  5464. \subsection{Implementation of the Garbage Collector}
  5465. \label{sec:organize-gz}
  5466. \index{prelude}
  5467. An implementation of the copying collector is provided in the
  5468. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5469. interface to the garbage collector that is used by the compiler. The
  5470. \code{initialize} function creates the FromSpace, ToSpace, and root
  5471. stack and should be called in the prelude of the \code{main}
  5472. function. The arguments of \code{initialize} are the root stack size
  5473. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5474. good choice for both. The \code{initialize} function puts the address
  5475. of the beginning of the FromSpace into the global variable
  5476. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5477. the address that is 1-past the last element of the FromSpace. (We use
  5478. half-open intervals to represent chunks of
  5479. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5480. points to the first element of the root stack.
  5481. As long as there is room left in the FromSpace, your generated code
  5482. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5483. %
  5484. The amount of room left in FromSpace is the difference between the
  5485. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5486. function should be called when there is not enough room left in the
  5487. FromSpace for the next allocation. The \code{collect} function takes
  5488. a pointer to the current top of the root stack (one past the last item
  5489. that was pushed) and the number of bytes that need to be
  5490. allocated. The \code{collect} function performs the copying collection
  5491. and leaves the heap in a state such that the next allocation will
  5492. succeed.
  5493. \begin{figure}[tbp]
  5494. \begin{lstlisting}
  5495. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5496. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5497. int64_t* free_ptr;
  5498. int64_t* fromspace_begin;
  5499. int64_t* fromspace_end;
  5500. int64_t** rootstack_begin;
  5501. \end{lstlisting}
  5502. \caption{The compiler's interface to the garbage collector.}
  5503. \label{fig:gc-header}
  5504. \end{figure}
  5505. %% \begin{exercise}
  5506. %% In the file \code{runtime.c} you will find the implementation of
  5507. %% \code{initialize} and a partial implementation of \code{collect}.
  5508. %% The \code{collect} function calls another function, \code{cheney},
  5509. %% to perform the actual copy, and that function is left to the reader
  5510. %% to implement. The following is the prototype for \code{cheney}.
  5511. %% \begin{lstlisting}
  5512. %% static void cheney(int64_t** rootstack_ptr);
  5513. %% \end{lstlisting}
  5514. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5515. %% rootstack (which is an array of pointers). The \code{cheney} function
  5516. %% also communicates with \code{collect} through the global
  5517. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5518. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5519. %% the ToSpace:
  5520. %% \begin{lstlisting}
  5521. %% static int64_t* tospace_begin;
  5522. %% static int64_t* tospace_end;
  5523. %% \end{lstlisting}
  5524. %% The job of the \code{cheney} function is to copy all the live
  5525. %% objects (reachable from the root stack) into the ToSpace, update
  5526. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5527. %% update the root stack so that it points to the objects in the
  5528. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5529. %% and ToSpace.
  5530. %% \end{exercise}
  5531. %% \section{Compiler Passes}
  5532. %% \label{sec:code-generation-gc}
  5533. The introduction of garbage collection has a non-trivial impact on our
  5534. compiler passes. We introduce two new compiler passes named
  5535. \code{expose-allocation} and \code{uncover-locals}. We make
  5536. significant changes to \code{select-instructions},
  5537. \code{build-interference}, \code{allocate-registers}, and
  5538. \code{print-x86} and make minor changes in severl more passes. The
  5539. following program will serve as our running example. It creates two
  5540. tuples, one nested inside the other. Both tuples have length one. The
  5541. program accesses the element in the inner tuple tuple via two vector
  5542. references.
  5543. % tests/s2_17.rkt
  5544. \begin{lstlisting}
  5545. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5546. \end{lstlisting}
  5547. \section{Shrink}
  5548. \label{sec:shrink-R3}
  5549. Recall that the \code{shrink} pass translates the primitives operators
  5550. into a smaller set of primitives. Because this pass comes after type
  5551. checking, but before the passes that require the type information in
  5552. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5553. to wrap \code{HasType} around each AST node that it generates.
  5554. \section{Expose Allocation}
  5555. \label{sec:expose-allocation}
  5556. The pass \code{expose-allocation} lowers the \code{vector} creation
  5557. form into a conditional call to the collector followed by the
  5558. allocation. We choose to place the \code{expose-allocation} pass
  5559. before \code{remove-complex-opera*} because the code generated by
  5560. \code{expose-allocation} contains complex operands. We also place
  5561. \code{expose-allocation} before \code{explicate-control} because
  5562. \code{expose-allocation} introduces new variables using \code{let},
  5563. but \code{let} is gone after \code{explicate-control}.
  5564. The output of \code{expose-allocation} is a language $R'_3$ that
  5565. extends $R_3$ with the three new forms that we use in the translation
  5566. of the \code{vector} form.
  5567. \[
  5568. \begin{array}{lcl}
  5569. \Exp &::=& \cdots
  5570. \mid (\key{collect} \,\itm{int})
  5571. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5572. \mid (\key{global-value} \,\itm{name})
  5573. \end{array}
  5574. \]
  5575. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5576. $n$ bytes. It will become a call to the \code{collect} function in
  5577. \code{runtime.c} in \code{select-instructions}. The
  5578. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5579. \index{allocate}
  5580. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5581. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5582. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5583. a global variable, such as \code{free\_ptr}.
  5584. In the following, we show the transformation for the \code{vector}
  5585. form into 1) a sequence of let-bindings for the initializing
  5586. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5587. \code{allocate}, and 4) the initialization of the vector. In the
  5588. following, \itm{len} refers to the length of the vector and
  5589. \itm{bytes} is how many total bytes need to be allocated for the
  5590. vector, which is 8 for the tag plus \itm{len} times 8.
  5591. \begin{lstlisting}
  5592. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5593. |$\Longrightarrow$|
  5594. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5595. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5596. (global-value fromspace_end))
  5597. (void)
  5598. (collect |\itm{bytes}|))])
  5599. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5600. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5601. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5602. |$v$|) ... )))) ...)
  5603. \end{lstlisting}
  5604. In the above, we suppressed all of the \code{has-type} forms in the
  5605. output for the sake of readability. The placement of the initializing
  5606. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5607. sequence of \code{vector-set!} is important, as those expressions may
  5608. trigger garbage collection and we cannot have an allocated but
  5609. uninitialized tuple on the heap during a collection.
  5610. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5611. \code{expose-allocation} pass on our running example.
  5612. \begin{figure}[tbp]
  5613. % tests/s2_17.rkt
  5614. \begin{lstlisting}
  5615. (vector-ref
  5616. (vector-ref
  5617. (let ([vecinit7976
  5618. (let ([vecinit7972 42])
  5619. (let ([collectret7974
  5620. (if (< (+ (global-value free_ptr) 16)
  5621. (global-value fromspace_end))
  5622. (void)
  5623. (collect 16)
  5624. )])
  5625. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5626. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5627. alloc7971)
  5628. )
  5629. )
  5630. )
  5631. ])
  5632. (let ([collectret7978
  5633. (if (< (+ (global-value free_ptr) 16)
  5634. (global-value fromspace_end))
  5635. (void)
  5636. (collect 16)
  5637. )])
  5638. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5639. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5640. alloc7975)
  5641. )
  5642. )
  5643. )
  5644. 0)
  5645. 0)
  5646. \end{lstlisting}
  5647. \caption{Output of the \code{expose-allocation} pass, minus
  5648. all of the \code{has-type} forms.}
  5649. \label{fig:expose-alloc-output}
  5650. \end{figure}
  5651. \section{Remove Complex Operands}
  5652. \label{sec:remove-complex-opera-R3}
  5653. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5654. should all be treated as complex operands. A new case for
  5655. \code{HasType} is needed and the case for \code{Prim} needs to be
  5656. handled carefully to prevent the \code{Prim} node from being separated
  5657. from its enclosing \code{HasType}.
  5658. \section{Explicate Control and the $C_2$ language}
  5659. \label{sec:explicate-control-r3}
  5660. \begin{figure}[tbp]
  5661. \fbox{
  5662. \begin{minipage}{0.96\textwidth}
  5663. \small
  5664. \[
  5665. \begin{array}{lcl}
  5666. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5667. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5668. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5669. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5670. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5671. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5672. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5673. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5674. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5675. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5676. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5677. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5678. \end{array}
  5679. \]
  5680. \end{minipage}
  5681. }
  5682. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5683. \label{fig:c2-concrete-syntax}
  5684. \end{figure}
  5685. \begin{figure}[tp]
  5686. \fbox{
  5687. \begin{minipage}{0.96\textwidth}
  5688. \small
  5689. \[
  5690. \begin{array}{lcl}
  5691. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5692. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5693. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5694. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5695. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5696. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5697. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5698. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5699. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5700. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5701. \mid (\key{Collect} \,\itm{int}) \\
  5702. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5703. \mid \GOTO{\itm{label}} } \\
  5704. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5705. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5706. \end{array}
  5707. \]
  5708. \end{minipage}
  5709. }
  5710. \caption{The abstract syntax of $C_2$, extending $C_1$
  5711. (Figure~\ref{fig:c1-syntax}).}
  5712. \label{fig:c2-syntax}
  5713. \end{figure}
  5714. The output of \code{explicate-control} is a program in the
  5715. intermediate language $C_2$, whose concrete syntax is defined in
  5716. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5717. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5718. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5719. \key{global-value} expressions and the \code{collect} statement. The
  5720. \code{explicate-control} pass can treat these new forms much like the
  5721. other forms.
  5722. \section{Uncover Locals}
  5723. \label{sec:uncover-locals-r3}
  5724. Recall that the \code{explicate-control} function collects all of the
  5725. local variables so that it can store them in the $\itm{info}$ field of
  5726. the \code{Program} structure. Also recall that we need to know the
  5727. types of all the local variables for purposes of identifying the root
  5728. set for the garbage collector. Thus, we create a pass named
  5729. \code{uncover-locals} to collect not just the variables but the
  5730. variables and their types in the form of an alist. Thanks to the
  5731. \code{HasType} nodes, the types are readily available at every
  5732. assignment to a variable. We recommend storing the resulting alist in
  5733. the $\itm{info}$ field of the program, associated with the
  5734. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5735. of the \code{uncover-locals} pass on the running example.
  5736. \begin{figure}[tbp]
  5737. % tests/s2_17.rkt
  5738. \begin{lstlisting}
  5739. locals:
  5740. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5741. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5742. collectret7974 : 'Void, initret7977 : 'Void,
  5743. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5744. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5745. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5746. vecinit7972 : 'Integer, initret7973 : 'Void,
  5747. block91:
  5748. (collect 16)
  5749. goto block89;
  5750. block90:
  5751. collectret7974 = (void);
  5752. goto block89;
  5753. block89:
  5754. alloc7971 = (allocate 1 (Vector Integer));
  5755. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5756. vecinit7976 = alloc7971;
  5757. tmp7982 = (global-value free_ptr);
  5758. tmp7983 = (+ tmp7982 16);
  5759. tmp7984 = (global-value fromspace_end);
  5760. if (< tmp7983 tmp7984) then
  5761. goto block87;
  5762. else
  5763. goto block88;
  5764. block88:
  5765. (collect 16)
  5766. goto block86;
  5767. block87:
  5768. collectret7978 = (void);
  5769. goto block86;
  5770. block86:
  5771. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5772. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5773. tmp7985 = (vector-ref alloc7975 0);
  5774. return (vector-ref tmp7985 0);
  5775. start:
  5776. vecinit7972 = 42;
  5777. tmp7979 = (global-value free_ptr);
  5778. tmp7980 = (+ tmp7979 16);
  5779. tmp7981 = (global-value fromspace_end);
  5780. if (< tmp7980 tmp7981) then
  5781. goto block90;
  5782. else
  5783. goto block91;
  5784. \end{lstlisting}
  5785. \caption{Output of \code{uncover-locals} for the running example.}
  5786. \label{fig:uncover-locals-r3}
  5787. \end{figure}
  5788. \clearpage
  5789. \section{Select Instructions and the x86$_2$ Language}
  5790. \label{sec:select-instructions-gc}
  5791. \index{instruction selection}
  5792. %% void (rep as zero)
  5793. %% allocate
  5794. %% collect (callq collect)
  5795. %% vector-ref
  5796. %% vector-set!
  5797. %% global (postpone)
  5798. In this pass we generate x86 code for most of the new operations that
  5799. were needed to compile tuples, including \code{Allocate},
  5800. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5801. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5802. the later has a different concrete syntax (see
  5803. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5804. \index{x86}
  5805. The \code{vector-ref} and \code{vector-set!} forms translate into
  5806. \code{movq} instructions. (The plus one in the offset is to get past
  5807. the tag at the beginning of the tuple representation.)
  5808. \begin{lstlisting}
  5809. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5810. |$\Longrightarrow$|
  5811. movq |$\itm{vec}'$|, %r11
  5812. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  5813. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5814. |$\Longrightarrow$|
  5815. movq |$\itm{vec}'$|, %r11
  5816. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5817. movq $0, |$\itm{lhs'}$|
  5818. \end{lstlisting}
  5819. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5820. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5821. register \code{r11} ensures that offset expression
  5822. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5823. removing \code{r11} from consideration by the register allocating.
  5824. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5825. \code{rax}. Then the generated code for \code{vector-set!} would be
  5826. \begin{lstlisting}
  5827. movq |$\itm{vec}'$|, %rax
  5828. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5829. movq $0, |$\itm{lhs}'$|
  5830. \end{lstlisting}
  5831. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5832. \code{patch-instructions} would insert a move through \code{rax}
  5833. as follows.
  5834. \begin{lstlisting}
  5835. movq |$\itm{vec}'$|, %rax
  5836. movq |$\itm{arg}'$|, %rax
  5837. movq %rax, |$8(n+1)$|(%rax)
  5838. movq $0, |$\itm{lhs}'$|
  5839. \end{lstlisting}
  5840. But the above sequence of instructions does not work because we're
  5841. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5842. $\itm{arg}'$) at the same time!
  5843. We compile the \code{allocate} form to operations on the
  5844. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5845. is the next free address in the FromSpace, so we copy it into
  5846. \code{r11} and then move it forward by enough space for the tuple
  5847. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  5848. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  5849. initialize the \itm{tag} and finally copy the address in \code{r11} to
  5850. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  5851. tag is organized. We recommend using the Racket operations
  5852. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5853. during compilation. The type annotation in the \code{vector} form is
  5854. used to determine the pointer mask region of the tag.
  5855. \begin{lstlisting}
  5856. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5857. |$\Longrightarrow$|
  5858. movq free_ptr(%rip), %r11
  5859. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5860. movq $|$\itm{tag}$|, 0(%r11)
  5861. movq %r11, |$\itm{lhs}'$|
  5862. \end{lstlisting}
  5863. The \code{collect} form is compiled to a call to the \code{collect}
  5864. function in the runtime. The arguments to \code{collect} are 1) the
  5865. top of the root stack and 2) the number of bytes that need to be
  5866. allocated. We use another dedicated register, \code{r15}, to
  5867. store the pointer to the top of the root stack. So \code{r15} is not
  5868. available for use by the register allocator.
  5869. \begin{lstlisting}
  5870. (collect |$\itm{bytes}$|)
  5871. |$\Longrightarrow$|
  5872. movq %r15, %rdi
  5873. movq $|\itm{bytes}|, %rsi
  5874. callq collect
  5875. \end{lstlisting}
  5876. \begin{figure}[tp]
  5877. \fbox{
  5878. \begin{minipage}{0.96\textwidth}
  5879. \[
  5880. \begin{array}{lcl}
  5881. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5882. x86_1 &::= & \gray{ \key{.globl main} }\\
  5883. & & \gray{ \key{main:} \; \Instr\ldots }
  5884. \end{array}
  5885. \]
  5886. \end{minipage}
  5887. }
  5888. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5889. \label{fig:x86-2-concrete}
  5890. \end{figure}
  5891. \begin{figure}[tp]
  5892. \fbox{
  5893. \begin{minipage}{0.96\textwidth}
  5894. \small
  5895. \[
  5896. \begin{array}{lcl}
  5897. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5898. \mid \BYTEREG{\Reg}} \\
  5899. &\mid& (\key{Global}~\Var) \\
  5900. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5901. \end{array}
  5902. \]
  5903. \end{minipage}
  5904. }
  5905. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5906. \label{fig:x86-2}
  5907. \end{figure}
  5908. The concrete and abstract syntax of the $x86_2$ language is defined in
  5909. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5910. x86$_1$ just in the addition of the form for global variables.
  5911. %
  5912. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5913. \code{select-instructions} pass on the running example.
  5914. \begin{figure}[tbp]
  5915. \centering
  5916. % tests/s2_17.rkt
  5917. \begin{minipage}[t]{0.5\textwidth}
  5918. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5919. block35:
  5920. movq free_ptr(%rip), alloc9024
  5921. addq $16, free_ptr(%rip)
  5922. movq alloc9024, %r11
  5923. movq $131, 0(%r11)
  5924. movq alloc9024, %r11
  5925. movq vecinit9025, 8(%r11)
  5926. movq $0, initret9026
  5927. movq alloc9024, %r11
  5928. movq 8(%r11), tmp9034
  5929. movq tmp9034, %r11
  5930. movq 8(%r11), %rax
  5931. jmp conclusion
  5932. block36:
  5933. movq $0, collectret9027
  5934. jmp block35
  5935. block38:
  5936. movq free_ptr(%rip), alloc9020
  5937. addq $16, free_ptr(%rip)
  5938. movq alloc9020, %r11
  5939. movq $3, 0(%r11)
  5940. movq alloc9020, %r11
  5941. movq vecinit9021, 8(%r11)
  5942. movq $0, initret9022
  5943. movq alloc9020, vecinit9025
  5944. movq free_ptr(%rip), tmp9031
  5945. movq tmp9031, tmp9032
  5946. addq $16, tmp9032
  5947. movq fromspace_end(%rip), tmp9033
  5948. cmpq tmp9033, tmp9032
  5949. jl block36
  5950. jmp block37
  5951. block37:
  5952. movq %r15, %rdi
  5953. movq $16, %rsi
  5954. callq 'collect
  5955. jmp block35
  5956. block39:
  5957. movq $0, collectret9023
  5958. jmp block38
  5959. \end{lstlisting}
  5960. \end{minipage}
  5961. \begin{minipage}[t]{0.45\textwidth}
  5962. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5963. start:
  5964. movq $42, vecinit9021
  5965. movq free_ptr(%rip), tmp9028
  5966. movq tmp9028, tmp9029
  5967. addq $16, tmp9029
  5968. movq fromspace_end(%rip), tmp9030
  5969. cmpq tmp9030, tmp9029
  5970. jl block39
  5971. jmp block40
  5972. block40:
  5973. movq %r15, %rdi
  5974. movq $16, %rsi
  5975. callq 'collect
  5976. jmp block38
  5977. \end{lstlisting}
  5978. \end{minipage}
  5979. \caption{Output of the \code{select-instructions} pass.}
  5980. \label{fig:select-instr-output-gc}
  5981. \end{figure}
  5982. \clearpage
  5983. \section{Register Allocation}
  5984. \label{sec:reg-alloc-gc}
  5985. \index{register allocation}
  5986. As discussed earlier in this chapter, the garbage collector needs to
  5987. access all the pointers in the root set, that is, all variables that
  5988. are vectors. It will be the responsibility of the register allocator
  5989. to make sure that:
  5990. \begin{enumerate}
  5991. \item the root stack is used for spilling vector-typed variables, and
  5992. \item if a vector-typed variable is live during a call to the
  5993. collector, it must be spilled to ensure it is visible to the
  5994. collector.
  5995. \end{enumerate}
  5996. The later responsibility can be handled during construction of the
  5997. interference graph, by adding interference edges between the call-live
  5998. vector-typed variables and all the callee-saved registers. (They
  5999. already interfere with the caller-saved registers.) The type
  6000. information for variables is in the \code{Program} form, so we
  6001. recommend adding another parameter to the \code{build-interference}
  6002. function to communicate this alist.
  6003. The spilling of vector-typed variables to the root stack can be
  6004. handled after graph coloring, when choosing how to assign the colors
  6005. (integers) to registers and stack locations. The \code{Program} output
  6006. of this pass changes to also record the number of spills to the root
  6007. stack.
  6008. % build-interference
  6009. %
  6010. % callq
  6011. % extra parameter for var->type assoc. list
  6012. % update 'program' and 'if'
  6013. % allocate-registers
  6014. % allocate spilled vectors to the rootstack
  6015. % don't change color-graph
  6016. \section{Print x86}
  6017. \label{sec:print-x86-gc}
  6018. \index{prelude}\index{conclusion}
  6019. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6020. \code{print-x86} pass on the running example. In the prelude and
  6021. conclusion of the \code{main} function, we treat the root stack very
  6022. much like the regular stack in that we move the root stack pointer
  6023. (\code{r15}) to make room for the spills to the root stack, except
  6024. that the root stack grows up instead of down. For the running
  6025. example, there was just one spill so we increment \code{r15} by 8
  6026. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6027. One issue that deserves special care is that there may be a call to
  6028. \code{collect} prior to the initializing assignments for all the
  6029. variables in the root stack. We do not want the garbage collector to
  6030. accidentally think that some uninitialized variable is a pointer that
  6031. needs to be followed. Thus, we zero-out all locations on the root
  6032. stack in the prelude of \code{main}. In
  6033. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6034. %
  6035. \lstinline{movq $0, (%r15)}
  6036. %
  6037. accomplishes this task. The garbage collector tests each root to see
  6038. if it is null prior to dereferencing it.
  6039. \begin{figure}[htbp]
  6040. \begin{minipage}[t]{0.5\textwidth}
  6041. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6042. block35:
  6043. movq free_ptr(%rip), %rcx
  6044. addq $16, free_ptr(%rip)
  6045. movq %rcx, %r11
  6046. movq $131, 0(%r11)
  6047. movq %rcx, %r11
  6048. movq -8(%r15), %rax
  6049. movq %rax, 8(%r11)
  6050. movq $0, %rdx
  6051. movq %rcx, %r11
  6052. movq 8(%r11), %rcx
  6053. movq %rcx, %r11
  6054. movq 8(%r11), %rax
  6055. jmp conclusion
  6056. block36:
  6057. movq $0, %rcx
  6058. jmp block35
  6059. block38:
  6060. movq free_ptr(%rip), %rcx
  6061. addq $16, free_ptr(%rip)
  6062. movq %rcx, %r11
  6063. movq $3, 0(%r11)
  6064. movq %rcx, %r11
  6065. movq %rbx, 8(%r11)
  6066. movq $0, %rdx
  6067. movq %rcx, -8(%r15)
  6068. movq free_ptr(%rip), %rcx
  6069. addq $16, %rcx
  6070. movq fromspace_end(%rip), %rdx
  6071. cmpq %rdx, %rcx
  6072. jl block36
  6073. movq %r15, %rdi
  6074. movq $16, %rsi
  6075. callq collect
  6076. jmp block35
  6077. block39:
  6078. movq $0, %rcx
  6079. jmp block38
  6080. \end{lstlisting}
  6081. \end{minipage}
  6082. \begin{minipage}[t]{0.45\textwidth}
  6083. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6084. start:
  6085. movq $42, %rbx
  6086. movq free_ptr(%rip), %rdx
  6087. addq $16, %rdx
  6088. movq fromspace_end(%rip), %rcx
  6089. cmpq %rcx, %rdx
  6090. jl block39
  6091. movq %r15, %rdi
  6092. movq $16, %rsi
  6093. callq collect
  6094. jmp block38
  6095. .globl main
  6096. main:
  6097. pushq %rbp
  6098. movq %rsp, %rbp
  6099. pushq %r13
  6100. pushq %r12
  6101. pushq %rbx
  6102. pushq %r14
  6103. subq $0, %rsp
  6104. movq $16384, %rdi
  6105. movq $16384, %rsi
  6106. callq initialize
  6107. movq rootstack_begin(%rip), %r15
  6108. movq $0, (%r15)
  6109. addq $8, %r15
  6110. jmp start
  6111. conclusion:
  6112. subq $8, %r15
  6113. addq $0, %rsp
  6114. popq %r14
  6115. popq %rbx
  6116. popq %r12
  6117. popq %r13
  6118. popq %rbp
  6119. retq
  6120. \end{lstlisting}
  6121. \end{minipage}
  6122. \caption{Output of the \code{print-x86} pass.}
  6123. \label{fig:print-x86-output-gc}
  6124. \end{figure}
  6125. \begin{figure}[p]
  6126. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6127. \node (R3) at (0,2) {\large $R_3$};
  6128. \node (R3-2) at (3,2) {\large $R_3$};
  6129. \node (R3-3) at (6,2) {\large $R_3$};
  6130. \node (R3-4) at (9,2) {\large $R_3$};
  6131. \node (R3-5) at (9,0) {\large $R'_3$};
  6132. \node (R3-6) at (6,0) {\large $R'_3$};
  6133. \node (C2-4) at (3,-2) {\large $C_2$};
  6134. \node (C2-3) at (0,-2) {\large $C_2$};
  6135. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  6136. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  6137. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  6138. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  6139. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  6140. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  6141. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R3-2);
  6142. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  6143. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  6144. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  6145. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  6146. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  6147. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  6148. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6149. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6150. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  6151. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  6152. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6153. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6154. \end{tikzpicture}
  6155. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  6156. \label{fig:R3-passes}
  6157. \end{figure}
  6158. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6159. for the compilation of $R_3$.
  6160. \section{Challenge: Simple Structures}
  6161. \label{sec:simple-structures}
  6162. \index{struct}
  6163. \index{structure}
  6164. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6165. $R^s_3$, which extends $R^3$ with support for simple structures.
  6166. Recall that a \code{struct} in Typed Racket is a user-defined data
  6167. type that contains named fields and that is heap allocated, similar to
  6168. a vector. The following is an example of a structure definition, in
  6169. this case the definition of a \code{point} type.
  6170. \begin{lstlisting}
  6171. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6172. \end{lstlisting}
  6173. \begin{figure}[tbp]
  6174. \centering
  6175. \fbox{
  6176. \begin{minipage}{0.96\textwidth}
  6177. \[
  6178. \begin{array}{lcl}
  6179. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6180. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6181. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6182. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6183. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6184. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6185. \mid (\key{and}\;\Exp\;\Exp)
  6186. \mid (\key{or}\;\Exp\;\Exp)
  6187. \mid (\key{not}\;\Exp) } \\
  6188. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6189. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6190. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6191. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6192. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6193. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6194. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6195. R_3 &::=& \Def \ldots \; \Exp
  6196. \end{array}
  6197. \]
  6198. \end{minipage}
  6199. }
  6200. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6201. (Figure~\ref{fig:r3-concrete-syntax}).}
  6202. \label{fig:r3s-concrete-syntax}
  6203. \end{figure}
  6204. An instance of a structure is created using function call syntax, with
  6205. the name of the structure in the function position:
  6206. \begin{lstlisting}
  6207. (point 7 12)
  6208. \end{lstlisting}
  6209. Function-call syntax is also used to read the value in a field of a
  6210. structure. The function name is formed by the structure name, a dash,
  6211. and the field name. The following example uses \code{point-x} and
  6212. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6213. instances.
  6214. \begin{center}
  6215. \begin{lstlisting}
  6216. (let ([pt1 (point 7 12)])
  6217. (let ([pt2 (point 4 3)])
  6218. (+ (- (point-x pt1) (point-x pt2))
  6219. (- (point-y pt1) (point-y pt2)))))
  6220. \end{lstlisting}
  6221. \end{center}
  6222. Similarly, to write to a field of a structure, use its set function,
  6223. whose name starts with \code{set-}, followed by the structure name,
  6224. then a dash, then the field name, and conclused with an exclamation
  6225. mark. The folowing example uses \code{set-point-x!} to change the
  6226. \code{x} field from \code{7} to \code{42}.
  6227. \begin{center}
  6228. \begin{lstlisting}
  6229. (let ([pt (point 7 12)])
  6230. (let ([_ (set-point-x! pt 42)])
  6231. (point-x pt)))
  6232. \end{lstlisting}
  6233. \end{center}
  6234. \begin{exercise}\normalfont
  6235. Extend your compiler with support for simple structures, compiling
  6236. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6237. structures and test your compiler.
  6238. \end{exercise}
  6239. \section{Challenge: Generational Collection}
  6240. The copying collector described in Section~\ref{sec:GC} can incur
  6241. significant runtime overhead because the call to \code{collect} takes
  6242. time proportional to all of the live data. One way to reduce this
  6243. overhead is to reduce how much data is inspected in each call to
  6244. \code{collect}. In particular, researchers have observed that recently
  6245. allocated data is more likely to become garbage then data that has
  6246. survived one or more previous calls to \code{collect}. This insight
  6247. motivated the creation of \emph{generational garbage collectors}
  6248. \index{generational garbage collector} that
  6249. 1) segragates data according to its age into two or more generations,
  6250. 2) allocates less space for younger generations, so collecting them is
  6251. faster, and more space for the older generations, and 3) performs
  6252. collection on the younger generations more frequently then for older
  6253. generations~\citep{Wilson:1992fk}.
  6254. For this challenge assignment, the goal is to adapt the copying
  6255. collector implemented in \code{runtime.c} to use two generations, one
  6256. for young data and one for old data. Each generation consists of a
  6257. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6258. \code{collect} function to use the two generations.
  6259. \begin{enumerate}
  6260. \item Copy the young generation's FromSpace to its ToSpace then switch
  6261. the role of the ToSpace and FromSpace
  6262. \item If there is enough space for the requested number of bytes in
  6263. the young FromSpace, then return from \code{collect}.
  6264. \item If there is not enough space in the young FromSpace for the
  6265. requested bytes, then move the data from the young generation to the
  6266. old one with the following steps:
  6267. \begin{enumerate}
  6268. \item If there is enough room in the old FromSpace, copy the young
  6269. FromSpace to the old FromSpace and then return.
  6270. \item If there is not enough room in the old FromSpace, then collect
  6271. the old generation by copying the old FromSpace to the old ToSpace
  6272. and swap the roles of the old FromSpace and ToSpace.
  6273. \item If there is enough room now, copy the young FromSpace to the
  6274. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6275. and ToSpace for the old generation. Copy the young FromSpace and
  6276. the old FromSpace into the larger FromSpace for the old
  6277. generation and then return.
  6278. \end{enumerate}
  6279. \end{enumerate}
  6280. We recommend that you generalize the \code{cheney} function so that it
  6281. can be used for all the copies mentioned above: between the young
  6282. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6283. between the young FromSpace and old FromSpace. This can be
  6284. accomplished by adding parameters to \code{cheney} that replace its
  6285. use of the global variables \code{fromspace\_begin},
  6286. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6287. Note that the collection of the young generation does not traverse the
  6288. old generation. This introduces a potential problem: there may be
  6289. young data that is only reachable through pointers in the old
  6290. generation. If these pointers are not taken into account, the
  6291. collector could throw away young data that is live! One solution,
  6292. called \emph{pointer recording}, is to maintain a set of all the
  6293. pointers from the old generation into the new generation and consider
  6294. this set as part of the root set. To maintain this set, the compiler
  6295. must insert extra instructions around every \code{vector-set!}. If the
  6296. vector being modified is in the old generation, and if the value being
  6297. written is a pointer into the new generation, than that pointer must
  6298. be added to the set. Also, if the value being overwritten was a
  6299. pointer into the new generation, then that pointer should be removed
  6300. from the set.
  6301. \begin{exercise}\normalfont
  6302. Adapt the \code{collect} function in \code{runtime.c} to implement
  6303. generational garbage collection, as outlined in this section.
  6304. Update the code generation for \code{vector-set!} to implement
  6305. pointer recording. Make sure that your new compiler and runtime
  6306. passes your test suite.
  6307. \end{exercise}
  6308. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6309. \chapter{Functions}
  6310. \label{ch:functions}
  6311. \index{function}
  6312. This chapter studies the compilation of functions similar to those
  6313. found in the C language. This corresponds to a subset of Typed Racket
  6314. in which only top-level function definitions are allowed. This kind of
  6315. function is an important stepping stone to implementing
  6316. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6317. is the topic of Chapter~\ref{ch:lambdas}.
  6318. \section{The $R_4$ Language}
  6319. The concrete and abstract syntax for function definitions and function
  6320. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6321. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6322. $R_4$ begin with zero or more function definitions. The function
  6323. names from these definitions are in-scope for the entire program,
  6324. including all other function definitions (so the ordering of function
  6325. definitions does not matter). The concrete syntax for function
  6326. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6327. where the first expression must
  6328. evaluate to a function and the rest are the arguments.
  6329. The abstract syntax for function application is
  6330. $\APPLY{\Exp}{\Exp\ldots}$.
  6331. %% The syntax for function application does not include an explicit
  6332. %% keyword, which is error prone when using \code{match}. To alleviate
  6333. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6334. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6335. Functions are first-class in the sense that a function pointer
  6336. \index{function pointer} is data and can be stored in memory or passed
  6337. as a parameter to another function. Thus, we introduce a function
  6338. type, written
  6339. \begin{lstlisting}
  6340. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6341. \end{lstlisting}
  6342. for a function whose $n$ parameters have the types $\Type_1$ through
  6343. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6344. these functions (with respect to Racket functions) is that they are
  6345. not lexically scoped. That is, the only external entities that can be
  6346. referenced from inside a function body are other globally-defined
  6347. functions. The syntax of $R_4$ prevents functions from being nested
  6348. inside each other.
  6349. \begin{figure}[tp]
  6350. \centering
  6351. \fbox{
  6352. \begin{minipage}{0.96\textwidth}
  6353. \small
  6354. \[
  6355. \begin{array}{lcl}
  6356. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6357. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6358. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6359. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6360. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6361. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6362. \mid (\key{and}\;\Exp\;\Exp)
  6363. \mid (\key{or}\;\Exp\;\Exp)
  6364. \mid (\key{not}\;\Exp)} \\
  6365. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6366. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6367. (\key{vector-ref}\;\Exp\;\Int)} \\
  6368. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6369. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6370. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6371. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6372. R_4 &::=& \Def \ldots \; \Exp
  6373. \end{array}
  6374. \]
  6375. \end{minipage}
  6376. }
  6377. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6378. \label{fig:r4-concrete-syntax}
  6379. \end{figure}
  6380. \begin{figure}[tp]
  6381. \centering
  6382. \fbox{
  6383. \begin{minipage}{0.96\textwidth}
  6384. \small
  6385. \[
  6386. \begin{array}{lcl}
  6387. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6388. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6389. &\mid& \gray{ \BOOL{\itm{bool}}
  6390. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6391. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6392. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6393. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6394. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6395. \end{array}
  6396. \]
  6397. \end{minipage}
  6398. }
  6399. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6400. \label{fig:r4-syntax}
  6401. \end{figure}
  6402. The program in Figure~\ref{fig:r4-function-example} is a
  6403. representative example of defining and using functions in $R_4$. We
  6404. define a function \code{map-vec} that applies some other function
  6405. \code{f} to both elements of a vector and returns a new
  6406. vector containing the results. We also define a function \code{add1}.
  6407. The program applies
  6408. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6409. \code{(vector 1 42)}, from which we return the \code{42}.
  6410. \begin{figure}[tbp]
  6411. \begin{lstlisting}
  6412. (define (map-vec [f : (Integer -> Integer)]
  6413. [v : (Vector Integer Integer)])
  6414. : (Vector Integer Integer)
  6415. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6416. (define (add1 [x : Integer]) : Integer
  6417. (+ x 1))
  6418. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6419. \end{lstlisting}
  6420. \caption{Example of using functions in $R_4$.}
  6421. \label{fig:r4-function-example}
  6422. \end{figure}
  6423. The definitional interpreter for $R_4$ is in
  6424. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6425. responsible for setting up the mutual recursion between the top-level
  6426. function definitions. We use the classic back-patching \index{back-patching}
  6427. approach that uses mutable variables and makes two passes over the function
  6428. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6429. top-level environment using a mutable cons cell for each function
  6430. definition. Note that the \code{lambda} value for each function is
  6431. incomplete; it does not yet include the environment. Once the
  6432. top-level environment is constructed, we then iterate over it and
  6433. update the \code{lambda} values to use the top-level environment.
  6434. \begin{figure}[tp]
  6435. \begin{lstlisting}
  6436. (define (interp-exp env)
  6437. (lambda (e)
  6438. (define recur (interp-exp env))
  6439. (match e
  6440. ...
  6441. [(Apply fun args)
  6442. (define fun-val (recur fun))
  6443. (define arg-vals (for/list ([e args]) (recur e)))
  6444. (match fun-val
  6445. [`(lambda (,xs ...) ,body ,fun-env)
  6446. (define new-env (append (map cons xs arg-vals) fun-env))
  6447. ((interp-exp new-env) body)])]
  6448. ...
  6449. )))
  6450. (define (interp-def d)
  6451. (match d
  6452. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6453. (mcons f `(lambda ,xs ,body ()))]
  6454. ))
  6455. (define (interp-R4 p)
  6456. (match p
  6457. [(ProgramDefsExp info ds body)
  6458. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6459. (for/list ([b top-level])
  6460. (set-mcdr! b (match (mcdr b)
  6461. [`(lambda ,xs ,body ())
  6462. `(lambda ,xs ,body ,top-level)])))
  6463. ((interp-exp top-level) body))]
  6464. ))
  6465. \end{lstlisting}
  6466. \caption{Interpreter for the $R_4$ language.}
  6467. \label{fig:interp-R4}
  6468. \end{figure}
  6469. \margincomment{TODO: explain type checker}
  6470. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6471. \begin{figure}[tp]
  6472. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6473. (define (fun-def-name d)
  6474. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6475. (define (fun-def-type d)
  6476. (match d
  6477. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6478. (define (type-check-exp env)
  6479. (lambda (e)
  6480. (match e
  6481. ...
  6482. [(Apply e es)
  6483. (define-values (e^ ty) ((type-check-exp env) e))
  6484. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6485. ((type-check-exp env) e)))
  6486. (match ty
  6487. [`(,ty^* ... -> ,rt)
  6488. (for ([arg-ty ty*] [prm-ty ty^*])
  6489. (unless (equal? arg-ty prm-ty)
  6490. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6491. (values (HasType (Apply e^ e*) rt) rt)]
  6492. [else (error "expected a function, not" ty)])])))
  6493. (define (type-check-def env)
  6494. (lambda (e)
  6495. (match e
  6496. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6497. (define new-env (append (map cons xs ps) env))
  6498. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6499. (unless (equal? ty^ rt)
  6500. (error "body type ~a not equal to return type ~a" ty^ rt))
  6501. (Def f p:t* rt info body^)])))
  6502. (define (type-check env)
  6503. (lambda (e)
  6504. (match e
  6505. [(ProgramDefsExp info ds body)
  6506. (define new-env (for/list ([d ds])
  6507. (cons (fun-def-name d) (fun-def-type d))))
  6508. (define ds^ (for/list ([d ds])
  6509. ((type-check-def new-env) d)))
  6510. (define-values (body^ ty) ((type-check-exp new-env) body))
  6511. (unless (equal? ty 'Integer)
  6512. (error "result of the program must be an integer, not " ty))
  6513. (ProgramDefsExp info ds^ body^)]
  6514. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6515. \end{lstlisting}
  6516. \caption{Type checker for the $R_4$ language.}
  6517. \label{fig:type-check-R4}
  6518. \end{figure}
  6519. \section{Functions in x86}
  6520. \label{sec:fun-x86}
  6521. \margincomment{\tiny Make sure callee-saved registers are discussed
  6522. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6523. \margincomment{\tiny Talk about the return address on the
  6524. stack and what callq and retq does.\\ --Jeremy }
  6525. The x86 architecture provides a few features to support the
  6526. implementation of functions. We have already seen that x86 provides
  6527. labels so that one can refer to the location of an instruction, as is
  6528. needed for jump instructions. Labels can also be used to mark the
  6529. beginning of the instructions for a function. Going further, we can
  6530. obtain the address of a label by using the \key{leaq} instruction and
  6531. PC-relative addressing. For example, the following puts the
  6532. address of the \code{add1} label into the \code{rbx} register.
  6533. \begin{lstlisting}
  6534. leaq add1(%rip), %rbx
  6535. \end{lstlisting}
  6536. The instruction pointer register \key{rip} (aka. the program counter
  6537. \index{program counter}) always points to the next instruction to be
  6538. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6539. linker computes the distance $d$ between the address of \code{add1}
  6540. and where the \code{rip} would be at that moment and then changes
  6541. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6542. the address of \code{add1}.
  6543. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6544. jump to a function whose location is given by a label. To support
  6545. function calls in this chapter we instead will be jumping to a
  6546. function whose location is given by an address in a register, that is,
  6547. we need to make an \emph{indirect function call}. The x86 syntax for
  6548. this is a \code{callq} instruction but with an asterisk before the
  6549. register name.\index{indirect function call}
  6550. \begin{lstlisting}
  6551. callq *%rbx
  6552. \end{lstlisting}
  6553. \subsection{Calling Conventions}
  6554. \index{calling conventions}
  6555. The \code{callq} instruction provides partial support for implementing
  6556. functions: it pushes the return address on the stack and it jumps to
  6557. the target. However, \code{callq} does not handle
  6558. \begin{enumerate}
  6559. \item parameter passing,
  6560. \item pushing frames on the procedure call stack and popping them off,
  6561. or
  6562. \item determining how registers are shared by different functions.
  6563. \end{enumerate}
  6564. Regarding (1) parameter passing, recall that the following six
  6565. registers are used to pass arguments to a function, in this order.
  6566. \begin{lstlisting}
  6567. rdi rsi rdx rcx r8 r9
  6568. \end{lstlisting}
  6569. If there are
  6570. more than six arguments, then the convention is to use space on the
  6571. frame of the caller for the rest of the arguments. However, to ease
  6572. the implementation of efficient tail calls
  6573. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6574. arguments.
  6575. %
  6576. Also recall that the register \code{rax} is for the return value of
  6577. the function.
  6578. \index{prelude}\index{conclusion}
  6579. Regarding (2) frames \index{frame} and the procedure call stack,
  6580. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6581. the stack grows down, with each function call using a chunk of space
  6582. called a frame. The caller sets the stack pointer, register
  6583. \code{rsp}, to the last data item in its frame. The callee must not
  6584. change anything in the caller's frame, that is, anything that is at or
  6585. above the stack pointer. The callee is free to use locations that are
  6586. below the stack pointer.
  6587. Recall that we are storing variables of vector type on the root stack.
  6588. So the prelude needs to move the root stack pointer \code{r15} up and
  6589. the conclusion needs to move the root stack pointer back down. Also,
  6590. the prelude must initialize to \code{0} this frame's slots in the root
  6591. stack to signal to the garbage collector that those slots do not yet
  6592. contain a pointer to a vector. Otherwise the garbage collector will
  6593. interpret the garbage bits in those slots as memory addresses and try
  6594. to traverse them, causing serious mayhem!
  6595. Regarding (3) the sharing of registers between different functions,
  6596. recall from Section~\ref{sec:calling-conventions} that the registers
  6597. are divided into two groups, the caller-saved registers and the
  6598. callee-saved registers. The caller should assume that all the
  6599. caller-saved registers get overwritten with arbitrary values by the
  6600. callee. That is why we recommend in
  6601. Section~\ref{sec:calling-conventions} that variables that are live
  6602. during a function call should not be assigned to caller-saved
  6603. registers.
  6604. On the flip side, if the callee wants to use a callee-saved register,
  6605. the callee must save the contents of those registers on their stack
  6606. frame and then put them back prior to returning to the caller. That
  6607. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6608. the register allocator assigns a variable to a callee-saved register,
  6609. then the prelude of the \code{main} function must save that register
  6610. to the stack and the conclusion of \code{main} must restore it. This
  6611. recommendation now generalizes to all functions.
  6612. Also recall that the base pointer, register \code{rbp}, is used as a
  6613. point-of-reference within a frame, so that each local variable can be
  6614. accessed at a fixed offset from the base pointer
  6615. (Section~\ref{sec:x86}).
  6616. %
  6617. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6618. and callee frames.
  6619. \begin{figure}[tbp]
  6620. \centering
  6621. \begin{tabular}{r|r|l|l} \hline
  6622. Caller View & Callee View & Contents & Frame \\ \hline
  6623. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6624. 0(\key{\%rbp}) & & old \key{rbp} \\
  6625. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6626. \ldots & & \ldots \\
  6627. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6628. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6629. \ldots & & \ldots \\
  6630. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6631. %% & & \\
  6632. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6633. %% & \ldots & \ldots \\
  6634. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6635. \hline
  6636. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6637. & 0(\key{\%rbp}) & old \key{rbp} \\
  6638. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6639. & \ldots & \ldots \\
  6640. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6641. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6642. & \ldots & \ldots \\
  6643. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6644. \end{tabular}
  6645. \caption{Memory layout of caller and callee frames.}
  6646. \label{fig:call-frames}
  6647. \end{figure}
  6648. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6649. %% local variables and for storing the values of callee-saved registers
  6650. %% (we shall refer to all of these collectively as ``locals''), and that
  6651. %% at the beginning of a function we move the stack pointer \code{rsp}
  6652. %% down to make room for them.
  6653. %% We recommend storing the local variables
  6654. %% first and then the callee-saved registers, so that the local variables
  6655. %% can be accessed using \code{rbp} the same as before the addition of
  6656. %% functions.
  6657. %% To make additional room for passing arguments, we shall
  6658. %% move the stack pointer even further down. We count how many stack
  6659. %% arguments are needed for each function call that occurs inside the
  6660. %% body of the function and find their maximum. Adding this number to the
  6661. %% number of locals gives us how much the \code{rsp} should be moved at
  6662. %% the beginning of the function. In preparation for a function call, we
  6663. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6664. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6665. %% so on.
  6666. %% Upon calling the function, the stack arguments are retrieved by the
  6667. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6668. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6669. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6670. %% the layout of the caller and callee frames. Notice how important it is
  6671. %% that we correctly compute the maximum number of arguments needed for
  6672. %% function calls; if that number is too small then the arguments and
  6673. %% local variables will smash into each other!
  6674. \subsection{Efficient Tail Calls}
  6675. \label{sec:tail-call}
  6676. In general, the amount of stack space used by a program is determined
  6677. by the longest chain of nested function calls. That is, if function
  6678. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6679. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6680. $n$ can grow quite large in the case of recursive or mutually
  6681. recursive functions. However, in some cases we can arrange to use only
  6682. constant space, i.e. $O(1)$, instead of $O(n)$.
  6683. If a function call is the last action in a function body, then that
  6684. call is said to be a \emph{tail call}\index{tail call}.
  6685. For example, in the following
  6686. program, the recursive call to \code{tail-sum} is a tail call.
  6687. \begin{center}
  6688. \begin{lstlisting}
  6689. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6690. (if (eq? n 0)
  6691. r
  6692. (tail-sum (- n 1) (+ n r))))
  6693. (+ (tail-sum 5 0) 27)
  6694. \end{lstlisting}
  6695. \end{center}
  6696. At a tail call, the frame of the caller is no longer needed, so we
  6697. can pop the caller's frame before making the tail call. With this
  6698. approach, a recursive function that only makes tail calls will only
  6699. use $O(1)$ stack space. Functional languages like Racket typically
  6700. rely heavily on recursive functions, so they typically guarantee that
  6701. all tail calls will be optimized in this way.
  6702. \index{frame}
  6703. However, some care is needed with regards to argument passing in tail
  6704. calls. As mentioned above, for arguments beyond the sixth, the
  6705. convention is to use space in the caller's frame for passing
  6706. arguments. But for a tail call we pop the caller's frame and can no
  6707. longer use it. Another alternative is to use space in the callee's
  6708. frame for passing arguments. However, this option is also problematic
  6709. because the caller and callee's frame overlap in memory. As we begin
  6710. to copy the arguments from their sources in the caller's frame, the
  6711. target locations in the callee's frame might overlap with the sources
  6712. for later arguments! We solve this problem by not using the stack for
  6713. passing more than six arguments but instead using the heap, as we
  6714. describe in the Section~\ref{sec:limit-functions-r4}.
  6715. As mentioned above, for a tail call we pop the caller's frame prior to
  6716. making the tail call. The instructions for popping a frame are the
  6717. instructions that we usually place in the conclusion of a
  6718. function. Thus, we also need to place such code immediately before
  6719. each tail call. These instructions include restoring the callee-saved
  6720. registers, so it is good that the argument passing registers are all
  6721. caller-saved registers.
  6722. One last note regarding which instruction to use to make the tail
  6723. call. When the callee is finished, it should not return to the current
  6724. function, but it should return to the function that called the current
  6725. one. Thus, the return address that is already on the stack is the
  6726. right one, and we should not use \key{callq} to make the tail call, as
  6727. that would unnecessarily overwrite the return address. Instead we can
  6728. simply use the \key{jmp} instruction. Like the indirect function call,
  6729. we write an \emph{indirect jump}\index{indirect jump} with a register
  6730. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6731. jump target because the preceding conclusion overwrites just about
  6732. everything else.
  6733. \begin{lstlisting}
  6734. jmp *%rax
  6735. \end{lstlisting}
  6736. \section{Shrink $R_4$}
  6737. \label{sec:shrink-r4}
  6738. The \code{shrink} pass performs a minor modification to ease the
  6739. later passes. This pass introduces an explicit \code{main} function
  6740. and changes the top \code{ProgramDefsExp} form to
  6741. \code{ProgramDefs} as follows.
  6742. \begin{lstlisting}
  6743. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6744. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6745. \end{lstlisting}
  6746. where $\itm{mainDef}$ is
  6747. \begin{lstlisting}
  6748. (Def 'main '() 'Integer '() |$\Exp'$|)
  6749. \end{lstlisting}
  6750. \section{Reveal Functions and the $F_1$ language}
  6751. \label{sec:reveal-functions-r4}
  6752. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6753. respect: it conflates the use of function names and local
  6754. variables. This is a problem because we need to compile the use of a
  6755. function name differently than the use of a local variable; we need to
  6756. use \code{leaq} to convert the function name (a label in x86) to an
  6757. address in a register. Thus, it is a good idea to create a new pass
  6758. that changes function references from just a symbol $f$ to
  6759. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6760. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6761. \begin{figure}[tp]
  6762. \centering
  6763. \fbox{
  6764. \begin{minipage}{0.96\textwidth}
  6765. \[
  6766. \begin{array}{lcl}
  6767. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6768. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6769. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6770. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6771. &\mid& \gray{ \BOOL{\itm{bool}}
  6772. \mid \AND{\Exp}{\Exp} }\\
  6773. &\mid& \gray{ \OR{\Exp}{\Exp}
  6774. \mid \NOT{\Exp} } \\
  6775. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6776. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6777. &\mid& \gray{ \VECTOR{\Exp} } \\
  6778. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6779. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6780. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6781. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6782. &\mid& \FUNREF{\Var}\\
  6783. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6784. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6785. \end{array}
  6786. \]
  6787. \end{minipage}
  6788. }
  6789. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6790. (Figure~\ref{fig:r4-syntax}).}
  6791. \label{fig:f1-syntax}
  6792. \end{figure}
  6793. %% Distinguishing between calls in tail position and non-tail position
  6794. %% requires the pass to have some notion of context. We recommend using
  6795. %% two mutually recursive functions, one for processing expressions in
  6796. %% tail position and another for the rest.
  6797. Placing this pass after \code{uniquify} will make sure that there are
  6798. no local variables and functions that share the same name. On the
  6799. other hand, \code{reveal-functions} needs to come before the
  6800. \code{explicate-control} pass because that pass helps us compile
  6801. \code{FunRef} forms into assignment statements.
  6802. \section{Limit Functions}
  6803. \label{sec:limit-functions-r4}
  6804. Recall that we wish to limit the number of function parameters to six
  6805. so that we do not need to use the stack for argument passing, which
  6806. makes it easier to implement efficient tail calls. However, because
  6807. the input language $R_4$ supports arbitrary numbers of function
  6808. arguments, we have some work to do!
  6809. This pass transforms functions and function calls that involve more
  6810. than six arguments to pass the first five arguments as usual, but it
  6811. packs the rest of the arguments into a vector and passes it as the
  6812. sixth argument.
  6813. Each function definition with too many parameters is transformed as
  6814. follows.
  6815. \begin{lstlisting}
  6816. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6817. |$\Rightarrow$|
  6818. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6819. \end{lstlisting}
  6820. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6821. the occurences of the later parameters with vector references.
  6822. \begin{lstlisting}
  6823. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6824. \end{lstlisting}
  6825. For function calls with too many arguments, the \code{limit-functions}
  6826. pass transforms them in the following way.
  6827. \begin{tabular}{lll}
  6828. \begin{minipage}{0.2\textwidth}
  6829. \begin{lstlisting}
  6830. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6831. \end{lstlisting}
  6832. \end{minipage}
  6833. &
  6834. $\Rightarrow$
  6835. &
  6836. \begin{minipage}{0.4\textwidth}
  6837. \begin{lstlisting}
  6838. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6839. \end{lstlisting}
  6840. \end{minipage}
  6841. \end{tabular}
  6842. \section{Remove Complex Operators and Operands}
  6843. \label{sec:rco-r4}
  6844. The primary decisions to make for this pass is whether to classify
  6845. \code{FunRef} and \code{Apply} as either simple or complex
  6846. expressions. Recall that a simple expression will eventually end up as
  6847. just an ``immediate'' argument of an x86 instruction. Function
  6848. application will be translated to a sequence of instructions, so
  6849. \code{Apply} must be classified as complex expression. Regarding
  6850. \code{FunRef}, as discussed above, the function label needs to
  6851. be converted to an address using the \code{leaq} instruction. Thus,
  6852. even though \code{FunRef} seems rather simple, it needs to be
  6853. classified as a complex expression so that we generate an assignment
  6854. statement with a left-hand side that can serve as the target of the
  6855. \code{leaq}.
  6856. \section{Explicate Control and the $C_3$ language}
  6857. \label{sec:explicate-control-r4}
  6858. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6859. the concrete and abstract syntax for $C_3$, the output of
  6860. \key{explicate-control}. The auxiliary functions for assignment and
  6861. tail contexts should be updated with cases for \code{Apply} and
  6862. \code{FunRef} and the function for predicate context should be updated
  6863. for \code{Apply} but not \code{FunRef}. (A \code{FunRef} can't be a
  6864. Boolean.) In assignment and predicate contexts, \code{Apply} becomes
  6865. \code{Call}, whereas in tail position \code{Apply} becomes
  6866. \code{TailCall}. We recommend defining a new auxiliary function for
  6867. processing function definitions. This code is similar to the case for
  6868. \code{Program} in $R_3$. The top-level \code{explicate-control}
  6869. function that handles the \code{ProgramDefs} form of $R_4$ can then
  6870. apply this new function to all the function definitions.
  6871. \begin{figure}[tp]
  6872. \fbox{
  6873. \begin{minipage}{0.96\textwidth}
  6874. \[
  6875. \begin{array}{lcl}
  6876. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6877. \\
  6878. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6879. \Exp &::= & \gray{ \Atm \mid (\key{read}) \mid (\key{-}\;\Atm) \mid (\key{+} \; \Atm\;\Atm)
  6880. \mid (\key{not}\;\Atm) \mid (\itm{cmp}\;\Atm\;\Atm) } \\
  6881. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6882. \mid (\key{vector-ref}\, \Atm\, \Int) } \\
  6883. &\mid& \gray{ (\key{vector-set!}\,\Atm\,\Int\,\Atm) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6884. &\mid& (\key{fun-ref}~\itm{label}) \mid (\key{call} \,\Atm\,\Atm\ldots) \\
  6885. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6886. \mid (\key{collect} \,\itm{int}) }\\
  6887. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6888. &\mid& \gray{(\key{goto}\,\itm{label})
  6889. \mid \IF{(\itm{cmp}\, \Atm\,\Atm)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6890. &\mid& (\key{tail-call}\,\Atm\,\Atm\ldots) \\
  6891. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6892. C_3 & ::= & \Def\ldots
  6893. \end{array}
  6894. \]
  6895. \end{minipage}
  6896. }
  6897. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  6898. \label{fig:c3-concrete-syntax}
  6899. \end{figure}
  6900. \begin{figure}[tp]
  6901. \fbox{
  6902. \begin{minipage}{0.96\textwidth}
  6903. \small
  6904. \[
  6905. \begin{array}{lcl}
  6906. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6907. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6908. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6909. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6910. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6911. &\mid& \gray{ (\key{Allocate} \,\itm{int}\,\itm{type}) } \\
  6912. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  6913. &\mid& \gray{ (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm)) }\\
  6914. &\mid& \gray{ (\key{GlobalValue} \,\Var) \mid (\key{Void}) }\\
  6915. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\Atm\ldots} \\
  6916. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  6917. \mid (\key{Collect} \,\itm{int}) } \\
  6918. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6919. \mid \GOTO{\itm{label}} } \\
  6920. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6921. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  6922. \Def &::=& \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{\itm{info}}{((\itm{label}\,\key{.}\,\Tail)\ldots)}\\
  6923. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6924. \end{array}
  6925. \]
  6926. \end{minipage}
  6927. }
  6928. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  6929. \label{fig:c3-syntax}
  6930. \end{figure}
  6931. \section{Uncover Locals}
  6932. \label{sec:uncover-locals-r4}
  6933. The function for processing $\Tail$ should be updated with a case for
  6934. \code{TailCall}. We also recommend creating a new function for
  6935. processing function definitions. Each function definition in $C_3$ has
  6936. its own set of local variables, so the code for function definitions
  6937. should be similar to the case for the \code{Program} form in $C_2$.
  6938. \section{Select Instructions and the x86$_3$ Language}
  6939. \label{sec:select-r4}
  6940. \index{instruction selection}
  6941. The output of select instructions is a program in the x86$_3$
  6942. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6943. \index{x86}
  6944. \begin{figure}[tp]
  6945. \fbox{
  6946. \begin{minipage}{0.96\textwidth}
  6947. \small
  6948. \[
  6949. \begin{array}{lcl}
  6950. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  6951. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  6952. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6953. \Instr &::=& \ldots
  6954. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  6955. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  6956. \Block &::= & \Instr\ldots \\
  6957. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  6958. x86_3 &::= & \Def\ldots
  6959. \end{array}
  6960. \]
  6961. \end{minipage}
  6962. }
  6963. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2-concrete}).}
  6964. \label{fig:x86-3-concrete}
  6965. \end{figure}
  6966. \begin{figure}[tp]
  6967. \fbox{
  6968. \begin{minipage}{0.96\textwidth}
  6969. \small
  6970. \[
  6971. \begin{array}{lcl}
  6972. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6973. \mid \BYTEREG{\Reg} } \\
  6974. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  6975. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  6976. \mid \TAILJMP{\Arg}{\itm{int}}\\
  6977. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  6978. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  6979. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  6980. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  6981. \end{array}
  6982. \]
  6983. \end{minipage}
  6984. }
  6985. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6986. \label{fig:x86-3}
  6987. \end{figure}
  6988. An assignment of a function reference to a variable becomes a
  6989. load-effective-address instruction as follows: \\
  6990. \begin{tabular}{lcl}
  6991. \begin{minipage}{0.35\textwidth}
  6992. \begin{lstlisting}
  6993. |$\itm{lhs}$| = (fun-ref |$f$|);
  6994. \end{lstlisting}
  6995. \end{minipage}
  6996. &
  6997. $\Rightarrow$\qquad\qquad
  6998. &
  6999. \begin{minipage}{0.3\textwidth}
  7000. \begin{lstlisting}
  7001. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7002. \end{lstlisting}
  7003. \end{minipage}
  7004. \end{tabular} \\
  7005. Regarding function definitions, we need to remove the parameters and
  7006. instead perform parameter passing using the conventions discussed in
  7007. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7008. registers. We recommend turning the parameters into local variables
  7009. and generating instructions at the beginning of the function to move
  7010. from the argument passing registers to these local variables.
  7011. \begin{lstlisting}
  7012. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7013. |$\Rightarrow$|
  7014. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7015. \end{lstlisting}
  7016. The $G'$ control-flow graph is the same as $G$ except that the
  7017. \code{start} block is modified to add the instructions for moving from
  7018. the argument registers to the parameter variables. So the \code{start}
  7019. block of $G$ shown on the left is changed to the code on the right.
  7020. \begin{center}
  7021. \begin{minipage}{0.3\textwidth}
  7022. \begin{lstlisting}
  7023. start:
  7024. |$\itm{instr}_1$|
  7025. |$\vdots$|
  7026. |$\itm{instr}_n$|
  7027. \end{lstlisting}
  7028. \end{minipage}
  7029. $\Rightarrow$
  7030. \begin{minipage}{0.3\textwidth}
  7031. \begin{lstlisting}
  7032. start:
  7033. movq %rdi, |$x_1$|
  7034. movq %rsi, |$x_2$|
  7035. |$\vdots$|
  7036. |$\itm{instr}_1$|
  7037. |$\vdots$|
  7038. |$\itm{instr}_n$|
  7039. \end{lstlisting}
  7040. \end{minipage}
  7041. \end{center}
  7042. By changing the parameters to local variables, we are giving the
  7043. register allocator control over which registers or stack locations to
  7044. use for them. If you implemented the move-biasing challenge
  7045. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7046. assign the parameter variables to the corresponding argument register,
  7047. in which case the \code{patch-instructions} pass will remove the
  7048. \code{movq} instruction. This happens in the example translation in
  7049. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7050. the \code{add} function.
  7051. %
  7052. Also, note that the register allocator will perform liveness analysis
  7053. on this sequence of move instructions and build the interference
  7054. graph. So, for example, $x_1$ will be marked as interfering with
  7055. \code{rsi} and that will prevent the assignment of $x_1$ to
  7056. \code{rsi}, which is good, because that would overwrite the argument
  7057. that needs to move into $x_2$.
  7058. Next, consider the compilation of function calls. In the mirror image
  7059. of handling the parameters of function definitions, the arguments need
  7060. to be moved to the argument passing registers. The function call
  7061. itself is performed with an indirect function call. The return value
  7062. from the function is stored in \code{rax}, so it needs to be moved
  7063. into the \itm{lhs}.
  7064. \begin{lstlisting}
  7065. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7066. |$\Rightarrow$|
  7067. movq |$\itm{arg}_1$|, %rdi
  7068. movq |$\itm{arg}_2$|, %rsi
  7069. |$\vdots$|
  7070. callq *|\itm{fun}|
  7071. movq %rax, |\itm{lhs}|
  7072. \end{lstlisting}
  7073. The \code{IndirectCallq} AST node includes an integer for the arity of
  7074. the function, i.e., the number of parameters. That information is
  7075. useful in the \code{uncover-live} pass for determining which
  7076. argument-passing registers are potentially read during the call.
  7077. For tail calls, the parameter passing is the same as non-tail calls:
  7078. generate instructions to move the arguments into to the argument
  7079. passing registers. After that we need to pop the frame from the
  7080. procedure call stack. However, we do not yet know how big the frame
  7081. is; that gets determined during register allocation. So instead of
  7082. generating those instructions here, we invent a new instruction that
  7083. means ``pop the frame and then do an indirect jump'', which we name
  7084. \code{TailJmp}. The abstract syntax for this instruction includes an
  7085. argument that specifies where to jump and an integer that represents
  7086. the arity of the function being called.
  7087. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7088. using the label \code{start} for the initial block of a program, and
  7089. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7090. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7091. can be compiled to an assignment to \code{rax} followed by a jump to
  7092. \code{conclusion}. With the addition of function definitions, we will
  7093. have a starting block and conclusion for each function, but their
  7094. labels need to be unique. We recommend prepending the function's name
  7095. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7096. labels. (Alternatively, one could \code{gensym} labels for the start
  7097. and conclusion and store them in the $\itm{info}$ field of the
  7098. function definition.)
  7099. \section{Uncover Live}
  7100. %% The rest of the passes need only minor modifications to handle the new
  7101. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7102. %% \code{leaq}.
  7103. The \code{IndirectCallq} instruction should be treated like
  7104. \code{Callq} regarding its written locations $W$, in that they should
  7105. include all the caller-saved registers. Recall that the reason for
  7106. that is to force call-live variables to be assigned to callee-saved
  7107. registers or to be spilled to the stack. Also, the arity field of
  7108. \code{IndirectCallq} determines how many of the argument-passing
  7109. registers should be considered in the set of read locations $R$.
  7110. \section{Build Interference Graph}
  7111. With the addition of function definitions, we compute an interference
  7112. graph for each function (not just one for the whole program).
  7113. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7114. spill vector-typed variables that are live during a call to the
  7115. \code{collect}. With the addition of functions to our language, we
  7116. need to revisit this issue. Many functions perform allocation and
  7117. therefore have calls to the collector inside of them. Thus, we should
  7118. not only spill a vector-typed variable when it is live during a call
  7119. to \code{collect}, but we should spill the variable if it is live
  7120. during any function call. Thus, in the \code{build-interference} pass,
  7121. we recommend adding interference edges between call-live vector-typed
  7122. variables and the callee-saved registers (in addition to the usual
  7123. addition of edges between call-live variables and the caller-saved
  7124. registers).
  7125. \section{Patch Instructions}
  7126. In \code{patch-instructions}, you should deal with the x86
  7127. idiosyncrasy that the destination argument of \code{leaq} must be a
  7128. register. Additionally, you should ensure that the argument of
  7129. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7130. code generation more convenient, because we trample many registers
  7131. before the tail call (as explained in the next section).
  7132. \section{Print x86}
  7133. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7134. \code{IndirectCallq} are straightforward: output their concrete
  7135. syntax.
  7136. \begin{lstlisting}
  7137. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7138. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7139. \end{lstlisting}
  7140. The \code{TailJmp} node requires a bit work. A straightforward
  7141. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7142. before the jump we need to pop the current frame. This sequence of
  7143. instructions is the same as the code for the conclusion of a function,
  7144. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7145. Note that your \code{print-x86} pass needs to add the code for saving
  7146. and restoring callee-saved registers, if you have not already
  7147. implemented that. This is necessary when generating code for function
  7148. definitions.
  7149. \begin{exercise}\normalfont
  7150. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7151. Create 5 new programs that use functions, including examples that pass
  7152. functions and return functions from other functions and including
  7153. recursive functions. Test your compiler on these new programs and all
  7154. of your previously created test programs.
  7155. \end{exercise}
  7156. \begin{figure}[tbp]
  7157. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7158. \node (R4) at (0,2) {\large $R_4$};
  7159. \node (R4-2) at (3,2) {\large $R_4$};
  7160. \node (R4-3) at (6,2) {\large $R_4$};
  7161. \node (F1-1) at (12,0) {\large $F_1$};
  7162. \node (F1-2) at (9,0) {\large $F_1$};
  7163. \node (F1-3) at (6,0) {\large $F_1$};
  7164. \node (F1-4) at (3,0) {\large $F_1$};
  7165. \node (C3-1) at (6,-2) {\large $C_3$};
  7166. \node (C3-2) at (3,-2) {\large $C_3$};
  7167. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7168. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7169. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7170. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7171. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7172. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7173. \path[->,bend left=15] (R4) edge [above] node
  7174. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7175. \path[->,bend left=15] (R4-2) edge [above] node
  7176. {\ttfamily\footnotesize uniquify} (R4-3);
  7177. \path[->,bend left=15] (R4-3) edge [right] node
  7178. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7179. \path[->,bend left=15] (F1-1) edge [below] node
  7180. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7181. \path[->,bend right=15] (F1-2) edge [above] node
  7182. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7183. \path[->,bend right=15] (F1-3) edge [above] node
  7184. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7185. \path[->,bend left=15] (F1-4) edge [right] node
  7186. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  7187. \path[->,bend left=15] (C3-1) edge [below] node
  7188. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  7189. \path[->,bend right=15] (C3-2) edge [left] node
  7190. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7191. \path[->,bend left=15] (x86-2) edge [left] node
  7192. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7193. \path[->,bend right=15] (x86-2-1) edge [below] node
  7194. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7195. \path[->,bend right=15] (x86-2-2) edge [left] node
  7196. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7197. \path[->,bend left=15] (x86-3) edge [above] node
  7198. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7199. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7200. \end{tikzpicture}
  7201. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7202. \label{fig:R4-passes}
  7203. \end{figure}
  7204. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7205. compiling $R_4$ to x86.
  7206. \section{An Example Translation}
  7207. \label{sec:functions-example}
  7208. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7209. function in $R_4$ to x86. The figure also includes the results of the
  7210. \code{explicate-control} and \code{select-instructions} passes.
  7211. \begin{figure}[htbp]
  7212. \begin{tabular}{ll}
  7213. \begin{minipage}{0.5\textwidth}
  7214. % s3_2.rkt
  7215. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7216. (define (add [x : Integer] [y : Integer])
  7217. : Integer
  7218. (+ x y))
  7219. (add 40 2)
  7220. \end{lstlisting}
  7221. $\Downarrow$
  7222. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7223. (define (add86 [x87 : Integer]
  7224. [y88 : Integer]) : Integer
  7225. add86start:
  7226. return (+ x87 y88);
  7227. )
  7228. (define (main) : Integer ()
  7229. mainstart:
  7230. tmp89 = (fun-ref add86);
  7231. (tail-call tmp89 40 2)
  7232. )
  7233. \end{lstlisting}
  7234. \end{minipage}
  7235. &
  7236. $\Rightarrow$
  7237. \begin{minipage}{0.5\textwidth}
  7238. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7239. (define (add86) : Integer
  7240. add86start:
  7241. movq %rdi, x87
  7242. movq %rsi, y88
  7243. movq x87, %rax
  7244. addq y88, %rax
  7245. jmp add11389conclusion
  7246. )
  7247. (define (main) : Integer
  7248. mainstart:
  7249. leaq (fun-ref add86), tmp89
  7250. movq $40, %rdi
  7251. movq $2, %rsi
  7252. tail-jmp tmp89
  7253. )
  7254. \end{lstlisting}
  7255. $\Downarrow$
  7256. \end{minipage}
  7257. \end{tabular}
  7258. \begin{tabular}{ll}
  7259. \begin{minipage}{0.3\textwidth}
  7260. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7261. .globl add86
  7262. .align 16
  7263. add86:
  7264. pushq %rbp
  7265. movq %rsp, %rbp
  7266. jmp add86start
  7267. add86start:
  7268. movq %rdi, %rax
  7269. addq %rsi, %rax
  7270. jmp add86conclusion
  7271. add86conclusion:
  7272. popq %rbp
  7273. retq
  7274. \end{lstlisting}
  7275. \end{minipage}
  7276. &
  7277. \begin{minipage}{0.5\textwidth}
  7278. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7279. .globl main
  7280. .align 16
  7281. main:
  7282. pushq %rbp
  7283. movq %rsp, %rbp
  7284. movq $16384, %rdi
  7285. movq $16384, %rsi
  7286. callq initialize
  7287. movq rootstack_begin(%rip), %r15
  7288. jmp mainstart
  7289. mainstart:
  7290. leaq add86(%rip), %rcx
  7291. movq $40, %rdi
  7292. movq $2, %rsi
  7293. movq %rcx, %rax
  7294. popq %rbp
  7295. jmp *%rax
  7296. mainconclusion:
  7297. popq %rbp
  7298. retq
  7299. \end{lstlisting}
  7300. \end{minipage}
  7301. \end{tabular}
  7302. \caption{Example compilation of a simple function to x86.}
  7303. \label{fig:add-fun}
  7304. \end{figure}
  7305. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7306. \chapter{Lexically Scoped Functions}
  7307. \label{ch:lambdas}
  7308. \index{lambda}
  7309. \index{lexical scoping}
  7310. This chapter studies lexically scoped functions as they appear in
  7311. functional languages such as Racket. By lexical scoping we mean that a
  7312. function's body may refer to variables whose binding site is outside
  7313. of the function, in an enclosing scope.
  7314. %
  7315. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7316. $R_5$, which extends $R_4$ with anonymous functions using the
  7317. \key{lambda} form. The body of the \key{lambda}, refers to three
  7318. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7319. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7320. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7321. parameter of function \code{f}. The \key{lambda} is returned from the
  7322. function \code{f}. The main expression of the program includes two
  7323. calls to \code{f} with different arguments for \code{x}, first
  7324. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7325. to variables \code{g} and \code{h}. Even though these two functions
  7326. were created by the same \code{lambda}, they are really different
  7327. functions because they use different values for \code{x}. Applying
  7328. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7329. \code{15} produces \code{22}. The result of this program is \code{42}.
  7330. \begin{figure}[btp]
  7331. % s4_6.rkt
  7332. \begin{lstlisting}
  7333. (define (f [x : Integer]) : (Integer -> Integer)
  7334. (let ([y 4])
  7335. (lambda: ([z : Integer]) : Integer
  7336. (+ x (+ y z)))))
  7337. (let ([g (f 5)])
  7338. (let ([h (f 3)])
  7339. (+ (g 11) (h 15))))
  7340. \end{lstlisting}
  7341. \caption{Example of a lexically scoped function.}
  7342. \label{fig:lexical-scoping}
  7343. \end{figure}
  7344. The approach that we take for implementing lexically scoped
  7345. functions is to compile them into top-level function definitions,
  7346. translating from $R_5$ into $R_4$. However, the compiler will need to
  7347. provide special treatment for variable occurrences such as \code{x}
  7348. and \code{y} in the body of the \code{lambda} of
  7349. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7350. refer to variables defined outside of it. To identify such variable
  7351. occurrences, we review the standard notion of free variable.
  7352. \begin{definition}
  7353. A variable is \emph{free in expression} $e$ if the variable occurs
  7354. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7355. variable}
  7356. \end{definition}
  7357. For example, in the expression \code{(+ x (+ y z))} the variables
  7358. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7359. only \code{x} and \code{y} are free in the following expression
  7360. because \code{z} is bound by the \code{lambda}.
  7361. \begin{lstlisting}
  7362. (lambda: ([z : Integer]) : Integer
  7363. (+ x (+ y z)))
  7364. \end{lstlisting}
  7365. So the free variables of a \code{lambda} are the ones that will need
  7366. special treatment. We need to arrange for some way to transport, at
  7367. runtime, the values of those variables from the point where the
  7368. \code{lambda} was created to the point where the \code{lambda} is
  7369. applied. An efficient solution to the problem, due to
  7370. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7371. free variables together with the function pointer for the lambda's
  7372. code, an arrangement called a \emph{flat closure} (which we shorten to
  7373. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7374. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7375. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7376. pointers. The function pointer resides at index $0$ and the
  7377. values for the free variables will fill in the rest of the vector.
  7378. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7379. how closures work. It's a three-step dance. The program first calls
  7380. function \code{f}, which creates a closure for the \code{lambda}. The
  7381. closure is a vector whose first element is a pointer to the top-level
  7382. function that we will generate for the \code{lambda}, the second
  7383. element is the value of \code{x}, which is \code{5}, and the third
  7384. element is \code{4}, the value of \code{y}. The closure does not
  7385. contain an element for \code{z} because \code{z} is not a free
  7386. variable of the \code{lambda}. Creating the closure is step 1 of the
  7387. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7388. shown in Figure~\ref{fig:closures}.
  7389. %
  7390. The second call to \code{f} creates another closure, this time with
  7391. \code{3} in the second slot (for \code{x}). This closure is also
  7392. returned from \code{f} but bound to \code{h}, which is also shown in
  7393. Figure~\ref{fig:closures}.
  7394. \begin{figure}[tbp]
  7395. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7396. \caption{Example closure representation for the \key{lambda}'s
  7397. in Figure~\ref{fig:lexical-scoping}.}
  7398. \label{fig:closures}
  7399. \end{figure}
  7400. Continuing with the example, consider the application of \code{g} to
  7401. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7402. obtain the function pointer in the first element of the closure and
  7403. call it, passing in the closure itself and then the regular arguments,
  7404. in this case \code{11}. This technique for applying a closure is step
  7405. 2 of the dance.
  7406. %
  7407. But doesn't this \code{lambda} only take 1 argument, for parameter
  7408. \code{z}? The third and final step of the dance is generating a
  7409. top-level function for a \code{lambda}. We add an additional
  7410. parameter for the closure and we insert a \code{let} at the beginning
  7411. of the function for each free variable, to bind those variables to the
  7412. appropriate elements from the closure parameter.
  7413. %
  7414. This three-step dance is known as \emph{closure conversion}. We
  7415. discuss the details of closure conversion in
  7416. Section~\ref{sec:closure-conversion} and the code generated from the
  7417. example in Section~\ref{sec:example-lambda}. But first we define the
  7418. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7419. \section{The $R_5$ Language}
  7420. \label{sec:r5}
  7421. The concrete and abstract syntax for $R_5$, a language with anonymous
  7422. functions and lexical scoping, is defined in
  7423. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7424. the \key{lambda} form to the grammar for $R_4$, which already has
  7425. syntax for function application.
  7426. \begin{figure}[tp]
  7427. \centering
  7428. \fbox{
  7429. \begin{minipage}{0.96\textwidth}
  7430. \small
  7431. \[
  7432. \begin{array}{lcl}
  7433. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7434. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7435. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7436. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7437. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7438. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7439. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7440. \mid (\key{and}\;\Exp\;\Exp)
  7441. \mid (\key{or}\;\Exp\;\Exp)
  7442. \mid (\key{not}\;\Exp) } \\
  7443. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7444. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7445. (\key{vector-ref}\;\Exp\;\Int)} \\
  7446. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7447. \mid (\Exp \; \Exp\ldots) } \\
  7448. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7449. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7450. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7451. R_5 &::=& \gray{\Def\ldots \; \Exp}
  7452. \end{array}
  7453. \]
  7454. \end{minipage}
  7455. }
  7456. \caption{Concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7457. with \key{lambda}.}
  7458. \label{fig:r5-concrete-syntax}
  7459. \end{figure}
  7460. \begin{figure}[tp]
  7461. \centering
  7462. \fbox{
  7463. \begin{minipage}{0.96\textwidth}
  7464. \small
  7465. \[
  7466. \begin{array}{lcl}
  7467. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7468. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7469. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7470. &\mid& \gray{ \BOOL{\itm{bool}}
  7471. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7472. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7473. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7474. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7475. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7476. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7477. \end{array}
  7478. \]
  7479. \end{minipage}
  7480. }
  7481. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7482. \label{fig:r5-syntax}
  7483. \end{figure}
  7484. \index{interpreter}
  7485. \label{sec:interp-R5}
  7486. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7487. $R_5$. The clause for \key{lambda} saves the current environment
  7488. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7489. the environment from the \key{lambda}, the \code{lam-env}, when
  7490. interpreting the body of the \key{lambda}. The \code{lam-env}
  7491. environment is extended with the mapping of parameters to argument
  7492. values.
  7493. \begin{figure}[tbp]
  7494. \begin{lstlisting}
  7495. UPDATE ME
  7496. \end{lstlisting}
  7497. \caption{Interpreter for $R_5$.}
  7498. \label{fig:interp-R5}
  7499. \end{figure}
  7500. \label{sec:type-check-r5}
  7501. \index{type checking}
  7502. Figure~\ref{fig:type-check-R5} shows how to type check the new
  7503. \key{lambda} form. The body of the \key{lambda} is checked in an
  7504. environment that includes the current environment (because it is
  7505. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7506. require the body's type to match the declared return type.
  7507. \begin{figure}[tbp]
  7508. \begin{lstlisting}
  7509. (define (type-check-R5 env)
  7510. (lambda (e)
  7511. (match e
  7512. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7513. (define-values (new-body bodyT)
  7514. ((type-check-exp (append (map cons xs Ts) env)) body))
  7515. (define ty `(,@Ts -> ,rT))
  7516. (cond
  7517. [(equal? rT bodyT)
  7518. (values (HasType (Lambda params rT new-body) ty) ty)]
  7519. [else
  7520. (error "mismatch in return type" bodyT rT)])]
  7521. ...
  7522. )))
  7523. \end{lstlisting}
  7524. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7525. \label{fig:type-check-R5}
  7526. \end{figure}
  7527. \section{Closure Conversion}
  7528. \label{sec:closure-conversion}
  7529. \index{closure conversion}
  7530. The compiling of lexically-scoped functions into top-level function
  7531. definitions is accomplished in the pass \code{convert-to-closures}
  7532. that comes after \code{reveal-functions} and before
  7533. \code{limit-functions}.
  7534. As usual, we implement the pass as a recursive function over the
  7535. AST. All of the action is in the clauses for \key{lambda} and
  7536. \key{Apply}. We transform a \key{lambda} expression into an expression
  7537. that creates a closure, that is, creates a vector whose first element
  7538. is a function pointer and the rest of the elements are the free
  7539. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7540. generated to identify the function.
  7541. \begin{tabular}{lll}
  7542. \begin{minipage}{0.4\textwidth}
  7543. \begin{lstlisting}
  7544. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7545. \end{lstlisting}
  7546. \end{minipage}
  7547. &
  7548. $\Rightarrow$
  7549. &
  7550. \begin{minipage}{0.4\textwidth}
  7551. \begin{lstlisting}
  7552. (vector |\itm{name}| |\itm{fvs}| ...)
  7553. \end{lstlisting}
  7554. \end{minipage}
  7555. \end{tabular} \\
  7556. %
  7557. In addition to transforming each \key{lambda} into a \key{vector}, we
  7558. must create a top-level function definition for each \key{lambda}, as
  7559. shown below.\\
  7560. \begin{minipage}{0.8\textwidth}
  7561. \begin{lstlisting}
  7562. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7563. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7564. ...
  7565. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7566. |\itm{body'}|)...))
  7567. \end{lstlisting}
  7568. \end{minipage}\\
  7569. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7570. parameters are the normal parameters of the \key{lambda}. The types
  7571. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7572. underscore is a dummy type because it is rather difficult to give a
  7573. type to the function in the closure's type, and it does not matter.
  7574. The sequence of \key{let} forms bind the free variables to their
  7575. values obtained from the closure.
  7576. We transform function application into code that retrieves the
  7577. function pointer from the closure and then calls the function, passing
  7578. in the closure as the first argument. We bind $e'$ to a temporary
  7579. variable to avoid code duplication.
  7580. \begin{tabular}{lll}
  7581. \begin{minipage}{0.3\textwidth}
  7582. \begin{lstlisting}
  7583. (app |$e$| |\itm{es}| ...)
  7584. \end{lstlisting}
  7585. \end{minipage}
  7586. &
  7587. $\Rightarrow$
  7588. &
  7589. \begin{minipage}{0.5\textwidth}
  7590. \begin{lstlisting}
  7591. (let ([|\itm{tmp}| |$e'$|])
  7592. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7593. \end{lstlisting}
  7594. \end{minipage}
  7595. \end{tabular} \\
  7596. There is also the question of what to do with top-level function
  7597. definitions. To maintain a uniform translation of function
  7598. application, we turn function references into closures.
  7599. \begin{tabular}{lll}
  7600. \begin{minipage}{0.3\textwidth}
  7601. \begin{lstlisting}
  7602. (fun-ref |$f$|)
  7603. \end{lstlisting}
  7604. \end{minipage}
  7605. &
  7606. $\Rightarrow$
  7607. &
  7608. \begin{minipage}{0.5\textwidth}
  7609. \begin{lstlisting}
  7610. (vector (fun-ref |$f$|))
  7611. \end{lstlisting}
  7612. \end{minipage}
  7613. \end{tabular} \\
  7614. %
  7615. The top-level function definitions need to be updated as well to take
  7616. an extra closure parameter.
  7617. \section{An Example Translation}
  7618. \label{sec:example-lambda}
  7619. Figure~\ref{fig:lexical-functions-example} shows the result of
  7620. \code{reveal-functions} and then \code{convert-to-closures} for the
  7621. example program demonstrating lexical scoping that we discussed at the
  7622. beginning of this chapter.
  7623. \begin{figure}[h]
  7624. \begin{minipage}{0.8\textwidth}
  7625. % tests/s4_6.rkt
  7626. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7627. (define (f74 [x75 : Integer]) : (Integer -> Integer)
  7628. (let ([y76 4])
  7629. (lambda: ( [z77 : Integer]) : Integer
  7630. (+ x75 (+ y76 z77)))))
  7631. (define (main) : Integer
  7632. (let ([g78 ((fun-ref f74) 5)])
  7633. (let ([h79 ((fun-ref f74) 3)])
  7634. (+ (g78 11) (h79 15)))))
  7635. \end{lstlisting}
  7636. $\Downarrow$
  7637. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7638. (define (f74 [fvs82 : _] [x75 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7639. (let ([y76 4])
  7640. (vector (fun-ref lambda80) x75 y76)))
  7641. (define (lambda80 [fvs81 : (Vector _ Integer Integer)] [z77 : Integer]) : Integer
  7642. (let ([x75 (vector-ref fvs81 1)])
  7643. (let ([y76 (vector-ref fvs81 2)])
  7644. (+ x75 (+ y76 z77)))))
  7645. (define (main) : Integer
  7646. (let ([g78 (let ([app83 (vector (fun-ref f74))])
  7647. ((vector-ref app83 0) app83 5))])
  7648. (let ([h79 (let ([app84 (vector (fun-ref f74))])
  7649. ((vector-ref app84 0) app84 3))])
  7650. (+ (let ([app85 g78])
  7651. ((vector-ref app85 0) app85 11))
  7652. (let ([app86 h79])
  7653. ((vector-ref app86 0) app86 15))))))
  7654. \end{lstlisting}
  7655. \end{minipage}
  7656. \caption{Example of closure conversion.}
  7657. \label{fig:lexical-functions-example}
  7658. \end{figure}
  7659. \begin{figure}[p]
  7660. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7661. \node (R4) at (0,2) {\large $R_4$};
  7662. \node (R4-2) at (3,2) {\large $R_4$};
  7663. \node (R4-3) at (6,2) {\large $R_4$};
  7664. \node (F1-1) at (12,0) {\large $F_1$};
  7665. \node (F1-2) at (9,0) {\large $F_1$};
  7666. \node (F1-3) at (6,0) {\large $F_1$};
  7667. \node (F1-4) at (3,0) {\large $F_1$};
  7668. \node (F1-5) at (0,0) {\large $F_1$};
  7669. \node (C3-1) at (6,-2) {\large $C_3$};
  7670. \node (C3-2) at (3,-2) {\large $C_3$};
  7671. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7672. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7673. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7674. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7675. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7676. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7677. \path[->,bend left=15] (R4) edge [above] node
  7678. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7679. \path[->,bend left=15] (R4-2) edge [above] node
  7680. {\ttfamily\footnotesize uniquify} (R4-3);
  7681. \path[->] (R4-3) edge [right] node
  7682. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7683. \path[->,bend left=15] (F1-1) edge [below] node
  7684. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7685. \path[->,bend right=15] (F1-2) edge [above] node
  7686. {\ttfamily\footnotesize limit-functions} (F1-3);
  7687. \path[->,bend right=15] (F1-3) edge [above] node
  7688. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7689. \path[->,bend right=15] (F1-4) edge [above] node
  7690. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7691. \path[->] (F1-5) edge [left] node
  7692. {\ttfamily\footnotesize explicate-control} (C3-1);
  7693. \path[->,bend left=15] (C3-1) edge [below] node
  7694. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7695. \path[->,bend right=15] (C3-2) edge [left] node
  7696. {\ttfamily\footnotesize select-instr.} (x86-2);
  7697. \path[->,bend left=15] (x86-2) edge [left] node
  7698. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7699. \path[->,bend right=15] (x86-2-1) edge [below] node
  7700. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7701. \path[->,bend right=15] (x86-2-2) edge [left] node
  7702. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7703. \path[->,bend left=15] (x86-3) edge [above] node
  7704. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7705. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7706. \end{tikzpicture}
  7707. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7708. functions.}
  7709. \label{fig:R5-passes}
  7710. \end{figure}
  7711. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7712. for the compilation of $R_5$.
  7713. \begin{exercise}\normalfont
  7714. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7715. Create 5 new programs that use \key{lambda} functions and make use of
  7716. lexical scoping. Test your compiler on these new programs and all of
  7717. your previously created test programs.
  7718. \end{exercise}
  7719. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7720. \chapter{Dynamic Typing}
  7721. \label{ch:type-dynamic}
  7722. \index{dynamic typing}
  7723. In this chapter we discuss the compilation $R_7$, a dynamically typed
  7724. language and a subset of the Racket language. Recall that in the
  7725. previous chapters we have compiled subsets of the \emph{Typed} Racket
  7726. language. In dynamically typed languages, each evaluation of an
  7727. expression may produce a value of a different type. Consider the
  7728. following example with a conditional expression that may return a
  7729. Boolean or an integer depending on the input to the program.
  7730. \begin{lstlisting}
  7731. (not (if (eq? (read) 1) #f 0))
  7732. \end{lstlisting}
  7733. Languages that allow expressions to produce different kinds of values
  7734. are called \emph{polymorphic}, a word composed of the Greek roots
  7735. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  7736. are several kinds of polymorphism in programming languages, such as
  7737. subtype polymorphism and parametric
  7738. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  7739. study in this chapter does not have a special name but it is the kind
  7740. that arises in dynamically typed languages.
  7741. Another characteristic of dynamically typed languages is that
  7742. primitive operations, such as \code{not}, are often defined to operate
  7743. on many different types of values. In fact, in Racket, the \code{not}
  7744. operator produces a result for any kind of value: given \code{\#f} it
  7745. returns \code{\#t} and given anything else it returns \code{\#f}.
  7746. Furthermore, even when primitive operations restrict their inputs to
  7747. values of a certain type, this restriction is enforced at runtime
  7748. instead of during compilation. For example, the following vector
  7749. reference results in a run-time contract violation because the index
  7750. must be in integer, not a Boolean such as \code{\#t}.
  7751. \begin{lstlisting}
  7752. (vector-ref (vector 42) #t)
  7753. \end{lstlisting}
  7754. \begin{figure}[tp]
  7755. \centering
  7756. \fbox{
  7757. \begin{minipage}{0.97\textwidth}
  7758. \[
  7759. \begin{array}{rcl}
  7760. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7761. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7762. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  7763. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  7764. &\mid& \key{\#t} \mid \key{\#f}
  7765. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  7766. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  7767. \mid \CUNIOP{\key{not}}{\Exp} \\
  7768. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  7769. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  7770. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  7771. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  7772. &\mid& \LP\Exp \; \Exp\ldots\RP
  7773. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  7774. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  7775. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  7776. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  7777. R_7 &::=& \Def\ldots\; \Exp
  7778. \end{array}
  7779. \]
  7780. \end{minipage}
  7781. }
  7782. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7783. \label{fig:r7-concrete-syntax}
  7784. \end{figure}
  7785. \begin{figure}[tp]
  7786. \centering
  7787. \fbox{
  7788. \begin{minipage}{0.96\textwidth}
  7789. \small
  7790. \[
  7791. \begin{array}{lcl}
  7792. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  7793. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  7794. &\mid& \BOOL{\itm{bool}}
  7795. \mid \IF{\Exp}{\Exp}{\Exp} \\
  7796. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  7797. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  7798. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  7799. R_7 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  7800. \end{array}
  7801. \]
  7802. \end{minipage}
  7803. }
  7804. \caption{The abstract syntax of $R_7$.}
  7805. \label{fig:r7-syntax}
  7806. \end{figure}
  7807. The concrete and abstract syntax of $R_7$, our subset of Racket, is
  7808. defined in Figures~\ref{fig:r7-concrete-syntax} and
  7809. \ref{fig:r7-syntax}.
  7810. %
  7811. There is no type checker for $R_7$ because it is not a statically
  7812. typed language (it's dynamically typed!).
  7813. %
  7814. The definitional interpreter for $R_7$ is presented in
  7815. Figure~\ref{fig:interp-R7}.
  7816. \begin{figure}[tbp]
  7817. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7818. (define (interp-R7-exp env)
  7819. (lambda (ast)
  7820. (define recur (interp-R7-exp env))
  7821. (match ast
  7822. [(Var x) (lookup x env)]
  7823. [(Int n) `(tagged ,n Integer)]
  7824. [(Bool b) `(tagged ,b Boolean)]
  7825. [(Prim 'read '()) `(tagged ,(read-fixnum) Integer)]
  7826. [(Lambda xs rt body)
  7827. `(tagged (lambda ,xs ,body ,env) (,@(for/list ([x xs]) 'Any) -> Any))]
  7828. [(Prim 'vector es)
  7829. `(tagged ,(apply vector (for/list ([e es]) (recur e)))
  7830. (Vector ,@(for/list ([e es]) 'Any)))]
  7831. [(Prim 'vector-set! (list e1 n e2))
  7832. (define vec (value-of-any (recur e1)))
  7833. (define i (value-of-any (recur n)))
  7834. (vector-set! vec i (recur e2))
  7835. `(tagged ,(void) Void)]
  7836. [(Prim 'vector-ref (list e1 n))
  7837. (define vec (value-of-any (recur e1)))
  7838. (define i (value-of-any (recur n)))
  7839. (vector-ref vec i)]
  7840. [(Let x e body)
  7841. (define v (recur e))
  7842. ((interp-R7-exp (cons (cons x v) env)) body)]
  7843. [(Prim 'and (list e1 e2))
  7844. (recur (If e1 e2 (Bool #f)))]
  7845. [(Prim 'or (list e1 e2))
  7846. (define v1 (recur e1))
  7847. (match (value-of-any v1) [#f (recur e2)] [else v1])]
  7848. [(Prim 'eq? (list l r))
  7849. `(tagged ,(equal? (recur l) (recur r)) Boolean)]
  7850. [(If q t f)
  7851. (match (value-of-any (recur q)) [#f (recur f)] [else (recur t)])]
  7852. [(Prim op es)
  7853. (tag-value
  7854. (apply (interp-op op) (for/list ([e es]) (value-of-any (recur e)))))]
  7855. [(Apply f es)
  7856. (define new-args (map recur es))
  7857. (let ([f-val (value-of-any (recur f))])
  7858. (match f-val
  7859. [`(lambda (,xs ...) ,body ,lam-env)
  7860. (define new-env (append (map cons xs new-args) lam-env))
  7861. ((interp-R7-exp new-env) body)]
  7862. [else (error "interp-R7-exp, expected function, not" f-val)]))]
  7863. )))
  7864. \end{lstlisting}
  7865. \caption{Interpreter for the $R_7$ language.}
  7866. \label{fig:interp-R7}
  7867. \end{figure}
  7868. Let us consider how we might compile $R_7$ to x86, thinking about the
  7869. first example above. Our bit-level representation of the Boolean
  7870. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7871. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7872. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7873. general, cannot be determined at compile time, but depends on the
  7874. runtime type of its input, as in the example above that depends on the
  7875. result of \code{(read)}.
  7876. The way around this problem is to include information about a value's
  7877. runtime type in the value itself, so that this information can be
  7878. inspected by operators such as \code{not}. In particular, we
  7879. steal the 3 right-most bits from our 64-bit values to encode the
  7880. runtime type. We use $001$ to identify integers, $100$ for
  7881. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7882. void value. We refer to these 3 bits as the \emph{tag} and we
  7883. define the following auxiliary function.
  7884. \begin{align*}
  7885. \itm{tagof}(\key{Integer}) &= 001 \\
  7886. \itm{tagof}(\key{Boolean}) &= 100 \\
  7887. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7888. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7889. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7890. \itm{tagof}(\key{Void}) &= 101
  7891. \end{align*}
  7892. (We say more about the new \key{Vectorof} type shortly.)
  7893. This stealing of 3 bits comes at some
  7894. price: our integers are reduced to ranging from $-2^{60}$ to
  7895. $2^{60}$. The stealing does not adversely affect vectors and
  7896. procedures because those values are addresses, and our addresses are
  7897. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7898. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7899. bits with the tag and we can simply zero-out the tag to recover the
  7900. original address.
  7901. In some sense, these tagged values are a new kind of value. Indeed,
  7902. we can extend our \emph{typed} language with tagged values by adding a
  7903. new type to classify them, called \key{Any}, and with operations for
  7904. creating and using tagged values, yielding the $R_6$ language that we
  7905. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7906. fundamental support for polymorphism and runtime types that we need to
  7907. support dynamic typing.
  7908. There is an interesting interaction between tagged values and garbage
  7909. collection. A variable of type \code{Any} might refer to a vector and
  7910. therefore it might be a root that needs to be inspected and copied
  7911. during garbage collection. Thus, we need to treat variables of type
  7912. \code{Any} in a similar way to variables of type \code{Vector} for
  7913. purposes of register allocation, which we discuss in
  7914. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7915. variable of type \code{Any} is spilled, it must be spilled to the root
  7916. stack. But this means that the garbage collector needs to be able to
  7917. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7918. value that points to a tuple, and (3) a tagged value that is not a
  7919. tuple. We enable this differentiation by choosing not to use the tag
  7920. $000$ in $\itm{tagof}$. Instead, that bit pattern is reserved for
  7921. identifying plain old pointers to tuples. That way, if one of the
  7922. first three bits is set, then we have a tagged value and inspecting
  7923. the tag can differentiation between vectors ($010$) and the other
  7924. kinds of values.
  7925. We implement our untyped language $R_7$ by compiling it to $R_6$
  7926. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7927. extend our compiler to handle the new features of $R_6$
  7928. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7929. \ref{sec:register-allocation-r6}).
  7930. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7931. \label{sec:r6-lang}
  7932. \begin{figure}[tp]
  7933. \centering
  7934. \fbox{
  7935. \begin{minipage}{0.97\textwidth}\small
  7936. \[
  7937. \begin{array}{lcl}
  7938. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7939. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \LP\key{Vectorof}\;\Type\RP \mid \key{Void}} \\
  7940. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  7941. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid \LP\key{Vectorof}\;\key{Any}\RP \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  7942. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  7943. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7944. \Exp &::=& \ldots
  7945. \mid \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType} \\
  7946. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  7947. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  7948. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7949. R_6 &::=& \gray{\Def\ldots \; \Exp}
  7950. \end{array}
  7951. \]
  7952. \end{minipage}
  7953. }
  7954. \caption{Concrete syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7955. with \key{Any}.}
  7956. \label{fig:r6-concrete-syntax}
  7957. \end{figure}
  7958. \begin{figure}[tp]
  7959. \centering
  7960. \fbox{
  7961. \begin{minipage}{0.96\textwidth}
  7962. \small
  7963. \[
  7964. \begin{array}{lcl}
  7965. \itm{op} &::= & \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  7966. \mid \code{procedure?} \mid \code{void?} \\
  7967. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7968. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7969. &\mid& \gray{ \BOOL{\itm{bool}}
  7970. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7971. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7972. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7973. &\mid& \gray{ \LAMBDA{\LP[\Var\code{:}\Type]\ldots\RP}{\Type}{\Exp} }\\
  7974. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  7975. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7976. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7977. \end{array}
  7978. \]
  7979. \end{minipage}
  7980. }
  7981. \caption{The abstract syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  7982. \label{fig:r6-syntax}
  7983. \end{figure}
  7984. The concrete and abstract syntax of $R_6$ is defined in
  7985. Figures~\ref{fig:r6-concrete-syntax} and \ref{fig:r6-syntax}. The
  7986. $\LP\key{inject}\; e\; T\RP$ form converts the value produced by
  7987. expression $e$ of type $T$ into a tagged value. The
  7988. $\LP\key{project}\;e\;T\RP$ form converts the tagged value produced by
  7989. expression $e$ into a value of type $T$ or else halts the program if
  7990. the type tag is not equivalent to $T$. We treat
  7991. $\LP\key{Vectorof}\;\key{Any}\RP$ as equivalent to
  7992. $\LP\key{Vector}\;\key{Any}\;\ldots\RP$.
  7993. %
  7994. Note that in both \key{inject} and \key{project}, the type $T$ is
  7995. restricted to the flat types $\FType$, which simplifies the
  7996. implementation and corresponds with what is needed for compiling
  7997. untyped Racket.
  7998. The type predicates such as $\LP\key{boolean?}\,e\RP$ expect the
  7999. expression $e$ to produce a tagged value; they return \key{\#t} if the
  8000. tag corresponds to the predicate and they return \key{\#f} otherwise.
  8001. The type checker for $R_6$ is shown in Figures~\ref{fig:type-check-R6-part-1}
  8002. and \ref{fig:type-check-R6-part-2}.
  8003. The interpreter for $R_6$ is in Figure~\ref{fig:interp-R6}.
  8004. \begin{figure}[btp]
  8005. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8006. (define (operator-types)
  8007. '(...
  8008. (integer? . ((Any) . Boolean))
  8009. (vector? . ((Any) . Boolean))
  8010. (procedure? . ((Any) . Boolean))
  8011. (void? . ((Any) . Boolean))
  8012. ))
  8013. (define (type-check-exp env)
  8014. (lambda (e)
  8015. (define recur (type-check-exp env))
  8016. (match e
  8017. ...
  8018. [(Inject e ty)
  8019. (unless (flat-ty? ty)
  8020. (error 'type-check-exp
  8021. "may only inject a value of flat type, not ~a" ty))
  8022. (define-values (new-e e-ty) (recur e))
  8023. (cond
  8024. [(type-equal? e-ty ty)
  8025. (values (Inject new-e ty) 'Any)]
  8026. [else
  8027. (error 'type-check-exp
  8028. "injected expression does not have expected type"
  8029. e e-ty ty)])]
  8030. [(Project e ty)
  8031. (unless (flat-ty? ty)
  8032. (error 'type-check-exp
  8033. "may only project to a flat type, not ~a" ty))
  8034. (define-values (new-e e-ty) (recur e))
  8035. (cond
  8036. [(type-equal? e-ty 'Any)
  8037. (values (Project new-e ty) ty)]
  8038. [else
  8039. (error 'type-check-exp
  8040. "project expression does not have type Any" e)])]
  8041. [(Prim pred (list e))
  8042. #:when (set-member? type-predicates pred)
  8043. (define-values (new-e e-ty) (recur e))
  8044. (cond
  8045. [(type-equal? e-ty 'Any)
  8046. (values (Prim pred (list new-e)) 'Boolean)]
  8047. [else
  8048. (error 'type-check-exp
  8049. "type predicate expected argument of type Any, not ~a" e-ty)])]
  8050. ...
  8051. \end{lstlisting}
  8052. \caption{Type checker for the $R_6$ language, part 1.}
  8053. \label{fig:type-check-R6-part-1}
  8054. \end{figure}
  8055. \begin{figure}[btp]
  8056. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]U
  8057. UNDER CONSTRUCTION (vectors)
  8058. [else
  8059. (error 'type-check-exp "R6/unmatched ~a" e)]
  8060. )))
  8061. \end{lstlisting}
  8062. \caption{Type checker for the $R_6$ language, part 2.}
  8063. \label{fig:type-check-R6-part-2}
  8064. \end{figure}
  8065. % to do: add rules for vector-ref, etc. for Vectorof
  8066. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  8067. \begin{figure}[btp]
  8068. \begin{lstlisting}
  8069. (define (interp-op op)
  8070. (match op
  8071. ...
  8072. ['boolean? (lambda (v)
  8073. (match v
  8074. [`(tagged ,v1 ,tg)
  8075. (equal? tg (any-tag 'Boolean))]
  8076. [else #f]))]
  8077. ['integer? (lambda (v)
  8078. (match v
  8079. [`(tagged ,v1 ,tg)
  8080. (equal? tg (any-tag 'Integer))]
  8081. [else #f]))]
  8082. ['vector? (lambda (v)
  8083. (match v
  8084. [`(tagged ,v1 ,tg)
  8085. (equal? tg (any-tag `(Vector Any)))]
  8086. [else #f]))]
  8087. ['procedure? (lambda (v)
  8088. (match v
  8089. [`(tagged ,v1 ,tg)
  8090. (equal? tg (any-tag `(Any -> Any)))]
  8091. [else #f]))]
  8092. ...
  8093. ))
  8094. (define (interp-exp env)
  8095. (lambda (e)
  8096. (define recur (interp-exp env))
  8097. (let ([ret
  8098. (match e
  8099. ...
  8100. [(Inject e ty)
  8101. (apply-inject ((interp-exp env) e) (any-tag ty))]
  8102. [(Project e ty2)
  8103. (define v (recur e))
  8104. (apply-project v ty2)]
  8105. [(Exit)
  8106. (error 'interp-exp "exiting")]
  8107. [else (error 'interp-exp "unrecognized expression ~a" e)]
  8108. )])
  8109. (verbose "R6/interp-exp ==>" ret)
  8110. ret)))
  8111. \end{lstlisting}
  8112. \caption{Interpreter for $R_6$.}
  8113. \label{fig:interp-R6}
  8114. \end{figure}
  8115. %\clearpage
  8116. \section{Shrinking $R_6$}
  8117. \label{sec:shrink-r6}
  8118. In the \code{shrink} pass we recommend compiling \code{Project} into
  8119. an explicit \code{If} expression that uses two new forms,
  8120. \code{ValueOf} and \code{Exit}, and a new primitive operation,
  8121. \code{tag-of-any}. The \code{tag-of-any} operation retrieves the type
  8122. tag from a tagged value of type \code{Any}. The \code{ValueOf} form
  8123. retrieves the underlying value from a tagged value. The
  8124. \code{ValueOf} form includes the type for the underlying value which
  8125. is used by the type checker. Finally, the \code{Exit} form ends the
  8126. execution of the program.
  8127. %
  8128. If the target type of the projection is \code{Boolean} or
  8129. \code{Integer}, then \code{Project} can be translated as follows.
  8130. %(We have omitted the \code{has-type} AST nodes to make this
  8131. %output more readable.)
  8132. \begin{center}
  8133. \begin{minipage}{1.0\textwidth}
  8134. \begin{lstlisting}
  8135. (Project |$e$| |$\FType$|)
  8136. |$\Rightarrow$|
  8137. (Let |$\itm{tmp}$| |$e'$|
  8138. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  8139. (Int |$\itm{tagof}(\FType)$|)))
  8140. (ValueOf |$\itm{tmp}$| |$\FType$|)
  8141. (Exit)))
  8142. \end{lstlisting}
  8143. \end{minipage}
  8144. \end{center}
  8145. If the target type of the projection is a vector or function type,
  8146. then there is a bit more work to do. For vectors, check that the
  8147. length of the vector (use the \code{vector-length} primitive) matches
  8148. the length of the vector type. For functions, check that its arity
  8149. (\code{procedure-arity}) matches the number of parameters in the
  8150. function type.
  8151. Regarding \code{Inject}, we recommend compiling it to a slightly
  8152. lower-level primitive operation named \code{make-any}. This operation
  8153. takes a tag instead of a type. \\
  8154. \begin{center}
  8155. \begin{minipage}{1.0\textwidth}
  8156. \begin{lstlisting}
  8157. (Inject |$e$| |$\FType$|)
  8158. |$\Rightarrow$|
  8159. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  8160. \end{lstlisting}
  8161. \end{minipage}
  8162. \end{center}
  8163. We recommend translating the type predicates (\code{boolean?}, etc.)
  8164. into uses of \code{tag-of-any} and \code{eq?}.
  8165. \section{Closure Conversion for $R_6$}
  8166. \label{sec:closure-conversion-R6}
  8167. \section{Instruction Selection for $R_6$}
  8168. \label{sec:select-r6}
  8169. \paragraph{Inject}
  8170. We recommend compiling an \key{inject} as follows if the type is
  8171. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  8172. destination to the left by the number of bits specified its source
  8173. argument (in this case $3$, the length of the tag) and it preserves
  8174. the sign of the integer. We use the \key{orq} instruction to combine
  8175. the tag and the value to form the tagged value. \\
  8176. \begin{tabular}{lll}
  8177. \begin{minipage}{0.4\textwidth}
  8178. \begin{lstlisting}
  8179. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8180. \end{lstlisting}
  8181. \end{minipage}
  8182. &
  8183. $\Rightarrow$
  8184. &
  8185. \begin{minipage}{0.5\textwidth}
  8186. \begin{lstlisting}
  8187. (movq |$e'$| |\itm{lhs}'|)
  8188. (salq (int 3) |\itm{lhs}'|)
  8189. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8190. \end{lstlisting}
  8191. \end{minipage}
  8192. \end{tabular} \\
  8193. The instruction selection for vectors and procedures is different
  8194. because their is no need to shift them to the left. The rightmost 3
  8195. bits are already zeros as described above. So we just combine the
  8196. value and the tag using \key{orq}. \\
  8197. \begin{tabular}{lll}
  8198. \begin{minipage}{0.4\textwidth}
  8199. \begin{lstlisting}
  8200. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8201. \end{lstlisting}
  8202. \end{minipage}
  8203. &
  8204. $\Rightarrow$
  8205. &
  8206. \begin{minipage}{0.5\textwidth}
  8207. \begin{lstlisting}
  8208. (movq |$e'$| |\itm{lhs}'|)
  8209. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8210. \end{lstlisting}
  8211. \end{minipage}
  8212. \end{tabular}
  8213. \paragraph{Tag of Any}
  8214. Recall that the \code{tag-of-any} operation extracts the type tag from
  8215. a value of type \code{Any}. The type tag is the bottom three bits, so
  8216. we obtain the tag by taking the bitwise-and of the value with $111$
  8217. ($7$ in decimal).
  8218. \begin{tabular}{lll}
  8219. \begin{minipage}{0.4\textwidth}
  8220. \begin{lstlisting}
  8221. (assign |\itm{lhs}| (tag-of-any |$e$|))
  8222. \end{lstlisting}
  8223. \end{minipage}
  8224. &
  8225. $\Rightarrow$
  8226. &
  8227. \begin{minipage}{0.5\textwidth}
  8228. \begin{lstlisting}
  8229. (movq |$e'$| |\itm{lhs}'|)
  8230. (andq (int 7) |\itm{lhs}'|)
  8231. \end{lstlisting}
  8232. \end{minipage}
  8233. \end{tabular}
  8234. \paragraph{Value of Any}
  8235. Like \key{inject}, the instructions for \key{value-of-any} are
  8236. different depending on whether the type $T$ is a pointer (vector or
  8237. procedure) or not (Integer or Boolean). The following shows the
  8238. instruction selection for Integer and Boolean. We produce an untagged
  8239. value by shifting it to the right by 3 bits.
  8240. %
  8241. \\
  8242. \begin{tabular}{lll}
  8243. \begin{minipage}{0.4\textwidth}
  8244. \begin{lstlisting}
  8245. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8246. \end{lstlisting}
  8247. \end{minipage}
  8248. &
  8249. $\Rightarrow$
  8250. &
  8251. \begin{minipage}{0.5\textwidth}
  8252. \begin{lstlisting}
  8253. (movq |$e'$| |\itm{lhs}'|)
  8254. (sarq (int 3) |\itm{lhs}'|)
  8255. \end{lstlisting}
  8256. \end{minipage}
  8257. \end{tabular} \\
  8258. %
  8259. In the case for vectors and procedures, there is no need to
  8260. shift. Instead we just need to zero-out the rightmost 3 bits. We
  8261. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  8262. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  8263. \code{movq} into the destination $\itm{lhs}$. We then generate
  8264. \code{andq} with the tagged value to get the desired result. \\
  8265. %
  8266. \begin{tabular}{lll}
  8267. \begin{minipage}{0.4\textwidth}
  8268. \begin{lstlisting}
  8269. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8270. \end{lstlisting}
  8271. \end{minipage}
  8272. &
  8273. $\Rightarrow$
  8274. &
  8275. \begin{minipage}{0.5\textwidth}
  8276. \begin{lstlisting}
  8277. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  8278. (andq |$e'$| |\itm{lhs}'|)
  8279. \end{lstlisting}
  8280. \end{minipage}
  8281. \end{tabular}
  8282. %% \paragraph{Type Predicates} We leave it to the reader to
  8283. %% devise a sequence of instructions to implement the type predicates
  8284. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  8285. \section{Register Allocation for $R_6$}
  8286. \label{sec:register-allocation-r6}
  8287. \index{register allocation}
  8288. As mentioned above, a variable of type \code{Any} might refer to a
  8289. vector. Thus, the register allocator for $R_6$ needs to treat variable
  8290. of type \code{Any} in the same way that it treats variables of type
  8291. \code{Vector} for purposes of garbage collection. In particular,
  8292. \begin{itemize}
  8293. \item If a variable of type \code{Any} is live during a function call,
  8294. then it must be spilled. One way to accomplish this is to augment
  8295. the pass \code{build-interference} to mark all variables that are
  8296. live after a \code{callq} as interfering with all the registers.
  8297. \item If a variable of type \code{Any} is spilled, it must be spilled
  8298. to the root stack instead of the normal procedure call stack.
  8299. \end{itemize}
  8300. \begin{exercise}\normalfont
  8301. Expand your compiler to handle $R_6$ as discussed in the last few
  8302. sections. Create 5 new programs that use the \code{Any} type and the
  8303. new operations (\code{inject}, \code{project}, \code{boolean?},
  8304. etc.). Test your compiler on these new programs and all of your
  8305. previously created test programs.
  8306. \end{exercise}
  8307. \section{Compiling $R_7$ to $R_6$}
  8308. \label{sec:compile-r7}
  8309. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8310. $R_7$ forms into $R_6$. An important invariant of this pass is that
  8311. given a subexpression $e$ of $R_7$, the pass will produce an
  8312. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  8313. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8314. the Boolean \code{\#t}, which must be injected to produce an
  8315. expression of type \key{Any}.
  8316. %
  8317. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8318. addition, is representative of compilation for many operations: the
  8319. arguments have type \key{Any} and must be projected to \key{Integer}
  8320. before the addition can be performed.
  8321. The compilation of \key{lambda} (third row of
  8322. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8323. produce type annotations: we simply use \key{Any}.
  8324. %
  8325. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8326. has to account for some differences in behavior between $R_7$ and
  8327. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  8328. kind of values can be used in various places. For example, the
  8329. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8330. the arguments need not be of the same type (but in that case, the
  8331. result will be \code{\#f}).
  8332. \begin{figure}[btp]
  8333. \centering
  8334. \begin{tabular}{|lll|} \hline
  8335. \begin{minipage}{0.25\textwidth}
  8336. \begin{lstlisting}
  8337. #t
  8338. \end{lstlisting}
  8339. \end{minipage}
  8340. &
  8341. $\Rightarrow$
  8342. &
  8343. \begin{minipage}{0.6\textwidth}
  8344. \begin{lstlisting}
  8345. (inject #t Boolean)
  8346. \end{lstlisting}
  8347. \end{minipage}
  8348. \\[2ex]\hline
  8349. \begin{minipage}{0.25\textwidth}
  8350. \begin{lstlisting}
  8351. (+ |$e_1$| |$e_2$|)
  8352. \end{lstlisting}
  8353. \end{minipage}
  8354. &
  8355. $\Rightarrow$
  8356. &
  8357. \begin{minipage}{0.6\textwidth}
  8358. \begin{lstlisting}
  8359. (inject
  8360. (+ (project |$e'_1$| Integer)
  8361. (project |$e'_2$| Integer))
  8362. Integer)
  8363. \end{lstlisting}
  8364. \end{minipage}
  8365. \\[2ex]\hline
  8366. \begin{minipage}{0.25\textwidth}
  8367. \begin{lstlisting}
  8368. (lambda (|$x_1 \ldots$|) |$e$|)
  8369. \end{lstlisting}
  8370. \end{minipage}
  8371. &
  8372. $\Rightarrow$
  8373. &
  8374. \begin{minipage}{0.6\textwidth}
  8375. \begin{lstlisting}
  8376. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  8377. (Any|$\ldots$|Any -> Any))
  8378. \end{lstlisting}
  8379. \end{minipage}
  8380. \\[2ex]\hline
  8381. \begin{minipage}{0.25\textwidth}
  8382. \begin{lstlisting}
  8383. (app |$e_0$| |$e_1 \ldots e_n$|)
  8384. \end{lstlisting}
  8385. \end{minipage}
  8386. &
  8387. $\Rightarrow$
  8388. &
  8389. \begin{minipage}{0.6\textwidth}
  8390. \begin{lstlisting}
  8391. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  8392. |$e'_1 \ldots e'_n$|)
  8393. \end{lstlisting}
  8394. \end{minipage}
  8395. \\[2ex]\hline
  8396. \begin{minipage}{0.25\textwidth}
  8397. \begin{lstlisting}
  8398. (vector-ref |$e_1$| |$e_2$|)
  8399. \end{lstlisting}
  8400. \end{minipage}
  8401. &
  8402. $\Rightarrow$
  8403. &
  8404. \begin{minipage}{0.6\textwidth}
  8405. \begin{lstlisting}
  8406. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  8407. (let ([tmp2 (project |$e'_2$| Integer)])
  8408. (vector-ref tmp1 tmp2)))
  8409. \end{lstlisting}
  8410. \end{minipage}
  8411. \\[2ex]\hline
  8412. \begin{minipage}{0.25\textwidth}
  8413. \begin{lstlisting}
  8414. (if |$e_1$| |$e_2$| |$e_3$|)
  8415. \end{lstlisting}
  8416. \end{minipage}
  8417. &
  8418. $\Rightarrow$
  8419. &
  8420. \begin{minipage}{0.6\textwidth}
  8421. \begin{lstlisting}
  8422. (if (eq? |$e'_1$| (inject #f Boolean))
  8423. |$e'_3$|
  8424. |$e'_2$|)
  8425. \end{lstlisting}
  8426. \end{minipage}
  8427. \\[2ex]\hline
  8428. \begin{minipage}{0.25\textwidth}
  8429. \begin{lstlisting}
  8430. (eq? |$e_1$| |$e_2$|)
  8431. \end{lstlisting}
  8432. \end{minipage}
  8433. &
  8434. $\Rightarrow$
  8435. &
  8436. \begin{minipage}{0.6\textwidth}
  8437. \begin{lstlisting}
  8438. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8439. \end{lstlisting}
  8440. \end{minipage}
  8441. \\[2ex]\hline
  8442. \end{tabular}
  8443. \caption{Compiling $R_7$ to $R_6$.}
  8444. \label{fig:compile-r7-r6}
  8445. \end{figure}
  8446. \begin{exercise}\normalfont
  8447. Expand your compiler to handle $R_7$ as outlined in this chapter.
  8448. Create tests for $R_7$ by adapting all of your previous test programs
  8449. by removing type annotations. Add 5 more tests programs that
  8450. specifically rely on the language being dynamically typed. That is,
  8451. they should not be legal programs in a statically typed language, but
  8452. nevertheless, they should be valid $R_7$ programs that run to
  8453. completion without error.
  8454. \end{exercise}
  8455. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8456. \chapter{Gradual Typing}
  8457. \label{ch:gradual-typing}
  8458. \index{gradual typing}
  8459. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  8460. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8461. \chapter{Parametric Polymorphism}
  8462. \label{ch:parametric-polymorphism}
  8463. \index{parametric polymorphism}
  8464. \index{generics}
  8465. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  8466. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  8467. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8468. \chapter{High-level Optimization}
  8469. \label{ch:high-level-optimization}
  8470. This chapter will present a procedure inlining pass based on the
  8471. algorithm of \citet{Waddell:1997fk}.
  8472. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8473. \chapter{Appendix}
  8474. \section{Interpreters}
  8475. \label{appendix:interp}
  8476. \index{interpreter}
  8477. We provide interpreters for each of the source languages $R_0$, $R_1$,
  8478. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  8479. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  8480. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  8481. the rest of the intermediate languages, including pseudo-x86 and x86
  8482. are in the \key{interp.rkt} file.
  8483. \section{Utility Functions}
  8484. \label{appendix:utilities}
  8485. The utility functions described here are in the \key{utilities.rkt}
  8486. file.
  8487. \paragraph{\code{interp-tests}}
  8488. The \key{interp-tests} function runs the compiler passes and the
  8489. interpreters on each of the specified tests to check whether each pass
  8490. is correct. The \key{interp-tests} function has the following
  8491. parameters:
  8492. \begin{description}
  8493. \item[name (a string)] a name to identify the compiler,
  8494. \item[typechecker] a function of exactly one argument that either
  8495. raises an error using the \code{error} function when it encounters a
  8496. type error, or returns \code{\#f} when it encounters a type
  8497. error. If there is no type error, the type checker returns the
  8498. program.
  8499. \item[passes] a list with one entry per pass. An entry is a list with
  8500. four things:
  8501. \begin{enumerate}
  8502. \item a string giving the name of the pass,
  8503. \item the function that implements the pass (a translator from AST
  8504. to AST),
  8505. \item a function that implements the interpreter (a function from
  8506. AST to result value) for the output language,
  8507. \item and a type checker for the output language. Type checkers for
  8508. the $R$ and $C$ languages are provided in the support code. For
  8509. example, the type checkers for $R_1$ and $C_0$ are in
  8510. \code{type-check-R1.rkt}. The type checker entry is optional. The
  8511. support code does not provide type checkers for the x86 languages.
  8512. \end{enumerate}
  8513. \item[source-interp] an interpreter for the source language. The
  8514. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8515. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8516. \item[tests] a list of test numbers that specifies which tests to
  8517. run. (see below)
  8518. \end{description}
  8519. %
  8520. The \key{interp-tests} function assumes that the subdirectory
  8521. \key{tests} has a collection of Racket programs whose names all start
  8522. with the family name, followed by an underscore and then the test
  8523. number, ending with the file extension \key{.rkt}. Also, for each test
  8524. program that calls \code{read} one or more times, there is a file with
  8525. the same name except that the file extension is \key{.in} that
  8526. provides the input for the Racket program. If the test program is
  8527. expected to fail type checking, then there should be an empty file of
  8528. the same name but with extension \key{.tyerr}.
  8529. \paragraph{\code{compiler-tests}}
  8530. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8531. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8532. machine code and checks that the output is $42$. The parameters to the
  8533. \code{compiler-tests} function are similar to those of the
  8534. \code{interp-tests} function, and consist of
  8535. \begin{itemize}
  8536. \item a compiler name (a string),
  8537. \item a type checker,
  8538. \item description of the passes,
  8539. \item name of a test-family, and
  8540. \item a list of test numbers.
  8541. \end{itemize}
  8542. \paragraph{\code{compile-file}}
  8543. takes a description of the compiler passes (see the comment for
  8544. \key{interp-tests}) and returns a function that, given a program file
  8545. name (a string ending in \key{.rkt}), applies all of the passes and
  8546. writes the output to a file whose name is the same as the program file
  8547. name but with \key{.rkt} replaced with \key{.s}.
  8548. \paragraph{\code{read-program}}
  8549. takes a file path and parses that file (it must be a Racket program)
  8550. into an abstract syntax tree.
  8551. \paragraph{\code{parse-program}}
  8552. takes an S-expression representation of an abstract syntax tree and converts it into
  8553. the struct-based representation.
  8554. \paragraph{\code{assert}}
  8555. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8556. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8557. \paragraph{\code{lookup}}
  8558. % remove discussion of lookup? -Jeremy
  8559. takes a key and an alist, and returns the first value that is
  8560. associated with the given key, if there is one. If not, an error is
  8561. triggered. The alist may contain both immutable pairs (built with
  8562. \key{cons}) and mutable pairs (built with \key{mcons}).
  8563. %The \key{map2} function ...
  8564. \section{x86 Instruction Set Quick-Reference}
  8565. \label{sec:x86-quick-reference}
  8566. \index{x86}
  8567. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8568. do. We write $A \to B$ to mean that the value of $A$ is written into
  8569. location $B$. Address offsets are given in bytes. The instruction
  8570. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8571. registers (such as \code{\%rax}), or memory references (such as
  8572. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8573. reference per instruction. Other operands must be immediates or
  8574. registers.
  8575. \begin{table}[tbp]
  8576. \centering
  8577. \begin{tabular}{l|l}
  8578. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8579. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8580. \texttt{negq} $A$ & $- A \to A$ \\
  8581. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8582. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8583. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8584. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8585. \texttt{retq} & Pops the return address and jumps to it \\
  8586. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8587. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8588. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8589. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8590. be an immediate) \\
  8591. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8592. matches the condition code of the instruction, otherwise go to the
  8593. next instructions. The condition codes are \key{e} for ``equal'',
  8594. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8595. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8596. \texttt{jl} $L$ & \\
  8597. \texttt{jle} $L$ & \\
  8598. \texttt{jg} $L$ & \\
  8599. \texttt{jge} $L$ & \\
  8600. \texttt{jmp} $L$ & Jump to label $L$ \\
  8601. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8602. \texttt{movzbq} $A$, $B$ &
  8603. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8604. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8605. and the extra bytes of $B$ are set to zero.} \\
  8606. & \\
  8607. & \\
  8608. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8609. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8610. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8611. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8612. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8613. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8614. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8615. description of the condition codes. $A$ must be a single byte register
  8616. (e.g., \texttt{al} or \texttt{cl}).} \\
  8617. \texttt{setl} $A$ & \\
  8618. \texttt{setle} $A$ & \\
  8619. \texttt{setg} $A$ & \\
  8620. \texttt{setge} $A$ &
  8621. \end{tabular}
  8622. \vspace{5pt}
  8623. \caption{Quick-reference for the x86 instructions used in this book.}
  8624. \label{tab:x86-instr}
  8625. \end{table}
  8626. \cleardoublepage
  8627. \addcontentsline{toc}{chapter}{Index}
  8628. \printindex
  8629. \cleardoublepage
  8630. \bibliographystyle{plainnat}
  8631. \bibliography{all}
  8632. \addcontentsline{toc}{chapter}{Bibliography}
  8633. \end{document}
  8634. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8635. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8636. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8637. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8638. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8639. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8640. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8641. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8642. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8643. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8644. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8645. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8646. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  8647. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8648. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8649. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8650. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8651. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8652. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8653. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8654. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8655. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8656. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8657. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8658. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8659. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8660. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8661. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8662. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8663. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8664. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8665. % LocalWords: struct symtab