book.tex 303 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105
  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{multirow}
  49. \usepackage{color}
  50. \usepackage{upquote}
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. %% For pictures
  55. \usepackage{tikz}
  56. \usetikzlibrary{arrows.meta}
  57. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  58. % Computer Modern is already the default. -Jeremy
  59. %\renewcommand{\ttdefault}{cmtt}
  60. \definecolor{comment-red}{rgb}{0.8,0,0}
  61. \if{0}
  62. % Peanut gallery comments:
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{#1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then},
  73. deletekeywords={read},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~}
  77. }
  78. \newtheorem{theorem}{Theorem}
  79. \newtheorem{lemma}[theorem]{Lemma}
  80. \newtheorem{corollary}[theorem]{Corollary}
  81. \newtheorem{proposition}[theorem]{Proposition}
  82. \newtheorem{constraint}[theorem]{Constraint}
  83. \newtheorem{definition}[theorem]{Definition}
  84. \newtheorem{exercise}[theorem]{Exercise}
  85. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  86. % 'dedication' environment: To add a dedication paragraph at the start of book %
  87. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  88. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  89. \newenvironment{dedication}
  90. {
  91. \cleardoublepage
  92. \thispagestyle{empty}
  93. \vspace*{\stretch{1}}
  94. \hfill\begin{minipage}[t]{0.66\textwidth}
  95. \raggedright
  96. }
  97. {
  98. \end{minipage}
  99. \vspace*{\stretch{3}}
  100. \clearpage
  101. }
  102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  103. % Chapter quote at the start of chapter %
  104. % Source: http://tex.stackexchange.com/a/53380 %
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \makeatletter
  107. \renewcommand{\@chapapp}{}% Not necessary...
  108. \newenvironment{chapquote}[2][2em]
  109. {\setlength{\@tempdima}{#1}%
  110. \def\chapquote@author{#2}%
  111. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  112. \itshape}
  113. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  114. \makeatother
  115. \input{defs}
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \title{\Huge \textbf{Essentials of Compilation} \\
  118. \huge An Incremental Approach}
  119. \author{\textsc{Jeremy G. Siek} \\
  120. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  121. Indiana University \\
  122. \\
  123. with contributions from: \\
  124. Carl Factora \\
  125. Andre Kuhlenschmidt \\
  126. Ryan R. Newton \\
  127. Ryan Scott \\
  128. Cameron Swords \\
  129. Michael M. Vitousek \\
  130. Michael Vollmer
  131. }
  132. \begin{document}
  133. \frontmatter
  134. \maketitle
  135. \begin{dedication}
  136. This book is dedicated to the programming language wonks at Indiana
  137. University.
  138. \end{dedication}
  139. \tableofcontents
  140. \listoffigures
  141. %\listoftables
  142. \mainmatter
  143. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  144. \chapter*{Preface}
  145. The tradition of compiler writing at Indiana University goes back to
  146. research and courses about programming languages by Daniel Friedman in
  147. the 1970's and 1980's. Dan conducted research on lazy
  148. evaluation~\citep{Friedman:1976aa} in the context of
  149. Lisp~\citep{McCarthy:1960dz} and then studied
  150. continuations~\citep{Felleisen:kx} and
  151. macros~\citep{Kohlbecker:1986dk} in the context of the
  152. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  153. of those courses, Kent Dybvig, went on to build Chez
  154. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  155. compiler for Scheme. After completing his Ph.D. at the University of
  156. North Carolina, Kent returned to teach at Indiana University.
  157. Throughout the 1990's and 2000's, Kent continued development of Chez
  158. Scheme and taught the compiler course.
  159. The compiler course evolved to incorporate novel pedagogical ideas
  160. while also including elements of effective real-world compilers. One
  161. of Dan's ideas was to split the compiler into many small ``passes'' so
  162. that the code for each pass would be easy to understood in isolation.
  163. (In contrast, most compilers of the time were organized into only a
  164. few monolithic passes for reasons of compile-time efficiency.) Kent,
  165. with later help from his students Dipanwita Sarkar and Andrew Keep,
  166. developed infrastructure to support this approach and evolved the
  167. course, first to use micro-sized passes and then into even smaller
  168. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  169. student in this compiler course in the early 2000's, as part of his
  170. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  171. the course immensely!
  172. During that time, another student named Abdulaziz Ghuloum observed
  173. that the front-to-back organization of the course made it difficult
  174. for students to understand the rationale for the compiler
  175. design. Abdulaziz proposed an incremental approach in which the
  176. students build the compiler in stages; they start by implementing a
  177. complete compiler for a very small subset of the input language and in
  178. each subsequent stage they add a language feature and add or modify
  179. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  180. the students see how the language features motivate aspects of the
  181. compiler design.
  182. After graduating from Indiana University in 2005, Jeremy went on to
  183. teach at the University of Colorado. He adapted the nano pass and
  184. incremental approaches to compiling a subset of the Python
  185. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  186. on the surface but there is a large overlap in the compiler techniques
  187. required for the two languages. Thus, Jeremy was able to teach much of
  188. the same content from the Indiana compiler course. He very much
  189. enjoyed teaching the course organized in this way, and even better,
  190. many of the students learned a lot and got excited about compilers.
  191. Jeremy returned to teach at Indiana University in 2013. In his
  192. absence the compiler course had switched from the front-to-back
  193. organization to a back-to-front organization. Seeing how well the
  194. incremental approach worked at Colorado, he started porting and
  195. adapting the structure of the Colorado course back into the land of
  196. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  197. the course is now about compiling a subset of Racket (and Typed
  198. Racket) to the x86 assembly language. The compiler is implemented in
  199. Racket 7.1~\citep{plt-tr}.
  200. This is the textbook for the incremental version of the compiler
  201. course at Indiana University (Spring 2016 - present) and it is the
  202. first open textbook for an Indiana compiler course. With this book we
  203. hope to make the Indiana compiler course available to people that have
  204. not had the chance to study in Bloomington in person. Many of the
  205. compiler design decisions in this book are drawn from the assignment
  206. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  207. are the most important topics from \cite{Dybvig:2010aa} but we have
  208. omitted topics that we think are less interesting conceptually and we
  209. have made simplifications to reduce complexity. In this way, this
  210. book leans more towards pedagogy than towards the efficiency of the
  211. generated code. Also, the book differs in places where we saw the
  212. opportunity to make the topics more fun, such as in relating register
  213. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  214. \section*{Prerequisites}
  215. The material in this book is challenging but rewarding. It is meant to
  216. prepare students for a lifelong career in programming languages.
  217. The book uses the Racket language both for the implementation of the
  218. compiler and for the language that is compiled, so a student should be
  219. proficient with Racket (or Scheme) prior to reading this book. There
  220. are many excellent resources for learning Scheme and
  221. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  222. is helpful but not necessary for the student to have prior exposure to
  223. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  224. obtain from a computer systems
  225. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  226. parts of x86-64 assembly language that are needed.
  227. %\section*{Structure of book}
  228. % You might want to add short description about each chapter in this book.
  229. %\section*{About the companion website}
  230. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  231. %\begin{itemize}
  232. % \item A link to (freely downlodable) latest version of this document.
  233. % \item Link to download LaTeX source for this document.
  234. % \item Miscellaneous material (e.g. suggested readings etc).
  235. %\end{itemize}
  236. \section*{Acknowledgments}
  237. Many people have contributed to the ideas, techniques, organization,
  238. and teaching of the materials in this book. We especially thank the
  239. following people.
  240. \begin{itemize}
  241. \item Bor-Yuh Evan Chang
  242. \item Kent Dybvig
  243. \item Daniel P. Friedman
  244. \item Ronald Garcia
  245. \item Abdulaziz Ghuloum
  246. \item Jay McCarthy
  247. \item Dipanwita Sarkar
  248. \item Andrew Keep
  249. \item Oscar Waddell
  250. \item Michael Wollowski
  251. \end{itemize}
  252. \mbox{}\\
  253. \noindent Jeremy G. Siek \\
  254. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  255. %\noindent Spring 2016
  256. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  257. \chapter{Preliminaries}
  258. \label{ch:trees-recur}
  259. In this chapter we review the basic tools that are needed to implement
  260. a compiler. Programs are typically input by a programmer as text,
  261. i.e., a sequence of characters. The program-as-text representation is
  262. called \emph{concrete syntax}. We use concrete syntax to concisely
  263. write down and talk about programs. Inside the compiler, we use
  264. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  265. that efficiently supports the operations that the compiler needs to
  266. perform.
  267. %
  268. The translation from concrete syntax to abstract syntax is a process
  269. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  270. and implementation of parsing in this book. A parser is provided in
  271. the supporting materials for translating from concrete syntax to
  272. abstract syntax for the languages used in this book.
  273. ASTs can be represented in many different ways inside the compiler,
  274. depending on the programming language used to write the compiler.
  275. %
  276. We use Racket's \code{struct} feature to represent ASTs
  277. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  278. of programming languages (Section~\ref{sec:grammar}) and pattern
  279. matching to inspect individual nodes in an AST
  280. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  281. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  282. chapter provides an brief introduction to these ideas.
  283. \section{Abstract Syntax Trees and Racket Structures}
  284. \label{sec:ast}
  285. Compilers use abstract syntax trees to represent programs because
  286. compilers often need to ask questions like: for a given part of a
  287. program, what kind of language feature is it? What are the sub-parts
  288. of this part of the program? Consider the program on the left and its
  289. AST on the right. This program is an addition and it has two
  290. sub-parts, a read operation and a negation. The negation has another
  291. sub-part, the integer constant \code{8}. By using a tree to represent
  292. the program, we can easily follow the links to go from one part of a
  293. program to its sub-parts.
  294. \begin{center}
  295. \begin{minipage}{0.4\textwidth}
  296. \begin{lstlisting}
  297. (+ (read) (- 8))
  298. \end{lstlisting}
  299. \end{minipage}
  300. \begin{minipage}{0.4\textwidth}
  301. \begin{equation}
  302. \begin{tikzpicture}
  303. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  304. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  305. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  306. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  307. \draw[->] (plus) to (read);
  308. \draw[->] (plus) to (minus);
  309. \draw[->] (minus) to (8);
  310. \end{tikzpicture}
  311. \label{eq:arith-prog}
  312. \end{equation}
  313. \end{minipage}
  314. \end{center}
  315. We use the standard terminology for trees to describe ASTs: each
  316. circle above is called a \emph{node}. The arrows connect a node to its
  317. \emph{children} (which are also nodes). The top-most node is the
  318. \emph{root}. Every node except for the root has a \emph{parent} (the
  319. node it is the child of). If a node has no children, it is a
  320. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  321. %% Recall that an \emph{symbolic expression} (S-expression) is either
  322. %% \begin{enumerate}
  323. %% \item an atom, or
  324. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  325. %% where $e_1$ and $e_2$ are each an S-expression.
  326. %% \end{enumerate}
  327. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  328. %% null value \code{'()}, etc. We can create an S-expression in Racket
  329. %% simply by writing a backquote (called a quasi-quote in Racket)
  330. %% followed by the textual representation of the S-expression. It is
  331. %% quite common to use S-expressions to represent a list, such as $a, b
  332. %% ,c$ in the following way:
  333. %% \begin{lstlisting}
  334. %% `(a . (b . (c . ())))
  335. %% \end{lstlisting}
  336. %% Each element of the list is in the first slot of a pair, and the
  337. %% second slot is either the rest of the list or the null value, to mark
  338. %% the end of the list. Such lists are so common that Racket provides
  339. %% special notation for them that removes the need for the periods
  340. %% and so many parenthesis:
  341. %% \begin{lstlisting}
  342. %% `(a b c)
  343. %% \end{lstlisting}
  344. %% The following expression creates an S-expression that represents AST
  345. %% \eqref{eq:arith-prog}.
  346. %% \begin{lstlisting}
  347. %% `(+ (read) (- 8))
  348. %% \end{lstlisting}
  349. %% When using S-expressions to represent ASTs, the convention is to
  350. %% represent each AST node as a list and to put the operation symbol at
  351. %% the front of the list. The rest of the list contains the children. So
  352. %% in the above case, the root AST node has operation \code{`+} and its
  353. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  354. %% diagram \eqref{eq:arith-prog}.
  355. %% To build larger S-expressions one often needs to splice together
  356. %% several smaller S-expressions. Racket provides the comma operator to
  357. %% splice an S-expression into a larger one. For example, instead of
  358. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  359. %% we could have first created an S-expression for AST
  360. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  361. %% S-expression.
  362. %% \begin{lstlisting}
  363. %% (define ast1.4 `(- 8))
  364. %% (define ast1.1 `(+ (read) ,ast1.4))
  365. %% \end{lstlisting}
  366. %% In general, the Racket expression that follows the comma (splice)
  367. %% can be any expression that produces an S-expression.
  368. We define a Racket \code{struct} for each kind of node. For this
  369. chapter we require just two kinds of nodes: one for integer constants
  370. and one for primitive operations. The following is the \code{struct}
  371. definition for integer constants.
  372. \begin{lstlisting}
  373. (struct Int (value))
  374. \end{lstlisting}
  375. An integer node includes just one thing: the integer value.
  376. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  377. \begin{lstlisting}
  378. (define eight (Int 8))
  379. \end{lstlisting}
  380. We say that the value created by \code{(Int 8)} is an
  381. \emph{instance} of the \code{Int} structure.
  382. The following is the \code{struct} definition for primitives operations.
  383. \begin{lstlisting}
  384. (struct Prim (op arg*))
  385. \end{lstlisting}
  386. A primitive operation node includes an operator symbol \code{op}
  387. and a list of children \code{arg*}. For example, to create
  388. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  389. \begin{lstlisting}
  390. (define neg-eight (Prim '- (list eight)))
  391. \end{lstlisting}
  392. Primitive operations may have zero or more children. The \code{read}
  393. operator has zero children:
  394. \begin{lstlisting}
  395. (define rd (Prim 'read '()))
  396. \end{lstlisting}
  397. whereas the addition operator has two children:
  398. \begin{lstlisting}
  399. (define ast1.1 (Prim '+ (list rd neg-eight)))
  400. \end{lstlisting}
  401. We have made a design choice regarding the \code{Prim} structure.
  402. Instead of using one structure for many different operations
  403. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  404. structure for each operation, as follows.
  405. \begin{lstlisting}
  406. (struct Read ())
  407. (struct Add (left right))
  408. (struct Neg (value))
  409. \end{lstlisting}
  410. The reason we choose to use just one structure is that in many parts
  411. of the compiler the code for the different primitive operators is the
  412. same, so we might as well just write that code once, which is enabled
  413. by using a single structure.
  414. When compiling a program such as \eqref{eq:arith-prog}, we need to
  415. know that the operation associated with the root node is addition and
  416. we need to be able to access its two children. Racket provides pattern
  417. matching over structures to support these kinds of queries, as we
  418. shall see in Section~\ref{sec:pattern-matching}.
  419. In this book, we often write down the concrete syntax of a program
  420. even when we really have in mind the AST because the concrete syntax
  421. is more concise. We recommend that, in your mind, you always think of
  422. programs as abstract syntax trees.
  423. \section{Grammars}
  424. \label{sec:grammar}
  425. A programming language can be thought of as a \emph{set} of programs.
  426. The set is typically infinite (one can always create larger and larger
  427. programs), so one cannot simply describe a language by listing all of
  428. the programs in the language. Instead we write down a set of rules, a
  429. \emph{grammar}, for building programs. Grammars are often used to
  430. define the concrete syntax of a language, but they can also be used to
  431. describe the abstract syntax. We shall write our rules in a variant of
  432. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  433. example, we describe a small language, named $R_0$, that consists of
  434. integers and arithmetic operations.
  435. The first grammar rule for the abstract syntax of $R_0$ says that an
  436. instance of the \code{Int} structure is an expression:
  437. \begin{equation}
  438. \Exp ::= \INT{\Int} \label{eq:arith-int}
  439. \end{equation}
  440. %
  441. Each rule has a left-hand-side and a right-hand-side. The way to read
  442. a rule is that if you have all the program parts on the
  443. right-hand-side, then you can create an AST node and categorize it
  444. according to the left-hand-side.
  445. %
  446. A name such as $\Exp$ that is
  447. defined by the grammar rules is a \emph{non-terminal}.
  448. %
  449. The name $\Int$ is a also a non-terminal, but instead of defining it
  450. with a grammar rule, we define it with the following explanation. We
  451. make the simplifying design decision that all of the languages in this
  452. book only handle machine-representable integers. On most modern
  453. machines this corresponds to integers represented with 64-bits, i.e.,
  454. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  455. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  456. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  457. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  458. that the sequence of decimals represent an integer in range $-2^{62}$
  459. to $2^{62}-1$.
  460. The second grammar rule is the \texttt{read} operation that receives
  461. an input integer from the user of the program.
  462. \begin{equation}
  463. \Exp ::= \READ{} \label{eq:arith-read}
  464. \end{equation}
  465. The third rule says that, given an $\Exp$ node, you can build another
  466. $\Exp$ node by negating it.
  467. \begin{equation}
  468. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  469. \end{equation}
  470. Symbols in typewriter font such as \key{-} and \key{read} are
  471. \emph{terminal} symbols and must literally appear in the program for
  472. the rule to be applicable.
  473. We can apply the rules to build ASTs in the $R_0$
  474. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  475. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  476. an $\Exp$.
  477. \begin{center}
  478. \begin{minipage}{0.4\textwidth}
  479. \begin{lstlisting}
  480. (Prim '- (list (Int 8)))
  481. \end{lstlisting}
  482. \end{minipage}
  483. \begin{minipage}{0.25\textwidth}
  484. \begin{equation}
  485. \begin{tikzpicture}
  486. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  487. \node[draw, circle] (8) at (0, -1.2) {$8$};
  488. \draw[->] (minus) to (8);
  489. \end{tikzpicture}
  490. \label{eq:arith-neg8}
  491. \end{equation}
  492. \end{minipage}
  493. \end{center}
  494. The next grammar rule defines addition expressions:
  495. \begin{equation}
  496. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  497. \end{equation}
  498. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  499. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  500. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  501. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  502. to show that
  503. \begin{lstlisting}
  504. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  505. \end{lstlisting}
  506. is an $\Exp$ in the $R_0$ language.
  507. If you have an AST for which the above rules do not apply, then the
  508. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  509. is not in $R_0$ because there are no rules for \code{+} with only one
  510. argument, nor for \key{-} with two arguments. Whenever we define a
  511. language with a grammar, the language only includes those programs
  512. that are justified by the rules.
  513. The last grammar rule for $R_0$ states that there is a \code{Program}
  514. node to mark the top of the whole program:
  515. \[
  516. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  517. \]
  518. The \code{Program} structure is defined as follows
  519. \begin{lstlisting}
  520. (struct Program (info body))
  521. \end{lstlisting}
  522. where \code{body} is an expression. In later chapters, the \code{info}
  523. part will be used to store auxiliary information but for now it is
  524. just the empty list.
  525. It is common to have many grammar rules with the same left-hand side
  526. but different right-hand sides, such as the rules for $\Exp$ in the
  527. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  528. combine several right-hand-sides into a single rule.
  529. We collect all of the grammar rules for the abstract syntax of $R_0$
  530. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  531. defined in Figure~\ref{fig:r0-concrete-syntax}.
  532. The \code{read-program} function provided in \code{utilities.rkt} of
  533. the support materials reads a program in from a file (the sequence of
  534. characters in the concrete syntax of Racket) and parses it into an
  535. abstract syntax tree. See the description of \code{read-program} in
  536. Appendix~\ref{appendix:utilities} for more details.
  537. \begin{figure}[tp]
  538. \fbox{
  539. \begin{minipage}{0.96\textwidth}
  540. \[
  541. \begin{array}{rcl}
  542. \begin{array}{rcl}
  543. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  544. R_0 &::=& \Exp
  545. \end{array}
  546. \end{array}
  547. \]
  548. \end{minipage}
  549. }
  550. \caption{The concrete syntax of $R_0$.}
  551. \label{fig:r0-concrete-syntax}
  552. \end{figure}
  553. \begin{figure}[tp]
  554. \fbox{
  555. \begin{minipage}{0.96\textwidth}
  556. \[
  557. \begin{array}{rcl}
  558. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  559. &\mid& \ADD{\Exp}{\Exp} \\
  560. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  561. \end{array}
  562. \]
  563. \end{minipage}
  564. }
  565. \caption{The abstract syntax of $R_0$.}
  566. \label{fig:r0-syntax}
  567. \end{figure}
  568. \section{Pattern Matching}
  569. \label{sec:pattern-matching}
  570. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  571. the parts of an AST node. Racket provides the \texttt{match} form to
  572. access the parts of a structure. Consider the following example and
  573. the output on the right.
  574. \begin{center}
  575. \begin{minipage}{0.5\textwidth}
  576. \begin{lstlisting}
  577. (match ast1.1
  578. [(Prim op (list child1 child2))
  579. (print op)])
  580. \end{lstlisting}
  581. \end{minipage}
  582. \vrule
  583. \begin{minipage}{0.25\textwidth}
  584. \begin{lstlisting}
  585. '+
  586. \end{lstlisting}
  587. \end{minipage}
  588. \end{center}
  589. In the above example, the \texttt{match} form takes the AST
  590. \eqref{eq:arith-prog} and binds its parts to the three pattern
  591. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  592. general, a match clause consists of a \emph{pattern} and a
  593. \emph{body}. Patterns are recursively defined to be either a pattern
  594. variable, a structure name followed by a pattern for each of the
  595. structure's arguments, or an S-expression (symbols, lists, etc.).
  596. (See Chapter 12 of The Racket
  597. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  598. and Chapter 9 of The Racket
  599. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  600. for a complete description of \code{match}.)
  601. %
  602. The body of a match clause may contain arbitrary Racket code. The
  603. pattern variables can be used in the scope of the body.
  604. A \code{match} form may contain several clauses, as in the following
  605. function \code{leaf?} that recognizes when an $R_0$ node is
  606. a leaf. The \code{match} proceeds through the clauses in order,
  607. checking whether the pattern can match the input AST. The
  608. body of the first clause that matches is executed. The output of
  609. \code{leaf?} for several ASTs is shown on the right.
  610. \begin{center}
  611. \begin{minipage}{0.6\textwidth}
  612. \begin{lstlisting}
  613. (define (leaf? arith)
  614. (match arith
  615. [(Int n) #t]
  616. [(Prim 'read '()) #t]
  617. [(Prim '- (list c1)) #f]
  618. [(Prim '+ (list c1 c2)) #f]))
  619. (leaf? (Prim 'read '()))
  620. (leaf? (Prim '- (list (Int 8))))
  621. (leaf? (Int 8))
  622. \end{lstlisting}
  623. \end{minipage}
  624. \vrule
  625. \begin{minipage}{0.25\textwidth}
  626. \begin{lstlisting}
  627. #t
  628. #f
  629. #t
  630. \end{lstlisting}
  631. \end{minipage}
  632. \end{center}
  633. When writing a \code{match}, we refer to the grammar definition to
  634. identify which non-terminal we are expecting to match against, then we
  635. make sure that 1) we have one clause for each alternative of that
  636. non-terminal and 2) that the pattern in each clause corresponds to the
  637. corresponding right-hand side of a grammar rule. For the \code{match}
  638. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  639. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  640. alternatives, so the \code{match} has 4 clauses. The pattern in each
  641. clause corresponds to the right-hand side of a grammar rule. For
  642. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  643. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  644. patterns, replace non-terminals such as $\Exp$ with pattern variables
  645. of your choice (e.g. \code{c1} and \code{c2}).
  646. \section{Recursion}
  647. \label{sec:recursion}
  648. Programs are inherently recursive. For example, an $R_0$ expression is
  649. often made of smaller expressions. Thus, the natural way to process an
  650. entire program is with a recursive function. As a first example of
  651. such a recursive function, we define \texttt{exp?} below, which takes
  652. an arbitrary value and determines whether or not it is an $R_0$
  653. expression.
  654. %
  655. When a recursive function is defined using a sequence of match clauses
  656. that correspond to a grammar, and the body of each clause makes a
  657. recursive call on each child node, then we say the function is defined
  658. by \emph{structural recursion}\footnote{This principle of structuring
  659. code according to the data definition is advocated in the book
  660. \emph{How to Design Programs}
  661. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  662. define a second function, named \code{R0?}, that determines whether a
  663. value is an $R_0$ program. In general we can expect to write one
  664. recursive function to handle each non-terminal in a grammar.
  665. %
  666. \begin{center}
  667. \begin{minipage}{0.7\textwidth}
  668. \begin{lstlisting}
  669. (define (exp? ast)
  670. (match ast
  671. [(Int n) #t]
  672. [(Prim 'read '()) #t]
  673. [(Prim '- (list e)) (exp? e)]
  674. [(Prim '+ (list e1 e2))
  675. (and (exp? e1) (exp? e2))]
  676. [else #f]))
  677. (define (R0? ast)
  678. (match ast
  679. [(Program '() e) (exp? e)]
  680. [else #f]))
  681. (R0? (Program '() ast1.1)
  682. (R0? (Program '()
  683. (Prim '- (list (Prim 'read '())
  684. (Prim '+ (list (Num 8)))))))
  685. \end{lstlisting}
  686. \end{minipage}
  687. \vrule
  688. \begin{minipage}{0.25\textwidth}
  689. \begin{lstlisting}
  690. #t
  691. #f
  692. \end{lstlisting}
  693. \end{minipage}
  694. \end{center}
  695. You may be tempted to merge the two functions into one, like this:
  696. \begin{center}
  697. \begin{minipage}{0.5\textwidth}
  698. \begin{lstlisting}
  699. (define (R0? ast)
  700. (match ast
  701. [(Int n) #t]
  702. [(Prim 'read '()) #t]
  703. [(Prim '- (list e)) (R0? e)]
  704. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  705. [(Program '() e) (R0? e)]
  706. [else #f]))
  707. \end{lstlisting}
  708. \end{minipage}
  709. \end{center}
  710. %
  711. Sometimes such a trick will save a few lines of code, especially when
  712. it comes to the \code{Program} wrapper. Yet this style is generally
  713. \emph{not} recommended because it can get you into trouble.
  714. %
  715. For example, the above function is subtly wrong:
  716. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  717. will return true, when it should return false.
  718. %% NOTE FIXME - must check for consistency on this issue throughout.
  719. \section{Interpreters}
  720. \label{sec:interp-R0}
  721. The meaning, or semantics, of a program is typically defined in the
  722. specification of the language. For example, the Scheme language is
  723. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  724. defined in its reference manual~\citep{plt-tr}. In this book we use an
  725. interpreter to define the meaning of each language that we consider,
  726. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  727. interpreter that is designated (by some people) as the definition of a
  728. language is called a \emph{definitional interpreter}. We warm up by
  729. creating a definitional interpreter for the $R_0$ language, which
  730. serves as a second example of structural recursion. The
  731. \texttt{interp-R0} function is defined in
  732. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  733. input program followed by a call to the \lstinline{interp-exp} helper
  734. function, which in turn has one match clause per grammar rule for
  735. $R_0$ expressions.
  736. \begin{figure}[tbp]
  737. \begin{lstlisting}
  738. (define (interp-exp e)
  739. (match e
  740. [(Int n) n]
  741. [(Prim 'read '())
  742. (define r (read))
  743. (cond [(fixnum? r) r]
  744. [else (error 'interp-R1 "expected an integer" r)])]
  745. [(Prim '- (list e))
  746. (define v (interp-exp e))
  747. (fx- 0 v)]
  748. [(Prim '+ (list e1 e2))
  749. (define v1 (interp-exp e1))
  750. (define v2 (interp-exp e2))
  751. (fx+ v1 v2)]
  752. ))
  753. (define (interp-R0 p)
  754. (match p
  755. [(Program '() e) (interp-exp e)]
  756. ))
  757. \end{lstlisting}
  758. \caption{Interpreter for the $R_0$ language.}
  759. \label{fig:interp-R0}
  760. \end{figure}
  761. Let us consider the result of interpreting a few $R_0$ programs. The
  762. following program adds two integers.
  763. \begin{lstlisting}
  764. (+ 10 32)
  765. \end{lstlisting}
  766. The result is \key{42}. We wrote the above program in concrete syntax,
  767. whereas the parsed abstract syntax is:
  768. \begin{lstlisting}
  769. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  770. \end{lstlisting}
  771. The next example demonstrates that expressions may be nested within
  772. each other, in this case nesting several additions and negations.
  773. \begin{lstlisting}
  774. (+ 10 (- (+ 12 20)))
  775. \end{lstlisting}
  776. What is the result of the above program?
  777. As mentioned previously, the $R_0$ language does not support
  778. arbitrarily-large integers, but only $63$-bit integers, so we
  779. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  780. in Racket.
  781. Suppose
  782. \[
  783. n = 999999999999999999
  784. \]
  785. which indeed fits in $63$-bits. What happens when we run the
  786. following program in our interpreter?
  787. \begin{lstlisting}
  788. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  789. \end{lstlisting}
  790. It produces an error:
  791. \begin{lstlisting}
  792. fx+: result is not a fixnum
  793. \end{lstlisting}
  794. We establish the convention that if running the definitional
  795. interpreter on a program produces an error, then the meaning of that
  796. program is \emph{unspecified}. That means a compiler for the language
  797. is under no obligations regarding that program; it may or may not
  798. produce an executable, and if it does, that executable can do
  799. anything. This convention applies to the languages defined in this
  800. book, as a way to simplify the student's task of implementing them,
  801. but this convention is not applicable to all programming languages.
  802. Moving on to the last feature of the $R_0$ language, the \key{read}
  803. operation prompts the user of the program for an integer. Recall that
  804. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  805. \code{8}. So if we run
  806. \begin{lstlisting}
  807. (interp-R0 ast1.1)
  808. \end{lstlisting}
  809. and if the input is \code{50}, then we get the answer to life, the
  810. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  811. Guide to the Galaxy} by Douglas Adams.}
  812. We include the \key{read} operation in $R_0$ so a clever student
  813. cannot implement a compiler for $R_0$ that simply runs the interpreter
  814. during compilation to obtain the output and then generates the trivial
  815. code to produce the output. (Yes, a clever student did this in the
  816. first instance of this course.)
  817. The job of a compiler is to translate a program in one language into a
  818. program in another language so that the output program behaves the
  819. same way as the input program does according to its definitional
  820. interpreter. This idea is depicted in the following diagram. Suppose
  821. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  822. interpreter for each language. Suppose that the compiler translates
  823. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  824. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  825. respective interpreters with input $i$ should yield the same output
  826. $o$.
  827. \begin{equation} \label{eq:compile-correct}
  828. \begin{tikzpicture}[baseline=(current bounding box.center)]
  829. \node (p1) at (0, 0) {$P_1$};
  830. \node (p2) at (3, 0) {$P_2$};
  831. \node (o) at (3, -2.5) {$o$};
  832. \path[->] (p1) edge [above] node {compile} (p2);
  833. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  834. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  835. \end{tikzpicture}
  836. \end{equation}
  837. In the next section we see our first example of a compiler.
  838. \section{Example Compiler: a Partial Evaluator}
  839. \label{sec:partial-evaluation}
  840. In this section we consider a compiler that translates $R_0$ programs
  841. into $R_0$ programs that may be more efficient, that is, this compiler
  842. is an optimizer. This optimizer eagerly computes the parts of the
  843. program that do not depend on any inputs, a process known as
  844. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  845. following program
  846. \begin{lstlisting}
  847. (+ (read) (- (+ 5 3)))
  848. \end{lstlisting}
  849. our compiler will translate it into the program
  850. \begin{lstlisting}
  851. (+ (read) -8)
  852. \end{lstlisting}
  853. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  854. evaluator for the $R_0$ language. The output of the partial evaluator
  855. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  856. recursion over $\Exp$ is captured in the \code{pe-exp} function
  857. whereas the code for partially evaluating the negation and addition
  858. operations is factored into two separate helper functions:
  859. \code{pe-neg} and \code{pe-add}. The input to these helper
  860. functions is the output of partially evaluating the children.
  861. \begin{figure}[tbp]
  862. \begin{lstlisting}
  863. (define (pe-neg r)
  864. (match r
  865. [(Int n) (Int (fx- 0 n))]
  866. [else (Prim '- (list r))]))
  867. (define (pe-add r1 r2)
  868. (match* (r1 r2)
  869. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  870. [(_ _) (Prim '+ (list r1 r2))]))
  871. (define (pe-exp e)
  872. (match e
  873. [(Int n) (Int n)]
  874. [(Prim 'read '()) (Prim 'read '())]
  875. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  876. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  877. ))
  878. (define (pe-R0 p)
  879. (match p
  880. [(Program info e) (Program info (pe-exp e))]
  881. ))
  882. \end{lstlisting}
  883. \caption{A partial evaluator for $R_0$ expressions.}
  884. \label{fig:pe-arith}
  885. \end{figure}
  886. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  887. arguments are integers and if they are, perform the appropriate
  888. arithmetic. Otherwise, they create an AST node for the operation
  889. (either negation or addition).
  890. To gain some confidence that the partial evaluator is correct, we can
  891. test whether it produces programs that get the same result as the
  892. input programs. That is, we can test whether it satisfies Diagram
  893. \eqref{eq:compile-correct}. The following code runs the partial
  894. evaluator on several examples and tests the output program. The
  895. \texttt{parse-program} and \texttt{assert} functions are defined in
  896. Appendix~\ref{appendix:utilities}.\\
  897. \begin{minipage}{1.0\textwidth}
  898. \begin{lstlisting}
  899. (define (test-pe p)
  900. (assert "testing pe-R0"
  901. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  902. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  903. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  904. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  905. \end{lstlisting}
  906. \end{minipage}
  907. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  908. \chapter{Integers and Variables}
  909. \label{ch:int-exp}
  910. This chapter is about compiling the subset of Racket that includes
  911. integer arithmetic and local variable binding, which we name $R_1$, to
  912. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  913. to x86-64 simply as x86. The chapter begins with a description of the
  914. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  915. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  916. discuss only what is needed for compiling $R_1$. We introduce more of
  917. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  918. reflect on their differences and come up with a plan to break down the
  919. translation from $R_1$ to x86 into a handful of steps
  920. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  921. chapter give detailed hints regarding each step
  922. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  923. to give enough hints that the well-prepared reader, together with a
  924. few friends, can implement a compiler from $R_1$ to x86 in a couple
  925. weeks while at the same time leaving room for some fun and creativity.
  926. To give the reader a feeling for the scale of this first compiler, the
  927. instructor solution for the $R_1$ compiler is less than 500 lines of
  928. code.
  929. \section{The $R_1$ Language}
  930. \label{sec:s0}
  931. The $R_1$ language extends the $R_0$ language with variable
  932. definitions. The concrete syntax of the $R_1$ language is defined by
  933. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  934. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  935. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  936. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  937. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  938. \key{Program} struct to mark the top of the program.
  939. %% The $\itm{info}$
  940. %% field of the \key{Program} structure contains an \emph{association
  941. %% list} (a list of key-value pairs) that is used to communicate
  942. %% auxiliary data from one compiler pass the next.
  943. Despite the simplicity of the $R_1$ language, it is rich enough to
  944. exhibit several compilation techniques.
  945. \begin{figure}[btp]
  946. \centering
  947. \fbox{
  948. \begin{minipage}{0.96\textwidth}
  949. \[
  950. \begin{array}{rcl}
  951. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  952. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  953. R_1 &::=& \Exp
  954. \end{array}
  955. \]
  956. \end{minipage}
  957. }
  958. \caption{The concrete syntax of $R_1$.}
  959. \label{fig:r1-concrete-syntax}
  960. \end{figure}
  961. \begin{figure}[btp]
  962. \centering
  963. \fbox{
  964. \begin{minipage}{0.96\textwidth}
  965. \[
  966. \begin{array}{rcl}
  967. \Exp &::=& \INT{\Int} \mid \READ{} \\
  968. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  969. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  970. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  971. \end{array}
  972. \]
  973. \end{minipage}
  974. }
  975. \caption{The abstract syntax of $R_1$.}
  976. \label{fig:r1-syntax}
  977. \end{figure}
  978. Let us dive further into the syntax and semantics of the $R_1$
  979. language. The \key{Let} feature defines a variable for use within its
  980. body and initializes the variable with the value of an expression.
  981. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  982. The concrete syntax for \key{Let} is
  983. \begin{lstlisting}
  984. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  985. \end{lstlisting}
  986. For example, the following program initializes \code{x} to $32$ and then
  987. evaluates the body \code{(+ 10 x)}, producing $42$.
  988. \begin{lstlisting}
  989. (let ([x (+ 12 20)]) (+ 10 x))
  990. \end{lstlisting}
  991. When there are multiple \key{let}'s for the same variable, the closest
  992. enclosing \key{let} is used. That is, variable definitions overshadow
  993. prior definitions. Consider the following program with two \key{let}'s
  994. that define variables named \code{x}. Can you figure out the result?
  995. \begin{lstlisting}
  996. (let ([x 32]) (+ (let ([x 10]) x) x))
  997. \end{lstlisting}
  998. For the purposes of depicting which variable uses correspond to which
  999. definitions, the following shows the \code{x}'s annotated with
  1000. subscripts to distinguish them. Double check that your answer for the
  1001. above is the same as your answer for this annotated version of the
  1002. program.
  1003. \begin{lstlisting}
  1004. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1005. \end{lstlisting}
  1006. The initializing expression is always evaluated before the body of the
  1007. \key{let}, so in the following, the \key{read} for \code{x} is
  1008. performed before the \key{read} for \code{y}. Given the input
  1009. $52$ then $10$, the following produces $42$ (not $-42$).
  1010. \begin{lstlisting}
  1011. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1012. \end{lstlisting}
  1013. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1014. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1015. \key{match} clauses for variables and for \key{let}. For \key{let},
  1016. we need a way to communicate the value of a variable to all the uses
  1017. of a variable. To accomplish this, we maintain a mapping from
  1018. variables to values, which is called an \emph{environment}. For
  1019. simplicity, here we use an association list to represent the
  1020. environment. The \code{interp-R1} function takes the current
  1021. environment, \code{env}, as an extra parameter. When the interpreter
  1022. encounters a variable, it finds the corresponding value using the
  1023. \code{dict-ref} function from the \code{racket/dict} package. When
  1024. the interpreter encounters a \key{Let}, it evaluates the initializing
  1025. expression, extends the environment with the result value bound to the
  1026. variable (using \code{dict-set}), then evaluates the body of the
  1027. \key{Let}.
  1028. \begin{figure}[tbp]
  1029. \begin{lstlisting}
  1030. (define (interp-exp env)
  1031. (lambda (e)
  1032. (match e
  1033. [(Int n) n]
  1034. [(Prim 'read '())
  1035. (define r (read))
  1036. (cond [(fixnum? r) r]
  1037. [else (error 'interp-R1 "expected an integer" r)])]
  1038. [(Prim '- (list e))
  1039. (define v ((interp-exp env) e))
  1040. (fx- 0 v)]
  1041. [(Prim '+ (list e1 e2))
  1042. (define v1 ((interp-exp env) e1))
  1043. (define v2 ((interp-exp env) e2))
  1044. (fx+ v1 v2)]
  1045. [(Var x) (dict-ref env x)]
  1046. [(Let x e body)
  1047. (define new-env (dict-set env x ((interp-exp env) e)))
  1048. ((interp-exp new-env) body)]
  1049. )))
  1050. (define (interp-R1 p)
  1051. (match p
  1052. [(Program info e) ((interp-exp '()) e)]
  1053. ))
  1054. \end{lstlisting}
  1055. \caption{Interpreter for the $R_1$ language.}
  1056. \label{fig:interp-R1}
  1057. \end{figure}
  1058. The goal for this chapter is to implement a compiler that translates
  1059. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1060. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1061. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1062. is, they both output the same integer $n$. We depict this correctness
  1063. criteria in the following diagram.
  1064. \[
  1065. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1066. \node (p1) at (0, 0) {$P_1$};
  1067. \node (p2) at (4, 0) {$P_2$};
  1068. \node (o) at (4, -2) {$n$};
  1069. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1070. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1071. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1072. \end{tikzpicture}
  1073. \]
  1074. In the next section we introduce enough of the x86 assembly
  1075. language to compile $R_1$.
  1076. \section{The x86 Assembly Language}
  1077. \label{sec:x86}
  1078. Figure~\ref{fig:x86-a} defines the concrete syntax for the subset of
  1079. the x86 assembly language needed for this chapter.
  1080. %
  1081. An x86 program is a sequence of instructions. The program is stored in
  1082. the computer's memory and the computer has a \emph{program counter}
  1083. that points to the address of the next instruction to be executed. For
  1084. most instructions, once the instruction is executed, the program
  1085. counter is incremented to point to the immediately following
  1086. instruction in memory. Most x86 instructions take two operands, where
  1087. each operand is either an integer constant (called \emph{immediate
  1088. value}), a \emph{register}, or a \emph{memory} location. A register
  1089. is a special kind of variable. Each one holds a 64-bit value; there
  1090. are 16 registers in the computer and their names are given in
  1091. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  1092. addresses to 64-bit values%
  1093. \footnote{This simple story suffices for describing how sequential
  1094. programs access memory but is not sufficient for multi-threaded
  1095. programs. However, multi-threaded execution is beyond the scope of
  1096. this book.}.
  1097. %
  1098. We use the AT\&T syntax expected by the GNU assembler, which comes
  1099. with the \key{gcc} compiler that we use for compiling assembly code to
  1100. machine code.
  1101. %
  1102. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1103. the x86 instructions used in this book.
  1104. % to do: finish treatment of imulq
  1105. % it's needed for vector's in R6/R7
  1106. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1107. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1108. && \key{r8} \mid \key{r9} \mid \key{r10}
  1109. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1110. \mid \key{r14} \mid \key{r15}}
  1111. \begin{figure}[tp]
  1112. \fbox{
  1113. \begin{minipage}{0.96\textwidth}
  1114. \[
  1115. \begin{array}{lcl}
  1116. \Reg &::=& \allregisters{} \\
  1117. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1118. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1119. \key{subq} \; \Arg\key{,} \Arg \mid
  1120. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1121. && \key{callq} \; \mathit{label} \mid
  1122. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1123. \Prog &::= & \key{.globl main}\\
  1124. & & \key{main:} \; \Instr^{+}
  1125. \end{array}
  1126. \]
  1127. \end{minipage}
  1128. }
  1129. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1130. \label{fig:x86-a}
  1131. \end{figure}
  1132. An immediate value is written using the notation \key{\$}$n$ where $n$
  1133. is an integer.
  1134. %
  1135. A register is written with a \key{\%} followed by the register name,
  1136. such as \key{\%rax}.
  1137. %
  1138. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1139. which obtains the address stored in register $r$ and then adds $n$
  1140. bytes to the address. The resulting address is used to either load or
  1141. store to memory depending on whether it occurs as a source or
  1142. destination argument of an instruction.
  1143. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1144. source $s$ and destination $d$, applies the arithmetic operation, then
  1145. writes the result back to the destination $d$.
  1146. %
  1147. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1148. stores the result in $d$.
  1149. %
  1150. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1151. specified by the label. We discuss procedure calls in more detail
  1152. later in this chapter and in Chapter~\ref{ch:functions}.
  1153. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1154. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1155. \key{main} procedure is externally visible, which is necessary so
  1156. that the operating system can call it. The label \key{main:}
  1157. indicates the beginning of the \key{main} procedure which is where
  1158. the operating system starts executing this program. The instruction
  1159. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1160. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1161. $10$ in \key{rax} and puts the result, $42$, back into
  1162. \key{rax}.
  1163. %
  1164. The last instruction, \key{retq}, finishes the \key{main} function by
  1165. returning the integer in \key{rax} to the operating system. The
  1166. operating system interprets this integer as the program's exit
  1167. code. By convention, an exit code of 0 indicates that a program
  1168. completed successfully, and all other exit codes indicate various
  1169. errors. Nevertheless, we return the result of the program as the exit
  1170. code.
  1171. %\begin{wrapfigure}{r}{2.25in}
  1172. \begin{figure}[tbp]
  1173. \begin{lstlisting}
  1174. .globl main
  1175. main:
  1176. movq $10, %rax
  1177. addq $32, %rax
  1178. retq
  1179. \end{lstlisting}
  1180. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1181. \label{fig:p0-x86}
  1182. %\end{wrapfigure}
  1183. \end{figure}
  1184. Unfortunately, x86 varies in a couple ways depending on what operating
  1185. system it is assembled in. The code examples shown here are correct on
  1186. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1187. labels like \key{main} must be prefixed with an underscore, as in
  1188. \key{\_main}.
  1189. We exhibit the use of memory for storing intermediate results in the
  1190. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1191. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1192. region of memory called the \emph{procedure call stack} (or
  1193. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1194. for each procedure call. The memory layout for an individual frame is
  1195. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1196. \emph{stack pointer} and points to the item at the top of the
  1197. stack. The stack grows downward in memory, so we increase the size of
  1198. the stack by subtracting from the stack pointer. Some operating
  1199. systems require the frame size to be a multiple of 16 bytes. In the
  1200. context of a procedure call, the \emph{return address} is the next
  1201. instruction after the call instruction on the caller side. During a
  1202. function call, the return address is pushed onto the stack. The
  1203. register \key{rbp} is the \emph{base pointer} which serves two
  1204. purposes: 1) it saves the location of the stack pointer for the
  1205. calling procedure and 2) it is used to access variables associated
  1206. with the current procedure. The base pointer of the calling procedure
  1207. is pushed onto the stack after the return address. We number the
  1208. variables from $1$ to $n$. Variable $1$ is stored at address
  1209. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1210. \begin{figure}[tbp]
  1211. \begin{lstlisting}
  1212. start:
  1213. movq $10, -8(%rbp)
  1214. negq -8(%rbp)
  1215. movq -8(%rbp), %rax
  1216. addq $52, %rax
  1217. jmp conclusion
  1218. .globl main
  1219. main:
  1220. pushq %rbp
  1221. movq %rsp, %rbp
  1222. subq $16, %rsp
  1223. jmp start
  1224. conclusion:
  1225. addq $16, %rsp
  1226. popq %rbp
  1227. retq
  1228. \end{lstlisting}
  1229. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1230. \label{fig:p1-x86}
  1231. \end{figure}
  1232. \begin{figure}[tbp]
  1233. \centering
  1234. \begin{tabular}{|r|l|} \hline
  1235. Position & Contents \\ \hline
  1236. 8(\key{\%rbp}) & return address \\
  1237. 0(\key{\%rbp}) & old \key{rbp} \\
  1238. -8(\key{\%rbp}) & variable $1$ \\
  1239. -16(\key{\%rbp}) & variable $2$ \\
  1240. \ldots & \ldots \\
  1241. 0(\key{\%rsp}) & variable $n$\\ \hline
  1242. \end{tabular}
  1243. \caption{Memory layout of a frame.}
  1244. \label{fig:frame}
  1245. \end{figure}
  1246. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1247. three instructions are the typical \emph{prelude} for a procedure.
  1248. The instruction \key{pushq \%rbp} saves the base pointer for the
  1249. caller onto the stack and subtracts $8$ from the stack pointer. The
  1250. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1251. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1252. stack pointer down to make enough room for storing variables. This
  1253. program needs one variable ($8$ bytes) but because the frame size is
  1254. required to be a multiple of 16 bytes, the space for variables is
  1255. rounded to 16 bytes.
  1256. The four instructions under the label \code{start} carry out the work
  1257. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1258. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1259. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1260. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1261. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1262. \key{rax}, at which point \key{rax} contains $42$.
  1263. The three instructions under the label \code{conclusion} are the
  1264. typical \emph{finale} of a procedure. The first two instructions are
  1265. necessary to get the state of the machine back to where it was at the
  1266. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1267. moves the stack pointer back to point at the old base pointer. The
  1268. amount added here needs to match the amount that was subtracted in the
  1269. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1270. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1271. instruction, \key{retq}, jumps back to the procedure that called this
  1272. one and adds 8 to the stack pointer, which returns the stack pointer
  1273. to where it was prior to the procedure call.
  1274. The compiler will need a convenient representation for manipulating
  1275. x86 programs, so we define an abstract syntax for x86 in
  1276. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1277. a subscript $0$ because later we introduce extended versions of this
  1278. assembly language. The main difference compared to the concrete syntax
  1279. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1280. instructions to appear anywhere, but instead organizes instructions
  1281. into groups called \emph{blocks} and associates a label with every
  1282. block, which is why the \key{CFG} struct (for control-flow graph)
  1283. includes an association list mapping labels to blocks. The reason for
  1284. this organization becomes apparent in Chapter~\ref{ch:bool-types} when
  1285. we introduce conditional branching.
  1286. \begin{figure}[tp]
  1287. \fbox{
  1288. \begin{minipage}{0.96\textwidth}
  1289. \small
  1290. \[
  1291. \begin{array}{lcl}
  1292. \Reg &::=& \allregisters{} \\
  1293. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1294. \mid \DEREF{\Reg}{\Int} \\
  1295. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1296. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1297. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1298. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1299. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1300. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \\
  1301. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1302. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1303. \end{array}
  1304. \]
  1305. \end{minipage}
  1306. }
  1307. \caption{Abstract syntax of $x86_0$ assembly.}
  1308. \label{fig:x86-ast-a}
  1309. \end{figure}
  1310. \section{Planning the trip to x86 via the $C_0$ language}
  1311. \label{sec:plan-s0-x86}
  1312. To compile one language to another it helps to focus on the
  1313. differences between the two languages because the compiler will need
  1314. to bridge those differences. What are the differences between $R_1$
  1315. and x86 assembly? Here are some of the most important ones:
  1316. \begin{enumerate}
  1317. \item[(a)] x86 arithmetic instructions typically have two arguments
  1318. and update the second argument in place. In contrast, $R_1$
  1319. arithmetic operations take two arguments and produce a new value.
  1320. An x86 instruction may have at most one memory-accessing argument.
  1321. Furthermore, some instructions place special restrictions on their
  1322. arguments.
  1323. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1324. whereas x86 instructions restrict their arguments to be integers
  1325. constants, registers, and memory locations.
  1326. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1327. sequence of instructions and jumps to labeled positions, whereas in
  1328. $R_1$ the order of evaluation is a left-to-right depth-first
  1329. traversal of the abstract syntax tree.
  1330. \item[(d)] An $R_1$ program can have any number of variables whereas
  1331. x86 has 16 registers and the procedure calls stack.
  1332. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1333. same name. The registers and memory locations of x86 all have unique
  1334. names or addresses.
  1335. \end{enumerate}
  1336. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1337. the problem into several steps, dealing with the above differences one
  1338. at a time. Each of these steps is called a \emph{pass} of the
  1339. compiler.
  1340. %
  1341. This terminology comes from each step traverses (i.e. passes over) the
  1342. AST of the program.
  1343. %
  1344. We begin by sketching how we might implement each pass, and give them
  1345. names. We then figure out an ordering of the passes and the
  1346. input/output language for each pass. The very first pass has $R_1$ as
  1347. its input language and the last pass has x86 as its output
  1348. language. In between we can choose whichever language is most
  1349. convenient for expressing the output of each pass, whether that be
  1350. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1351. Finally, to implement each pass we write one recursive function per
  1352. non-terminal in the grammar of the input language of the pass.
  1353. \begin{description}
  1354. \item[Pass \key{select-instructions}] To handle the difference between
  1355. $R_1$ operations and x86 instructions we convert each $R_1$
  1356. operation to a short sequence of instructions that accomplishes the
  1357. same task.
  1358. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1359. subexpression (i.e. operator and operand, and hence the name
  1360. \key{opera*}) is an \emph{atomic} expression (a variable or
  1361. integer), we introduce temporary variables to hold the results
  1362. of subexpressions.
  1363. \item[Pass \key{explicate-control}] To make the execution order of the
  1364. program explicit, we convert from the abstract syntax tree
  1365. representation into a \emph{control-flow graph} in which each node
  1366. contains a sequence of statements and the edges between nodes say
  1367. where to go at the end of the sequence.
  1368. \item[Pass \key{assign-homes}] To handle the difference between the
  1369. variables in $R_1$ versus the registers and stack locations in x86,
  1370. we assignment of each variable to a register or stack location.
  1371. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1372. by renaming every variable to a unique name, so that shadowing no
  1373. longer occurs.
  1374. \end{description}
  1375. The next question is: in what order should we apply these passes? This
  1376. question can be challenging because it is difficult to know ahead of
  1377. time which orders will be better (easier to implement, produce more
  1378. efficient code, etc.) so oftentimes trial-and-error is
  1379. involved. Nevertheless, we can try to plan ahead and make educated
  1380. choices regarding the ordering.
  1381. Let us consider the ordering of \key{uniquify} and
  1382. \key{remove-complex-opera*}. The assignment of subexpressions to
  1383. temporary variables involves introducing new variables and moving
  1384. subexpressions, which might change the shadowing of variables and
  1385. inadvertently change the behavior of the program. But if we apply
  1386. \key{uniquify} first, this will not be an issue. Of course, this means
  1387. that in \key{remove-complex-opera*}, we need to ensure that the
  1388. temporary variables that it creates are unique.
  1389. What should be the ordering of \key{explicate-control} with respect to
  1390. \key{uniquify}? The \key{uniquify} pass should come first because
  1391. \key{explicate-control} changes all the \key{let}-bound variables to
  1392. become local variables whose scope is the entire program, which would
  1393. confuse variables with the same name.
  1394. %
  1395. Likewise, we place \key{explicate-control} after
  1396. \key{remove-complex-opera*} because \key{explicate-control} removes
  1397. the \key{let} form, but it is convenient to use \key{let} in the
  1398. output of \key{remove-complex-opera*}.
  1399. %
  1400. Regarding \key{assign-homes}, it is helpful to place
  1401. \key{explicate-control} first because \key{explicate-control} changes
  1402. \key{let}-bound variables into program-scope variables. This means
  1403. that the \key{assign-homes} pass can read off the variables from the
  1404. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1405. entire program in search of \key{let}-bound variables.
  1406. Last, we need to decide on the ordering of \key{select-instructions}
  1407. and \key{assign-homes}. These two passes are intertwined, creating a
  1408. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1409. have already determined which instructions will be used, because x86
  1410. instructions have restrictions about which of their arguments can be
  1411. registers versus stack locations. One might want to give preferential
  1412. treatment to variables that occur in register-argument positions. On
  1413. the other hand, it may turn out to be impossible to make sure that all
  1414. such variables are assigned to registers, and then one must redo the
  1415. selection of instructions. Some compilers handle this problem by
  1416. iteratively repeating these two passes until a good solution is found.
  1417. We shall use a simpler approach in which \key{select-instructions}
  1418. comes first, followed by the \key{assign-homes}, then a third
  1419. pass named \key{patch-instructions} that uses a reserved register to
  1420. patch-up outstanding problems regarding instructions with too many
  1421. memory accesses. The disadvantage of this approach is some programs
  1422. may not execute as efficiently as they would if we used the iterative
  1423. approach and used all of the registers for variables.
  1424. \begin{figure}[tbp]
  1425. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1426. \node (R1) at (0,2) {\large $R_1$};
  1427. \node (R1-2) at (3,2) {\large $R_1$};
  1428. \node (R1-3) at (6,2) {\large $R_1$};
  1429. %\node (C0-1) at (6,0) {\large $C_0$};
  1430. \node (C0-2) at (3,0) {\large $C_0$};
  1431. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1432. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1433. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1434. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1435. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1436. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1437. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1438. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1439. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1440. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1441. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1442. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1443. \end{tikzpicture}
  1444. \caption{Overview of the passes for compiling $R_1$. }
  1445. \label{fig:R1-passes}
  1446. \end{figure}
  1447. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1448. passes in the form of a graph. Each pass is an edge and the
  1449. input/output language of each pass is a node in the graph. The output
  1450. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1451. are still in the $R_1$ language, but the output of the pass
  1452. \key{explicate-control} is in a different language $C_0$ that is
  1453. designed to make the order of evaluation explicit in its syntax, which
  1454. we introduce in the next section. The \key{select-instruction} pass
  1455. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1456. \key{patch-instructions} passes input and output variants of x86
  1457. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1458. \key{print-x86}, which converts from the abstract syntax of
  1459. $\text{x86}_0$ to the concrete syntax of x86.
  1460. In the next sections we discuss the $C_0$ language and the
  1461. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1462. remainder of this chapter gives hints regarding the implementation of
  1463. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1464. \subsection{The $C_0$ Intermediate Language}
  1465. The output of \key{explicate-control} is similar to the $C$
  1466. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1467. categories for expressions and statements, so we name it $C_0$. The
  1468. concrete syntax for $C_0$ is defined in
  1469. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1470. is defined in Figure~\ref{fig:c0-syntax}.
  1471. %
  1472. The $C_0$ language supports the same operators as $R_1$ but the
  1473. arguments of operators are restricted to atomic expressions (variables
  1474. and integers), thanks to the \key{remove-complex-opera*} pass. In the
  1475. literature this style of intermediate language is called
  1476. administrative normal form, or ANF for
  1477. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{Let}
  1478. expressions, $C_0$ has assignment statements which can be executed in
  1479. sequence using the \key{Seq} form. A sequence of statements always
  1480. ends with \key{Return}, a guarantee that is baked into the grammar
  1481. rules for the \itm{tail} non-terminal. The naming of this non-terminal
  1482. comes from the term \emph{tail position}, which refers to an
  1483. expression that is the last one to execute within a function. (A
  1484. expression in tail position may contain subexpressions, and those may
  1485. or may not be in tail position depending on the kind of expression.)
  1486. A $C_0$ program consists of a control-flow graph (represented as an
  1487. association list mapping labels to tails). This is more general than
  1488. necessary for the present chapter, as we do not yet need to introduce
  1489. \key{goto} for jumping to labels, but it saves us from having to
  1490. change the syntax of the program construct in
  1491. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1492. \key{start}, and the whole program is its tail.
  1493. %
  1494. The $\itm{info}$ field of the \key{Program} form, after the
  1495. \key{explicate-control} pass, contains a mapping from the symbol
  1496. \key{locals} to a list of variables, that is, a list of all the
  1497. variables used in the program. At the start of the program, these
  1498. variables are uninitialized; they become initialized on their first
  1499. assignment.
  1500. \begin{figure}[tbp]
  1501. \fbox{
  1502. \begin{minipage}{0.96\textwidth}
  1503. \[
  1504. \begin{array}{lcl}
  1505. \Atm &::=& \Int \mid \Var \\
  1506. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1507. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1508. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1509. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1510. \end{array}
  1511. \]
  1512. \end{minipage}
  1513. }
  1514. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1515. \label{fig:c0-concrete-syntax}
  1516. \end{figure}
  1517. \begin{figure}[tbp]
  1518. \fbox{
  1519. \begin{minipage}{0.96\textwidth}
  1520. \[
  1521. \begin{array}{lcl}
  1522. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1523. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1524. &\mid& \ADD{\Atm}{\Atm}\\
  1525. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1526. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1527. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1528. \end{array}
  1529. \]
  1530. \end{minipage}
  1531. }
  1532. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1533. \label{fig:c0-syntax}
  1534. \end{figure}
  1535. %% The \key{select-instructions} pass is optimistic in the sense that it
  1536. %% treats variables as if they were all mapped to registers. The
  1537. %% \key{select-instructions} pass generates a program that consists of
  1538. %% x86 instructions but that still uses variables, so it is an
  1539. %% intermediate language that is technically different than x86, which
  1540. %% explains the asterisks in the diagram above.
  1541. %% In this Chapter we shall take the easy road to implementing
  1542. %% \key{assign-homes} and simply map all variables to stack locations.
  1543. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1544. %% smarter approach in which we make a best-effort to map variables to
  1545. %% registers, resorting to the stack only when necessary.
  1546. %% Once variables have been assigned to their homes, we can finalize the
  1547. %% instruction selection by dealing with an idiosyncrasy of x86
  1548. %% assembly. Many x86 instructions have two arguments but only one of the
  1549. %% arguments may be a memory reference (and the stack is a part of
  1550. %% memory). Because some variables may get mapped to stack locations,
  1551. %% some of our generated instructions may violate this restriction. The
  1552. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1553. %% replacing every violating instruction with a short sequence of
  1554. %% instructions that use the \key{rax} register. Once we have implemented
  1555. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1556. %% need to patch instructions will be relatively rare.
  1557. \subsection{The dialects of x86}
  1558. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1559. the pass \key{select-instructions}. It extends $x86_0$ with an
  1560. unbounded number of program-scope variables and has looser rules
  1561. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1562. output of \key{print-x86}, is the concrete syntax for x86.
  1563. \section{Uniquify Variables}
  1564. \label{sec:uniquify-s0}
  1565. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1566. programs in which every \key{let} uses a unique variable name. For
  1567. example, the \code{uniquify} pass should translate the program on the
  1568. left into the program on the right. \\
  1569. \begin{tabular}{lll}
  1570. \begin{minipage}{0.4\textwidth}
  1571. \begin{lstlisting}
  1572. (let ([x 32])
  1573. (+ (let ([x 10]) x) x))
  1574. \end{lstlisting}
  1575. \end{minipage}
  1576. &
  1577. $\Rightarrow$
  1578. &
  1579. \begin{minipage}{0.4\textwidth}
  1580. \begin{lstlisting}
  1581. (let ([x.1 32])
  1582. (+ (let ([x.2 10]) x.2) x.1))
  1583. \end{lstlisting}
  1584. \end{minipage}
  1585. \end{tabular} \\
  1586. %
  1587. The following is another example translation, this time of a program
  1588. with a \key{let} nested inside the initializing expression of another
  1589. \key{let}.\\
  1590. \begin{tabular}{lll}
  1591. \begin{minipage}{0.4\textwidth}
  1592. \begin{lstlisting}
  1593. (let ([x (let ([x 4])
  1594. (+ x 1))])
  1595. (+ x 2))
  1596. \end{lstlisting}
  1597. \end{minipage}
  1598. &
  1599. $\Rightarrow$
  1600. &
  1601. \begin{minipage}{0.4\textwidth}
  1602. \begin{lstlisting}
  1603. (let ([x.2 (let ([x.1 4])
  1604. (+ x.1 1))])
  1605. (+ x.2 2))
  1606. \end{lstlisting}
  1607. \end{minipage}
  1608. \end{tabular}
  1609. We recommend implementing \code{uniquify} by creating a function named
  1610. \code{uniquify-exp} that is structurally recursive function and mostly
  1611. just copies the input program. However, when encountering a \key{let},
  1612. it should generate a unique name for the variable (the Racket function
  1613. \code{gensym} is handy for this) and associate the old name with the
  1614. new unique name in an association list. The \code{uniquify-exp}
  1615. function will need to access this association list when it gets to a
  1616. variable reference, so we add another parameter to \code{uniquify-exp}
  1617. for the association list. It is quite common for a compiler pass to
  1618. need a map to store extra information about variables. Such maps are
  1619. traditionally called \emph{symbol tables}.
  1620. The skeleton of the \code{uniquify-exp} function is shown in
  1621. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1622. convenient to partially apply it to a symbol table and then apply it
  1623. to different expressions, as in the last clause for primitive
  1624. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1625. is useful for applying a function to each element of a list to produce
  1626. a new list.
  1627. \begin{exercise}
  1628. \normalfont % I don't like the italics for exercises. -Jeremy
  1629. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1630. implement the clauses for variables and for the \key{let} form.
  1631. \end{exercise}
  1632. \begin{figure}[tbp]
  1633. \begin{lstlisting}
  1634. (define (uniquify-exp symtab)
  1635. (lambda (e)
  1636. (match e
  1637. [(Var x) ___]
  1638. [(Int n) (Int n)]
  1639. [(Let x e body) ___]
  1640. [(Prim op es)
  1641. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1642. )))
  1643. (define (uniquify p)
  1644. (match p
  1645. [(Program info e)
  1646. (Program info ((uniquify-exp '()) e))]
  1647. )))
  1648. \end{lstlisting}
  1649. \caption{Skeleton for the \key{uniquify} pass.}
  1650. \label{fig:uniquify-s0}
  1651. \end{figure}
  1652. \begin{exercise}
  1653. \normalfont % I don't like the italics for exercises. -Jeremy
  1654. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1655. and checking whether the output programs produce the same result as
  1656. the input programs. The $R_1$ programs should be designed to test the
  1657. most interesting parts of the \key{uniquify} pass, that is, the
  1658. programs should include \key{let} forms, variables, and variables
  1659. that overshadow each other. The five programs should be in a
  1660. subdirectory named \key{tests} and they should have the same file name
  1661. except for a different integer at the end of the name, followed by the
  1662. ending \key{.rkt}. Use the \key{interp-tests} function
  1663. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1664. your \key{uniquify} pass on the example programs. See the
  1665. \key{run-tests.rkt} script in the student support code for an example
  1666. of how to use \key{interp-tests}.
  1667. \end{exercise}
  1668. \section{Remove Complex Operands}
  1669. \label{sec:remove-complex-opera-r1}
  1670. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1671. $R_1$ programs in which the arguments of operations are atomic
  1672. expressions. Put another way, this pass removes complex operands,
  1673. such as the expression \code{(- 10)} in the program below. This is
  1674. accomplished by introducing a new \key{let}-bound variable, binding
  1675. the complex operand to the new variable, and then using the new
  1676. variable in place of the complex operand, as shown in the output of
  1677. \code{remove-complex-opera*} on the right.\\
  1678. \begin{tabular}{lll}
  1679. \begin{minipage}{0.4\textwidth}
  1680. % s0_19.rkt
  1681. \begin{lstlisting}
  1682. (+ 52 (- 10))
  1683. \end{lstlisting}
  1684. \end{minipage}
  1685. &
  1686. $\Rightarrow$
  1687. &
  1688. \begin{minipage}{0.4\textwidth}
  1689. \begin{lstlisting}
  1690. (let ([tmp.1 (- 10)])
  1691. (+ 52 tmp.1))
  1692. \end{lstlisting}
  1693. \end{minipage}
  1694. \end{tabular}
  1695. We recommend implementing this pass with two mutually recursive
  1696. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1697. \code{rco-atom} to subexpressions that need to become atomic and to
  1698. apply \code{rco-exp} to subexpressions that can be atomic or complex.
  1699. Both functions take an $R_1$ expression as input. The \code{rco-exp}
  1700. function returns an expression. The \code{rco-atom} function returns
  1701. two things: an atomic expression and association list mapping
  1702. temporary variables to complex subexpressions. You can return multiple
  1703. things from a function using Racket's \key{values} form and you can
  1704. receive multiple things from a function call using the
  1705. \key{define-values} form. If you are not familiar with these features,
  1706. review the Racket documentation. Also, the \key{for/lists} form is
  1707. useful for applying a function to each element of a list, in the case
  1708. where the function returns multiple values.
  1709. The following shows the output of \code{rco-atom} on the expression
  1710. \code{(- 10)} (using concrete syntax to be concise).
  1711. \begin{tabular}{lll}
  1712. \begin{minipage}{0.4\textwidth}
  1713. \begin{lstlisting}
  1714. (- 10)
  1715. \end{lstlisting}
  1716. \end{minipage}
  1717. &
  1718. $\Rightarrow$
  1719. &
  1720. \begin{minipage}{0.4\textwidth}
  1721. \begin{lstlisting}
  1722. tmp.1
  1723. ((tmp.1 . (- 10)))
  1724. \end{lstlisting}
  1725. \end{minipage}
  1726. \end{tabular}
  1727. Take special care of programs such as the next one that \key{let}-bind
  1728. variables with integers or other variables. You should leave them
  1729. unchanged, as shown in to the program on the right \\
  1730. \begin{tabular}{lll}
  1731. \begin{minipage}{0.4\textwidth}
  1732. % s0_20.rkt
  1733. \begin{lstlisting}
  1734. (let ([a 42])
  1735. (let ([b a])
  1736. b))
  1737. \end{lstlisting}
  1738. \end{minipage}
  1739. &
  1740. $\Rightarrow$
  1741. &
  1742. \begin{minipage}{0.4\textwidth}
  1743. \begin{lstlisting}
  1744. (let ([a 42])
  1745. (let ([b a])
  1746. b))
  1747. \end{lstlisting}
  1748. \end{minipage}
  1749. \end{tabular} \\
  1750. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1751. produce the following output.\\
  1752. \begin{minipage}{0.4\textwidth}
  1753. \begin{lstlisting}
  1754. (let ([tmp.1 42])
  1755. (let ([a tmp.1])
  1756. (let ([tmp.2 a])
  1757. (let ([b tmp.2])
  1758. b))))
  1759. \end{lstlisting}
  1760. \end{minipage}
  1761. \begin{exercise}
  1762. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1763. it on all of the example programs that you created to test the
  1764. \key{uniquify} pass and create three new example programs that are
  1765. designed to exercise the interesting code in the
  1766. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1767. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1768. your passes on the example programs.
  1769. \end{exercise}
  1770. \section{Explicate Control}
  1771. \label{sec:explicate-control-r1}
  1772. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1773. programs that make the order of execution explicit in their
  1774. syntax. For now this amounts to flattening \key{let} constructs into a
  1775. sequence of assignment statements. For example, consider the following
  1776. $R_1$ program.\\
  1777. % s0_11.rkt
  1778. \begin{minipage}{0.96\textwidth}
  1779. \begin{lstlisting}
  1780. (let ([y (let ([x 20])
  1781. (+ x (let ([x 22]) x)))])
  1782. y)
  1783. \end{lstlisting}
  1784. \end{minipage}\\
  1785. %
  1786. The output of the previous pass and of \code{explicate-control} is
  1787. shown below. Recall that the right-hand-side of a \key{let} executes
  1788. before its body, so the order of evaluation for this program is to
  1789. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1790. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1791. output of \code{explicate-control} makes this ordering explicit.\\
  1792. \begin{tabular}{lll}
  1793. \begin{minipage}{0.4\textwidth}
  1794. \begin{lstlisting}
  1795. (let ([y (let ([x.1 20])
  1796. (let ([x.2 22])
  1797. (+ x.1 x.2)))])
  1798. y)
  1799. \end{lstlisting}
  1800. \end{minipage}
  1801. &
  1802. $\Rightarrow$
  1803. &
  1804. \begin{minipage}{0.4\textwidth}
  1805. \begin{lstlisting}
  1806. locals: y x.1 x.2
  1807. start:
  1808. x.1 = 20;
  1809. x.2 = 22;
  1810. y = (+ x.1 x.2);
  1811. return y;
  1812. \end{lstlisting}
  1813. \end{minipage}
  1814. \end{tabular}
  1815. We recommend implementing \code{explicate-control} using two mutually
  1816. recursive functions: \code{explicate-tail} and
  1817. \code{explicate-assign}. The first function should be applied to
  1818. expressions in tail position whereas the second should be applied to
  1819. expressions that occur on the right-hand-side of a \key{let}. The
  1820. \code{explicate-tail} function takes an $R_1$ expression as input and
  1821. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1822. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1823. function takes an $R_1$ expression, the variable that it is to be
  1824. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1825. assignment (e.g., the code generated for the body of the \key{let}).
  1826. It returns a $\Tail$ and a list of variables. The top-level
  1827. \code{explicate-control} function should invoke \code{explicate-tail}
  1828. on the body of the \key{program} and then associate the \code{locals}
  1829. symbol with the resulting list of variables in the $\itm{info}$ field,
  1830. as in the above example.
  1831. \section{Select Instructions}
  1832. \label{sec:select-r1}
  1833. In the \code{select-instructions} pass we begin the work of
  1834. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1835. this pass is a variable of x86 that still uses variables, so we add an
  1836. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1837. syntax of Figure~\ref{fig:x86-ast-a}. We recommend implementing the
  1838. \code{select-instructions} in terms of three auxiliary functions, one
  1839. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1840. The cases for $\Atm$ are straightforward, variables stay
  1841. the same and integer constants are changed to immediates:
  1842. $\INT{n}$ changes to $\IMM{n}$.
  1843. Next we consider the cases for $\Stmt$, starting with arithmetic
  1844. operations. For example, in $C_0$ an addition operation can take the
  1845. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1846. need to use the \key{addq} instruction which does an in-place
  1847. update. So we must first move \code{10} to \code{x}. \\
  1848. \begin{tabular}{lll}
  1849. \begin{minipage}{0.4\textwidth}
  1850. \begin{lstlisting}
  1851. x = (+ 10 32);
  1852. \end{lstlisting}
  1853. \end{minipage}
  1854. &
  1855. $\Rightarrow$
  1856. &
  1857. \begin{minipage}{0.4\textwidth}
  1858. \begin{lstlisting}
  1859. movq $10, x
  1860. addq $32, x
  1861. \end{lstlisting}
  1862. \end{minipage}
  1863. \end{tabular} \\
  1864. %
  1865. There are cases that require special care to avoid generating
  1866. needlessly complicated code. If one of the arguments of the addition
  1867. is the same as the left-hand side of the assignment, then there is no
  1868. need for the extra move instruction. For example, the following
  1869. assignment statement can be translated into a single \key{addq}
  1870. instruction.\\
  1871. \begin{tabular}{lll}
  1872. \begin{minipage}{0.4\textwidth}
  1873. \begin{lstlisting}
  1874. x = (+ 10 x);
  1875. \end{lstlisting}
  1876. \end{minipage}
  1877. &
  1878. $\Rightarrow$
  1879. &
  1880. \begin{minipage}{0.4\textwidth}
  1881. \begin{lstlisting}
  1882. addq $10, x
  1883. \end{lstlisting}
  1884. \end{minipage}
  1885. \end{tabular} \\
  1886. The \key{read} operation does not have a direct counterpart in x86
  1887. assembly, so we have instead implemented this functionality in the C
  1888. language, with the function \code{read\_int} in the file
  1889. \code{runtime.c}. In general, we refer to all of the functionality in
  1890. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1891. for short. When compiling your generated x86 assembly code, you need
  1892. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1893. using \code{gcc} option \code{-c}) and link it into the
  1894. executable. For our purposes of code generation, all you need to do is
  1895. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1896. (for left-hand side) into a call to the \code{read\_int} function
  1897. followed by a move from \code{rax} to the left-hand side. The move
  1898. from \code{rax} is needed because the return value from
  1899. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1900. \begin{tabular}{lll}
  1901. \begin{minipage}{0.4\textwidth}
  1902. \begin{lstlisting}
  1903. |$\itm{lhs}$| = (read);
  1904. \end{lstlisting}
  1905. \end{minipage}
  1906. &
  1907. $\Rightarrow$
  1908. &
  1909. \begin{minipage}{0.4\textwidth}
  1910. \begin{lstlisting}
  1911. callq read_int
  1912. movq %rax, |$\itm{lhs}$|
  1913. \end{lstlisting}
  1914. \end{minipage}
  1915. \end{tabular} \\
  1916. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1917. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1918. assignment to the \key{rax} register followed by a jump to the
  1919. conclusion of the program (so the conclusion needs to be labeled).
  1920. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1921. recursively and append the resulting instructions.
  1922. \begin{exercise}
  1923. \normalfont
  1924. Implement the \key{select-instructions} pass and test it on all of the
  1925. example programs that you created for the previous passes and create
  1926. three new example programs that are designed to exercise all of the
  1927. interesting code in this pass. Use the \key{interp-tests} function
  1928. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1929. your passes on the example programs.
  1930. \end{exercise}
  1931. \section{Assign Homes}
  1932. \label{sec:assign-r1}
  1933. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1934. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1935. Thus, the \key{assign-homes} pass is responsible for placing all of
  1936. the program variables in registers or on the stack. For runtime
  1937. efficiency, it is better to place variables in registers, but as there
  1938. are only 16 registers, some programs must necessarily resort to
  1939. placing some variables on the stack. In this chapter we focus on the
  1940. mechanics of placing variables on the stack. We study an algorithm for
  1941. placing variables in registers in
  1942. Chapter~\ref{ch:register-allocation-r1}.
  1943. Consider again the following $R_1$ program.
  1944. % s0_20.rkt
  1945. \begin{lstlisting}
  1946. (let ([a 42])
  1947. (let ([b a])
  1948. b))
  1949. \end{lstlisting}
  1950. For reference, we repeat the output of \code{select-instructions} on
  1951. the left and show the output of \code{assign-homes} on the right.
  1952. Recall that \key{explicate-control} associated the list of
  1953. variables with the \code{locals} symbol in the program's $\itm{info}$
  1954. field, so \code{assign-homes} has convenient access to the them. In
  1955. this example, we assign variable \code{a} to stack location
  1956. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1957. \begin{tabular}{l}
  1958. \begin{minipage}{0.4\textwidth}
  1959. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1960. locals: a b
  1961. start:
  1962. movq $42, a
  1963. movq a, b
  1964. movq b, %rax
  1965. jmp conclusion
  1966. \end{lstlisting}
  1967. \end{minipage}
  1968. {$\Rightarrow$}
  1969. \begin{minipage}{0.4\textwidth}
  1970. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1971. stack-space: 16
  1972. start:
  1973. movq $42, -8(%rbp)
  1974. movq -8(%rbp), -16(%rbp)
  1975. movq -16(%rbp), %rax
  1976. jmp conclusion
  1977. \end{lstlisting}
  1978. \end{minipage}
  1979. \end{tabular} \\
  1980. In the process of assigning variables to stack locations, it is
  1981. convenient to compute and store the size of the frame (in bytes) in
  1982. the $\itm{info}$ field of the \key{Program} node, with the key
  1983. \code{stack-space}, which will be needed later to generate the
  1984. procedure conclusion. Some operating systems place restrictions on
  1985. the frame size. For example, Mac OS X requires the frame size to be a
  1986. multiple of 16 bytes.
  1987. \begin{exercise}
  1988. \normalfont Implement the \key{assign-homes} pass and test it on all
  1989. of the example programs that you created for the previous passes pass.
  1990. We recommend that \key{assign-homes} take an extra parameter that is a
  1991. mapping of variable names to homes (stack locations for now). Use the
  1992. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1993. \key{utilities.rkt} to test your passes on the example programs.
  1994. \end{exercise}
  1995. \section{Patch Instructions}
  1996. \label{sec:patch-s0}
  1997. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  1998. programs to $\text{x86}_0$ programs by making sure that each
  1999. instruction adheres to the restrictions of the x86 assembly language.
  2000. In particular, at most one argument of an instruction may be a memory
  2001. reference.
  2002. We return to the following running example.
  2003. % s0_20.rkt
  2004. \begin{lstlisting}
  2005. (let ([a 42])
  2006. (let ([b a])
  2007. b))
  2008. \end{lstlisting}
  2009. After the \key{assign-homes} pass, the above program has been translated to
  2010. the following. \\
  2011. \begin{minipage}{0.5\textwidth}
  2012. \begin{lstlisting}
  2013. stack-space: 16
  2014. start:
  2015. movq $42, -8(%rbp)
  2016. movq -8(%rbp), -16(%rbp)
  2017. movq -16(%rbp), %rax
  2018. jmp conclusion
  2019. \end{lstlisting}
  2020. \end{minipage}\\
  2021. The second \key{movq} instruction is problematic because both
  2022. arguments are stack locations. We suggest fixing this problem by
  2023. moving from the source location to the register \key{rax} and then
  2024. from \key{rax} to the destination location, as follows.
  2025. \begin{lstlisting}
  2026. movq -8(%rbp), %rax
  2027. movq %rax, -16(%rbp)
  2028. \end{lstlisting}
  2029. \begin{exercise}
  2030. \normalfont
  2031. Implement the \key{patch-instructions} pass and test it on all of the
  2032. example programs that you created for the previous passes and create
  2033. three new example programs that are designed to exercise all of the
  2034. interesting code in this pass. Use the \key{interp-tests} function
  2035. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2036. your passes on the example programs.
  2037. \end{exercise}
  2038. \section{Print x86}
  2039. \label{sec:print-x86}
  2040. The last step of the compiler from $R_1$ to x86 is to convert the
  2041. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  2042. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  2043. \key{format} and \key{string-append} functions are useful in this
  2044. regard. The main work that this step needs to perform is to create the
  2045. \key{main} function and the standard instructions for its prelude and
  2046. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2047. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2048. variables, so we suggest computing it in the \key{assign-homes} pass
  2049. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2050. of the \key{program} node.
  2051. %% Your compiled code should print the result of the program's execution
  2052. %% by using the \code{print\_int} function provided in
  2053. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2054. %% far, this final result should be stored in the \key{rax} register.
  2055. %% We'll talk more about how to perform function calls with arguments in
  2056. %% general later on, but for now, place the following after the compiled
  2057. %% code for the $R_1$ program but before the conclusion:
  2058. %% \begin{lstlisting}
  2059. %% movq %rax, %rdi
  2060. %% callq print_int
  2061. %% \end{lstlisting}
  2062. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2063. %% stores the first argument to be passed into \key{print\_int}.
  2064. If you want your program to run on Mac OS X, your code needs to
  2065. determine whether or not it is running on a Mac, and prefix
  2066. underscores to labels like \key{main}. You can determine the platform
  2067. with the Racket call \code{(system-type 'os)}, which returns
  2068. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2069. %% In addition to
  2070. %% placing underscores on \key{main}, you need to put them in front of
  2071. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2072. %% \_print\_int}).
  2073. \begin{exercise}
  2074. \normalfont Implement the \key{print-x86} pass and test it on all of
  2075. the example programs that you created for the previous passes. Use the
  2076. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2077. \key{utilities.rkt} to test your complete compiler on the example
  2078. programs. See the \key{run-tests.rkt} script in the student support
  2079. code for an example of how to use \key{compiler-tests}. Also, remember
  2080. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2081. \key{gcc}.
  2082. \end{exercise}
  2083. \section{Challenge: Partial Evaluator for $R_1$}
  2084. \label{sec:pe-R1}
  2085. This section describes optional challenge exercises that involve
  2086. adapting and improving the partial evaluator for $R_0$ that was
  2087. introduced in Section~\ref{sec:partial-evaluation}.
  2088. \begin{exercise}\label{ex:pe-R1}
  2089. \normalfont
  2090. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2091. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2092. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2093. and variables to the $R_0$ language, so you will need to add cases for
  2094. them in the \code{pe-exp} function. Also, note that the \key{program}
  2095. form changes slightly to include an $\itm{info}$ field. Once
  2096. complete, add the partial evaluation pass to the front of your
  2097. compiler and make sure that your compiler still passes all of the
  2098. tests.
  2099. \end{exercise}
  2100. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2101. \begin{exercise}
  2102. \normalfont
  2103. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2104. \code{pe-add} auxiliary functions with functions that know more about
  2105. arithmetic. For example, your partial evaluator should translate
  2106. \begin{lstlisting}
  2107. (+ 1 (+ (read) 1))
  2108. \end{lstlisting}
  2109. into
  2110. \begin{lstlisting}
  2111. (+ 2 (read))
  2112. \end{lstlisting}
  2113. To accomplish this, the \code{pe-exp} function should produce output
  2114. in the form of the $\itm{residual}$ non-terminal of the following
  2115. grammar.
  2116. \[
  2117. \begin{array}{lcl}
  2118. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2119. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2120. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2121. \end{array}
  2122. \]
  2123. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2124. that their inputs are $\itm{residual}$ expressions and they should
  2125. return $\itm{residual}$ expressions. Once the improvements are
  2126. complete, make sure that your compiler still passes all of the tests.
  2127. After all, fast code is useless if it produces incorrect results!
  2128. \end{exercise}
  2129. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2130. \chapter{Register Allocation}
  2131. \label{ch:register-allocation-r1}
  2132. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2133. make our life easier. However, we can improve the performance of the
  2134. generated code if we instead place some variables into registers. The
  2135. CPU can access a register in a single cycle, whereas accessing the
  2136. stack takes many cycles if the relevant data is in cache or many more
  2137. to access main memory if the data is not in cache.
  2138. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2139. serves as a running example. We show the source program and also the
  2140. output of instruction selection. At that point the program is almost
  2141. x86 assembly but not quite; it still contains variables instead of
  2142. stack locations or registers.
  2143. \begin{figure}
  2144. \begin{minipage}{0.45\textwidth}
  2145. Example $R_1$ program:
  2146. % s0_22.rkt
  2147. \begin{lstlisting}
  2148. (let ([v 1])
  2149. (let ([w 46])
  2150. (let ([x (+ v 7)])
  2151. (let ([y (+ 4 x)])
  2152. (let ([z (+ x w)])
  2153. (+ z (- y)))))))
  2154. \end{lstlisting}
  2155. \end{minipage}
  2156. \begin{minipage}{0.45\textwidth}
  2157. After instruction selection:
  2158. \begin{lstlisting}
  2159. locals: v w x y z t.1
  2160. start:
  2161. movq $1, v
  2162. movq $46, w
  2163. movq v, x
  2164. addq $7, x
  2165. movq x, y
  2166. addq $4, y
  2167. movq x, z
  2168. addq w, z
  2169. movq y, t.1
  2170. negq t.1
  2171. movq z, %rax
  2172. addq t.1, %rax
  2173. jmp conclusion
  2174. \end{lstlisting}
  2175. \end{minipage}
  2176. \caption{An example program for register allocation.}
  2177. \label{fig:reg-eg}
  2178. \end{figure}
  2179. The goal of register allocation is to fit as many variables into
  2180. registers as possible. A program sometimes has more variables than
  2181. registers, so we cannot map each variable to a different
  2182. register. Fortunately, it is common for different variables to be
  2183. needed during different periods of time during program execution, and
  2184. in such cases several variables can be mapped to the same register.
  2185. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2186. After the variable \code{x} is moved to \code{z} it is no longer
  2187. needed. Variable \code{y}, on the other hand, is used only after this
  2188. point, so \code{x} and \code{y} could share the same register. The
  2189. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2190. where a variable is needed. Once we have that information, we compute
  2191. which variables are needed at the same time, i.e., which ones
  2192. \emph{interfere}, and represent this relation as an undirected graph
  2193. whose vertices are variables and edges indicate when two variables
  2194. interfere with each other (Section~\ref{sec:build-interference}). We
  2195. then model register allocation as a graph coloring problem, which we
  2196. discuss in Section~\ref{sec:graph-coloring}.
  2197. In the event that we run out of registers despite these efforts, we
  2198. place the remaining variables on the stack, similar to what we did in
  2199. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2200. for assigning a variable to a stack location. The process of spilling
  2201. variables is handled as part of the graph coloring process described
  2202. in \ref{sec:graph-coloring}.
  2203. \section{Registers and Calling Conventions}
  2204. \label{sec:calling-conventions}
  2205. As we perform register allocation, we need to be aware of the
  2206. conventions that govern the way in which registers interact with
  2207. function calls, such as calls to the \code{read\_int} function. The
  2208. convention for x86 is that the caller is responsible for freeing up
  2209. some registers, the \emph{caller-saved registers}, prior to the
  2210. function call, and the callee is responsible for saving and restoring
  2211. some other registers, the \emph{callee-saved registers}, before and
  2212. after using them. The caller-saved registers are
  2213. \begin{lstlisting}
  2214. rax rdx rcx rsi rdi r8 r9 r10 r11
  2215. \end{lstlisting}
  2216. while the callee-saved registers are
  2217. \begin{lstlisting}
  2218. rsp rbp rbx r12 r13 r14 r15
  2219. \end{lstlisting}
  2220. Another way to think about this caller/callee convention is the
  2221. following. The caller should assume that all the caller-saved registers
  2222. get overwritten with arbitrary values by the callee. On the other
  2223. hand, the caller can safely assume that all the callee-saved registers
  2224. contain the same values after the call that they did before the call.
  2225. The callee can freely use any of the caller-saved registers. However,
  2226. if the callee wants to use a callee-saved register, the callee must
  2227. arrange to put the original value back in the register prior to
  2228. returning to the caller, which is usually accomplished by saving and
  2229. restoring the value from the stack.
  2230. \section{Liveness Analysis}
  2231. \label{sec:liveness-analysis-r1}
  2232. A variable is \emph{live} if the variable is used at some later point
  2233. in the program and there is not an intervening assignment to the
  2234. variable.
  2235. %
  2236. To understand the latter condition, consider the following code
  2237. fragment in which there are two writes to \code{b}. Are \code{a} and
  2238. \code{b} both live at the same time?
  2239. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2240. movq $5, a
  2241. movq $30, b
  2242. movq a, c
  2243. movq $10, b
  2244. addq b, c
  2245. \end{lstlisting}
  2246. The answer is no because the integer \code{30} written to \code{b} on
  2247. line 2 is never used. The variable \code{b} is read on line 5 and
  2248. there is an intervening write to \code{b} on line 4, so the read on
  2249. line 5 receives the value written on line 4, not line 2.
  2250. The live variables can be computed by traversing the instruction
  2251. sequence back to front (i.e., backwards in execution order). Let
  2252. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2253. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2254. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2255. variables before instruction $I_k$. The live variables after an
  2256. instruction are always the same as the live variables before the next
  2257. instruction.
  2258. \begin{equation} \label{eq:live-after-before-next}
  2259. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2260. \end{equation}
  2261. To start things off, there are no live variables after the last
  2262. instruction, so
  2263. \begin{equation}\label{eq:live-last-empty}
  2264. L_{\mathsf{after}}(n) = \emptyset
  2265. \end{equation}
  2266. We then apply the following rule repeatedly, traversing the
  2267. instruction sequence back to front.
  2268. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2269. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2270. \end{equation}
  2271. where $W(k)$ are the variables written to by instruction $I_k$ and
  2272. $R(k)$ are the variables read by instruction $I_k$.
  2273. Let us walk through the above example, applying these formulas
  2274. starting with the instruction on line 5. We collect the answers in the
  2275. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2276. instruction is $\emptyset$ because it is the last instruction
  2277. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2278. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2279. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2280. is
  2281. \[
  2282. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2283. \]
  2284. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2285. the live-before set from line 5 to be the live-after set for this
  2286. instruction (formula~\ref{eq:live-after-before-next}).
  2287. \[
  2288. L_{\mathsf{after}}(4) = \{ b, c \}
  2289. \]
  2290. This move instruction writes to $b$ and does not read from any
  2291. variables, so we have the following live-before set
  2292. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2293. \[
  2294. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2295. \]
  2296. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2297. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2298. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2299. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2300. variable that is not live and does not read from a variable.
  2301. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2302. because it writes to variable $a$.
  2303. \begin{center}
  2304. \begin{minipage}{0.45\textwidth}
  2305. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2306. movq $5, a
  2307. movq $30, b
  2308. movq a, c
  2309. movq $10, b
  2310. addq b, c
  2311. \end{lstlisting}
  2312. \end{minipage}
  2313. \vrule\hspace{10pt}
  2314. \begin{minipage}{0.45\textwidth}
  2315. \begin{align*}
  2316. L_{\mathsf{before}}(1)= \emptyset,
  2317. L_{\mathsf{after}}(1)= \{a\}\\
  2318. L_{\mathsf{before}}(2)= \{a\},
  2319. L_{\mathsf{after}}(2)= \{a\}\\
  2320. L_{\mathsf{before}}(3)= \{a\},
  2321. L_{\mathsf{after}}(2)= \{c\}\\
  2322. L_{\mathsf{before}}(4)= \{c\},
  2323. L_{\mathsf{after}}(4)= \{b,c\}\\
  2324. L_{\mathsf{before}}(5)= \{b,c\},
  2325. L_{\mathsf{after}}(5)= \emptyset
  2326. \end{align*}
  2327. \end{minipage}
  2328. \end{center}
  2329. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2330. for the running example program, with each instruction aligned with
  2331. its $L_{\mathtt{after}}$ set to make the figure easy to read.
  2332. \begin{figure}[tbp]
  2333. \hspace{20pt}
  2334. \begin{minipage}{0.45\textwidth}
  2335. \begin{lstlisting}[numbers=left]
  2336. movq $1, v
  2337. movq $46, w
  2338. movq v, x
  2339. addq $7, x
  2340. movq x, y
  2341. addq $4, y
  2342. movq x, z
  2343. addq w, z
  2344. movq y, t.1
  2345. negq t.1)
  2346. movq z, %rax
  2347. addq t.1, %rax
  2348. jmp conclusion
  2349. \end{lstlisting}
  2350. \end{minipage}
  2351. \vrule\hspace{10pt}
  2352. \begin{minipage}{0.45\textwidth}
  2353. \begin{lstlisting}
  2354. |$\{\}$|
  2355. |$\{v \}$|
  2356. |$\{v,w\}$|
  2357. |$\{w,x\}$|
  2358. |$\{w,x\}$|
  2359. |$\{w,x,y\}$|
  2360. |$\{w,x,y\}$|
  2361. |$\{w,y,z\}$|
  2362. |$\{y,z\}$|
  2363. |$\{z,t.1\}$|
  2364. |$\{z,t.1\}$|
  2365. |$\{t.1\}$|
  2366. |$\{\}$|
  2367. |$\{\}$|
  2368. \end{lstlisting}
  2369. \end{minipage}
  2370. \caption{The running example annotated with live-after sets.}
  2371. \label{fig:live-eg}
  2372. \end{figure}
  2373. \begin{exercise}\normalfont
  2374. Implement the compiler pass named \code{uncover-live} that computes
  2375. the live-after sets. We recommend storing the live-after sets (a list
  2376. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2377. structure.
  2378. %
  2379. We recommend organizing your code to use a helper function that takes
  2380. a list of instructions and an initial live-after set (typically empty)
  2381. and returns the list of live-after sets.
  2382. %
  2383. We recommend creating helper functions to 1) compute the set of
  2384. variables that appear in an argument (of an instruction), 2) compute
  2385. the variables read by an instruction which corresponds to the $R$
  2386. function discussed above, and 3) the variables written by an
  2387. instruction which corresponds to $W$.
  2388. \end{exercise}
  2389. \section{Building the Interference Graph}
  2390. \label{sec:build-interference}
  2391. Based on the liveness analysis, we know where each variable is needed.
  2392. However, during register allocation, we need to answer questions of
  2393. the specific form: are variables $u$ and $v$ live at the same time?
  2394. (And therefore cannot be assigned to the same register.) To make this
  2395. question easier to answer, we create an explicit data structure, an
  2396. \emph{interference graph}. An interference graph is an undirected
  2397. graph that has an edge between two variables if they are live at the
  2398. same time, that is, if they interfere with each other.
  2399. The most obvious way to compute the interference graph is to look at
  2400. the set of live variables between each statement in the program and
  2401. add an edge to the graph for every pair of variables in the same set.
  2402. This approach is less than ideal for two reasons. First, it can be
  2403. expensive because it takes $O(n^2)$ time to look at every pair in a
  2404. set of $n$ live variables. Second, there is a special case in which
  2405. two variables that are live at the same time do not actually interfere
  2406. with each other: when they both contain the same value because we have
  2407. assigned one to the other.
  2408. A better way to compute the interference graph is to focus on the
  2409. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2410. instruction to overwrite something in a live variable. So for each
  2411. instruction, we create an edge between the variable being written to
  2412. and all the \emph{other} live variables. (One should not create self
  2413. edges.) For a \key{callq} instruction, think of all caller-saved
  2414. registers as being written to, so an edge must be added between every
  2415. live variable and every caller-saved register. For \key{movq}, we deal
  2416. with the above-mentioned special case by not adding an edge between a
  2417. live variable $v$ and destination $d$ if $v$ matches the source of the
  2418. move. So we have the following three rules.
  2419. \begin{enumerate}
  2420. \item If instruction $I_k$ is an arithmetic instruction such as
  2421. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2422. L_{\mathsf{after}}(k)$ unless $v = d$.
  2423. \item If instruction $I_k$ is of the form \key{callq}
  2424. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2425. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2426. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2427. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2428. d$ or $v = s$.
  2429. \end{enumerate}
  2430. \margincomment{JM: I think you could give examples of each one of these
  2431. using the example program and use those to help explain why these
  2432. rules are correct.\\
  2433. JS: Agreed.}
  2434. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2435. the following interference for the instruction at the specified line
  2436. number.
  2437. \begin{quote}
  2438. Line 2: no interference,\\
  2439. Line 3: $w$ interferes with $v$,\\
  2440. Line 4: $x$ interferes with $w$,\\
  2441. Line 5: $x$ interferes with $w$,\\
  2442. Line 6: $y$ interferes with $w$,\\
  2443. Line 7: $y$ interferes with $w$ and $x$,\\
  2444. Line 8: $z$ interferes with $w$ and $y$,\\
  2445. Line 9: $z$ interferes with $y$, \\
  2446. Line 10: $t.1$ interferes with $z$, \\
  2447. Line 11: $t.1$ interferes with $z$, \\
  2448. Line 12: no interference, \\
  2449. Line 13: no interference. \\
  2450. Line 14: no interference.
  2451. \end{quote}
  2452. The resulting interference graph is shown in
  2453. Figure~\ref{fig:interfere}.
  2454. \begin{figure}[tbp]
  2455. \large
  2456. \[
  2457. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2458. \node (v) at (0,0) {$v$};
  2459. \node (w) at (2,0) {$w$};
  2460. \node (x) at (4,0) {$x$};
  2461. \node (t1) at (6,-2) {$t.1$};
  2462. \node (y) at (2,-2) {$y$};
  2463. \node (z) at (4,-2) {$z$};
  2464. \draw (v) to (w);
  2465. \foreach \i in {w,x,y}
  2466. {
  2467. \foreach \j in {w,x,y}
  2468. {
  2469. \draw (\i) to (\j);
  2470. }
  2471. }
  2472. \draw (z) to (w);
  2473. \draw (z) to (y);
  2474. \draw (t1) to (z);
  2475. \end{tikzpicture}
  2476. \]
  2477. \caption{The interference graph of the example program.}
  2478. \label{fig:interfere}
  2479. \end{figure}
  2480. %% Our next concern is to choose a data structure for representing the
  2481. %% interference graph. There are many choices for how to represent a
  2482. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2483. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2484. %% data structure is to study the algorithm that uses the data structure,
  2485. %% determine what operations need to be performed, and then choose the
  2486. %% data structure that provide the most efficient implementations of
  2487. %% those operations. Often times the choice of data structure can have an
  2488. %% effect on the time complexity of the algorithm, as it does here. If
  2489. %% you skim the next section, you will see that the register allocation
  2490. %% algorithm needs to ask the graph for all of its vertices and, given a
  2491. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2492. %% correct choice of graph representation is that of an adjacency
  2493. %% list. There are helper functions in \code{utilities.rkt} for
  2494. %% representing graphs using the adjacency list representation:
  2495. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2496. %% (Appendix~\ref{appendix:utilities}).
  2497. %% %
  2498. %% \margincomment{\footnotesize To do: change to use the
  2499. %% Racket graph library. \\ --Jeremy}
  2500. %% %
  2501. %% In particular, those functions use a hash table to map each vertex to
  2502. %% the set of adjacent vertices, and the sets are represented using
  2503. %% Racket's \key{set}, which is also a hash table.
  2504. \begin{exercise}\normalfont
  2505. Implement the compiler pass named \code{build-interference} according
  2506. to the algorithm suggested above. We recommend using the Racket
  2507. \code{graph} package to create and inspect the interference graph.
  2508. The output graph of this pass should be stored in the $\itm{info}$
  2509. field of the program, under the key \code{conflicts}.
  2510. \end{exercise}
  2511. \section{Graph Coloring via Sudoku}
  2512. \label{sec:graph-coloring}
  2513. We come to the main event, mapping variables to registers (or to stack
  2514. locations in the event that we run out of registers). We need to make
  2515. sure that two variables do not get mapped to the same register if the
  2516. two variables interfere with each other. Thinking about the
  2517. interference graph, this means that adjacent vertices must be mapped
  2518. to different registers. If we think of registers as colors, the
  2519. register allocation problem becomes the widely-studied graph coloring
  2520. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2521. The reader may be more familiar with the graph coloring problem than he
  2522. or she realizes; the popular game of Sudoku is an instance of the
  2523. graph coloring problem. The following describes how to build a graph
  2524. out of an initial Sudoku board.
  2525. \begin{itemize}
  2526. \item There is one vertex in the graph for each Sudoku square.
  2527. \item There is an edge between two vertices if the corresponding squares
  2528. are in the same row, in the same column, or if the squares are in
  2529. the same $3\times 3$ region.
  2530. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2531. \item Based on the initial assignment of numbers to squares in the
  2532. Sudoku board, assign the corresponding colors to the corresponding
  2533. vertices in the graph.
  2534. \end{itemize}
  2535. If you can color the remaining vertices in the graph with the nine
  2536. colors, then you have also solved the corresponding game of Sudoku.
  2537. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2538. the corresponding graph with colored vertices. We map the Sudoku
  2539. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2540. sampling of the vertices (the colored ones) because showing edges for
  2541. all of the vertices would make the graph unreadable.
  2542. \begin{figure}[tbp]
  2543. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2544. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2545. \caption{A Sudoku game board and the corresponding colored graph.}
  2546. \label{fig:sudoku-graph}
  2547. \end{figure}
  2548. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2549. strategies to come up with an algorithm for allocating registers. For
  2550. example, one of the basic techniques for Sudoku is called Pencil
  2551. Marks. The idea is to use a process of elimination to determine what
  2552. numbers no longer make sense for a square and write down those
  2553. numbers in the square (writing very small). For example, if the number
  2554. $1$ is assigned to a square, then by process of elimination, you can
  2555. write the pencil mark $1$ in all the squares in the same row, column,
  2556. and region. Many Sudoku computer games provide automatic support for
  2557. Pencil Marks.
  2558. %
  2559. The Pencil Marks technique corresponds to the notion of
  2560. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2561. vertex, in Sudoku terms, is the set of numbers that are no longer
  2562. available. In graph terminology, we have the following definition:
  2563. \begin{equation*}
  2564. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2565. \text{ and } \mathrm{color}(v) = c \}
  2566. \end{equation*}
  2567. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2568. edge with $u$.
  2569. Using the Pencil Marks technique leads to a simple strategy for
  2570. filling in numbers: if there is a square with only one possible number
  2571. left, then choose that number! But what if there are no squares with
  2572. only one possibility left? One brute-force approach is to try them
  2573. all: choose the first and if it ultimately leads to a solution,
  2574. great. If not, backtrack and choose the next possibility. One good
  2575. thing about Pencil Marks is that it reduces the degree of branching in
  2576. the search tree. Nevertheless, backtracking can be horribly time
  2577. consuming. One way to reduce the amount of backtracking is to use the
  2578. most-constrained-first heuristic. That is, when choosing a square,
  2579. always choose one with the fewest possibilities left (the vertex with
  2580. the highest saturation). The idea is that choosing highly constrained
  2581. squares earlier rather than later is better because later on there may
  2582. not be any possibilities left for those squares.
  2583. In some sense, register allocation is easier than Sudoku because the
  2584. register allocator can choose to map variables to stack locations when
  2585. the registers run out. Thus, it makes sense to drop backtracking in
  2586. favor of greedy search, that is, make the best choice at the time and
  2587. keep going. We still wish to minimize the number of colors needed, so
  2588. keeping the most-constrained-first heuristic is a good idea.
  2589. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2590. algorithm for register allocation based on saturation and the
  2591. most-constrained-first heuristic. It is roughly equivalent to the
  2592. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2593. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2594. Sudoku, the algorithm represents colors with integers. The first $k$
  2595. colors corresponding to the $k$ registers in a given machine and the
  2596. rest of the integers corresponding to stack locations.
  2597. \begin{figure}[btp]
  2598. \centering
  2599. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2600. Algorithm: DSATUR
  2601. Input: a graph |$G$|
  2602. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2603. |$W \gets \mathit{vertices}(G)$|
  2604. while |$W \neq \emptyset$| do
  2605. pick a vertex |$u$| from |$W$| with the highest saturation,
  2606. breaking ties randomly
  2607. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2608. |$\mathrm{color}[u] \gets c$|
  2609. |$W \gets W - \{u\}$|
  2610. \end{lstlisting}
  2611. \caption{The saturation-based greedy graph coloring algorithm.}
  2612. \label{fig:satur-algo}
  2613. \end{figure}
  2614. With this algorithm in hand, let us return to the running example and
  2615. consider how to color the interference graph in
  2616. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2617. colored and they are unsaturated, so we annotate each of them with a
  2618. dash for their color and an empty set for the saturation.
  2619. \[
  2620. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2621. \node (v) at (0,0) {$v:-,\{\}$};
  2622. \node (w) at (3,0) {$w:-,\{\}$};
  2623. \node (x) at (6,0) {$x:-,\{\}$};
  2624. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2625. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2626. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2627. \draw (v) to (w);
  2628. \foreach \i in {w,x,y}
  2629. {
  2630. \foreach \j in {w,x,y}
  2631. {
  2632. \draw (\i) to (\j);
  2633. }
  2634. }
  2635. \draw (z) to (w);
  2636. \draw (z) to (y);
  2637. \draw (t1) to (z);
  2638. \end{tikzpicture}
  2639. \]
  2640. The algorithm says to select a maximally saturated vertex and color it
  2641. $0$. In this case we have a 7-way tie, so we arbitrarily pick
  2642. $t.1$. We then mark color $0$ as no longer available for $z$ because
  2643. it interferes with $t.1$.
  2644. \[
  2645. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2646. \node (v) at (0,0) {$v:-,\{\}$};
  2647. \node (w) at (3,0) {$w:-,\{\}$};
  2648. \node (x) at (6,0) {$x:-,\{\}$};
  2649. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2650. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2651. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2652. \draw (v) to (w);
  2653. \foreach \i in {w,x,y}
  2654. {
  2655. \foreach \j in {w,x,y}
  2656. {
  2657. \draw (\i) to (\j);
  2658. }
  2659. }
  2660. \draw (z) to (w);
  2661. \draw (z) to (y);
  2662. \draw (t1) to (z);
  2663. \end{tikzpicture}
  2664. \]
  2665. Next we repeat the process, selecting another maximally saturated
  2666. vertex, which is $z$, and color it with the first available number,
  2667. which is $1$.
  2668. \[
  2669. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2670. \node (v) at (0,0) {$v:-,\{\}$};
  2671. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2672. \node (x) at (6,0) {$x:-,\{\}$};
  2673. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2674. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2675. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2676. \draw (t1) to (z);
  2677. \draw (v) to (w);
  2678. \foreach \i in {w,x,y}
  2679. {
  2680. \foreach \j in {w,x,y}
  2681. {
  2682. \draw (\i) to (\j);
  2683. }
  2684. }
  2685. \draw (z) to (w);
  2686. \draw (z) to (y);
  2687. \end{tikzpicture}
  2688. \]
  2689. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2690. first available color, which is $0$.
  2691. \[
  2692. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2693. \node (v) at (0,0) {$v:-,\{\}$};
  2694. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2695. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2696. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2697. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2698. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2699. \draw (t1) to (z);
  2700. \draw (v) to (w);
  2701. \foreach \i in {w,x,y}
  2702. {
  2703. \foreach \j in {w,x,y}
  2704. {
  2705. \draw (\i) to (\j);
  2706. }
  2707. }
  2708. \draw (z) to (w);
  2709. \draw (z) to (y);
  2710. \end{tikzpicture}
  2711. \]
  2712. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2713. We cannot choose $0$ or $1$ because those numbers are in $w$'s
  2714. saturation set. Indeed, $w$ interferes with $y$ and $z$, whose colors
  2715. are $0$ and $1$ respectively.
  2716. \[
  2717. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2718. \node (v) at (0,0) {$v:-,\{2\}$};
  2719. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2720. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2721. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2722. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2723. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2724. \draw (t1) to (z);
  2725. \draw (v) to (w);
  2726. \foreach \i in {w,x,y}
  2727. {
  2728. \foreach \j in {w,x,y}
  2729. {
  2730. \draw (\i) to (\j);
  2731. }
  2732. }
  2733. \draw (z) to (w);
  2734. \draw (z) to (y);
  2735. \end{tikzpicture}
  2736. \]
  2737. Now $x$ has the highest saturation, so we color it $1$.
  2738. \[
  2739. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2740. \node (v) at (0,0) {$v:-,\{2\}$};
  2741. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2742. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2743. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2744. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2745. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2746. \draw (t1) to (z);
  2747. \draw (v) to (w);
  2748. \foreach \i in {w,x,y}
  2749. {
  2750. \foreach \j in {w,x,y}
  2751. {
  2752. \draw (\i) to (\j);
  2753. }
  2754. }
  2755. \draw (z) to (w);
  2756. \draw (z) to (y);
  2757. \end{tikzpicture}
  2758. \]
  2759. In the last step of the algorithm, we color $v$ with $0$.
  2760. \[
  2761. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2762. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2763. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2764. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2765. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2766. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2767. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2768. \draw (t1) to (z);
  2769. \draw (v) to (w);
  2770. \foreach \i in {w,x,y}
  2771. {
  2772. \foreach \j in {w,x,y}
  2773. {
  2774. \draw (\i) to (\j);
  2775. }
  2776. }
  2777. \draw (z) to (w);
  2778. \draw (z) to (y);
  2779. \end{tikzpicture}
  2780. \]
  2781. With the coloring complete, we finalize the assignment of variables to
  2782. registers and stack locations. Recall that if we have $k$ registers,
  2783. we map the first $k$ colors to registers and the rest to stack
  2784. locations. Suppose for the moment that we have just one register to
  2785. use for register allocation, \key{rcx}. Then the following is the
  2786. mapping of colors to registers and stack allocations.
  2787. \[
  2788. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2789. \]
  2790. Putting this mapping together with the above coloring of the
  2791. variables, we arrive at the following assignment of variables to
  2792. registers and stack locations.
  2793. \begin{gather*}
  2794. \{ v \mapsto \key{\%rcx}, \,
  2795. w \mapsto \key{-16(\%rbp)}, \,
  2796. x \mapsto \key{-8(\%rbp)}, \\
  2797. y \mapsto \key{\%rcx}, \,
  2798. z\mapsto \key{-8(\%rbp)},
  2799. t.1\mapsto \key{\%rcx} \}
  2800. \end{gather*}
  2801. Applying this assignment to our running example, on the left, yields
  2802. the program on the right.
  2803. % why frame size of 32? -JGS
  2804. \begin{center}
  2805. \begin{minipage}{0.3\textwidth}
  2806. \begin{lstlisting}
  2807. movq $1, v
  2808. movq $46, w
  2809. movq v, x
  2810. addq $7, x
  2811. movq x, y
  2812. addq $4, y
  2813. movq x, z
  2814. addq w, z
  2815. movq y, t.1
  2816. negq t.1
  2817. movq z, %rax
  2818. addq t.1, %rax
  2819. jmp conclusion
  2820. \end{lstlisting}
  2821. \end{minipage}
  2822. $\Rightarrow\qquad$
  2823. \begin{minipage}{0.45\textwidth}
  2824. \begin{lstlisting}
  2825. movq $1, %rcx
  2826. movq $46, -16(%rbp)
  2827. movq %rcx, -8(%rbp)
  2828. addq $7, -8(%rbp)
  2829. movq -8(%rbp), %rcx
  2830. addq $4, %rcx
  2831. movq -8(%rbp), -8(%rbp)
  2832. addq -16(%rbp), -8(%rbp)
  2833. movq %rcx, %rcx
  2834. negq %rcx
  2835. movq -8(%rbp), %rax
  2836. addq %rcx, %rax
  2837. jmp conclusion
  2838. \end{lstlisting}
  2839. \end{minipage}
  2840. \end{center}
  2841. The resulting program is almost an x86 program. The remaining step is
  2842. the patch instructions pass. In this example, the trivial move of
  2843. \code{-8(\%rbp)} to itself is deleted and the addition of
  2844. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2845. \code{rax} as follows.
  2846. \begin{lstlisting}
  2847. movq -16(%rbp), %rax
  2848. addq %rax, -8(%rbp)
  2849. \end{lstlisting}
  2850. An overview of all of the passes involved in register allocation is
  2851. shown in Figure~\ref{fig:reg-alloc-passes}.
  2852. \begin{figure}[tbp]
  2853. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2854. \node (R1) at (0,2) {\large $R_1$};
  2855. \node (R1-2) at (3,2) {\large $R_1$};
  2856. \node (R1-3) at (6,2) {\large $R_1$};
  2857. \node (C0-1) at (6,0) {\large $C_0$};
  2858. \node (C0-2) at (3,0) {\large $C_0$};
  2859. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2860. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2861. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2862. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2863. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2864. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2865. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2866. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2867. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2868. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2869. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2870. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2871. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2872. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2873. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2874. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2875. \end{tikzpicture}
  2876. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2877. \label{fig:reg-alloc-passes}
  2878. \end{figure}
  2879. \begin{exercise}\normalfont
  2880. Implement the pass \code{allocate-registers}, which should come
  2881. after the \code{build-interference} pass. The three new passes,
  2882. \code{uncover-live}, \code{build-interference}, and
  2883. \code{allocate-registers} replace the \code{assign-homes} pass of
  2884. Section~\ref{sec:assign-r1}.
  2885. We recommend that you create a helper function named
  2886. \code{color-graph} that takes an interference graph and a list of
  2887. all the variables in the program. This function should return a
  2888. mapping of variables to their colors (represented as natural
  2889. numbers). By creating this helper function, you will be able to
  2890. reuse it in Chapter~\ref{ch:functions} when you add support for
  2891. functions.
  2892. Once you have obtained the coloring from \code{color-graph}, you can
  2893. assign the variables to registers or stack locations and then reuse
  2894. code from the \code{assign-homes} pass from
  2895. Section~\ref{sec:assign-r1} to replace the variables with their
  2896. assigned location.
  2897. Test your updated compiler by creating new example programs that
  2898. exercise all of the register allocation algorithm, such as forcing
  2899. variables to be spilled to the stack.
  2900. \end{exercise}
  2901. \section{Print x86 and Conventions for Registers}
  2902. \label{sec:print-x86-reg-alloc}
  2903. Recall that the \code{print-x86} pass generates the prelude and
  2904. conclusion instructions for the \code{main} function.
  2905. %
  2906. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2907. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2908. reason for this is that our \code{main} function must adhere to the
  2909. x86 calling conventions that we described in
  2910. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2911. function needs to restore (in the conclusion) any callee-saved
  2912. registers that get used during register allocation. The simplest
  2913. approach is to save and restore all of the callee-saved registers. The
  2914. more efficient approach is to keep track of which callee-saved
  2915. registers were used and only save and restore them. Either way, make
  2916. sure to take this use of stack space into account when you are
  2917. calculating the size of the frame. Also, don't forget that the size of
  2918. the frame needs to be a multiple of 16 bytes.
  2919. \section{Challenge: Move Biasing}
  2920. \label{sec:move-biasing}
  2921. This section describes an optional enhancement to register allocation
  2922. for those students who are looking for an extra challenge or who have
  2923. a deeper interest in register allocation.
  2924. We return to the running example, but we remove the supposition that
  2925. we only have one register to use. So we have the following mapping of
  2926. color numbers to registers.
  2927. \[
  2928. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  2929. \]
  2930. Using the same assignment of variables to color numbers that was
  2931. produced by the register allocator described in the last section, we
  2932. get the following program.
  2933. \begin{minipage}{0.3\textwidth}
  2934. \begin{lstlisting}
  2935. movq $1, v
  2936. movq $46, w
  2937. movq v, x
  2938. addq $7, x
  2939. movq x, y
  2940. addq $4, y
  2941. movq x, z
  2942. addq w, z
  2943. movq y, t.1
  2944. negq t.1
  2945. movq z, %rax
  2946. addq t.1, %rax
  2947. jmp conclusion
  2948. \end{lstlisting}
  2949. \end{minipage}
  2950. $\Rightarrow\qquad$
  2951. \begin{minipage}{0.45\textwidth}
  2952. \begin{lstlisting}
  2953. movq $1, %rbx
  2954. movq $46, %rdx
  2955. movq %rbx, %rcx
  2956. addq $7, %rcx
  2957. movq %rcx, %rbx
  2958. addq $4, %rbx
  2959. movq %rcx, %rcx
  2960. addq %rdx, %rcx
  2961. movq %rbx, %rbx
  2962. negq %rbx
  2963. movq %rcx, %rax
  2964. addq %rbx, %rax
  2965. jmp conclusion
  2966. \end{lstlisting}
  2967. \end{minipage}
  2968. While this allocation is quite good, we could do better. For example,
  2969. the variables \key{v} and \key{x} ended up in different registers, but
  2970. if they had been placed in the same register, then the move from
  2971. \key{v} to \key{x} could be removed.
  2972. We say that two variables $p$ and $q$ are \emph{move related} if they
  2973. participate together in a \key{movq} instruction, that is, \key{movq}
  2974. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  2975. allocator chooses a color for a variable, it should prefer a color
  2976. that has already been used for a move-related variable (assuming that
  2977. they do not interfere). Of course, this preference should not override
  2978. the preference for registers over stack locations. This preference
  2979. should be used as a tie breaker when choosing between registers or
  2980. when choosing between stack locations.
  2981. We recommend representing the move relationships in a graph, similar
  2982. to how we represented interference. The following is the \emph{move
  2983. graph} for our running example.
  2984. \[
  2985. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2986. \node (v) at (0,0) {$v$};
  2987. \node (w) at (3,0) {$w$};
  2988. \node (x) at (6,0) {$x$};
  2989. \node (y) at (3,-1.5) {$y$};
  2990. \node (z) at (6,-1.5) {$z$};
  2991. \node (t1) at (9,-1.5) {$t.1$};
  2992. \draw[bend left=15] (t1) to (y);
  2993. \draw[bend left=15] (v) to (x);
  2994. \draw (x) to (y);
  2995. \draw (x) to (z);
  2996. \end{tikzpicture}
  2997. \]
  2998. Now we replay the graph coloring, pausing to see the coloring of $x$
  2999. and $v$. So we have the following coloring and the most saturated
  3000. vertex is $x$.
  3001. \[
  3002. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3003. \node (v) at (0,0) {$v:-,\{2\}$};
  3004. \node (w) at (3,0) {$w:2,\{0,1\}$};
  3005. \node (x) at (6,0) {$x:-,\{0,2\}$};
  3006. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3007. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3008. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3009. \draw (t1) to (z);
  3010. \draw (v) to (w);
  3011. \foreach \i in {w,x,y}
  3012. {
  3013. \foreach \j in {w,x,y}
  3014. {
  3015. \draw (\i) to (\j);
  3016. }
  3017. }
  3018. \draw (z) to (w);
  3019. \draw (z) to (y);
  3020. \end{tikzpicture}
  3021. \]
  3022. Last time we chose to color $x$ with $1$,
  3023. %
  3024. which so happens to be the color of $z$, and $x$ is move related to
  3025. $z$. This was lucky, and if the program had been a little different,
  3026. and say $z$ had been already assigned to $2$, then $x$ would still get
  3027. $1$ and our luck would have run out. With move biasing, we use the
  3028. fact that $x$ and $z$ are move related to influence the choice of
  3029. color for $x$, in this case choosing $1$ because that is the color of
  3030. $z$.
  3031. \[
  3032. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3033. \node (v) at (0,0) {$v:-,\{2\}$};
  3034. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3035. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  3036. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  3037. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3038. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3039. \draw (t1) to (z);
  3040. \draw (v) to (w);
  3041. \foreach \i in {w,x,y}
  3042. {
  3043. \foreach \j in {w,x,y}
  3044. {
  3045. \draw (\i) to (\j);
  3046. }
  3047. }
  3048. \draw (z) to (w);
  3049. \draw (z) to (y);
  3050. \end{tikzpicture}
  3051. \]
  3052. Next we consider coloring the variable $v$. We need to avoid choosing
  3053. $2$ because of the interference with $w$. Last time we chose the color
  3054. $0$ because it was the lowest, but this time we know that $v$ is move
  3055. related to $x$, so we choose the color $1$.
  3056. \[
  3057. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3058. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  3059. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3060. \node (x) at (6,0) {$x:1,\{0,2\}$};
  3061. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3062. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3063. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3064. \draw (t1) to (z);
  3065. \draw (v) to (w);
  3066. \foreach \i in {w,x,y}
  3067. {
  3068. \foreach \j in {w,x,y}
  3069. {
  3070. \draw (\i) to (\j);
  3071. }
  3072. }
  3073. \draw (z) to (w);
  3074. \draw (z) to (y);
  3075. \end{tikzpicture}
  3076. \]
  3077. We apply this register assignment to the running example, on the left,
  3078. to obtain the code on right.
  3079. \begin{minipage}{0.3\textwidth}
  3080. \begin{lstlisting}
  3081. movq $1, v
  3082. movq $46, w
  3083. movq v, x
  3084. addq $7, x
  3085. movq x, y
  3086. addq $4, y
  3087. movq x, z
  3088. addq w, z
  3089. movq y, t.1
  3090. negq t.1
  3091. movq z, %rax
  3092. addq t.1, %rax
  3093. jmp conclusion
  3094. \end{lstlisting}
  3095. \end{minipage}
  3096. $\Rightarrow\qquad$
  3097. \begin{minipage}{0.45\textwidth}
  3098. \begin{lstlisting}
  3099. movq $1, %rcx
  3100. movq $46, %rbx
  3101. movq %rcx, %rcx
  3102. addq $7, %rcx
  3103. movq %rcx, %rdx
  3104. addq $4, %rdx
  3105. movq %rcx, %rcx
  3106. addq %rbx, %rcx
  3107. movq %rdx, %rbx
  3108. negq %rbx
  3109. movq %rcx, %rax
  3110. addq %rbx, %rax
  3111. jmp conclusion
  3112. \end{lstlisting}
  3113. \end{minipage}
  3114. The \code{patch-instructions} then removes the trivial moves from
  3115. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3116. result.
  3117. \begin{minipage}{0.45\textwidth}
  3118. \begin{lstlisting}
  3119. movq $1 %rcx
  3120. movq $46 %rbx
  3121. addq $7 %rcx
  3122. movq %rcx %rdx
  3123. addq $4 %rdx
  3124. addq %rbx %rcx
  3125. movq %rdx %rbx
  3126. negq %rbx
  3127. movq %rcx %rax
  3128. addq %rbx %rax
  3129. jmp conclusion
  3130. \end{lstlisting}
  3131. \end{minipage}
  3132. \begin{exercise}\normalfont
  3133. Change your implementation of \code{allocate-registers} to take move
  3134. biasing into account. Make sure that your compiler still passes all of
  3135. the previous tests. Create two new tests that include at least one
  3136. opportunity for move biasing and visually inspect the output x86
  3137. programs to make sure that your move biasing is working properly.
  3138. \end{exercise}
  3139. \margincomment{\footnotesize To do: another neat challenge would be to do
  3140. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3141. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3142. \chapter{Booleans and Control Flow}
  3143. \label{ch:bool-types}
  3144. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3145. integers. In this chapter we add a second kind of value, the Booleans,
  3146. to create the $R_2$ language. The Boolean values \emph{true} and
  3147. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3148. Racket. The $R_2$ language includes several operations that involve
  3149. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3150. conditional \key{if} expression. With the addition of \key{if}
  3151. expressions, programs can have non-trivial control flow which which
  3152. significantly impacts the \code{explicate-control} and the liveness
  3153. analysis for register allocation. Also, because we now have two kinds
  3154. of values, we need to handle programs that apply an operation to the
  3155. wrong kind of value, such as \code{(not 1)}.
  3156. There are two language design options for such situations. One option
  3157. is to signal an error and the other is to provide a wider
  3158. interpretation of the operation. The Racket language uses a mixture of
  3159. these two options, depending on the operation and the kind of
  3160. value. For example, the result of \code{(not 1)} in Racket is
  3161. \code{\#f} because Racket treats non-zero integers as if they were
  3162. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3163. error in Racket stating that \code{car} expects a pair.
  3164. The Typed Racket language makes similar design choices as Racket,
  3165. except much of the error detection happens at compile time instead of
  3166. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3167. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3168. reports a compile-time error because Typed Racket expects the type of
  3169. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3170. For the $R_2$ language we choose to be more like Typed Racket in that
  3171. we shall perform type checking during compilation. In
  3172. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3173. is, how to compile a dynamically typed language like Racket. The
  3174. $R_2$ language is a subset of Typed Racket but by no means includes
  3175. all of Typed Racket. For many operations we take a narrower
  3176. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3177. This chapter is organized as follows. We begin by defining the syntax
  3178. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3179. then introduce the idea of type checking and build a type checker for
  3180. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3181. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3182. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3183. how our compiler passes need to change to accommodate Booleans and
  3184. conditional control flow.
  3185. \section{The $R_2$ Language}
  3186. \label{sec:r2-lang}
  3187. The concrete syntax of the $R_2$ language is defined in
  3188. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3189. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3190. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3191. and the conditional \code{if} expression. Also, we expand the
  3192. operators to include subtraction, \key{and}, \key{or} and \key{not},
  3193. the \key{eq?} operations for comparing two integers or two Booleans,
  3194. and the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3195. comparing integers.
  3196. \begin{figure}[tp]
  3197. \centering
  3198. \fbox{
  3199. \begin{minipage}{0.96\textwidth}
  3200. \[
  3201. \begin{array}{lcl}
  3202. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3203. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3204. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3205. &\mid& \key{\#t} \mid \key{\#f}
  3206. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3207. \mid (\key{not}\;\Exp) \\
  3208. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3209. R_2 &::=& \Exp
  3210. \end{array}
  3211. \]
  3212. \end{minipage}
  3213. }
  3214. \caption{The concrete syntax of $R_2$, extending $R_1$
  3215. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3216. \label{fig:r2-concrete-syntax}
  3217. \end{figure}
  3218. \begin{figure}[tp]
  3219. \centering
  3220. \fbox{
  3221. \begin{minipage}{0.96\textwidth}
  3222. \[
  3223. \begin{array}{lcl}
  3224. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3225. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3226. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3227. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3228. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3229. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3230. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3231. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3232. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3233. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3234. \end{array}
  3235. \]
  3236. \end{minipage}
  3237. }
  3238. \caption{The abstract syntax of $R_2$.}
  3239. \label{fig:r2-syntax}
  3240. \end{figure}
  3241. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3242. the parts that are the same as the interpreter for $R_1$
  3243. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3244. simply evaluate to themselves. The conditional expression $(\key{if}\,
  3245. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  3246. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3247. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3248. operations \code{not} and \code{and} behave as you might expect, but
  3249. note that the \code{and} operation is short-circuiting. That is, given
  3250. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3251. evaluated if $e_1$ evaluates to \code{\#f}.
  3252. With the addition of the comparison operations, there are quite a few
  3253. primitive operations and the interpreter code for them could become
  3254. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3255. out the different parts of the code for primitve operations into the
  3256. \code{interp-op} function and the similar parts into the match clause
  3257. for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We do not use
  3258. \code{interp-op} for the \code{and} operation because of the
  3259. short-circuiting behavior in the order of evaluation of its arguments.
  3260. \begin{figure}[tbp]
  3261. \begin{lstlisting}
  3262. (define (interp-op op)
  3263. (match op
  3264. ...
  3265. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3266. ['eq? (lambda (v1 v2)
  3267. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3268. (and (boolean? v1) (boolean? v2)))
  3269. (eq? v1 v2)]))]
  3270. ['< (lambda (v1 v2)
  3271. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3272. ['<= (lambda (v1 v2)
  3273. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3274. ['> (lambda (v1 v2)
  3275. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3276. ['>= (lambda (v1 v2)
  3277. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3278. [else (error 'interp-op "unknown operator")]))
  3279. (define (interp-exp env)
  3280. (lambda (e)
  3281. (define recur (interp-exp env))
  3282. (match e
  3283. ...
  3284. [(Bool b) b]
  3285. [(If cnd thn els)
  3286. (define b (recur cnd))
  3287. (match b
  3288. [#t (recur thn)]
  3289. [#f (recur els)])]
  3290. [(Prim 'and (list e1 e2))
  3291. (define v1 (recur e1))
  3292. (match v1
  3293. [#t (match (recur e2) [#t #t] [#f #f])]
  3294. [#f #f])]
  3295. [(Prim op args)
  3296. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3297. )))
  3298. (define (interp-R2 p)
  3299. (match p
  3300. [(Program info e)
  3301. ((interp-exp '()) e)]
  3302. ))
  3303. \end{lstlisting}
  3304. \caption{Interpreter for the $R_2$ language.}
  3305. \label{fig:interp-R2}
  3306. \end{figure}
  3307. \section{Type Checking $R_2$ Programs}
  3308. \label{sec:type-check-r2}
  3309. It is helpful to think about type checking in two complementary
  3310. ways. A type checker predicts the type of value that will be produced
  3311. by each expression in the program. For $R_2$, we have just two types,
  3312. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3313. \begin{lstlisting}
  3314. (+ 10 (- (+ 12 20)))
  3315. \end{lstlisting}
  3316. produces an \key{Integer} while
  3317. \begin{lstlisting}
  3318. (and (not #f) #t)
  3319. \end{lstlisting}
  3320. produces a \key{Boolean}.
  3321. Another way to think about type checking is that it enforces a set of
  3322. rules about which operators can be applied to which kinds of
  3323. values. For example, our type checker for $R_2$ will signal an error
  3324. for the below expression because, as we have seen above, the
  3325. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3326. checker enforces the rule that the argument of \code{not} must be a
  3327. \key{Boolean}.
  3328. \begin{lstlisting}
  3329. (not (+ 10 (- (+ 12 20))))
  3330. \end{lstlisting}
  3331. The type checker for $R_2$ is best implemented as a structurally
  3332. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3333. many of the clauses for the \code{type-check-exp} function. Given an
  3334. input expression \code{e}, the type checker either returns a type
  3335. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3336. the type of an integer literal is \code{Integer} and the type of a
  3337. Boolean literal is \code{Boolean}. To handle variables, the type
  3338. checker, like the interpreter, uses an environment that maps variables
  3339. to types. Consider the clause for \key{let}. We type check the
  3340. initializing expression to obtain its type \key{T} and then associate
  3341. type \code{T} with the variable \code{x}. When the type checker
  3342. encounters the use of a variable, it can find its type in the
  3343. environment.
  3344. \begin{figure}[tbp]
  3345. \begin{lstlisting}
  3346. (define (type-check-exp env)
  3347. (lambda (e)
  3348. (match e
  3349. [(Var x) (dict-ref env x)]
  3350. [(Int n) 'Integer]
  3351. [(Bool b) 'Boolean]
  3352. [(Let x e body)
  3353. (define Te ((type-check-exp env) e))
  3354. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3355. Tb]
  3356. ...
  3357. [else
  3358. (error "type-check-exp couldn't match" e)])))
  3359. (define (type-check env)
  3360. (lambda (e)
  3361. (match e
  3362. [(Program info body)
  3363. (define Tb ((type-check-exp '()) body))
  3364. (unless (equal? Tb 'Integer)
  3365. (error "result of the program must be an integer, not " Tb))
  3366. (Program info body)]
  3367. )))
  3368. \end{lstlisting}
  3369. \caption{Skeleton of a type checker for the $R_2$ language.}
  3370. \label{fig:type-check-R2}
  3371. \end{figure}
  3372. \begin{exercise}\normalfont
  3373. Complete the implementation of \code{type-check-R2} and test it on 10
  3374. new example programs in $R_2$ that you choose based on how thoroughly
  3375. they test the type checking algorithm. Half of the example programs
  3376. should have a type error, to make sure that your type checker properly
  3377. rejects them. The other half of the example programs should not have
  3378. type errors. Your testing should check that the result of the type
  3379. checker agrees with the value returned by the interpreter, that is, if
  3380. the type checker returns \key{Integer}, then the interpreter should
  3381. return an integer. Likewise, if the type checker returns
  3382. \key{Boolean}, then the interpreter should return \code{\#t} or
  3383. \code{\#f}. Note that if your type checker does not signal an error
  3384. for a program, then interpreting that program should not encounter an
  3385. error. If it does, there is something wrong with your type checker.
  3386. \end{exercise}
  3387. \section{Shrink the $R_2$ Language}
  3388. \label{sec:shrink-r2}
  3389. The $R_2$ language includes several operators that are easily
  3390. expressible in terms of other operators. For example, subtraction is
  3391. expressible in terms of addition and negation.
  3392. \[
  3393. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3394. \]
  3395. Several of the comparison operations are expressible in terms of
  3396. less-than and logical negation.
  3397. \[
  3398. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad
  3399. \LET{t_1}{e_1}{(\key{not}\;(\key{<}\;e_2\;t_1))}
  3400. \]
  3401. By performing these translations near the front-end of the compiler,
  3402. the later passes of the compiler do not need to deal with these
  3403. constructs, making those passes shorter. On the other hand, sometimes
  3404. these translations make it more difficult to generate the most
  3405. efficient code with respect to the number of instructions. However,
  3406. these differences typically do not affect the number of accesses to
  3407. memory, which is the primary factor that determines execution time on
  3408. modern computer architectures.
  3409. \begin{exercise}\normalfont
  3410. Implement the pass \code{shrink} that removes subtraction,
  3411. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3412. by translating them to other constructs in $R_2$. Create tests to
  3413. make sure that the behavior of all of these constructs stays the
  3414. same after translation.
  3415. \end{exercise}
  3416. \section{XOR, Comparisons, and Control Flow in x86}
  3417. \label{sec:x86-1}
  3418. To implement the new logical operations, the comparison operations,
  3419. and the \key{if} expression, we need to delve further into the x86
  3420. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3421. larger subset of x86 that includes instructions for logical
  3422. operations, comparisons, and jumps.
  3423. One small challenge is that x86 does not provide an instruction that
  3424. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3425. However, the \code{xorq} instruction can be used to encode \code{not}.
  3426. The \key{xorq} instruction takes two arguments, performs a pairwise
  3427. exclusive-or operation on each bit of its arguments, and writes the
  3428. results into its second argument. Recall the truth table for
  3429. exclusive-or:
  3430. \begin{center}
  3431. \begin{tabular}{l|cc}
  3432. & 0 & 1 \\ \hline
  3433. 0 & 0 & 1 \\
  3434. 1 & 1 & 0
  3435. \end{tabular}
  3436. \end{center}
  3437. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3438. in the row of the table for the bit $1$, the result is the opposite of the
  3439. second bit. Thus, the \code{not} operation can be implemented by
  3440. \code{xorq} with $1$ as the first argument:
  3441. \begin{align*}
  3442. 0001 \mathrel{\mathrm{XOR}} 0000 &= 0001\\
  3443. 0001 \mathrel{\mathrm{XOR}} 0001 &= 0000
  3444. \end{align*}
  3445. \begin{figure}[tp]
  3446. \fbox{
  3447. \begin{minipage}{0.96\textwidth}
  3448. \small
  3449. \[
  3450. \begin{array}{lcl}
  3451. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3452. \mid \BYTEREG{\code{'}\Reg} \\
  3453. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3454. \Instr &::=& \gray{\BININSTR{\code{'addq}}{\Arg}{\Arg}}
  3455. \mid \gray{\BININSTR{\code{'subq}}{\Arg}{\Arg}} \\
  3456. &\mid& \gray{\BININSTR{\code{'movq}}{\Arg}{\Arg}}
  3457. \mid \gray{\UNIINSTR{\code{'negq}}{\Arg}} \\
  3458. &\mid& \gray{\CALLQ{\itm{label}} \mid \RETQ{}}
  3459. \mid \gray{\PUSHQ{\Arg} \mid \POPQ{\Arg}} \\
  3460. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3461. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3462. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3463. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3464. &\mid& \JMP{\itm{label}}
  3465. \mid \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3466. % &\mid& (\key{label} \; \itm{label}) \\
  3467. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3468. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3469. \end{array}
  3470. \]
  3471. \end{minipage}
  3472. }
  3473. \caption{The abstract syntax of $x86_1$ (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3474. \label{fig:x86-1}
  3475. \end{figure}
  3476. Next we consider the x86 instructions that are relevant for compiling
  3477. the comparison operations. The \key{cmpq} instruction compares its two
  3478. arguments to determine whether one argument is less than, equal, or
  3479. greater than the other argument. The \key{cmpq} instruction is unusual
  3480. regarding the order of its arguments and where the result is
  3481. placed. The argument order is backwards: if you want to test whether
  3482. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3483. \key{cmpq} is placed in the special EFLAGS register. This register
  3484. cannot be accessed directly but it can be queried by a number of
  3485. instructions, including the \key{set} instruction. The \key{set}
  3486. instruction puts a \key{1} or \key{0} into its destination depending
  3487. on whether the comparison came out according to the condition code
  3488. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3489. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3490. The \key{set} instruction has an annoying quirk in that its
  3491. destination argument must be single byte register, such as \code{al},
  3492. which is part of the \code{rax} register. Thankfully, the
  3493. \key{movzbq} instruction can then be used to move from a single byte
  3494. register to a normal 64-bit register.
  3495. For compiling the \key{if} expression, the x86 instructions for
  3496. jumping are relevant. The \key{Jmp} instruction updates the program
  3497. counter to point to the instruction after the indicated label. The
  3498. \key{JmpIf} instruction updates the program counter to point to the
  3499. instruction after the indicated label depending on whether the result
  3500. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3501. the \key{JmpIf} instruction falls through to the next
  3502. instruction. Because the \key{JmpIf} instruction relies on the EFLAGS
  3503. register, it is quite common for the \key{JmpIf} to be immediately
  3504. preceded by a \key{cmpq} instruction, to set the EFLAGS register.
  3505. Our abstract syntax for \key{JmpIf} differs from the concrete syntax
  3506. for x86 to separate the instruction name from the condition code. For
  3507. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}.
  3508. \section{The $C_1$ Intermediate Language}
  3509. \label{sec:c1}
  3510. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3511. language, but we need to grow that intermediate language to handle the
  3512. new features in $R_2$: Booleans and conditional expressions.
  3513. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3514. logic and comparison operators to the $\Exp$ non-terminal, the
  3515. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3516. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3517. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3518. goto's in the grammar for $\Tail$. This means that a sequence of
  3519. statements may now end with a \code{goto} or a conditional
  3520. \code{goto}, which jumps to one of two labeled pieces of code
  3521. depending on the outcome of the comparison. In
  3522. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3523. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3524. and \key{goto}'s.
  3525. \begin{figure}[tp]
  3526. \fbox{
  3527. \begin{minipage}{0.96\textwidth}
  3528. \small
  3529. \[
  3530. \begin{array}{lcl}
  3531. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3532. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3533. \Exp &::= & \gray{\Atm \mid \READ{} \mid \NEG{\Atm} }\\
  3534. &\mid& \gray{ \ADD{\Atm}{\Atm} }
  3535. \mid \UNIOP{\key{'not}}{\Atm} \\
  3536. &\mid& \BINOP{'\itm{cmp}}{\Atm}{\Atm} \\
  3537. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3538. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} } \\
  3539. &\mid& \GOTO{\itm{label}} \\
  3540. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3541. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3542. \end{array}
  3543. \]
  3544. \end{minipage}
  3545. }
  3546. \caption{The abstract syntax of $C_1$, extending $C_0$ with Booleans and conditionals.}
  3547. \label{fig:c1-syntax}
  3548. \end{figure}
  3549. \section{Explicate Control}
  3550. \label{sec:explicate-control-r2}
  3551. Recall that the purpose of \code{explicate-control} is to make the
  3552. order of evaluation explicit in the syntax of the program. With the
  3553. addition of \key{if} in $R_2$, things get more interesting.
  3554. As a motivating example, consider the following program that has an
  3555. \key{if} expression nested in the predicate of another \key{if}.
  3556. % s1_38.rkt
  3557. \begin{center}
  3558. \begin{minipage}{0.96\textwidth}
  3559. \begin{lstlisting}
  3560. (if (if (eq? (read) 1)
  3561. (eq? (read) 0)
  3562. (eq? (read) 2))
  3563. (+ 10 32)
  3564. (+ 700 77))
  3565. \end{lstlisting}
  3566. \end{minipage}
  3567. \end{center}
  3568. %
  3569. The naive way to compile \key{if} and \key{eq?} would be to handle
  3570. each of them in isolation, regardless of their context. Each
  3571. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3572. by a couple instructions to move the result from the EFLAGS register
  3573. into a general purpose register or stack location. Each \key{if} would
  3574. be translated into the combination of a \key{cmpq} and \key{JmpIf}.
  3575. However, if we take context into account we can do better and reduce
  3576. the use of \key{cmpq} and EFLAG-accessing instructions.
  3577. One idea is to try and reorganize the code at the level of $R_2$,
  3578. pushing the outer \key{if} inside the inner one. This would yield the
  3579. following code.
  3580. \begin{center}
  3581. \begin{minipage}{0.96\textwidth}
  3582. \begin{lstlisting}
  3583. (if (eq? (read) 1)
  3584. (if (eq? (read) 0)
  3585. (+ 10 32)
  3586. (+ 700 77))
  3587. (if (eq? (read) 2))
  3588. (+ 10 32)
  3589. (+ 700 77))
  3590. \end{lstlisting}
  3591. \end{minipage}
  3592. \end{center}
  3593. Unfortunately, this approach duplicates the two branches, and a
  3594. compiler must never duplicate code!
  3595. We need a way to perform the above transformation, but without
  3596. duplicating code. The solution is straightforward if we think at the
  3597. level of x86 assembly: we can label the code for each of the branches
  3598. and insert jumps in all the places that need to execute the
  3599. branches. Put another way, we need to move away from abstract syntax
  3600. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3601. use a standard program representation called a \emph{control flow
  3602. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3603. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3604. each edge represents a jump to another block. The \key{Program}
  3605. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3606. as an association list mapping labels to basic blocks. Each block is
  3607. represented by the $\Tail$ non-terminal.
  3608. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3609. \code{remove-complex-opera*} pass and then the
  3610. \code{explicate-control} pass on the example program. We walk through
  3611. the output program and then discuss the algorithm.
  3612. %
  3613. Following the order of evaluation in the output of
  3614. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3615. comparison to \code{1} from the predicate of the inner \key{if}. In
  3616. the output of \code{explicate-control}, in the \code{start} block,
  3617. this becomes a \code{(read)} followed by a conditional goto to either
  3618. \code{block61} or \code{block62}. Each of these contains the
  3619. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3620. 1)}, respectively. Regarding \code{block61}, we start with the
  3621. \code{(read)} and comparison to \code{0} and then have a conditional
  3622. goto, either to \code{block59} or \code{block60}, which indirectly
  3623. take us to \code{block55} and \code{block56}, the two branches of the
  3624. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3625. story for \code{block62} is similar.
  3626. \begin{figure}[tbp]
  3627. \begin{tabular}{lll}
  3628. \begin{minipage}{0.4\textwidth}
  3629. \begin{lstlisting}
  3630. (if (if (eq? (read) 1)
  3631. (eq? (read) 0)
  3632. (eq? (read) 2))
  3633. (+ 10 32)
  3634. (+ 700 77))
  3635. \end{lstlisting}
  3636. \hspace{40pt}$\Downarrow$
  3637. \begin{lstlisting}
  3638. (if (if (let ([tmp52 (read)])
  3639. (eq? tmp52 1))
  3640. (let ([tmp53 (read)])
  3641. (eq? tmp53 0))
  3642. (let ([tmp54 (read)])
  3643. (eq? tmp54 2)))
  3644. (+ 10 32)
  3645. (+ 700 77))
  3646. \end{lstlisting}
  3647. \end{minipage}
  3648. &
  3649. $\Rightarrow$
  3650. &
  3651. \begin{minipage}{0.55\textwidth}
  3652. \begin{lstlisting}
  3653. block62:
  3654. tmp54 = (read);
  3655. if (eq? tmp54 2) then
  3656. goto block59;
  3657. else
  3658. goto block60;
  3659. block61:
  3660. tmp53 = (read);
  3661. if (eq? tmp53 0) then
  3662. goto block57;
  3663. else
  3664. goto block58;
  3665. block60:
  3666. goto block56;
  3667. block59:
  3668. goto block55;
  3669. block58:
  3670. goto block56;
  3671. block57:
  3672. goto block55;
  3673. block56:
  3674. return (+ 700 77);
  3675. block55:
  3676. return (+ 10 32);
  3677. start:
  3678. tmp52 = (read);
  3679. if (eq? tmp52 1) then
  3680. goto block61;
  3681. else
  3682. goto block62;
  3683. \end{lstlisting}
  3684. \end{minipage}
  3685. \end{tabular}
  3686. \caption{Example translation from $R_2$ to $C_1$
  3687. via the \code{explicate-control}.}
  3688. \label{fig:explicate-control-s1-38}
  3689. \end{figure}
  3690. The nice thing about the output of \code{explicate-control} is that
  3691. there are no unnecessary uses of \code{eq?} and every use of
  3692. \code{eq?} is part of a conditional jump. The down-side of this output
  3693. is that it includes trivial blocks, such as \code{block57} through
  3694. \code{block60}, that only jump to another block. We discuss a solution
  3695. to this problem in Section~\ref{sec:opt-jumps}.
  3696. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3697. \code{explicate-control} for $R_1$ using two mutually recursive
  3698. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3699. former function translates expressions in tail position whereas the
  3700. later function translates expressions on the right-hand-side of a
  3701. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3702. new kind of context to deal with: the predicate position of the
  3703. \key{if}. We need another function, \code{explicate-pred}, that takes
  3704. an $R_2$ expression and two pieces of $C_1$ code (two $\Tail$'s) for
  3705. the then-branch and else-branch. The output of \code{explicate-pred}
  3706. is a $C_1$ $\Tail$ and a list of formerly \key{let}-bound variables.
  3707. However, these three functions also need to
  3708. construct the control-flow graph, which we recommend they do via
  3709. updates to a global variable (be careful!). Next we consider the
  3710. specific additions to the tail and assign functions, and some of cases
  3711. for the pred function.
  3712. The \code{explicate-tail} function needs an additional case for
  3713. \key{if}. The branches of the \key{if} inherit the current context, so
  3714. they are in tail position. Let $B_1$ be the result of
  3715. \code{explicate-tail} on the ``then'' branch of the \key{if} and $B_2$
  3716. be the result of apply \code{explicate-tail} to the ``else''
  3717. branch. Then the \key{if} as a whole translates to the block $B_3$
  3718. which is the result of applying \code{explicate-pred} to the predicate
  3719. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3720. \[
  3721. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3722. \]
  3723. Next we consider the case for \key{if} in the \code{explicate-assign}
  3724. function. The context of the \key{if} is an assignment to some
  3725. variable $x$ and then the control continues to some block $B_1$. The
  3726. code that we generate for the $\itm{thn}$ and $\itm{els}$ branches
  3727. needs to continue to $B_1$, so we add $B_1$ to the control flow graph
  3728. with a fresh label $\ell_1$. Again, the branches of the \key{if}
  3729. inherit the current context, so that are in assignment positions. Let
  3730. $B_2$ be the result of applying \code{explicate-assign} to the
  3731. $\itm{thn}$ branch, variable $x$, and the block \GOTO{$\ell_1$}. Let
  3732. $B_3$ be the result of applying \code{explicate-assign} to the
  3733. $\itm{else}$ branch, variable $x$, and the block \GOTO{$\ell_1$}. The
  3734. \key{if} translates to the block $B_4$ which is the result of applying
  3735. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  3736. $B_2$ and $B_3$.
  3737. \[
  3738. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3739. \]
  3740. The function \code{explicate-pred} will need a case for every
  3741. expression that can have type \code{Boolean}. We detail a few cases
  3742. here and leave the rest for the reader. The input to this function is
  3743. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3744. enclosing \key{if}. Suppose the expression is the Boolean \code{\#t}.
  3745. Then we can perform a kind of partial evaluation and translate it to the
  3746. ``then'' branch $B_1$. Likewise, we translate
  3747. \code{\#f} to the ``else`` branch $B_2$.
  3748. \[
  3749. \key{\#t} \quad\Rightarrow\quad B_1,
  3750. \qquad\qquad\qquad
  3751. \key{\#f} \quad\Rightarrow\quad B_2
  3752. \]
  3753. Next, suppose the
  3754. expression is a less-than comparison. We translate it to a conditional
  3755. goto. We need labels for the two branches $B_1$ and $B_2$, so we add
  3756. those blocks to the control flow graph and obtain some labels $\ell_1$
  3757. and $\ell_2$. The translation of the less-than comparison is as
  3758. follows.
  3759. \[
  3760. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  3761. \begin{array}{l}
  3762. \key{if}~(\key{<}~e_1~e_2)~\key{then} \\
  3763. \qquad\key{goto}~\ell_1\key{;}\\
  3764. \key{else}\\
  3765. \qquad\key{goto}~\ell_2\key{;}
  3766. \end{array}
  3767. \]
  3768. The case for \key{if} in \code{explicate-pred} is particularly
  3769. illuminating, as it deals with the challenges that we discussed above
  3770. regarding the example of the nested \key{if} expressions. Again, we
  3771. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3772. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3773. and $\itm{els}$ of the current \key{if} inherit their context from the
  3774. current one, i.e., predicate context. So we apply
  3775. \code{explicate-pred} to $\itm{thn}$ with the two blocks
  3776. \GOTO{$\ell_1$} and \GOTO{$\ell_2$}, to obtain $B_3$.
  3777. Proceed in a similar way with the $\itm{els}$ branch, to obtain $B_4$.
  3778. Finally, we apply \code{explicate-pred} to
  3779. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3780. to obtain the result $B_5$.
  3781. \[
  3782. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3783. \quad\Rightarrow\quad
  3784. B_5
  3785. \]
  3786. \begin{exercise}\normalfont
  3787. Implement the pass \code{explicate-control} by adding the cases for
  3788. \key{if} to the functions for tail and assignment contexts, and
  3789. implement \code{explicate-pred} for predicate contexts. Create test
  3790. cases that exercise all of the new cases in the code for this pass.
  3791. \end{exercise}
  3792. \section{Select Instructions}
  3793. \label{sec:select-r2}
  3794. Recall that the \code{select-instructions} pass lowers from our
  3795. $C$-like intermediate representation to the pseudo-x86 language, which
  3796. is suitable for conducting register allocation. The pass is
  3797. implemented using three auxiliary functions, one for each of the
  3798. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  3799. For $\Atm$, we have new cases for the Booleans. We take the usual
  3800. approach of encoding them as integers, with true as 1 and false as 0.
  3801. \[
  3802. \key{\#t} \Rightarrow \key{1}
  3803. \qquad
  3804. \key{\#f} \Rightarrow \key{0}
  3805. \]
  3806. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3807. be implemented in terms of \code{xorq} as we discussed at the
  3808. beginning of this section. Given an assignment
  3809. $\itm{lhs}$ \key{=} \key{(not} $\Arg$\key{);},
  3810. if the left-hand side $\itm{lhs}$ is
  3811. the same as $\Arg$, then just the \code{xorq} suffices.
  3812. \[
  3813. x~\key{=}~ \key{(not}\; x\key{);}
  3814. \quad\Rightarrow\quad
  3815. \key{xorq}~\key{\$}1\key{,}~x
  3816. \]
  3817. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3818. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3819. $\Arg$. Then we have
  3820. \[
  3821. \itm{lhs}~\key{=}~ \key{(not}\; \Arg\key{);}
  3822. \quad\Rightarrow\quad
  3823. \begin{array}{l}
  3824. \key{movq}~\Arg'\key{,}~\itm{lhs}\\
  3825. \key{xorq}~\key{\$}1\key{,}~\itm{lhs}
  3826. \end{array}
  3827. \]
  3828. Next consider the cases for \code{eq?} and less-than comparison.
  3829. Translating these operations to x86 is slightly involved due to the
  3830. unusual nature of the \key{cmpq} instruction discussed above. We
  3831. recommend translating an assignment from \code{eq?} into the following
  3832. sequence of three instructions. \\
  3833. \begin{tabular}{lll}
  3834. \begin{minipage}{0.4\textwidth}
  3835. \begin{lstlisting}
  3836. |$\itm{lhs}$| = (eq? |$\Arg_1$| |$\Arg_2$|);
  3837. \end{lstlisting}
  3838. \end{minipage}
  3839. &
  3840. $\Rightarrow$
  3841. &
  3842. \begin{minipage}{0.4\textwidth}
  3843. \begin{lstlisting}
  3844. cmpq |$\Arg'_2$|, |$\Arg'_1$|
  3845. sete %al
  3846. movzbq %al, |$\itm{lhs}'$|
  3847. \end{lstlisting}
  3848. \end{minipage}
  3849. \end{tabular} \\
  3850. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3851. \key{goto} and conditional \key{goto}. Both are straightforward
  3852. to handle. A \key{goto} becomes a jump instruction.
  3853. \[
  3854. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  3855. \]
  3856. A conditional \key{goto} becomes a compare instruction followed
  3857. by a conditional jump (for ``then'') and the fall-through is
  3858. to a regular jump (for ``else'').\\
  3859. \begin{tabular}{lll}
  3860. \begin{minipage}{0.4\textwidth}
  3861. \begin{lstlisting}
  3862. if (eq? |$\Arg_1$| |$\Arg_2$|) then
  3863. goto |$\ell_1$|;
  3864. else
  3865. goto |$\ell_2$|;
  3866. \end{lstlisting}
  3867. \end{minipage}
  3868. &
  3869. $\Rightarrow$
  3870. &
  3871. \begin{minipage}{0.4\textwidth}
  3872. \begin{lstlisting}
  3873. cmpq |$\Arg'_2$| |$\Arg'_1$|
  3874. je |$\ell_1$|
  3875. jmp |$\ell_2$|
  3876. \end{lstlisting}
  3877. \end{minipage}
  3878. \end{tabular} \\
  3879. \begin{exercise}\normalfont
  3880. Expand your \code{select-instructions} pass to handle the new features
  3881. of the $R_2$ language. Test the pass on all the examples you have
  3882. created and make sure that you have some test programs that use the
  3883. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3884. the output using the \code{interp-x86} interpreter
  3885. (Appendix~\ref{appendix:interp}).
  3886. \end{exercise}
  3887. \section{Register Allocation}
  3888. \label{sec:register-allocation-r2}
  3889. The changes required for $R_2$ affect liveness analysis, building the
  3890. interference graph, and assigning homes, but the graph coloring
  3891. algorithm itself does not change.
  3892. \subsection{Liveness Analysis}
  3893. \label{sec:liveness-analysis-r2}
  3894. Recall that for $R_1$ we implemented liveness analysis for a single
  3895. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3896. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3897. now produces many basic blocks arranged in a control-flow graph. The
  3898. first question we need to consider is: what order should we process
  3899. the basic blocks? Recall that to perform liveness analysis, we need to
  3900. know the live-after set. If a basic block has no successor blocks
  3901. (i.e. no out-edges in the control flow graph), then it has an empty
  3902. live-after set and we can immediately apply liveness analysis to
  3903. it. If a basic block has some successors, then we need to complete
  3904. liveness analysis on those blocks first. Furthermore, we know that
  3905. the control flow graph does not contain any cycles (it is a DAG, that
  3906. is, a directed acyclic graph)\footnote{If we were to add loops to the
  3907. language, then the CFG could contain cycles and we would instead
  3908. need to use the classic worklist algorithm for computing the fixed
  3909. point of the liveness analysis~\citep{Aho:1986qf}.}. Returning to
  3910. the question of what order should we process the basic blocks: the
  3911. answer is reverse topological order. We recommend using the
  3912. \code{tsort} (topological sort) and \code{transpose} functions of the
  3913. Racket \code{graph} package to obtain this ordering.
  3914. The next question is how to compute the live-after set of a block
  3915. given the live-before sets of all its successor blocks. During
  3916. compilation we do not know which way the branch will go, so we do not
  3917. know which of the successor's live-before set to use. The solution
  3918. comes from the observation that there is no harm to the correctness of
  3919. the compiler if we classify more variables as live than the ones that
  3920. are truly live during program execution. Thus, we can take the union
  3921. of the live-before sets from all the successors to be the live-after
  3922. set for the block. Once we have computed the live-after set, we can
  3923. proceed to perform liveness analysis on the block just as we did in
  3924. Section~\ref{sec:liveness-analysis-r1}.
  3925. The helper functions for computing the variables in an instruction's
  3926. argument and for computing the variables read-from ($R$) or written-to
  3927. ($W$) by an instruction need to be updated to handle the new kinds of
  3928. arguments and instructions in x86$_1$.
  3929. \subsection{Build Interference}
  3930. \label{sec:build-interference-r2}
  3931. Many of the new instructions in x86$_1$ can be handled in the same way
  3932. as the instructions in x86$_0$. Thus, if your code was already quite
  3933. general, it will not need to be changed to handle the new
  3934. instructions. If not, I recommend that you change your code to be more
  3935. general. The \key{movzbq} instruction should be handled like the
  3936. \key{movq} instruction.
  3937. %% \subsection{Assign Homes}
  3938. %% \label{sec:assign-homes-r2}
  3939. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3940. %% to be updated to handle the \key{if} statement, simply by recursively
  3941. %% processing the child nodes. Hopefully your code already handles the
  3942. %% other new instructions, but if not, you can generalize your code.
  3943. \begin{exercise}\normalfont
  3944. Update the \code{register-allocation} pass so that it works for $R_2$
  3945. and test your compiler using your previously created programs on the
  3946. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3947. \end{exercise}
  3948. \section{Patch Instructions}
  3949. The second argument of the \key{cmpq} instruction must not be an
  3950. immediate value (such as an integer). So if you are comparing two
  3951. immediates, we recommend inserting a \key{movq} instruction to put the
  3952. second argument in \key{rax}.
  3953. %
  3954. The second argument of the \key{movzbq} must be a register.
  3955. %
  3956. There are no special restrictions on the x86 instructions \key{JmpIf}
  3957. and \key{Jmp}.
  3958. \begin{exercise}\normalfont
  3959. Update \code{patch-instructions} to handle the new x86 instructions.
  3960. Test your compiler using your previously created programs on the
  3961. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3962. \end{exercise}
  3963. \section{An Example Translation}
  3964. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3965. $R_2$ translated to x86, showing the results of
  3966. \code{explicate-control}, \code{select-instructions}, and the final
  3967. x86 assembly code.
  3968. \begin{figure}[tbp]
  3969. \begin{tabular}{lll}
  3970. \begin{minipage}{0.5\textwidth}
  3971. % s1_20.rkt
  3972. \begin{lstlisting}
  3973. (if (eq? (read) 1) 42 0)
  3974. \end{lstlisting}
  3975. $\Downarrow$
  3976. \begin{lstlisting}
  3977. start:
  3978. tmp7951 = (read);
  3979. if (eq? tmp7951 1) then
  3980. goto block7952;
  3981. else
  3982. goto block7953;
  3983. block7952:
  3984. return 42;
  3985. block7953:
  3986. return 0;
  3987. \end{lstlisting}
  3988. $\Downarrow$
  3989. \begin{lstlisting}
  3990. start:
  3991. callq read_int
  3992. movq %rax, tmp7951
  3993. cmpq $1, tmp7951
  3994. je block7952
  3995. jmp block7953
  3996. block7953:
  3997. movq $0, %rax
  3998. jmp conclusion
  3999. block7952:
  4000. movq $42, %rax
  4001. jmp conclusion
  4002. \end{lstlisting}
  4003. \end{minipage}
  4004. &
  4005. $\Rightarrow\qquad$
  4006. \begin{minipage}{0.4\textwidth}
  4007. \begin{lstlisting}
  4008. start:
  4009. callq read_int
  4010. movq %rax, %rcx
  4011. cmpq $1, %rcx
  4012. je block7952
  4013. jmp block7953
  4014. block7953:
  4015. movq $0, %rax
  4016. jmp conclusion
  4017. block7952:
  4018. movq $42, %rax
  4019. jmp conclusion
  4020. .globl main
  4021. main:
  4022. pushq %rbp
  4023. movq %rsp, %rbp
  4024. pushq %r13
  4025. pushq %r12
  4026. pushq %rbx
  4027. pushq %r14
  4028. subq $0, %rsp
  4029. jmp start
  4030. conclusion:
  4031. addq $0, %rsp
  4032. popq %r14
  4033. popq %rbx
  4034. popq %r12
  4035. popq %r13
  4036. popq %rbp
  4037. retq
  4038. \end{lstlisting}
  4039. \end{minipage}
  4040. \end{tabular}
  4041. \caption{Example compilation of an \key{if} expression to x86.}
  4042. \label{fig:if-example-x86}
  4043. \end{figure}
  4044. \begin{figure}[p]
  4045. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4046. \node (R2) at (0,2) {\large $R_2$};
  4047. \node (R2-2) at (3,2) {\large $R_2$};
  4048. \node (R2-3) at (6,2) {\large $R_2$};
  4049. \node (R2-4) at (9,2) {\large $R_2$};
  4050. \node (R2-5) at (12,2) {\large $R_2$};
  4051. \node (C1-1) at (6,0) {\large $C_1$};
  4052. %\node (C1-2) at (3,0) {\large $C_1$};
  4053. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4054. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4055. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4056. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4057. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4058. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4059. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4060. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4061. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4062. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4063. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4064. %\path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4065. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4066. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4067. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4068. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4069. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4070. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4071. \end{tikzpicture}
  4072. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4073. \label{fig:R2-passes}
  4074. \end{figure}
  4075. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4076. compilation of $R_2$.
  4077. \section{Challenge: Optimize Jumps}
  4078. \label{sec:opt-jumps}
  4079. Recall that in the example output of \code{explicate-control} in
  4080. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4081. \code{block60} are trivial blocks, they do nothing but jump to another
  4082. block. The first goal of this challenge assignment is to remove those
  4083. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4084. \code{explicate-control} on the left and shows the result of bypassing
  4085. the trivial blocks on the right. Let us focus on \code{block61}. The
  4086. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4087. \code{block55}. The optimized code on the right of
  4088. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4089. \code{then} branch jumping directly to \code{block55}. The story is
  4090. similar for the \code{else} branch, as well as for the two branchs in
  4091. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4092. have been optimized in this way, there are no longer any jumps to
  4093. blocks \code{block57} through \code{block60}, so they can be removed.
  4094. \begin{figure}[tbp]
  4095. \begin{tabular}{lll}
  4096. \begin{minipage}{0.4\textwidth}
  4097. \begin{lstlisting}
  4098. block62:
  4099. tmp54 = (read);
  4100. if (eq? tmp54 2) then
  4101. goto block59;
  4102. else
  4103. goto block60;
  4104. block61:
  4105. tmp53 = (read);
  4106. if (eq? tmp53 0) then
  4107. goto block57;
  4108. else
  4109. goto block58;
  4110. block60:
  4111. goto block56;
  4112. block59:
  4113. goto block55;
  4114. block58:
  4115. goto block56;
  4116. block57:
  4117. goto block55;
  4118. block56:
  4119. return (+ 700 77);
  4120. block55:
  4121. return (+ 10 32);
  4122. start:
  4123. tmp52 = (read);
  4124. if (eq? tmp52 1) then
  4125. goto block61;
  4126. else
  4127. goto block62;
  4128. \end{lstlisting}
  4129. \end{minipage}
  4130. &
  4131. $\Rightarrow$
  4132. &
  4133. \begin{minipage}{0.55\textwidth}
  4134. \begin{lstlisting}
  4135. block62:
  4136. tmp54 = (read);
  4137. if (eq? tmp54 2) then
  4138. goto block55;
  4139. else
  4140. goto block56;
  4141. block61:
  4142. tmp53 = (read);
  4143. if (eq? tmp53 0) then
  4144. goto block55;
  4145. else
  4146. goto block56;
  4147. block56:
  4148. return (+ 700 77);
  4149. block55:
  4150. return (+ 10 32);
  4151. start:
  4152. tmp52 = (read);
  4153. if (eq? tmp52 1) then
  4154. goto block61;
  4155. else
  4156. goto block62;
  4157. \end{lstlisting}
  4158. \end{minipage}
  4159. \end{tabular}
  4160. \caption{Optimize jumps by removing trivial blocks.}
  4161. \label{fig:optimize-jumps}
  4162. \end{figure}
  4163. The name of this pass is \code{optimize-jumps}. We recommend
  4164. implementing this pass in two phases. The first phrase builds a hash
  4165. table that maps labels to possibly improved labels. The second phase
  4166. changes the target of each \code{goto} to use the improved label. If
  4167. the label is for a trivial block, then the hash table should map the
  4168. label to the first non-trivial block that can be reached from this
  4169. label by jumping through trivial blocks. If the label is for a
  4170. non-trivial block, then the hash table should map the label to itself;
  4171. we do not want to change jumps to non-trivial blocks.
  4172. The first phase can be accomplished by constructing an empty hash
  4173. table, call it \code{short-cut}, and then iterating over the control
  4174. flow graph. Each time you encouter a block that is just a \code{goto},
  4175. then update the hash table, mapping the block's source to the target
  4176. of the \code{goto}. Also, the hash table may already have mapped some
  4177. labels to the block's source, to you must iterate through the hash
  4178. table and update all of those so that they instead map to the target
  4179. of the \code{goto}.
  4180. For the second phase, we recommend iterating through the $\Tail$ of
  4181. each block in the program, updating the target of every \code{goto}
  4182. according to the mapping in \code{short-cut}.
  4183. \begin{exercise}\normalfont
  4184. Implement the \code{optimize-jumps} pass and check that it remove
  4185. trivial blocks in a few example programs. Then check that your
  4186. compiler still passes all of your tests.
  4187. \end{exercise}
  4188. There is another opportunity for optimizing jumps that is apparent in
  4189. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4190. end with a jump to \code{block7953} and there are no other jumps to
  4191. \code{block7953} in the rest of the program. In this situation we can
  4192. avoid the runtime overhead of this jump by merging \code{block7953}
  4193. into the preceeding block, in this case the \code{start} block.
  4194. Figure~\ref{fig:remove-jumps} shows the output of
  4195. \code{select-instructions} on the left and the result of this
  4196. optimization on the right.
  4197. \begin{figure}[tbp]
  4198. \begin{tabular}{lll}
  4199. \begin{minipage}{0.5\textwidth}
  4200. % s1_20.rkt
  4201. \begin{lstlisting}
  4202. start:
  4203. callq read_int
  4204. movq %rax, tmp7951
  4205. cmpq $1, tmp7951
  4206. je block7952
  4207. jmp block7953
  4208. block7953:
  4209. movq $0, %rax
  4210. jmp conclusion
  4211. block7952:
  4212. movq $42, %rax
  4213. jmp conclusion
  4214. \end{lstlisting}
  4215. \end{minipage}
  4216. &
  4217. $\Rightarrow\qquad$
  4218. \begin{minipage}{0.4\textwidth}
  4219. \begin{lstlisting}
  4220. start:
  4221. callq read_int
  4222. movq %rax, tmp7951
  4223. cmpq $1, tmp7951
  4224. je block7952
  4225. movq $0, %rax
  4226. jmp conclusion
  4227. block7952:
  4228. movq $42, %rax
  4229. jmp conclusion
  4230. \end{lstlisting}
  4231. \end{minipage}
  4232. \end{tabular}
  4233. \caption{Merging basic blocks by removing unnecessary jumps.}
  4234. \label{fig:remove-jumps}
  4235. \end{figure}
  4236. \begin{exercise}\normalfont
  4237. Implement a pass named \code{remove-jumps} that merges basic blocks
  4238. into their preceeding basic block, when there is only one preceeding
  4239. block. Check that your pass accomplishes this goal on several test
  4240. programs and check that your compiler passes all of your tests.
  4241. \end{exercise}
  4242. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4243. \chapter{Tuples and Garbage Collection}
  4244. \label{ch:tuples}
  4245. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4246. things to discuss in this chapter. \\ --Jeremy}
  4247. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4248. all the IR grammars are spelled out! \\ --Jeremy}
  4249. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4250. but keep type annotations on vector creation and local variables, function
  4251. parameters, etc. \\ --Jeremy}
  4252. \margincomment{\scriptsize Be more explicit about how to deal with
  4253. the root stack. \\ --Jeremy}
  4254. In this chapter we study the implementation of mutable tuples (called
  4255. ``vectors'' in Racket). This language feature is the first to use the
  4256. computer's \emph{heap} because the lifetime of a Racket tuple is
  4257. indefinite, that is, a tuple lives forever from the programmer's
  4258. viewpoint. Of course, from an implementer's viewpoint, it is important
  4259. to reclaim the space associated with a tuple when it is no longer
  4260. needed, which is why we also study \emph{garbage collection}
  4261. techniques in this chapter.
  4262. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4263. interpreter and type checker. The $R_3$ language extends the $R_2$
  4264. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4265. \code{void} value. The reason for including the later is that the
  4266. \code{vector-set!} operation returns a value of type
  4267. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4268. called the \code{Unit} type in the programming languages
  4269. literature. Racket's \code{Void} type is inhabited by a single value
  4270. \code{void} which corresponds to \code{unit} or \code{()} in the
  4271. literature~\citep{Pierce:2002hj}.}.
  4272. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4273. copying live objects back and forth between two halves of the
  4274. heap. The garbage collector requires coordination with the compiler so
  4275. that it can see all of the \emph{root} pointers, that is, pointers in
  4276. registers or on the procedure call stack.
  4277. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4278. discuss all the necessary changes and additions to the compiler
  4279. passes, including a new compiler pass named \code{expose-allocation}.
  4280. \section{The $R_3$ Language}
  4281. \label{sec:r3}
  4282. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4283. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4284. $R_3$ language includes three new forms for creating a tuple, reading
  4285. an element of a tuple, and writing to an element of a tuple. The
  4286. program in Figure~\ref{fig:vector-eg} shows the usage of tuples in
  4287. Racket. We create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is
  4288. stored at index $2$ of the 3-tuple, demonstrating that tuples are
  4289. first-class values. The element at index $1$ of \code{t} is
  4290. \code{\#t}, so the ``then'' branch of the \key{if} is taken. The
  4291. element at index $0$ of \code{t} is $40$, to which we add $2$, the
  4292. element at index $0$ of the 1-tuple. So the result of the program is
  4293. $42$.
  4294. \begin{figure}[tbp]
  4295. \begin{lstlisting}
  4296. (let ([t (vector 40 #t (vector 2))])
  4297. (if (vector-ref t 1)
  4298. (+ (vector-ref t 0)
  4299. (vector-ref (vector-ref t 2) 0))
  4300. 44))
  4301. \end{lstlisting}
  4302. \caption{Example program that creates tuples and reads from them.}
  4303. \label{fig:vector-eg}
  4304. \end{figure}
  4305. \begin{figure}[tbp]
  4306. \centering
  4307. \fbox{
  4308. \begin{minipage}{0.96\textwidth}
  4309. \[
  4310. \begin{array}{lcl}
  4311. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4312. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4313. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4314. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4315. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4316. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4317. \mid (\key{and}\;\Exp\;\Exp)
  4318. \mid (\key{or}\;\Exp\;\Exp)
  4319. \mid (\key{not}\;\Exp) } \\
  4320. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4321. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4322. &\mid& (\key{vector}\;\Exp^{+})
  4323. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4324. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4325. &\mid& (\key{void}) \\
  4326. R_3 &::=& \Exp
  4327. \end{array}
  4328. \]
  4329. \end{minipage}
  4330. }
  4331. \caption{The concrete syntax of $R_3$, extending $R_2$
  4332. (Figure~\ref{fig:r2-concrete-syntax}).}
  4333. \label{fig:r3-concrete-syntax}
  4334. \end{figure}
  4335. \begin{figure}[tp]
  4336. \centering
  4337. \fbox{
  4338. \begin{minipage}{0.96\textwidth}
  4339. \[
  4340. \begin{array}{lcl}
  4341. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4342. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4343. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4344. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4345. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4346. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4347. &\mid& \gray{ \BOOL{\itm{bool}}
  4348. \mid \AND{\Exp}{\Exp} }\\
  4349. &\mid& \gray{ \OR{\Exp}{\Exp}
  4350. \mid \NOT{\Exp} } \\
  4351. &\mid& \gray{ \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp}
  4352. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4353. &\mid& \VECTOR{\Exp} \\
  4354. &\mid& \VECREF{\Exp}{\Int}\\
  4355. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4356. &\mid& \VOID{} \\
  4357. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4358. \end{array}
  4359. \]
  4360. \end{minipage}
  4361. }
  4362. \caption{The abstract syntax of $R_3$.}
  4363. \label{fig:r3-syntax}
  4364. \end{figure}
  4365. Tuples are our first encounter with heap-allocated data, which raises
  4366. several interesting issues. First, variable binding performs a
  4367. shallow-copy when dealing with tuples, which means that different
  4368. variables can refer to the same tuple, i.e., different variables can
  4369. be \emph{aliases} for the same thing. Consider the following example
  4370. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4371. the mutation through \code{t2} is visible when referencing the tuple
  4372. from \code{t1}, so the result of this program is \code{42}.
  4373. \begin{center}
  4374. \begin{minipage}{0.96\textwidth}
  4375. \begin{lstlisting}
  4376. (let ([t1 (vector 3 7)])
  4377. (let ([t2 t1])
  4378. (let ([_ (vector-set! t2 0 42)])
  4379. (vector-ref t1 0))))
  4380. \end{lstlisting}
  4381. \end{minipage}
  4382. \end{center}
  4383. The next issue concerns the lifetime of tuples. Of course, they are
  4384. created by the \code{vector} form, but when does their lifetime end?
  4385. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4386. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4387. is not tied to any notion of static scoping. For example, the
  4388. following program returns \code{3} even though the variable \code{t}
  4389. goes out of scope prior to accessing the vector.
  4390. \begin{center}
  4391. \begin{minipage}{0.96\textwidth}
  4392. \begin{lstlisting}
  4393. (vector-ref
  4394. (let ([t (vector 3 7)])
  4395. t)
  4396. 0)
  4397. \end{lstlisting}
  4398. \end{minipage}
  4399. \end{center}
  4400. From the perspective of programmer-observable behavior, tuples live
  4401. forever. Of course, if they really lived forever, then many programs
  4402. would run out of memory.\footnote{The $R_3$ language does not have
  4403. looping or recursive function, so it is nigh impossible to write a
  4404. program in $R_3$ that will run out of memory. However, we add
  4405. recursive functions in the next Chapter!} A Racket implementation
  4406. must therefore perform automatic garbage collection.
  4407. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4408. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4409. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4410. operations in Racket. One subtle point is that the \code{vector-set!}
  4411. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4412. can be passed around just like other values inside an $R_3$ program,
  4413. but there are no operations specific to the the \code{\#<void>} value
  4414. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4415. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4416. otherwise.
  4417. \begin{figure}[tbp]
  4418. \begin{lstlisting}
  4419. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4420. (define (interp-op op)
  4421. (match op
  4422. ...
  4423. ['vector vector]
  4424. ['vector-ref vector-ref]
  4425. ['vector-set! vector-set!]
  4426. [else (error 'interp-op "unknown operator")]))
  4427. (define (interp-R3 env)
  4428. (lambda (e)
  4429. (match e
  4430. ...
  4431. [else (error 'interp-R3 "unrecognized expression")]
  4432. )))
  4433. \end{lstlisting}
  4434. \caption{Interpreter for the $R_3$ language.}
  4435. \label{fig:interp-R3}
  4436. \end{figure}
  4437. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4438. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4439. need to know which variables are pointers into the heap, that is,
  4440. which variables are vectors. Also, when allocating a vector, we need
  4441. to know which elements of the vector are pointers. We can obtain this
  4442. information during type checking. The type checker in
  4443. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4444. expression, it also wraps every sub-expression $e$ with the form
  4445. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4446. % TODO: UPDATE? -Jeremy
  4447. Subsequently, in the \code{uncover-locals} pass
  4448. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4449. propagated to all variables (including the temporaries generated by
  4450. \code{remove-complex-opera*}).
  4451. \begin{figure}[tbp]
  4452. \begin{lstlisting}
  4453. (define (type-check-exp env)
  4454. (lambda (e)
  4455. (define recur (type-check-exp env))
  4456. (match e
  4457. ...
  4458. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4459. [(Prim 'vector es)
  4460. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4461. (recur e)))
  4462. (let ([t `(Vector ,@t*)])
  4463. (values (HasType (Prim 'vector e*) t) t))]
  4464. [(Prim 'vector-ref (list e (Int i)))
  4465. (define-values (e^ t) (recur e))
  4466. (match t
  4467. [`(Vector ,ts ...)
  4468. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4469. (error 'type-check-exp "invalid index ~a" i))
  4470. (let ([t (list-ref ts i)])
  4471. (values
  4472. (HasType (Prim 'vector-ref (list e^ (HasType (Int i) 'Integer))) t)
  4473. t))]
  4474. [else (error "expected a vector in vector-ref, not" t)])]
  4475. [(Prim 'eq? (list e1 e2))
  4476. (define-values (e1^ T1) (recur e1))
  4477. (define-values (e2^ T2) (recur e2))
  4478. (unless (equal? T1 T2)
  4479. (error "arguments of eq? must have the same type, but are not"
  4480. (list T1 T2)))
  4481. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4482. ...
  4483. )))
  4484. \end{lstlisting}
  4485. \caption{Type checker for the $R_3$ language.}
  4486. \label{fig:typecheck-R3}
  4487. \end{figure}
  4488. \section{Garbage Collection}
  4489. \label{sec:GC}
  4490. Here we study a relatively simple algorithm for garbage collection
  4491. that is the basis of state-of-the-art garbage
  4492. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4493. particular, we describe a two-space copying
  4494. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4495. perform the
  4496. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4497. coarse-grained depiction of what happens in a two-space collector,
  4498. showing two time steps, prior to garbage collection on the top and
  4499. after garbage collection on the bottom. In a two-space collector, the
  4500. heap is divided into two parts, the FromSpace and the
  4501. ToSpace. Initially, all allocations go to the FromSpace until there is
  4502. not enough room for the next allocation request. At that point, the
  4503. garbage collector goes to work to make more room.
  4504. The garbage collector must be careful not to reclaim tuples that will
  4505. be used by the program in the future. Of course, it is impossible in
  4506. general to predict what a program will do, but we can over approximate
  4507. the will-be-used tuples by preserving all tuples that could be
  4508. accessed by \emph{any} program given the current computer state. A
  4509. program could access any tuple whose address is in a register or on
  4510. the procedure call stack. These addresses are called the \emph{root
  4511. set}. In addition, a program could access any tuple that is
  4512. transitively reachable from the root set. Thus, it is safe for the
  4513. garbage collector to reclaim the tuples that are not reachable in this
  4514. way.
  4515. So the goal of the garbage collector is twofold:
  4516. \begin{enumerate}
  4517. \item preserve all tuple that are reachable from the root set via a
  4518. path of pointers, that is, the \emph{live} tuples, and
  4519. \item reclaim the memory of everything else, that is, the
  4520. \emph{garbage}.
  4521. \end{enumerate}
  4522. A copying collector accomplishes this by copying all of the live
  4523. objects from the FromSpace into the ToSpace and then performs a slight
  4524. of hand, treating the ToSpace as the new FromSpace and the old
  4525. FromSpace as the new ToSpace. In the example of
  4526. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4527. root set, one in a register and two on the stack. All of the live
  4528. objects have been copied to the ToSpace (the right-hand side of
  4529. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4530. pointer relationships. For example, the pointer in the register still
  4531. points to a 2-tuple whose first element is a 3-tuple and second
  4532. element is a 2-tuple. There are four tuples that are not reachable
  4533. from the root set and therefore do not get copied into the ToSpace.
  4534. (The situation in Figure~\ref{fig:copying-collector}, with a
  4535. cycle, cannot be created by a well-typed program in $R_3$. However,
  4536. creating cycles will be possible once we get to $R_6$. We design
  4537. the garbage collector to deal with cycles to begin with, so we will
  4538. not need to revisit this issue.)
  4539. \begin{figure}[tbp]
  4540. \centering
  4541. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4542. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4543. \caption{A copying collector in action.}
  4544. \label{fig:copying-collector}
  4545. \end{figure}
  4546. There are many alternatives to copying collectors (and their older
  4547. siblings, the generational collectors) when its comes to garbage
  4548. collection, such as mark-and-sweep and reference counting. The
  4549. strengths of copying collectors are that allocation is fast (just a
  4550. test and pointer increment), there is no fragmentation, cyclic garbage
  4551. is collected, and the time complexity of collection only depends on
  4552. the amount of live data, and not on the amount of
  4553. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4554. copying collectors is that they use a lot of space, though that
  4555. problem is ameliorated in generational collectors. Racket and Scheme
  4556. programs tend to allocate many small objects and generate a lot of
  4557. garbage, so copying and generational collectors are a good fit. Of
  4558. course, garbage collection is an active research topic, especially
  4559. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4560. continuously developing new techniques and revisiting old
  4561. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4562. \subsection{Graph Copying via Cheney's Algorithm}
  4563. \label{sec:cheney}
  4564. Let us take a closer look at how the copy works. The allocated objects
  4565. and pointers can be viewed as a graph and we need to copy the part of
  4566. the graph that is reachable from the root set. To make sure we copy
  4567. all of the reachable vertices in the graph, we need an exhaustive
  4568. graph traversal algorithm, such as depth-first search or breadth-first
  4569. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4570. take into account the possibility of cycles by marking which vertices
  4571. have already been visited, so as to ensure termination of the
  4572. algorithm. These search algorithms also use a data structure such as a
  4573. stack or queue as a to-do list to keep track of the vertices that need
  4574. to be visited. We shall use breadth-first search and a trick due to
  4575. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4576. copying tuples into the ToSpace.
  4577. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4578. copy progresses. The queue is represented by a chunk of contiguous
  4579. memory at the beginning of the ToSpace, using two pointers to track
  4580. the front and the back of the queue. The algorithm starts by copying
  4581. all tuples that are immediately reachable from the root set into the
  4582. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4583. old tuple to indicate that it has been visited. (We discuss the
  4584. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4585. inside the copied tuples in the queue still point back to the
  4586. FromSpace. Once the initial queue has been created, the algorithm
  4587. enters a loop in which it repeatedly processes the tuple at the front
  4588. of the queue and pops it off the queue. To process a tuple, the
  4589. algorithm copies all the tuple that are directly reachable from it to
  4590. the ToSpace, placing them at the back of the queue. The algorithm then
  4591. updates the pointers in the popped tuple so they point to the newly
  4592. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4593. step we copy the tuple whose second element is $42$ to the back of the
  4594. queue. The other pointer goes to a tuple that has already been copied,
  4595. so we do not need to copy it again, but we do need to update the
  4596. pointer to the new location. This can be accomplished by storing a
  4597. \emph{forwarding} pointer to the new location in the old tuple, back
  4598. when we initially copied the tuple into the ToSpace. This completes
  4599. one step of the algorithm. The algorithm continues in this way until
  4600. the front of the queue is empty, that is, until the front catches up
  4601. with the back.
  4602. \begin{figure}[tbp]
  4603. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4604. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4605. \label{fig:cheney}
  4606. \end{figure}
  4607. \subsection{Data Representation}
  4608. \label{sec:data-rep-gc}
  4609. The garbage collector places some requirements on the data
  4610. representations used by our compiler. First, the garbage collector
  4611. needs to distinguish between pointers and other kinds of data. There
  4612. are several ways to accomplish this.
  4613. \begin{enumerate}
  4614. \item Attached a tag to each object that identifies what type of
  4615. object it is~\citep{McCarthy:1960dz}.
  4616. \item Store different types of objects in different
  4617. regions~\citep{Steele:1977ab}.
  4618. \item Use type information from the program to either generate
  4619. type-specific code for collecting or to generate tables that can
  4620. guide the
  4621. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4622. \end{enumerate}
  4623. Dynamically typed languages, such as Lisp, need to tag objects
  4624. anyways, so option 1 is a natural choice for those languages.
  4625. However, $R_3$ is a statically typed language, so it would be
  4626. unfortunate to require tags on every object, especially small and
  4627. pervasive objects like integers and Booleans. Option 3 is the
  4628. best-performing choice for statically typed languages, but comes with
  4629. a relatively high implementation complexity. To keep this chapter to a
  4630. 2-week time budget, we recommend a combination of options 1 and 2,
  4631. with separate strategies used for the stack and the heap.
  4632. Regarding the stack, we recommend using a separate stack for
  4633. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4634. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4635. local variable needs to be spilled and is of type \code{(Vector
  4636. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4637. of the normal procedure call stack. Furthermore, we always spill
  4638. vector-typed variables if they are live during a call to the
  4639. collector, thereby ensuring that no pointers are in registers during a
  4640. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4641. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4642. layout using a root stack. The root stack contains the two pointers
  4643. from the regular stack and also the pointer in the second
  4644. register.
  4645. \begin{figure}[tbp]
  4646. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4647. \caption{Maintaining a root stack to facilitate garbage collection.}
  4648. \label{fig:shadow-stack}
  4649. \end{figure}
  4650. The problem of distinguishing between pointers and other kinds of data
  4651. also arises inside of each tuple. We solve this problem by attaching a
  4652. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4653. in on the tags for two of the tuples in the example from
  4654. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4655. in a big-endian way, from right-to-left, with bit location 0 (the
  4656. least significant bit) on the far right, which corresponds to the
  4657. directional of the x86 shifting instructions \key{salq} (shift
  4658. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4659. specifying which elements of the tuple are pointers, the part labeled
  4660. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4661. a pointer and a 0 bit indicates some other kind of data. The pointer
  4662. mask starts at bit location 7. We have limited tuples to a maximum
  4663. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4664. tag also contains two other pieces of information. The length of the
  4665. tuple (number of elements) is stored in bits location 1 through
  4666. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4667. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4668. has not yet been copied. If the bit has value 0 then the entire tag
  4669. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4670. always zero anyways because our tuples are 8-byte aligned.)
  4671. \begin{figure}[tbp]
  4672. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4673. \caption{Representation for tuples in the heap.}
  4674. \label{fig:tuple-rep}
  4675. \end{figure}
  4676. \subsection{Implementation of the Garbage Collector}
  4677. \label{sec:organize-gz}
  4678. The implementation of the garbage collector needs to do a lot of
  4679. bit-level data manipulation and we need to link it with our
  4680. compiler-generated x86 code. Thus, we recommend implementing the
  4681. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4682. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4683. interface to the garbage collector. The \code{initialize} function
  4684. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4685. function is meant to be called near the beginning of \code{main},
  4686. before the rest of the program executes. The \code{initialize}
  4687. function puts the address of the beginning of the FromSpace into the
  4688. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4689. points to the address that is 1-past the last element of the
  4690. FromSpace. (We use half-open intervals to represent chunks of
  4691. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4692. points to the first element of the root stack.
  4693. As long as there is room left in the FromSpace, your generated code
  4694. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4695. %
  4696. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4697. --Jeremy}
  4698. %
  4699. The amount of room left in FromSpace is the difference between the
  4700. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4701. function should be called when there is not enough room left in the
  4702. FromSpace for the next allocation. The \code{collect} function takes
  4703. a pointer to the current top of the root stack (one past the last item
  4704. that was pushed) and the number of bytes that need to be
  4705. allocated. The \code{collect} function performs the copying collection
  4706. and leaves the heap in a state such that the next allocation will
  4707. succeed.
  4708. \begin{figure}[tbp]
  4709. \begin{lstlisting}
  4710. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4711. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4712. int64_t* free_ptr;
  4713. int64_t* fromspace_begin;
  4714. int64_t* fromspace_end;
  4715. int64_t** rootstack_begin;
  4716. \end{lstlisting}
  4717. \caption{The compiler's interface to the garbage collector.}
  4718. \label{fig:gc-header}
  4719. \end{figure}
  4720. \begin{exercise}
  4721. In the file \code{runtime.c} you will find the implementation of
  4722. \code{initialize} and a partial implementation of \code{collect}.
  4723. The \code{collect} function calls another function, \code{cheney},
  4724. to perform the actual copy, and that function is left to the reader
  4725. to implement. The following is the prototype for \code{cheney}.
  4726. \begin{lstlisting}
  4727. static void cheney(int64_t** rootstack_ptr);
  4728. \end{lstlisting}
  4729. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4730. rootstack (which is an array of pointers). The \code{cheney} function
  4731. also communicates with \code{collect} through the global
  4732. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4733. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4734. the ToSpace:
  4735. \begin{lstlisting}
  4736. static int64_t* tospace_begin;
  4737. static int64_t* tospace_end;
  4738. \end{lstlisting}
  4739. The job of the \code{cheney} function is to copy all the live
  4740. objects (reachable from the root stack) into the ToSpace, update
  4741. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4742. update the root stack so that it points to the objects in the
  4743. ToSpace, and finally to swap the global pointers for the FromSpace
  4744. and ToSpace.
  4745. \end{exercise}
  4746. %% \section{Compiler Passes}
  4747. %% \label{sec:code-generation-gc}
  4748. The introduction of garbage collection has a non-trivial impact on our
  4749. compiler passes. We introduce one new compiler pass called
  4750. \code{expose-allocation} and make non-trivial changes to
  4751. \code{type-check}, \code{flatten}, \code{select-instructions},
  4752. \code{allocate-registers}, and \code{print-x86}. The following
  4753. program will serve as our running example. It creates two tuples, one
  4754. nested inside the other. Both tuples have length one. The example then
  4755. accesses the element in the inner tuple tuple via two vector
  4756. references.
  4757. % tests/s2_17.rkt
  4758. \begin{lstlisting}
  4759. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4760. \end{lstlisting}
  4761. Next we proceed to discuss the new \code{expose-allocation} pass.
  4762. \section{Expose Allocation}
  4763. \label{sec:expose-allocation}
  4764. The pass \code{expose-allocation} lowers the \code{vector} creation
  4765. form into a conditional call to the collector followed by the
  4766. allocation. We choose to place the \code{expose-allocation} pass
  4767. before \code{flatten} because \code{expose-allocation} introduces new
  4768. variables, which can be done locally with \code{let}, but \code{let}
  4769. is gone after \code{flatten}. In the following, we show the
  4770. transformation for the \code{vector} form into let-bindings for the
  4771. initializing expressions, by a conditional \code{collect}, an
  4772. \code{allocate}, and the initialization of the vector.
  4773. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4774. total bytes need to be allocated for the vector, which is 8 for the
  4775. tag plus \itm{len} times 8.)
  4776. \begin{lstlisting}
  4777. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4778. |$\Longrightarrow$|
  4779. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4780. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4781. (global-value fromspace_end))
  4782. (void)
  4783. (collect |\itm{bytes}|))])
  4784. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4785. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4786. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4787. |$v$|) ... )))) ...)
  4788. \end{lstlisting}
  4789. (In the above, we suppressed all of the \code{has-type} forms in the
  4790. output for the sake of readability.) The placement of the initializing
  4791. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4792. the sequence of \code{vector-set!}'s is important, as those expressions
  4793. may trigger garbage collection and we do not want an allocated but
  4794. uninitialized tuple to be present during a garbage collection.
  4795. The output of \code{expose-allocation} is a language that extends
  4796. $R_3$ with the three new forms that we use above in the translation of
  4797. \code{vector}.
  4798. \[
  4799. \begin{array}{lcl}
  4800. \Exp &::=& \cdots
  4801. \mid (\key{collect} \,\itm{int})
  4802. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4803. \mid (\key{global-value} \,\itm{name})
  4804. \end{array}
  4805. \]
  4806. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4807. %% the beginning of the program which will instruct the garbage collector
  4808. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4809. %% two arguments of \code{initialize} specify the initial allocated space
  4810. %% for the root stack and for the heap.
  4811. %
  4812. %% The \code{expose-allocation} pass annotates all of the local variables
  4813. %% in the \code{program} form with their type.
  4814. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4815. \code{expose-allocation} pass on our running example.
  4816. \begin{figure}[tbp]
  4817. % tests/s2_17.rkt
  4818. \begin{lstlisting}
  4819. (vector-ref
  4820. (vector-ref
  4821. (let ([vecinit7976
  4822. (let ([vecinit7972 42])
  4823. (let ([collectret7974
  4824. (if (< (+ free_ptr 16) fromspace_end)
  4825. (void)
  4826. (collect 16);
  4827. )])
  4828. (let ([alloc7971 (allocate 1 (Vector Integer))])
  4829. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  4830. alloc7971)
  4831. )
  4832. )
  4833. )
  4834. ])
  4835. (let ([collectret7978
  4836. (if (< (+ free_ptr 16) fromspace_end)
  4837. (void)
  4838. (collect 16);
  4839. )])
  4840. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  4841. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  4842. alloc7975)
  4843. )
  4844. )
  4845. )
  4846. 0)
  4847. 0)
  4848. \end{lstlisting}
  4849. \caption{Output of the \code{expose-allocation} pass, minus
  4850. all of the \code{HasType} forms.}
  4851. \label{fig:expose-alloc-output}
  4852. \end{figure}
  4853. %\clearpage
  4854. \section{Explicate Control and the $C_2$ language}
  4855. \label{sec:explicate-control-r3}
  4856. \begin{figure}[tp]
  4857. \fbox{
  4858. \begin{minipage}{0.96\textwidth}
  4859. \small
  4860. \[
  4861. \begin{array}{lcl}
  4862. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  4863. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4864. \Exp &::= & \gray{ \Atm \mid \READ{} \mid \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  4865. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  4866. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type})
  4867. \mid \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  4868. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  4869. &\mid& (\key{GlobalValue} \,\itm{name}) \mid (\key{Void}) \\
  4870. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} \mid \RETURN{\Exp} }
  4871. \mid (\key{Collect} \,\itm{int}) \\
  4872. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }\\
  4873. &\mid& \gray{ \GOTO{\itm{label}} }\\
  4874. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  4875. C_2 & ::= & \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)^{+}}}
  4876. \end{array}
  4877. \]
  4878. \end{minipage}
  4879. }
  4880. \caption{The abstract syntax of the $C_2$ language.
  4881. TODO: UPDATE}
  4882. \label{fig:c2-syntax}
  4883. \end{figure}
  4884. The output of \code{explicate-control} is a program in the
  4885. intermediate language $C_2$, whose syntax is defined in
  4886. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4887. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4888. \key{global-value} expressions and the \code{collect} statement. The
  4889. \code{explicate-control} pass can treat these new forms much like the
  4890. other forms.
  4891. \section{Uncover Locals}
  4892. \label{sec:uncover-locals-r3}
  4893. Recall that the \code{explicate-control} function collects all of the
  4894. local variables so that it can store them in the $\itm{info}$ field of
  4895. the \code{Program} structure. Also recall that we need to know the
  4896. types of all the local variables for purposes of identifying the root
  4897. set for the garbage collector. Thus, we create a pass named
  4898. \code{uncover-locals} to collect not just the variables but the
  4899. variables and their types in the form of an association list. Thanks
  4900. to the \code{HasType} nodes, the types are readily available in the
  4901. AST. Figure~\ref{fig:uncover-locals-r3} lists the output of the
  4902. \code{uncover-locals} pass on the running example.
  4903. \begin{figure}[tbp]
  4904. % tests/s2_17.rkt
  4905. \begin{lstlisting}
  4906. program:
  4907. locals:
  4908. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  4909. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  4910. collectret7974 : 'Void, initret7977 : 'Void,
  4911. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  4912. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  4913. alloc7971 : '(Vector Integer), tmp7981 : 'Integer, vecinit7972 : 'Integer,
  4914. initret7973 : 'Void,
  4915. block7991:
  4916. (collect 16);
  4917. goto block7989;
  4918. block7990:
  4919. collectret7974 = (void);
  4920. goto block7989;
  4921. block7989:
  4922. alloc7971 = (allocate 1 (Vector Integer));
  4923. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  4924. vecinit7976 = alloc7971;
  4925. tmp7982 = free_ptr;
  4926. tmp7983 = (+ tmp7982 16);
  4927. tmp7984 = fromspace_end;
  4928. if (< tmp7983 tmp7984) then
  4929. goto block7987;
  4930. else
  4931. goto block7988;
  4932. block7988:
  4933. (collect 16);
  4934. goto block7986;
  4935. block7987:
  4936. collectret7978 = (void);
  4937. goto block7986;
  4938. block7986:
  4939. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  4940. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  4941. tmp7985 = (vector-ref alloc7975 0);
  4942. return (vector-ref tmp7985 0);
  4943. start:
  4944. vecinit7972 = 42;
  4945. tmp7979 = free_ptr;
  4946. tmp7980 = (+ tmp7979 16);
  4947. tmp7981 = fromspace_end;
  4948. if (< tmp7980 tmp7981) then
  4949. goto block7990;
  4950. else
  4951. goto block7991;
  4952. \end{lstlisting}
  4953. \caption{Output of \code{uncover-locals} for the running example.}
  4954. \label{fig:uncover-locals-r3}
  4955. \end{figure}
  4956. \clearpage
  4957. \section{Select Instructions}
  4958. \label{sec:select-instructions-gc}
  4959. %% void (rep as zero)
  4960. %% allocate
  4961. %% collect (callq collect)
  4962. %% vector-ref
  4963. %% vector-set!
  4964. %% global-value (postpone)
  4965. In this pass we generate x86 code for most of the new operations that
  4966. were needed to compile tuples, including \code{allocate},
  4967. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4968. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4969. The \code{vector-ref} and \code{vector-set!} forms translate into
  4970. \code{movq} instructions with the appropriate \key{deref}. (The
  4971. plus one is to get past the tag at the beginning of the tuple
  4972. representation.)
  4973. \begin{lstlisting}
  4974. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4975. |$\Longrightarrow$|
  4976. (movq |$\itm{vec}'$| (reg r11))
  4977. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4978. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4979. |$\Longrightarrow$|
  4980. (movq |$\itm{vec}'$| (reg r11))
  4981. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4982. (movq (int 0) |$\itm{lhs}$|)
  4983. \end{lstlisting}
  4984. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4985. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4986. register \code{r11} ensures that offsets are only performed with
  4987. register operands. This requires removing \code{r11} from
  4988. consideration by the register allocating.
  4989. We compile the \code{allocate} form to operations on the
  4990. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4991. is the next free address in the FromSpace, so we move it into the
  4992. \itm{lhs} and then move it forward by enough space for the tuple being
  4993. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4994. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4995. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4996. how the tag is organized. We recommend using the Racket operations
  4997. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4998. The type annotation in the \code{vector} form is used to determine the
  4999. pointer mask region of the tag.
  5000. \begin{lstlisting}
  5001. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  5002. |$\Longrightarrow$|
  5003. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  5004. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  5005. (movq |$\itm{lhs}'$| (reg r11))
  5006. (movq (int |$\itm{tag}$|) (deref r11 0))
  5007. \end{lstlisting}
  5008. The \code{collect} form is compiled to a call to the \code{collect}
  5009. function in the runtime. The arguments to \code{collect} are the top
  5010. of the root stack and the number of bytes that need to be allocated.
  5011. We shall use a dedicated register, \code{r15}, to store the pointer to
  5012. the top of the root stack. So \code{r15} is not available for use by
  5013. the register allocator.
  5014. \begin{lstlisting}
  5015. (collect |$\itm{bytes}$|)
  5016. |$\Longrightarrow$|
  5017. (movq (reg r15) (reg rdi))
  5018. (movq |\itm{bytes}| (reg rsi))
  5019. (callq collect)
  5020. \end{lstlisting}
  5021. \begin{figure}[tp]
  5022. \fbox{
  5023. \begin{minipage}{0.96\textwidth}
  5024. \[
  5025. \begin{array}{lcl}
  5026. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5027. \mid (\key{deref}\,\Reg\,\Int) } \\
  5028. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  5029. \mid (\key{global-value}\; \itm{name}) \\
  5030. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5031. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  5032. (\key{subq} \; \Arg\; \Arg) \mid
  5033. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  5034. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  5035. (\key{pushq}\;\Arg) \mid
  5036. (\key{popq}\;\Arg) \mid
  5037. (\key{retq})} \\
  5038. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5039. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5040. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5041. \mid (\key{jmp} \; \itm{label})
  5042. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  5043. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  5044. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  5045. \end{array}
  5046. \]
  5047. \end{minipage}
  5048. }
  5049. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5050. \label{fig:x86-2}
  5051. \end{figure}
  5052. The syntax of the $x86_2$ language is defined in
  5053. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  5054. of the form for global variables.
  5055. %
  5056. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5057. \code{select-instructions} pass on the running example.
  5058. \begin{figure}[tbp]
  5059. \centering
  5060. \begin{minipage}{0.75\textwidth}
  5061. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5062. (program
  5063. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5064. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5065. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5066. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5067. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5068. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5069. ((block63 . (block ()
  5070. (movq (reg r15) (reg rdi))
  5071. (movq (int 16) (reg rsi))
  5072. (callq collect)
  5073. (jmp block61)))
  5074. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5075. (block61 . (block ()
  5076. (movq (global-value free_ptr) (var alloc43))
  5077. (addq (int 16) (global-value free_ptr))
  5078. (movq (var alloc43) (reg r11))
  5079. (movq (int 3) (deref r11 0))
  5080. (movq (var alloc43) (reg r11))
  5081. (movq (var vecinit44) (deref r11 8))
  5082. (movq (int 0) (var initret45))
  5083. (movq (var alloc43) (var vecinit48))
  5084. (movq (global-value free_ptr) (var tmp54))
  5085. (movq (var tmp54) (var tmp55))
  5086. (addq (int 16) (var tmp55))
  5087. (movq (global-value fromspace_end) (var tmp56))
  5088. (cmpq (var tmp56) (var tmp55))
  5089. (jmp-if l block59)
  5090. (jmp block60)))
  5091. (block60 . (block ()
  5092. (movq (reg r15) (reg rdi))
  5093. (movq (int 16) (reg rsi))
  5094. (callq collect)
  5095. (jmp block58))
  5096. (block59 . (block ()
  5097. (movq (int 0) (var collectret50))
  5098. (jmp block58)))
  5099. (block58 . (block ()
  5100. (movq (global-value free_ptr) (var alloc47))
  5101. (addq (int 16) (global-value free_ptr))
  5102. (movq (var alloc47) (reg r11))
  5103. (movq (int 131) (deref r11 0))
  5104. (movq (var alloc47) (reg r11))
  5105. (movq (var vecinit48) (deref r11 8))
  5106. (movq (int 0) (var initret49))
  5107. (movq (var alloc47) (reg r11))
  5108. (movq (deref r11 8) (var tmp57))
  5109. (movq (var tmp57) (reg r11))
  5110. (movq (deref r11 8) (reg rax))
  5111. (jmp conclusion)))
  5112. (start . (block ()
  5113. (movq (int 42) (var vecinit44))
  5114. (movq (global-value free_ptr) (var tmp51))
  5115. (movq (var tmp51) (var tmp52))
  5116. (addq (int 16) (var tmp52))
  5117. (movq (global-value fromspace_end) (var tmp53))
  5118. (cmpq (var tmp53) (var tmp52))
  5119. (jmp-if l block62)
  5120. (jmp block63))))))
  5121. \end{lstlisting}
  5122. \end{minipage}
  5123. \caption{Output of the \code{select-instructions} pass.}
  5124. \label{fig:select-instr-output-gc}
  5125. \end{figure}
  5126. \clearpage
  5127. \section{Register Allocation}
  5128. \label{sec:reg-alloc-gc}
  5129. As discussed earlier in this chapter, the garbage collector needs to
  5130. access all the pointers in the root set, that is, all variables that
  5131. are vectors. It will be the responsibility of the register allocator
  5132. to make sure that:
  5133. \begin{enumerate}
  5134. \item the root stack is used for spilling vector-typed variables, and
  5135. \item if a vector-typed variable is live during a call to the
  5136. collector, it must be spilled to ensure it is visible to the
  5137. collector.
  5138. \end{enumerate}
  5139. The later responsibility can be handled during construction of the
  5140. inference graph, by adding interference edges between the call-live
  5141. vector-typed variables and all the callee-saved registers. (They
  5142. already interfere with the caller-saved registers.) The type
  5143. information for variables is in the \code{program} form, so we
  5144. recommend adding another parameter to the \code{build-interference}
  5145. function to communicate this association list.
  5146. The spilling of vector-typed variables to the root stack can be
  5147. handled after graph coloring, when choosing how to assign the colors
  5148. (integers) to registers and stack locations. The \code{program} output
  5149. of this pass changes to also record the number of spills to the root
  5150. stack.
  5151. % build-interference
  5152. %
  5153. % callq
  5154. % extra parameter for var->type assoc. list
  5155. % update 'program' and 'if'
  5156. % allocate-registers
  5157. % allocate spilled vectors to the rootstack
  5158. % don't change color-graph
  5159. \section{Print x86}
  5160. \label{sec:print-x86-gc}
  5161. \margincomment{\scriptsize We need to show the translation to x86 and what
  5162. to do about global-value. \\ --Jeremy}
  5163. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5164. \code{print-x86} pass on the running example. In the prelude and
  5165. conclusion of the \code{main} function, we treat the root stack very
  5166. much like the regular stack in that we move the root stack pointer
  5167. (\code{r15}) to make room for all of the spills to the root stack,
  5168. except that the root stack grows up instead of down. For the running
  5169. example, there was just one spill so we increment \code{r15} by 8
  5170. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5171. One issue that deserves special care is that there may be a call to
  5172. \code{collect} prior to the initializing assignments for all the
  5173. variables in the root stack. We do not want the garbage collector to
  5174. accidentally think that some uninitialized variable is a pointer that
  5175. needs to be followed. Thus, we zero-out all locations on the root
  5176. stack in the prelude of \code{main}. In
  5177. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5178. %
  5179. \lstinline{movq $0, (%r15)}
  5180. %
  5181. accomplishes this task. The garbage collector tests each root to see
  5182. if it is null prior to dereferencing it.
  5183. \begin{figure}[htbp]
  5184. \begin{minipage}[t]{0.5\textwidth}
  5185. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5186. _block58:
  5187. movq _free_ptr(%rip), %rcx
  5188. addq $16, _free_ptr(%rip)
  5189. movq %rcx, %r11
  5190. movq $131, 0(%r11)
  5191. movq %rcx, %r11
  5192. movq -8(%r15), %rax
  5193. movq %rax, 8(%r11)
  5194. movq $0, %rdx
  5195. movq %rcx, %r11
  5196. movq 8(%r11), %rcx
  5197. movq %rcx, %r11
  5198. movq 8(%r11), %rax
  5199. jmp _conclusion
  5200. _block59:
  5201. movq $0, %rcx
  5202. jmp _block58
  5203. _block62:
  5204. movq $0, %rcx
  5205. jmp _block61
  5206. _block60:
  5207. movq %r15, %rdi
  5208. movq $16, %rsi
  5209. callq _collect
  5210. jmp _block58
  5211. _block63:
  5212. movq %r15, %rdi
  5213. movq $16, %rsi
  5214. callq _collect
  5215. jmp _block61
  5216. _start:
  5217. movq $42, %rbx
  5218. movq _free_ptr(%rip), %rdx
  5219. addq $16, %rdx
  5220. movq _fromspace_end(%rip), %rcx
  5221. cmpq %rcx, %rdx
  5222. jl _block62
  5223. jmp _block63
  5224. \end{lstlisting}
  5225. \end{minipage}
  5226. \begin{minipage}[t]{0.45\textwidth}
  5227. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5228. _block61:
  5229. movq _free_ptr(%rip), %rcx
  5230. addq $16, _free_ptr(%rip)
  5231. movq %rcx, %r11
  5232. movq $3, 0(%r11)
  5233. movq %rcx, %r11
  5234. movq %rbx, 8(%r11)
  5235. movq $0, %rdx
  5236. movq %rcx, -8(%r15)
  5237. movq _free_ptr(%rip), %rcx
  5238. addq $16, %rcx
  5239. movq _fromspace_end(%rip), %rdx
  5240. cmpq %rdx, %rcx
  5241. jl _block59
  5242. jmp _block60
  5243. .globl _main
  5244. _main:
  5245. pushq %rbp
  5246. movq %rsp, %rbp
  5247. pushq %r12
  5248. pushq %rbx
  5249. pushq %r13
  5250. pushq %r14
  5251. subq $0, %rsp
  5252. movq $16384, %rdi
  5253. movq $16, %rsi
  5254. callq _initialize
  5255. movq _rootstack_begin(%rip), %r15
  5256. movq $0, (%r15)
  5257. addq $8, %r15
  5258. jmp _start
  5259. _conclusion:
  5260. subq $8, %r15
  5261. addq $0, %rsp
  5262. popq %r14
  5263. popq %r13
  5264. popq %rbx
  5265. popq %r12
  5266. popq %rbp
  5267. retq
  5268. \end{lstlisting}
  5269. \end{minipage}
  5270. \caption{Output of the \code{print-x86} pass.}
  5271. \label{fig:print-x86-output-gc}
  5272. \end{figure}
  5273. \margincomment{\scriptsize Suggest an implementation strategy
  5274. in which the students first do the code gen and test that
  5275. without GC (just use a big heap), then after that is debugged,
  5276. implement the GC. \\ --Jeremy}
  5277. \begin{figure}[p]
  5278. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5279. \node (R3) at (0,2) {\large $R_3$};
  5280. \node (R3-2) at (3,2) {\large $R_3$};
  5281. \node (R3-3) at (6,2) {\large $R_3$};
  5282. \node (R3-4) at (9,2) {\large $R_3$};
  5283. \node (R3-5) at (12,2) {\large $R_3$};
  5284. \node (C2-4) at (3,0) {\large $C_2$};
  5285. \node (C2-3) at (6,0) {\large $C_2$};
  5286. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5287. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5288. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5289. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5290. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5291. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5292. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5293. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5294. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5295. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5296. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5297. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5298. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5299. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5300. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5301. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5302. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5303. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5304. \end{tikzpicture}
  5305. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5306. \label{fig:R3-passes}
  5307. \end{figure}
  5308. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5309. for the compilation of $R_3$.
  5310. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5311. \chapter{Functions}
  5312. \label{ch:functions}
  5313. This chapter studies the compilation of functions at the level of
  5314. abstraction of the C language. This corresponds to a subset of Typed
  5315. Racket in which only top-level function definitions are allowed. These
  5316. kind of functions are an important stepping stone to implementing
  5317. lexically-scoped functions in the form of \key{lambda} abstractions,
  5318. which is the topic of Chapter~\ref{ch:lambdas}.
  5319. \section{The $R_4$ Language}
  5320. The syntax for function definitions and function application is shown
  5321. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5322. Programs in $R_4$ start with zero or more function definitions. The
  5323. function names from these definitions are in-scope for the entire
  5324. program, including all other function definitions (so the ordering of
  5325. function definitions does not matter). The syntax for function
  5326. application does not include an explicit keyword, which is error prone
  5327. when using \code{match}. To alleviate this problem, we change the
  5328. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5329. during type checking.
  5330. Functions are first-class in the sense that a function pointer is data
  5331. and can be stored in memory or passed as a parameter to another
  5332. function. Thus, we introduce a function type, written
  5333. \begin{lstlisting}
  5334. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5335. \end{lstlisting}
  5336. for a function whose $n$ parameters have the types $\Type_1$ through
  5337. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5338. these functions (with respect to Racket functions) is that they are
  5339. not lexically scoped. That is, the only external entities that can be
  5340. referenced from inside a function body are other globally-defined
  5341. functions. The syntax of $R_4$ prevents functions from being nested
  5342. inside each other.
  5343. \begin{figure}[tp]
  5344. \centering
  5345. \fbox{
  5346. \begin{minipage}{0.96\textwidth}
  5347. \[
  5348. \begin{array}{lcl}
  5349. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5350. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5351. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5352. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5353. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5354. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5355. \mid (\key{and}\;\Exp\;\Exp)
  5356. \mid (\key{or}\;\Exp\;\Exp)
  5357. \mid (\key{not}\;\Exp)} \\
  5358. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5359. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5360. (\key{vector-ref}\;\Exp\;\Int)} \\
  5361. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5362. &\mid& (\Exp \; \Exp^{*}) \\
  5363. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5364. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5365. \end{array}
  5366. \]
  5367. \end{minipage}
  5368. }
  5369. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5370. with functions.}
  5371. \label{fig:r4-syntax}
  5372. \end{figure}
  5373. The program in Figure~\ref{fig:r4-function-example} is a
  5374. representative example of defining and using functions in $R_4$. We
  5375. define a function \code{map-vec} that applies some other function
  5376. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5377. vector containing the results. We also define a function \code{add1}
  5378. that does what its name suggests. The program then applies
  5379. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5380. \code{(vector 1 42)}, from which we return the \code{42}.
  5381. \begin{figure}[tbp]
  5382. \begin{lstlisting}
  5383. (program ()
  5384. (define (map-vec [f : (Integer -> Integer)]
  5385. [v : (Vector Integer Integer)])
  5386. : (Vector Integer Integer)
  5387. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5388. (define (add1 [x : Integer]) : Integer
  5389. (+ x 1))
  5390. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5391. )
  5392. \end{lstlisting}
  5393. \caption{Example of using functions in $R_4$.}
  5394. \label{fig:r4-function-example}
  5395. \end{figure}
  5396. The definitional interpreter for $R_4$ is in
  5397. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5398. responsible for setting up the mutual recursion between the top-level
  5399. function definitions. We use the classic back-patching approach that
  5400. uses mutable variables and makes two passes over the function
  5401. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5402. top-level environment using a mutable cons cell for each function
  5403. definition. Note that the \code{lambda} value for each function is
  5404. incomplete; it does not yet include the environment. Once the
  5405. top-level environment is constructed, we then iterate over it and
  5406. update the \code{lambda} value's to use the top-level environment.
  5407. \begin{figure}[tp]
  5408. \begin{lstlisting}
  5409. (define (interp-exp env)
  5410. (lambda (e)
  5411. (define recur (interp-exp env))
  5412. (match e
  5413. ...
  5414. [`(,fun ,args ...)
  5415. (define arg-vals (for/list ([e args]) (recur e)))
  5416. (define fun-val (recur fun))
  5417. (match fun-val
  5418. [`(lambda (,xs ...) ,body ,fun-env)
  5419. (define new-env (append (map cons xs arg-vals) fun-env))
  5420. ((interp-exp new-env) body)]
  5421. [else (error "interp-exp, expected function, not" fun-val)])]
  5422. [else (error 'interp-exp "unrecognized expression")]
  5423. )))
  5424. (define (interp-def d)
  5425. (match d
  5426. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5427. (mcons f `(lambda ,xs ,body ()))]
  5428. ))
  5429. (define (interp-R4 p)
  5430. (match p
  5431. [`(program ,ds ... ,body)
  5432. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5433. (for/list ([b top-level])
  5434. (set-mcdr! b (match (mcdr b)
  5435. [`(lambda ,xs ,body ())
  5436. `(lambda ,xs ,body ,top-level)])))
  5437. ((interp-exp top-level) body))]
  5438. ))
  5439. \end{lstlisting}
  5440. \caption{Interpreter for the $R_4$ language.}
  5441. \label{fig:interp-R4}
  5442. \end{figure}
  5443. \section{Functions in x86}
  5444. \label{sec:fun-x86}
  5445. \margincomment{\tiny Make sure callee-saved registers are discussed
  5446. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5447. \margincomment{\tiny Talk about the return address on the
  5448. stack and what callq and retq does.\\ --Jeremy }
  5449. The x86 architecture provides a few features to support the
  5450. implementation of functions. We have already seen that x86 provides
  5451. labels so that one can refer to the location of an instruction, as is
  5452. needed for jump instructions. Labels can also be used to mark the
  5453. beginning of the instructions for a function. Going further, we can
  5454. obtain the address of a label by using the \key{leaq} instruction and
  5455. \key{rip}-relative addressing. For example, the following puts the
  5456. address of the \code{add1} label into the \code{rbx} register.
  5457. \begin{lstlisting}
  5458. leaq add1(%rip), %rbx
  5459. \end{lstlisting}
  5460. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5461. instruction for jumping to a function whose location is given by a
  5462. label. Here we instead will be jumping to a function whose location is
  5463. given by an address, that is, we need to make an \emph{indirect
  5464. function call}. The x86 syntax is to give the register name prefixed
  5465. with an asterisk.
  5466. \begin{lstlisting}
  5467. callq *%rbx
  5468. \end{lstlisting}
  5469. \subsection{Calling Conventions}
  5470. The \code{callq} instruction provides partial support for implementing
  5471. functions, but it does not handle (1) parameter passing, (2) saving
  5472. and restoring frames on the procedure call stack, or (3) determining
  5473. how registers are shared by different functions. These issues require
  5474. coordination between the caller and the callee, which is often
  5475. assembly code written by different programmers or generated by
  5476. different compilers. As a result, people have developed
  5477. \emph{conventions} that govern how functions calls are performed.
  5478. Here we shall use the same conventions used by the \code{gcc}
  5479. compiler~\citep{Matz:2013aa}.
  5480. Regarding (1) parameter passing, the convention is to use the
  5481. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5482. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5483. than six arguments, then the convention is to use space on the frame
  5484. of the caller for the rest of the arguments. However, to ease the
  5485. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5486. we shall arrange to never have more than six arguments.
  5487. %
  5488. The register \code{rax} is for the return value of the function.
  5489. Regarding (2) frames and the procedure call stack, the convention is
  5490. that the stack grows down, with each function call using a chunk of
  5491. space called a frame. The caller sets the stack pointer, register
  5492. \code{rsp}, to the last data item in its frame. The callee must not
  5493. change anything in the caller's frame, that is, anything that is at or
  5494. above the stack pointer. The callee is free to use locations that are
  5495. below the stack pointer.
  5496. Regarding (3) the sharing of registers between different functions,
  5497. recall from Section~\ref{sec:calling-conventions} that the registers
  5498. are divided into two groups, the caller-saved registers and the
  5499. callee-saved registers. The caller should assume that all the
  5500. caller-saved registers get overwritten with arbitrary values by the
  5501. callee. Thus, the caller should either 1) not put values that are live
  5502. across a call in caller-saved registers, or 2) save and restore values
  5503. that are live across calls. We shall recommend option 1). On the flip
  5504. side, if the callee wants to use a callee-saved register, the callee
  5505. must save the contents of those registers on their stack frame and
  5506. then put them back prior to returning to the caller. The base
  5507. pointer, register \code{rbp}, is used as a point-of-reference within a
  5508. frame, so that each local variable can be accessed at a fixed offset
  5509. from the base pointer.
  5510. %
  5511. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5512. frames.
  5513. %% If we were to use stack arguments, they would be between the
  5514. %% caller locals and the callee return address.
  5515. \begin{figure}[tbp]
  5516. \centering
  5517. \begin{tabular}{r|r|l|l} \hline
  5518. Caller View & Callee View & Contents & Frame \\ \hline
  5519. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5520. 0(\key{\%rbp}) & & old \key{rbp} \\
  5521. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5522. \ldots & & \ldots \\
  5523. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5524. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5525. \ldots & & \ldots \\
  5526. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5527. %% & & \\
  5528. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5529. %% & \ldots & \ldots \\
  5530. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5531. \hline
  5532. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5533. & 0(\key{\%rbp}) & old \key{rbp} \\
  5534. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5535. & \ldots & \ldots \\
  5536. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5537. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5538. & \ldots & \ldots \\
  5539. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5540. \end{tabular}
  5541. \caption{Memory layout of caller and callee frames.}
  5542. \label{fig:call-frames}
  5543. \end{figure}
  5544. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5545. %% local variables and for storing the values of callee-saved registers
  5546. %% (we shall refer to all of these collectively as ``locals''), and that
  5547. %% at the beginning of a function we move the stack pointer \code{rsp}
  5548. %% down to make room for them.
  5549. %% We recommend storing the local variables
  5550. %% first and then the callee-saved registers, so that the local variables
  5551. %% can be accessed using \code{rbp} the same as before the addition of
  5552. %% functions.
  5553. %% To make additional room for passing arguments, we shall
  5554. %% move the stack pointer even further down. We count how many stack
  5555. %% arguments are needed for each function call that occurs inside the
  5556. %% body of the function and find their maximum. Adding this number to the
  5557. %% number of locals gives us how much the \code{rsp} should be moved at
  5558. %% the beginning of the function. In preparation for a function call, we
  5559. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5560. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5561. %% so on.
  5562. %% Upon calling the function, the stack arguments are retrieved by the
  5563. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5564. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5565. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5566. %% the layout of the caller and callee frames. Notice how important it is
  5567. %% that we correctly compute the maximum number of arguments needed for
  5568. %% function calls; if that number is too small then the arguments and
  5569. %% local variables will smash into each other!
  5570. \subsection{Efficient Tail Calls}
  5571. \label{sec:tail-call}
  5572. In general, the amount of stack space used by a program is determined
  5573. by the longest chain of nested function calls. That is, if function
  5574. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5575. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5576. $n$ can grow quite large in the case of recursive or mutually
  5577. recursive functions. However, in some cases we can arrange to use only
  5578. constant space, i.e. $O(1)$, instead of $O(n)$.
  5579. If a function call is the last action in a function body, then that
  5580. call is said to be a \emph{tail call}. In such situations, the frame
  5581. of the caller is no longer needed, so we can pop the caller's frame
  5582. before making the tail call. With this approach, a recursive function
  5583. that only makes tail calls will only use $O(1)$ stack space.
  5584. Functional languages like Racket typically rely heavily on recursive
  5585. functions, so they typically guarantee that all tail calls will be
  5586. optimized in this way.
  5587. However, some care is needed with regards to argument passing in tail
  5588. calls. As mentioned above, for arguments beyond the sixth, the
  5589. convention is to use space in the caller's frame for passing
  5590. arguments. But here we've popped the caller's frame and can no longer
  5591. use it. Another alternative is to use space in the callee's frame for
  5592. passing arguments. However, this option is also problematic because
  5593. the caller and callee's frame overlap in memory. As we begin to copy
  5594. the arguments from their sources in the caller's frame, the target
  5595. locations in the callee's frame might overlap with the sources for
  5596. later arguments! We solve this problem by not using the stack for
  5597. parameter passing but instead use the heap, as we describe in the
  5598. Section~\ref{sec:limit-functions-r4}.
  5599. As mentioned above, for a tail call we pop the caller's frame prior to
  5600. making the tail call. The instructions for popping a frame are the
  5601. instructions that we usually place in the conclusion of a
  5602. function. Thus, we also need to place such code immediately before
  5603. each tail call. These instructions include restoring the callee-saved
  5604. registers, so it is good that the argument passing registers are all
  5605. caller-saved registers.
  5606. One last note regarding which instruction to use to make the tail
  5607. call. When the callee is finished, it should not return to the current
  5608. function, but it should return to the function that called the current
  5609. one. Thus, the return address that is already on the stack is the
  5610. right one, and we should not use \key{callq} to make the tail call, as
  5611. that would unnecessarily overwrite the return address. Instead we can
  5612. simply use the \key{jmp} instruction. Like the indirect function call,
  5613. we write an indirect jump with a register prefixed with an asterisk.
  5614. We recommend using \code{rax} to hold the jump target because the
  5615. preceding ``conclusion'' overwrites just about everything else.
  5616. \begin{lstlisting}
  5617. jmp *%rax
  5618. \end{lstlisting}
  5619. %% Now that we have a good understanding of functions as they appear in
  5620. %% $R_4$ and the support for functions in x86, we need to plan the
  5621. %% changes to our compiler, that is, do we need any new passes and/or do
  5622. %% we need to change any existing passes? Also, do we need to add new
  5623. %% kinds of AST nodes to any of the intermediate languages?
  5624. \section{Shrink $R_4$}
  5625. \label{sec:shrink-r4}
  5626. The \code{shrink} pass performs a couple minor modifications to the
  5627. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5628. field to each function definition:
  5629. \begin{lstlisting}
  5630. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5631. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5632. \end{lstlisting}
  5633. and introduces an explicit \code{main} function.\\
  5634. \begin{tabular}{lll}
  5635. \begin{minipage}{0.45\textwidth}
  5636. \begin{lstlisting}
  5637. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5638. \end{lstlisting}
  5639. \end{minipage}
  5640. &
  5641. $\Rightarrow$
  5642. &
  5643. \begin{minipage}{0.45\textwidth}
  5644. \begin{lstlisting}
  5645. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5646. \end{lstlisting}
  5647. \end{minipage}
  5648. \end{tabular} \\
  5649. where $\itm{mainDef}$ is
  5650. \begin{lstlisting}
  5651. (define (main) : Integer () |$\Exp'$|)
  5652. \end{lstlisting}
  5653. \section{Reveal Functions}
  5654. \label{sec:reveal-functions-r4}
  5655. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5656. compilation because it conflates the use of function names and local
  5657. variables. This is a problem because we need to compile the use of a
  5658. function name differently than the use of a local variable; we need to
  5659. use \code{leaq} to convert the function name (a label in x86) to an
  5660. address in a register. Thus, it is a good idea to create a new pass
  5661. that changes function references from just a symbol $f$ to
  5662. \code{(fun-ref $f$)}. A good name for this pass is
  5663. \code{reveal-functions} and the output language, $F_1$, is defined in
  5664. Figure~\ref{fig:f1-syntax}.
  5665. \begin{figure}[tp]
  5666. \centering
  5667. \fbox{
  5668. \begin{minipage}{0.96\textwidth}
  5669. \[
  5670. \begin{array}{lcl}
  5671. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5672. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5673. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5674. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5675. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5676. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5677. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5678. (\key{vector-ref}\;\Exp\;\Int)} \\
  5679. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5680. (\key{app}\; \Exp \; \Exp^{*})} \\
  5681. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5682. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5683. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5684. \end{array}
  5685. \]
  5686. \end{minipage}
  5687. }
  5688. \caption{The $F_1$ language, an extension of $R_4$
  5689. (Figure~\ref{fig:r4-syntax}).}
  5690. \label{fig:f1-syntax}
  5691. \end{figure}
  5692. %% Distinguishing between calls in tail position and non-tail position
  5693. %% requires the pass to have some notion of context. We recommend using
  5694. %% two mutually recursive functions, one for processing expressions in
  5695. %% tail position and another for the rest.
  5696. Placing this pass after \code{uniquify} is a good idea, because it
  5697. will make sure that there are no local variables and functions that
  5698. share the same name. On the other hand, \code{reveal-functions} needs
  5699. to come before the \code{explicate-control} pass because that pass
  5700. will help us compile \code{fun-ref} into assignment statements.
  5701. \section{Limit Functions}
  5702. \label{sec:limit-functions-r4}
  5703. This pass transforms functions so that they have at most six
  5704. parameters and transforms all function calls so that they pass at most
  5705. six arguments. A simple strategy for imposing an argument limit of
  5706. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5707. into a vector, making that subsequent vector the $n$th argument.
  5708. \begin{tabular}{lll}
  5709. \begin{minipage}{0.2\textwidth}
  5710. \begin{lstlisting}
  5711. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5712. \end{lstlisting}
  5713. \end{minipage}
  5714. &
  5715. $\Rightarrow$
  5716. &
  5717. \begin{minipage}{0.4\textwidth}
  5718. \begin{lstlisting}
  5719. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5720. \end{lstlisting}
  5721. \end{minipage}
  5722. \end{tabular}
  5723. In the body of the function, all occurrences of the $i$th argument in
  5724. which $i>5$ must be replaced with a \code{vector-ref}.
  5725. \section{Remove Complex Operators and Operands}
  5726. \label{sec:rco-r4}
  5727. The primary decisions to make for this pass is whether to classify
  5728. \code{fun-ref} and \code{app} as either simple or complex
  5729. expressions. Recall that a simple expression will eventually end up as
  5730. just an ``immediate'' argument of an x86 instruction. Function
  5731. application will be translated to a sequence of instructions, so
  5732. \code{app} must be classified as complex expression. Regarding
  5733. \code{fun-ref}, as discussed above, the function label needs to
  5734. be converted to an address using the \code{leaq} instruction. Thus,
  5735. even though \code{fun-ref} seems rather simple, it needs to be
  5736. classified as a complex expression so that we generate an assignment
  5737. statement with a left-hand side that can serve as the target of the
  5738. \code{leaq}.
  5739. \section{Explicate Control and the $C_3$ language}
  5740. \label{sec:explicate-control-r4}
  5741. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5742. \key{explicate-control}. The three mutually recursive functions for
  5743. this pass, for assignment, tail, and predicate contexts, must all be
  5744. updated with cases for \code{fun-ref} and \code{app}. In
  5745. assignment and predicate contexts, \code{app} becomes \code{call},
  5746. whereas in tail position \code{app} becomes \code{tailcall}. We
  5747. recommend defining a new function for processing function definitions.
  5748. This code is similar to the case for \code{program} in $R_3$. The
  5749. top-level \code{explicate-control} function that handles the
  5750. \code{program} form of $R_4$ can then apply this new function to all
  5751. the function definitions.
  5752. \begin{figure}[tp]
  5753. \fbox{
  5754. \begin{minipage}{0.96\textwidth}
  5755. \[
  5756. \begin{array}{lcl}
  5757. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5758. \\
  5759. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5760. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5761. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5762. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5763. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5764. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5765. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5766. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5767. \mid (\key{collect} \,\itm{int}) }\\
  5768. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5769. &\mid& \gray{(\key{goto}\,\itm{label})
  5770. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5771. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5772. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5773. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5774. \end{array}
  5775. \]
  5776. \end{minipage}
  5777. }
  5778. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5779. \label{fig:c3-syntax}
  5780. \end{figure}
  5781. \section{Uncover Locals}
  5782. \label{sec:uncover-locals-r4}
  5783. The function for processing $\Tail$ should be updated with a case for
  5784. \code{tailcall}. We also recommend creating a new function for
  5785. processing function definitions. Each function definition in $C_3$ has
  5786. its own set of local variables, so the code for function definitions
  5787. should be similar to the case for the \code{program} form in $C_2$.
  5788. \section{Select Instructions}
  5789. \label{sec:select-r4}
  5790. The output of select instructions is a program in the x86$_3$
  5791. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5792. \begin{figure}[tp]
  5793. \fbox{
  5794. \begin{minipage}{0.96\textwidth}
  5795. \[
  5796. \begin{array}{lcl}
  5797. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5798. \mid (\key{deref}\,\Reg\,\Int) } \\
  5799. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  5800. \mid (\key{global-value}\; \itm{name}) } \\
  5801. &\mid& (\key{fun-ref}\; \itm{label})\\
  5802. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5803. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5804. (\key{subq} \; \Arg\; \Arg) \mid
  5805. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5806. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5807. (\key{pushq}\;\Arg) \mid
  5808. (\key{popq}\;\Arg) \mid
  5809. (\key{retq}) } \\
  5810. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5811. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5812. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5813. \mid (\key{jmp} \; \itm{label})
  5814. \mid (\key{j}\itm{cc} \; \itm{label})
  5815. \mid (\key{label} \; \itm{label}) } \\
  5816. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5817. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5818. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5819. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5820. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5821. \end{array}
  5822. \]
  5823. \end{minipage}
  5824. }
  5825. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5826. \label{fig:x86-3}
  5827. \end{figure}
  5828. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5829. as follows: \\
  5830. \begin{tabular}{lll}
  5831. \begin{minipage}{0.45\textwidth}
  5832. \begin{lstlisting}
  5833. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5834. \end{lstlisting}
  5835. \end{minipage}
  5836. &
  5837. $\Rightarrow$
  5838. &
  5839. \begin{minipage}{0.4\textwidth}
  5840. \begin{lstlisting}
  5841. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5842. \end{lstlisting}
  5843. \end{minipage}
  5844. \end{tabular} \\
  5845. Regarding function definitions, we need to remove their parameters and
  5846. instead perform parameter passing in terms of the conventions
  5847. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5848. in the argument passing registers, and inside the function we should
  5849. generate a \code{movq} instruction for each parameter, to move the
  5850. argument value from the appropriate register to a new local variable
  5851. with the same name as the old parameter.
  5852. Next, consider the compilation of function calls, which have the
  5853. following form upon input to \code{select-instructions}.
  5854. \begin{lstlisting}
  5855. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5856. \end{lstlisting}
  5857. In the mirror image of handling the parameters of function
  5858. definitions, the arguments \itm{args} need to be moved to the argument
  5859. passing registers.
  5860. %
  5861. Once the instructions for parameter passing have been generated, the
  5862. function call itself can be performed with an indirect function call,
  5863. for which I recommend creating the new instruction
  5864. \code{indirect-callq}. Of course, the return value from the function
  5865. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5866. \begin{lstlisting}
  5867. (indirect-callq |\itm{fun}|)
  5868. (movq (reg rax) |\itm{lhs}|)
  5869. \end{lstlisting}
  5870. Regarding tail calls, the parameter passing is the same as non-tail
  5871. calls: generate instructions to move the arguments into to the
  5872. argument passing registers. After that we need to pop the frame from
  5873. the procedure call stack. However, we do not yet know how big the
  5874. frame is; that gets determined during register allocation. So instead
  5875. of generating those instructions here, we invent a new instruction
  5876. that means ``pop the frame and then do an indirect jump'', which we
  5877. name \code{tail-jmp}.
  5878. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5879. using the label \code{start} for the initial block of a program, and
  5880. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5881. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5882. can be compiled to an assignment to \code{rax} followed by a jump to
  5883. \code{conclusion}. With the addition of function definitions, we will
  5884. have a starting block and conclusion for each function, but their
  5885. labels need to be unique. We recommend prepending the function's name
  5886. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5887. labels. (Alternatively, one could \code{gensym} labels for the start
  5888. and conclusion and store them in the $\itm{info}$ field of the
  5889. function definition.)
  5890. \section{Uncover Live}
  5891. %% The rest of the passes need only minor modifications to handle the new
  5892. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5893. %% \code{leaq}.
  5894. Inside \code{uncover-live}, when computing the $W$ set (written
  5895. variables) for an \code{indirect-callq} instruction, we recommend
  5896. including all the caller-saved registers, which will have the affect
  5897. of making sure that no caller-saved register actually needs to be
  5898. saved.
  5899. \section{Build Interference Graph}
  5900. With the addition of function definitions, we compute an interference
  5901. graph for each function (not just one for the whole program).
  5902. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5903. spill vector-typed variables that are live during a call to the
  5904. \code{collect}. With the addition of functions to our language, we
  5905. need to revisit this issue. Many functions will perform allocation and
  5906. therefore have calls to the collector inside of them. Thus, we should
  5907. not only spill a vector-typed variable when it is live during a call
  5908. to \code{collect}, but we should spill the variable if it is live
  5909. during any function call. Thus, in the \code{build-interference} pass,
  5910. we recommend adding interference edges between call-live vector-typed
  5911. variables and the callee-saved registers (in addition to the usual
  5912. addition of edges between call-live variables and the caller-saved
  5913. registers).
  5914. \section{Patch Instructions}
  5915. In \code{patch-instructions}, you should deal with the x86
  5916. idiosyncrasy that the destination argument of \code{leaq} must be a
  5917. register. Additionally, you should ensure that the argument of
  5918. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5919. code generation more convenient, because we will be trampling many
  5920. registers before the tail call (as explained below).
  5921. \section{Print x86}
  5922. For the \code{print-x86} pass, we recommend the following translations:
  5923. \begin{lstlisting}
  5924. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5925. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5926. \end{lstlisting}
  5927. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5928. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5929. is what we will want to do, but before the jump we need to pop the
  5930. current frame. So we need to restore the state of the registers to the
  5931. point they were at when the current function was called. This
  5932. sequence of instructions is the same as the code for the conclusion of
  5933. a function.
  5934. Note that your \code{print-x86} pass needs to add the code for saving
  5935. and restoring callee-saved registers, if you have not already
  5936. implemented that. This is necessary when generating code for function
  5937. definitions.
  5938. \section{An Example Translation}
  5939. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5940. function in $R_4$ to x86. The figure also includes the results of the
  5941. \code{explicate-control} and \code{select-instructions} passes. We
  5942. have omitted the \code{has-type} AST nodes for readability. Can you
  5943. see any ways to improve the translation?
  5944. \begin{figure}[tbp]
  5945. \begin{tabular}{ll}
  5946. \begin{minipage}{0.45\textwidth}
  5947. % s3_2.rkt
  5948. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5949. (program
  5950. (define (add [x : Integer]
  5951. [y : Integer])
  5952. : Integer (+ x y))
  5953. (add 40 2))
  5954. \end{lstlisting}
  5955. $\Downarrow$
  5956. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5957. (program ()
  5958. (define (add86 [x87 : Integer]
  5959. [y88 : Integer]) : Integer ()
  5960. ((add86start . (return (+ x87 y88)))))
  5961. (define (main) : Integer ()
  5962. ((mainstart .
  5963. (seq (assign tmp89 (fun-ref add86))
  5964. (tailcall tmp89 40 2))))))
  5965. \end{lstlisting}
  5966. \end{minipage}
  5967. &
  5968. $\Rightarrow$
  5969. \begin{minipage}{0.5\textwidth}
  5970. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5971. (program ()
  5972. (define (add86)
  5973. ((locals (x87 . Integer) (y88 . Integer))
  5974. (num-params . 2))
  5975. ((add86start .
  5976. (block ()
  5977. (movq (reg rcx) (var x87))
  5978. (movq (reg rdx) (var y88))
  5979. (movq (var x87) (reg rax))
  5980. (addq (var y88) (reg rax))
  5981. (jmp add86conclusion)))))
  5982. (define (main)
  5983. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5984. (num-params . 0))
  5985. ((mainstart .
  5986. (block ()
  5987. (leaq (fun-ref add86) (var tmp89))
  5988. (movq (int 40) (reg rcx))
  5989. (movq (int 2) (reg rdx))
  5990. (tail-jmp (var tmp89))))))
  5991. \end{lstlisting}
  5992. $\Downarrow$
  5993. \end{minipage}
  5994. \end{tabular}
  5995. \begin{tabular}{lll}
  5996. \begin{minipage}{0.3\textwidth}
  5997. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5998. _add90start:
  5999. movq %rcx, %rsi
  6000. movq %rdx, %rcx
  6001. movq %rsi, %rax
  6002. addq %rcx, %rax
  6003. jmp _add90conclusion
  6004. .globl _add90
  6005. .align 16
  6006. _add90:
  6007. pushq %rbp
  6008. movq %rsp, %rbp
  6009. pushq %r12
  6010. pushq %rbx
  6011. pushq %r13
  6012. pushq %r14
  6013. subq $0, %rsp
  6014. jmp _add90start
  6015. _add90conclusion:
  6016. addq $0, %rsp
  6017. popq %r14
  6018. popq %r13
  6019. popq %rbx
  6020. popq %r12
  6021. subq $0, %r15
  6022. popq %rbp
  6023. retq
  6024. \end{lstlisting}
  6025. \end{minipage}
  6026. &
  6027. \begin{minipage}{0.3\textwidth}
  6028. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6029. _mainstart:
  6030. leaq _add90(%rip), %rsi
  6031. movq $40, %rcx
  6032. movq $2, %rdx
  6033. movq %rsi, %rax
  6034. addq $0, %rsp
  6035. popq %r14
  6036. popq %r13
  6037. popq %rbx
  6038. popq %r12
  6039. subq $0, %r15
  6040. popq %rbp
  6041. jmp *%rax
  6042. .globl _main
  6043. .align 16
  6044. _main:
  6045. pushq %rbp
  6046. movq %rsp, %rbp
  6047. pushq %r12
  6048. pushq %rbx
  6049. pushq %r13
  6050. pushq %r14
  6051. subq $0, %rsp
  6052. movq $16384, %rdi
  6053. movq $16, %rsi
  6054. callq _initialize
  6055. movq _rootstack_begin(%rip), %r15
  6056. jmp _mainstart
  6057. \end{lstlisting}
  6058. \end{minipage}
  6059. &
  6060. \begin{minipage}{0.3\textwidth}
  6061. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6062. _mainconclusion:
  6063. addq $0, %rsp
  6064. popq %r14
  6065. popq %r13
  6066. popq %rbx
  6067. popq %r12
  6068. subq $0, %r15
  6069. popq %rbp
  6070. retq
  6071. \end{lstlisting}
  6072. \end{minipage}
  6073. \end{tabular}
  6074. \caption{Example compilation of a simple function to x86.}
  6075. \label{fig:add-fun}
  6076. \end{figure}
  6077. \begin{exercise}\normalfont
  6078. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6079. Create 5 new programs that use functions, including examples that pass
  6080. functions and return functions from other functions and including
  6081. recursive functions. Test your compiler on these new programs and all
  6082. of your previously created test programs.
  6083. \end{exercise}
  6084. \begin{figure}[p]
  6085. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6086. \node (R4) at (0,2) {\large $R_4$};
  6087. \node (R4-2) at (3,2) {\large $R_4$};
  6088. \node (R4-3) at (6,2) {\large $R_4$};
  6089. \node (F1-1) at (12,0) {\large $F_1$};
  6090. \node (F1-2) at (9,0) {\large $F_1$};
  6091. \node (F1-3) at (6,0) {\large $F_1$};
  6092. \node (F1-4) at (3,0) {\large $F_1$};
  6093. \node (C3-1) at (6,-2) {\large $C_3$};
  6094. \node (C3-2) at (3,-2) {\large $C_3$};
  6095. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6096. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6097. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6098. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6099. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6100. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6101. \path[->,bend left=15] (R4) edge [above] node
  6102. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6103. \path[->,bend left=15] (R4-2) edge [above] node
  6104. {\ttfamily\footnotesize uniquify} (R4-3);
  6105. \path[->,bend left=15] (R4-3) edge [right] node
  6106. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6107. \path[->,bend left=15] (F1-1) edge [below] node
  6108. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6109. \path[->,bend right=15] (F1-2) edge [above] node
  6110. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6111. \path[->,bend right=15] (F1-3) edge [above] node
  6112. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6113. \path[->,bend left=15] (F1-4) edge [right] node
  6114. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6115. \path[->,bend left=15] (C3-1) edge [below] node
  6116. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6117. \path[->,bend right=15] (C3-2) edge [left] node
  6118. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6119. \path[->,bend left=15] (x86-2) edge [left] node
  6120. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6121. \path[->,bend right=15] (x86-2-1) edge [below] node
  6122. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6123. \path[->,bend right=15] (x86-2-2) edge [left] node
  6124. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6125. \path[->,bend left=15] (x86-3) edge [above] node
  6126. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6127. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6128. \end{tikzpicture}
  6129. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6130. \label{fig:R4-passes}
  6131. \end{figure}
  6132. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6133. the compilation of $R_4$.
  6134. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6135. \chapter{Lexically Scoped Functions}
  6136. \label{ch:lambdas}
  6137. This chapter studies lexically scoped functions as they appear in
  6138. functional languages such as Racket. By lexical scoping we mean that a
  6139. function's body may refer to variables whose binding site is outside
  6140. of the function, in an enclosing scope.
  6141. %
  6142. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6143. anonymous function defined using the \key{lambda} form. The body of
  6144. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6145. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6146. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6147. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6148. returned from the function \code{f}. Below the definition of \code{f},
  6149. we have two calls to \code{f} with different arguments for \code{x},
  6150. first \code{5} then \code{3}. The functions returned from \code{f} are
  6151. bound to variables \code{g} and \code{h}. Even though these two
  6152. functions were created by the same \code{lambda}, they are really
  6153. different functions because they use different values for
  6154. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6155. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6156. the result of this program is \code{42}.
  6157. \begin{figure}[btp]
  6158. % s4_6.rkt
  6159. \begin{lstlisting}
  6160. (define (f [x : Integer]) : (Integer -> Integer)
  6161. (let ([y 4])
  6162. (lambda: ([z : Integer]) : Integer
  6163. (+ x (+ y z)))))
  6164. (let ([g (f 5)])
  6165. (let ([h (f 3)])
  6166. (+ (g 11) (h 15))))
  6167. \end{lstlisting}
  6168. \caption{Example of a lexically scoped function.}
  6169. \label{fig:lexical-scoping}
  6170. \end{figure}
  6171. \section{The $R_5$ Language}
  6172. The syntax for this language with anonymous functions and lexical
  6173. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6174. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6175. for function application. In this chapter we shall describe how to
  6176. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6177. into a combination of functions (as in $R_4$) and tuples (as in
  6178. $R_3$).
  6179. \begin{figure}[tp]
  6180. \centering
  6181. \fbox{
  6182. \begin{minipage}{0.96\textwidth}
  6183. \[
  6184. \begin{array}{lcl}
  6185. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6186. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6187. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6188. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6189. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6190. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6191. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6192. \mid (\key{and}\;\Exp\;\Exp)
  6193. \mid (\key{or}\;\Exp\;\Exp)
  6194. \mid (\key{not}\;\Exp) } \\
  6195. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6196. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6197. (\key{vector-ref}\;\Exp\;\Int)} \\
  6198. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6199. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6200. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6201. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6202. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6203. \end{array}
  6204. \]
  6205. \end{minipage}
  6206. }
  6207. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6208. with \key{lambda}.}
  6209. \label{fig:r5-syntax}
  6210. \end{figure}
  6211. To compile lexically-scoped functions to top-level function
  6212. definitions, the compiler will need to provide special treatment to
  6213. variable occurrences such as \code{x} and \code{y} in the body of the
  6214. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6215. of $R_4$ may not refer to variables defined outside the function. To
  6216. identify such variable occurrences, we review the standard notion of
  6217. free variable.
  6218. \begin{definition}
  6219. A variable is \emph{free with respect to an expression} $e$ if the
  6220. variable occurs inside $e$ but does not have an enclosing binding in
  6221. $e$.
  6222. \end{definition}
  6223. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6224. free with respect to the expression \code{(+ x (+ y z))}. On the
  6225. other hand, only \code{x} and \code{y} are free with respect to the
  6226. following expression because \code{z} is bound by the \code{lambda}.
  6227. \begin{lstlisting}
  6228. (lambda: ([z : Integer]) : Integer
  6229. (+ x (+ y z)))
  6230. \end{lstlisting}
  6231. Once we have identified the free variables of a \code{lambda}, we need
  6232. to arrange for some way to transport, at runtime, the values of those
  6233. variables from the point where the \code{lambda} was created to the
  6234. point where the \code{lambda} is applied. Referring again to
  6235. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6236. needs to be used in the application of \code{g} to \code{11}, but the
  6237. binding of \code{x} to \code{3} needs to be used in the application of
  6238. \code{h} to \code{15}. An efficient solution to the problem, due to
  6239. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6240. free variables together with the function pointer for the lambda's
  6241. code, an arrangement called a \emph{flat closure} (which we shorten to
  6242. just ``closure'') . Fortunately, we have all the ingredients to make
  6243. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6244. Chapter~\ref{ch:functions} gave us function pointers. The function
  6245. pointer shall reside at index $0$ and the values for free variables
  6246. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6247. the two closures created by the two calls to \code{f} in
  6248. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6249. the same \key{lambda}, they share the same function pointer but differ
  6250. in the values for the free variable \code{x}.
  6251. \begin{figure}[tbp]
  6252. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6253. \caption{Example closure representation for the \key{lambda}'s
  6254. in Figure~\ref{fig:lexical-scoping}.}
  6255. \label{fig:closures}
  6256. \end{figure}
  6257. \section{Interpreting $R_5$}
  6258. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6259. $R_5$. The clause for \key{lambda} saves the current environment
  6260. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6261. the environment from the \key{lambda}, the \code{lam-env}, when
  6262. interpreting the body of the \key{lambda}. The \code{lam-env}
  6263. environment is extended with the mapping of parameters to argument
  6264. values.
  6265. \begin{figure}[tbp]
  6266. \begin{lstlisting}
  6267. (define (interp-exp env)
  6268. (lambda (e)
  6269. (define recur (interp-exp env))
  6270. (match e
  6271. ...
  6272. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6273. `(lambda ,xs ,body ,env)]
  6274. [`(app ,fun ,args ...)
  6275. (define fun-val ((interp-exp env) fun))
  6276. (define arg-vals (map (interp-exp env) args))
  6277. (match fun-val
  6278. [`(lambda (,xs ...) ,body ,lam-env)
  6279. (define new-env (append (map cons xs arg-vals) lam-env))
  6280. ((interp-exp new-env) body)]
  6281. [else (error "interp-exp, expected function, not" fun-val)])]
  6282. [else (error 'interp-exp "unrecognized expression")]
  6283. )))
  6284. \end{lstlisting}
  6285. \caption{Interpreter for $R_5$.}
  6286. \label{fig:interp-R5}
  6287. \end{figure}
  6288. \section{Type Checking $R_5$}
  6289. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6290. \key{lambda} form. The body of the \key{lambda} is checked in an
  6291. environment that includes the current environment (because it is
  6292. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6293. require the body's type to match the declared return type.
  6294. \begin{figure}[tbp]
  6295. \begin{lstlisting}
  6296. (define (typecheck-R5 env)
  6297. (lambda (e)
  6298. (match e
  6299. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6300. (define new-env (append (map cons xs Ts) env))
  6301. (define bodyT ((typecheck-R5 new-env) body))
  6302. (cond [(equal? rT bodyT)
  6303. `(,@Ts -> ,rT)]
  6304. [else
  6305. (error "mismatch in return type" bodyT rT)])]
  6306. ...
  6307. )))
  6308. \end{lstlisting}
  6309. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6310. \label{fig:typecheck-R5}
  6311. \end{figure}
  6312. \section{Closure Conversion}
  6313. The compiling of lexically-scoped functions into top-level function
  6314. definitions is accomplished in the pass \code{convert-to-closures}
  6315. that comes after \code{reveal-functions} and before
  6316. \code{limit-functions}.
  6317. As usual, we shall implement the pass as a recursive function over the
  6318. AST. All of the action is in the clauses for \key{lambda} and
  6319. \key{app}. We transform a \key{lambda} expression into an expression
  6320. that creates a closure, that is, creates a vector whose first element
  6321. is a function pointer and the rest of the elements are the free
  6322. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6323. generated to identify the function.
  6324. \begin{tabular}{lll}
  6325. \begin{minipage}{0.4\textwidth}
  6326. \begin{lstlisting}
  6327. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6328. \end{lstlisting}
  6329. \end{minipage}
  6330. &
  6331. $\Rightarrow$
  6332. &
  6333. \begin{minipage}{0.4\textwidth}
  6334. \begin{lstlisting}
  6335. (vector |\itm{name}| |\itm{fvs}| ...)
  6336. \end{lstlisting}
  6337. \end{minipage}
  6338. \end{tabular} \\
  6339. %
  6340. In addition to transforming each \key{lambda} into a \key{vector}, we
  6341. must create a top-level function definition for each \key{lambda}, as
  6342. shown below.\\
  6343. \begin{minipage}{0.8\textwidth}
  6344. \begin{lstlisting}
  6345. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6346. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6347. ...
  6348. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6349. |\itm{body'}|)...))
  6350. \end{lstlisting}
  6351. \end{minipage}\\
  6352. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6353. parameters are the normal parameters of the \key{lambda}. The types
  6354. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6355. underscore is a dummy type because it is rather difficult to give a
  6356. type to the function in the closure's type, and it does not matter.
  6357. The sequence of \key{let} forms bind the free variables to their
  6358. values obtained from the closure.
  6359. We transform function application into code that retrieves the
  6360. function pointer from the closure and then calls the function, passing
  6361. in the closure as the first argument. We bind $e'$ to a temporary
  6362. variable to avoid code duplication.
  6363. \begin{tabular}{lll}
  6364. \begin{minipage}{0.3\textwidth}
  6365. \begin{lstlisting}
  6366. (app |$e$| |\itm{es}| ...)
  6367. \end{lstlisting}
  6368. \end{minipage}
  6369. &
  6370. $\Rightarrow$
  6371. &
  6372. \begin{minipage}{0.5\textwidth}
  6373. \begin{lstlisting}
  6374. (let ([|\itm{tmp}| |$e'$|])
  6375. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6376. \end{lstlisting}
  6377. \end{minipage}
  6378. \end{tabular} \\
  6379. There is also the question of what to do with top-level function
  6380. definitions. To maintain a uniform translation of function
  6381. application, we turn function references into closures.
  6382. \begin{tabular}{lll}
  6383. \begin{minipage}{0.3\textwidth}
  6384. \begin{lstlisting}
  6385. (fun-ref |$f$|)
  6386. \end{lstlisting}
  6387. \end{minipage}
  6388. &
  6389. $\Rightarrow$
  6390. &
  6391. \begin{minipage}{0.5\textwidth}
  6392. \begin{lstlisting}
  6393. (vector (fun-ref |$f$|))
  6394. \end{lstlisting}
  6395. \end{minipage}
  6396. \end{tabular} \\
  6397. %
  6398. The top-level function definitions need to be updated as well to take
  6399. an extra closure parameter.
  6400. \section{An Example Translation}
  6401. \label{sec:example-lambda}
  6402. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6403. conversion for the example program demonstrating lexical scoping that
  6404. we discussed at the beginning of this chapter.
  6405. \begin{figure}[h]
  6406. \begin{minipage}{0.8\textwidth}
  6407. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6408. (program
  6409. (define (f [x : Integer]) : (Integer -> Integer)
  6410. (let ([y 4])
  6411. (lambda: ([z : Integer]) : Integer
  6412. (+ x (+ y z)))))
  6413. (let ([g (f 5)])
  6414. (let ([h (f 3)])
  6415. (+ (g 11) (h 15)))))
  6416. \end{lstlisting}
  6417. $\Downarrow$
  6418. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6419. (program (type Integer)
  6420. (define (f (x : Integer)) : (Integer -> Integer)
  6421. (let ((y 4))
  6422. (lambda: ((z : Integer)) : Integer
  6423. (+ x (+ y z)))))
  6424. (let ((g (app (fun-ref f) 5)))
  6425. (let ((h (app (fun-ref f) 3)))
  6426. (+ (app g 11) (app h 15)))))
  6427. \end{lstlisting}
  6428. $\Downarrow$
  6429. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6430. (program (type Integer)
  6431. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6432. (let ((y 4))
  6433. (vector (fun-ref lam.1) x y)))
  6434. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6435. (let ((x (vector-ref clos.2 1)))
  6436. (let ((y (vector-ref clos.2 2)))
  6437. (+ x (+ y z)))))
  6438. (let ((g (let ((t.1 (vector (fun-ref f))))
  6439. (app (vector-ref t.1 0) t.1 5))))
  6440. (let ((h (let ((t.2 (vector (fun-ref f))))
  6441. (app (vector-ref t.2 0) t.2 3))))
  6442. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6443. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6444. \end{lstlisting}
  6445. \end{minipage}
  6446. \caption{Example of closure conversion.}
  6447. \label{fig:lexical-functions-example}
  6448. \end{figure}
  6449. \begin{figure}[p]
  6450. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6451. \node (R4) at (0,2) {\large $R_4$};
  6452. \node (R4-2) at (3,2) {\large $R_4$};
  6453. \node (R4-3) at (6,2) {\large $R_4$};
  6454. \node (F1-1) at (12,0) {\large $F_1$};
  6455. \node (F1-2) at (9,0) {\large $F_1$};
  6456. \node (F1-3) at (6,0) {\large $F_1$};
  6457. \node (F1-4) at (3,0) {\large $F_1$};
  6458. \node (F1-5) at (0,0) {\large $F_1$};
  6459. \node (C3-1) at (6,-2) {\large $C_3$};
  6460. \node (C3-2) at (3,-2) {\large $C_3$};
  6461. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6462. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6463. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6464. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6465. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6466. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6467. \path[->,bend left=15] (R4) edge [above] node
  6468. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6469. \path[->,bend left=15] (R4-2) edge [above] node
  6470. {\ttfamily\footnotesize uniquify} (R4-3);
  6471. \path[->] (R4-3) edge [right] node
  6472. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6473. \path[->,bend left=15] (F1-1) edge [below] node
  6474. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6475. \path[->,bend right=15] (F1-2) edge [above] node
  6476. {\ttfamily\footnotesize limit-functions} (F1-3);
  6477. \path[->,bend right=15] (F1-3) edge [above] node
  6478. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6479. \path[->,bend right=15] (F1-4) edge [above] node
  6480. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6481. \path[->] (F1-5) edge [left] node
  6482. {\ttfamily\footnotesize explicate-control} (C3-1);
  6483. \path[->,bend left=15] (C3-1) edge [below] node
  6484. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6485. \path[->,bend right=15] (C3-2) edge [left] node
  6486. {\ttfamily\footnotesize select-instr.} (x86-2);
  6487. \path[->,bend left=15] (x86-2) edge [left] node
  6488. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6489. \path[->,bend right=15] (x86-2-1) edge [below] node
  6490. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6491. \path[->,bend right=15] (x86-2-2) edge [left] node
  6492. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6493. \path[->,bend left=15] (x86-3) edge [above] node
  6494. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6495. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6496. \end{tikzpicture}
  6497. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6498. functions.}
  6499. \label{fig:R5-passes}
  6500. \end{figure}
  6501. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6502. for the compilation of $R_5$.
  6503. \begin{exercise}\normalfont
  6504. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6505. Create 5 new programs that use \key{lambda} functions and make use of
  6506. lexical scoping. Test your compiler on these new programs and all of
  6507. your previously created test programs.
  6508. \end{exercise}
  6509. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6510. \chapter{Dynamic Typing}
  6511. \label{ch:type-dynamic}
  6512. In this chapter we discuss the compilation of a dynamically typed
  6513. language, named $R_7$, that is a subset of the Racket
  6514. language. (Recall that in the previous chapters we have studied
  6515. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6516. languages, an expression may produce values of differing
  6517. type. Consider the following example with a conditional expression
  6518. that may return a Boolean or an integer depending on the input to the
  6519. program.
  6520. \begin{lstlisting}
  6521. (not (if (eq? (read) 1) #f 0))
  6522. \end{lstlisting}
  6523. Languages that allow expressions to produce different kinds of values
  6524. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6525. such as subtype polymorphism and parametric
  6526. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6527. talking about here does not have a special name, but it is the usual
  6528. kind that arises in dynamically typed languages.
  6529. Another characteristic of dynamically typed languages is that
  6530. primitive operations, such as \code{not}, are often defined to operate
  6531. on many different types of values. In fact, in Racket, the \code{not}
  6532. operator produces a result for any kind of value: given \code{\#f} it
  6533. returns \code{\#t} and given anything else it returns \code{\#f}.
  6534. Furthermore, even when primitive operations restrict their inputs to
  6535. values of a certain type, this restriction is enforced at runtime
  6536. instead of during compilation. For example, the following vector
  6537. reference results in a run-time contract violation.
  6538. \begin{lstlisting}
  6539. (vector-ref (vector 42) #t)
  6540. \end{lstlisting}
  6541. \begin{figure}[tp]
  6542. \centering
  6543. \fbox{
  6544. \begin{minipage}{0.97\textwidth}
  6545. \[
  6546. \begin{array}{rcl}
  6547. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6548. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6549. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6550. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6551. &\mid& \key{\#t} \mid \key{\#f}
  6552. \mid (\key{and}\;\Exp\;\Exp)
  6553. \mid (\key{or}\;\Exp\;\Exp)
  6554. \mid (\key{not}\;\Exp) \\
  6555. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6556. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6557. (\key{vector-ref}\;\Exp\;\Exp) \\
  6558. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6559. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6560. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6561. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6562. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6563. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6564. \end{array}
  6565. \]
  6566. \end{minipage}
  6567. }
  6568. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6569. \label{fig:r7-syntax}
  6570. \end{figure}
  6571. The syntax of $R_7$, our subset of Racket, is defined in
  6572. Figure~\ref{fig:r7-syntax}.
  6573. %
  6574. The definitional interpreter for $R_7$ is given in
  6575. Figure~\ref{fig:interp-R7}.
  6576. \begin{figure}[tbp]
  6577. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6578. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6579. (define (valid-op? op) (member op '(+ - and or not)))
  6580. (define (interp-r7 env)
  6581. (lambda (ast)
  6582. (define recur (interp-r7 env))
  6583. (match ast
  6584. [(? symbol?) (lookup ast env)]
  6585. [(? integer?) `(inject ,ast Integer)]
  6586. [#t `(inject #t Boolean)]
  6587. [#f `(inject #f Boolean)]
  6588. [`(read) `(inject ,(read-fixnum) Integer)]
  6589. [`(lambda (,xs ...) ,body)
  6590. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6591. [`(define (,f ,xs ...) ,body)
  6592. (mcons f `(lambda ,xs ,body))]
  6593. [`(program ,ds ... ,body)
  6594. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6595. (for/list ([b top-level])
  6596. (set-mcdr! b (match (mcdr b)
  6597. [`(lambda ,xs ,body)
  6598. `(inject (lambda ,xs ,body ,top-level)
  6599. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6600. ((interp-r7 top-level) body))]
  6601. [`(vector ,(app recur elts) ...)
  6602. (define tys (map get-tagged-type elts))
  6603. `(inject ,(apply vector elts) (Vector ,@tys))]
  6604. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6605. (match v1
  6606. [`(inject ,vec ,ty)
  6607. (vector-set! vec n v2)
  6608. `(inject (void) Void)])]
  6609. [`(vector-ref ,(app recur v) ,n)
  6610. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6611. [`(let ([,x ,(app recur v)]) ,body)
  6612. ((interp-r7 (cons (cons x v) env)) body)]
  6613. [`(,op ,es ...) #:when (valid-op? op)
  6614. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6615. [`(eq? ,(app recur l) ,(app recur r))
  6616. `(inject ,(equal? l r) Boolean)]
  6617. [`(if ,(app recur q) ,t ,f)
  6618. (match q
  6619. [`(inject #f Boolean) (recur f)]
  6620. [else (recur t)])]
  6621. [`(,(app recur f-val) ,(app recur vs) ...)
  6622. (match f-val
  6623. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6624. (define new-env (append (map cons xs vs) lam-env))
  6625. ((interp-r7 new-env) body)]
  6626. [else (error "interp-r7, expected function, not" f-val)])])))
  6627. \end{lstlisting}
  6628. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6629. \label{fig:interp-R7}
  6630. \end{figure}
  6631. Let us consider how we might compile $R_7$ to x86, thinking about the
  6632. first example above. Our bit-level representation of the Boolean
  6633. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6634. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6635. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6636. general, cannot be determined at compile time, but depends on the
  6637. runtime type of its input, as in the example above that depends on the
  6638. result of \code{(read)}.
  6639. The way around this problem is to include information about a value's
  6640. runtime type in the value itself, so that this information can be
  6641. inspected by operators such as \code{not}. In particular, we shall
  6642. steal the 3 right-most bits from our 64-bit values to encode the
  6643. runtime type. We shall use $001$ to identify integers, $100$ for
  6644. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6645. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6646. define the following auxiliary function.
  6647. \begin{align*}
  6648. \itm{tagof}(\key{Integer}) &= 001 \\
  6649. \itm{tagof}(\key{Boolean}) &= 100 \\
  6650. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6651. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6652. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6653. \itm{tagof}(\key{Void}) &= 101
  6654. \end{align*}
  6655. (We shall say more about the new \key{Vectorof} type shortly.)
  6656. This stealing of 3 bits comes at some
  6657. price: our integers are reduced to ranging from $-2^{60}$ to
  6658. $2^{60}$. The stealing does not adversely affect vectors and
  6659. procedures because those values are addresses, and our addresses are
  6660. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6661. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6662. bits with the tag and we can simply zero-out the tag to recover the
  6663. original address.
  6664. In some sense, these tagged values are a new kind of value. Indeed,
  6665. we can extend our \emph{typed} language with tagged values by adding a
  6666. new type to classify them, called \key{Any}, and with operations for
  6667. creating and using tagged values, yielding the $R_6$ language that we
  6668. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6669. fundamental support for polymorphism and runtime types that we need to
  6670. support dynamic typing.
  6671. There is an interesting interaction between tagged values and garbage
  6672. collection. A variable of type \code{Any} might refer to a vector and
  6673. therefore it might be a root that needs to be inspected and copied
  6674. during garbage collection. Thus, we need to treat variables of type
  6675. \code{Any} in a similar way to variables of type \code{Vector} for
  6676. purposes of register allocation, which we discuss in
  6677. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6678. variable of type \code{Any} is spilled, it must be spilled to the root
  6679. stack. But this means that the garbage collector needs to be able to
  6680. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6681. value that points to a tuple, and (3) a tagged value that is not a
  6682. tuple. We enable this differentiation by choosing not to use the tag
  6683. $000$. Instead, that bit pattern is reserved for identifying plain old
  6684. pointers to tuples. On the other hand, if one of the first three bits
  6685. is set, then we have a tagged value, and inspecting the tag can
  6686. differentiation between vectors ($010$) and the other kinds of values.
  6687. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6688. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6689. extend our compiler to handle the new features of $R_6$
  6690. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6691. \ref{sec:register-allocation-r6}).
  6692. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6693. \label{sec:r6-lang}
  6694. \begin{figure}[tp]
  6695. \centering
  6696. \fbox{
  6697. \begin{minipage}{0.97\textwidth}
  6698. \[
  6699. \begin{array}{lcl}
  6700. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6701. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6702. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6703. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6704. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6705. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6706. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6707. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6708. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6709. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6710. \mid (\key{and}\;\Exp\;\Exp)
  6711. \mid (\key{or}\;\Exp\;\Exp)
  6712. \mid (\key{not}\;\Exp)} \\
  6713. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6714. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6715. (\key{vector-ref}\;\Exp\;\Int)} \\
  6716. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6717. &\mid& \gray{(\Exp \; \Exp^{*})
  6718. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6719. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6720. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6721. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6722. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6723. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6724. \end{array}
  6725. \]
  6726. \end{minipage}
  6727. }
  6728. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6729. with \key{Any}.}
  6730. \label{fig:r6-syntax}
  6731. \end{figure}
  6732. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6733. $(\key{inject}\; e\; T)$ form converts the value produced by
  6734. expression $e$ of type $T$ into a tagged value. The
  6735. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6736. expression $e$ into a value of type $T$ or else halts the program if
  6737. the type tag is equivalent to $T$. We treat
  6738. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6739. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6740. Note that in both \key{inject} and
  6741. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6742. which simplifies the implementation and corresponds with what is
  6743. needed for compiling untyped Racket. The type predicates,
  6744. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6745. if the tag corresponds to the predicate, and return \key{\#t}
  6746. otherwise.
  6747. %
  6748. Selections from the type checker for $R_6$ are shown in
  6749. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6750. Figure~\ref{fig:interp-R6}.
  6751. \begin{figure}[btp]
  6752. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6753. (define (flat-ty? ty) ...)
  6754. (define (typecheck-R6 env)
  6755. (lambda (e)
  6756. (define recur (typecheck-R6 env))
  6757. (match e
  6758. [`(inject ,e ,ty)
  6759. (unless (flat-ty? ty)
  6760. (error "may only inject a value of flat type, not ~a" ty))
  6761. (define-values (new-e e-ty) (recur e))
  6762. (cond
  6763. [(equal? e-ty ty)
  6764. (values `(inject ,new-e ,ty) 'Any)]
  6765. [else
  6766. (error "inject expected ~a to have type ~a" e ty)])]
  6767. [`(project ,e ,ty)
  6768. (unless (flat-ty? ty)
  6769. (error "may only project to a flat type, not ~a" ty))
  6770. (define-values (new-e e-ty) (recur e))
  6771. (cond
  6772. [(equal? e-ty 'Any)
  6773. (values `(project ,new-e ,ty) ty)]
  6774. [else
  6775. (error "project expected ~a to have type Any" e)])]
  6776. [`(vector-ref ,e ,i)
  6777. (define-values (new-e e-ty) (recur e))
  6778. (match e-ty
  6779. [`(Vector ,ts ...) ...]
  6780. [`(Vectorof ,ty)
  6781. (unless (exact-nonnegative-integer? i)
  6782. (error 'type-check "invalid index ~a" i))
  6783. (values `(vector-ref ,new-e ,i) ty)]
  6784. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6785. ...
  6786. )))
  6787. \end{lstlisting}
  6788. \caption{Type checker for parts of the $R_6$ language.}
  6789. \label{fig:typecheck-R6}
  6790. \end{figure}
  6791. % to do: add rules for vector-ref, etc. for Vectorof
  6792. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6793. \begin{figure}[btp]
  6794. \begin{lstlisting}
  6795. (define primitives (set 'boolean? ...))
  6796. (define (interp-op op)
  6797. (match op
  6798. ['boolean? (lambda (v)
  6799. (match v
  6800. [`(tagged ,v1 Boolean) #t]
  6801. [else #f]))]
  6802. ...))
  6803. ;; Equivalence of flat types
  6804. (define (tyeq? t1 t2)
  6805. (match `(,t1 ,t2)
  6806. [`((Vectorof Any) (Vector ,t2s ...))
  6807. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6808. [`((Vector ,t1s ...) (Vectorof Any))
  6809. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6810. [else (equal? t1 t2)]))
  6811. (define (interp-R6 env)
  6812. (lambda (ast)
  6813. (match ast
  6814. [`(inject ,e ,t)
  6815. `(tagged ,((interp-R6 env) e) ,t)]
  6816. [`(project ,e ,t2)
  6817. (define v ((interp-R6 env) e))
  6818. (match v
  6819. [`(tagged ,v1 ,t1)
  6820. (cond [(tyeq? t1 t2)
  6821. v1]
  6822. [else
  6823. (error "in project, type mismatch" t1 t2)])]
  6824. [else
  6825. (error "in project, expected tagged value" v)])]
  6826. ...)))
  6827. \end{lstlisting}
  6828. \caption{Interpreter for $R_6$.}
  6829. \label{fig:interp-R6}
  6830. \end{figure}
  6831. %\clearpage
  6832. \section{Shrinking $R_6$}
  6833. \label{sec:shrink-r6}
  6834. In the \code{shrink} pass we recommend compiling \code{project} into
  6835. an explicit \code{if} expression that uses three new operations:
  6836. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6837. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6838. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6839. value from a tagged value. Finally, the \code{exit} operation ends the
  6840. execution of the program by invoking the operating system's
  6841. \code{exit} function. So the translation for \code{project} is as
  6842. follows. (We have omitted the \code{has-type} AST nodes to make this
  6843. output more readable.)
  6844. \begin{tabular}{lll}
  6845. \begin{minipage}{0.3\textwidth}
  6846. \begin{lstlisting}
  6847. (project |$e$| |$\Type$|)
  6848. \end{lstlisting}
  6849. \end{minipage}
  6850. &
  6851. $\Rightarrow$
  6852. &
  6853. \begin{minipage}{0.5\textwidth}
  6854. \begin{lstlisting}
  6855. (let ([|$\itm{tmp}$| |$e'$|])
  6856. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6857. (value-of-any |$\itm{tmp}$|)
  6858. (exit)))
  6859. \end{lstlisting}
  6860. \end{minipage}
  6861. \end{tabular} \\
  6862. Similarly, we recommend translating the type predicates
  6863. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6864. \section{Instruction Selection for $R_6$}
  6865. \label{sec:select-r6}
  6866. \paragraph{Inject}
  6867. We recommend compiling an \key{inject} as follows if the type is
  6868. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6869. destination to the left by the number of bits specified its source
  6870. argument (in this case $3$, the length of the tag) and it preserves
  6871. the sign of the integer. We use the \key{orq} instruction to combine
  6872. the tag and the value to form the tagged value. \\
  6873. \begin{tabular}{lll}
  6874. \begin{minipage}{0.4\textwidth}
  6875. \begin{lstlisting}
  6876. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6877. \end{lstlisting}
  6878. \end{minipage}
  6879. &
  6880. $\Rightarrow$
  6881. &
  6882. \begin{minipage}{0.5\textwidth}
  6883. \begin{lstlisting}
  6884. (movq |$e'$| |\itm{lhs}'|)
  6885. (salq (int 3) |\itm{lhs}'|)
  6886. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6887. \end{lstlisting}
  6888. \end{minipage}
  6889. \end{tabular} \\
  6890. The instruction selection for vectors and procedures is different
  6891. because their is no need to shift them to the left. The rightmost 3
  6892. bits are already zeros as described above. So we just combine the
  6893. value and the tag using \key{orq}. \\
  6894. \begin{tabular}{lll}
  6895. \begin{minipage}{0.4\textwidth}
  6896. \begin{lstlisting}
  6897. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6898. \end{lstlisting}
  6899. \end{minipage}
  6900. &
  6901. $\Rightarrow$
  6902. &
  6903. \begin{minipage}{0.5\textwidth}
  6904. \begin{lstlisting}
  6905. (movq |$e'$| |\itm{lhs}'|)
  6906. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6907. \end{lstlisting}
  6908. \end{minipage}
  6909. \end{tabular}
  6910. \paragraph{Tag of Any}
  6911. Recall that the \code{tag-of-any} operation extracts the type tag from
  6912. a value of type \code{Any}. The type tag is the bottom three bits, so
  6913. we obtain the tag by taking the bitwise-and of the value with $111$
  6914. ($7$ in decimal).
  6915. \begin{tabular}{lll}
  6916. \begin{minipage}{0.4\textwidth}
  6917. \begin{lstlisting}
  6918. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6919. \end{lstlisting}
  6920. \end{minipage}
  6921. &
  6922. $\Rightarrow$
  6923. &
  6924. \begin{minipage}{0.5\textwidth}
  6925. \begin{lstlisting}
  6926. (movq |$e'$| |\itm{lhs}'|)
  6927. (andq (int 7) |\itm{lhs}'|)
  6928. \end{lstlisting}
  6929. \end{minipage}
  6930. \end{tabular}
  6931. \paragraph{Value of Any}
  6932. Like \key{inject}, the instructions for \key{value-of-any} are
  6933. different depending on whether the type $T$ is a pointer (vector or
  6934. procedure) or not (Integer or Boolean). The following shows the
  6935. instruction selection for Integer and Boolean. We produce an untagged
  6936. value by shifting it to the right by 3 bits.
  6937. %
  6938. \\
  6939. \begin{tabular}{lll}
  6940. \begin{minipage}{0.4\textwidth}
  6941. \begin{lstlisting}
  6942. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6943. \end{lstlisting}
  6944. \end{minipage}
  6945. &
  6946. $\Rightarrow$
  6947. &
  6948. \begin{minipage}{0.5\textwidth}
  6949. \begin{lstlisting}
  6950. (movq |$e'$| |\itm{lhs}'|)
  6951. (sarq (int 3) |\itm{lhs}'|)
  6952. \end{lstlisting}
  6953. \end{minipage}
  6954. \end{tabular} \\
  6955. %
  6956. In the case for vectors and procedures, there is no need to
  6957. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6958. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6959. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6960. \code{movq} into the destination $\itm{lhs}$. We then generate
  6961. \code{andq} with the tagged value to get the desired result. \\
  6962. %
  6963. \begin{tabular}{lll}
  6964. \begin{minipage}{0.4\textwidth}
  6965. \begin{lstlisting}
  6966. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6967. \end{lstlisting}
  6968. \end{minipage}
  6969. &
  6970. $\Rightarrow$
  6971. &
  6972. \begin{minipage}{0.5\textwidth}
  6973. \begin{lstlisting}
  6974. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6975. (andq |$e'$| |\itm{lhs}'|)
  6976. \end{lstlisting}
  6977. \end{minipage}
  6978. \end{tabular}
  6979. %% \paragraph{Type Predicates} We leave it to the reader to
  6980. %% devise a sequence of instructions to implement the type predicates
  6981. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6982. \section{Register Allocation for $R_6$}
  6983. \label{sec:register-allocation-r6}
  6984. As mentioned above, a variable of type \code{Any} might refer to a
  6985. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6986. of type \code{Any} in the same way that it treats variables of type
  6987. \code{Vector} for purposes of garbage collection. In particular,
  6988. \begin{itemize}
  6989. \item If a variable of type \code{Any} is live during a function call,
  6990. then it must be spilled. One way to accomplish this is to augment
  6991. the pass \code{build-interference} to mark all variables that are
  6992. live after a \code{callq} as interfering with all the registers.
  6993. \item If a variable of type \code{Any} is spilled, it must be spilled
  6994. to the root stack instead of the normal procedure call stack.
  6995. \end{itemize}
  6996. \begin{exercise}\normalfont
  6997. Expand your compiler to handle $R_6$ as discussed in the last few
  6998. sections. Create 5 new programs that use the \code{Any} type and the
  6999. new operations (\code{inject}, \code{project}, \code{boolean?},
  7000. etc.). Test your compiler on these new programs and all of your
  7001. previously created test programs.
  7002. \end{exercise}
  7003. \section{Compiling $R_7$ to $R_6$}
  7004. \label{sec:compile-r7}
  7005. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7006. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7007. given a subexpression $e$ of $R_7$, the pass will produce an
  7008. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7009. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7010. the Boolean \code{\#t}, which must be injected to produce an
  7011. expression of type \key{Any}.
  7012. %
  7013. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7014. addition, is representative of compilation for many operations: the
  7015. arguments have type \key{Any} and must be projected to \key{Integer}
  7016. before the addition can be performed.
  7017. The compilation of \key{lambda} (third row of
  7018. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7019. produce type annotations: we simply use \key{Any}.
  7020. %
  7021. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7022. has to account for some differences in behavior between $R_7$ and
  7023. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7024. kind of values can be used in various places. For example, the
  7025. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7026. the arguments need not be of the same type (but in that case, the
  7027. result will be \code{\#f}).
  7028. \begin{figure}[btp]
  7029. \centering
  7030. \begin{tabular}{|lll|} \hline
  7031. \begin{minipage}{0.25\textwidth}
  7032. \begin{lstlisting}
  7033. #t
  7034. \end{lstlisting}
  7035. \end{minipage}
  7036. &
  7037. $\Rightarrow$
  7038. &
  7039. \begin{minipage}{0.6\textwidth}
  7040. \begin{lstlisting}
  7041. (inject #t Boolean)
  7042. \end{lstlisting}
  7043. \end{minipage}
  7044. \\[2ex]\hline
  7045. \begin{minipage}{0.25\textwidth}
  7046. \begin{lstlisting}
  7047. (+ |$e_1$| |$e_2$|)
  7048. \end{lstlisting}
  7049. \end{minipage}
  7050. &
  7051. $\Rightarrow$
  7052. &
  7053. \begin{minipage}{0.6\textwidth}
  7054. \begin{lstlisting}
  7055. (inject
  7056. (+ (project |$e'_1$| Integer)
  7057. (project |$e'_2$| Integer))
  7058. Integer)
  7059. \end{lstlisting}
  7060. \end{minipage}
  7061. \\[2ex]\hline
  7062. \begin{minipage}{0.25\textwidth}
  7063. \begin{lstlisting}
  7064. (lambda (|$x_1 \ldots$|) |$e$|)
  7065. \end{lstlisting}
  7066. \end{minipage}
  7067. &
  7068. $\Rightarrow$
  7069. &
  7070. \begin{minipage}{0.6\textwidth}
  7071. \begin{lstlisting}
  7072. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7073. (Any|$\ldots$|Any -> Any))
  7074. \end{lstlisting}
  7075. \end{minipage}
  7076. \\[2ex]\hline
  7077. \begin{minipage}{0.25\textwidth}
  7078. \begin{lstlisting}
  7079. (app |$e_0$| |$e_1 \ldots e_n$|)
  7080. \end{lstlisting}
  7081. \end{minipage}
  7082. &
  7083. $\Rightarrow$
  7084. &
  7085. \begin{minipage}{0.6\textwidth}
  7086. \begin{lstlisting}
  7087. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7088. |$e'_1 \ldots e'_n$|)
  7089. \end{lstlisting}
  7090. \end{minipage}
  7091. \\[2ex]\hline
  7092. \begin{minipage}{0.25\textwidth}
  7093. \begin{lstlisting}
  7094. (vector-ref |$e_1$| |$e_2$|)
  7095. \end{lstlisting}
  7096. \end{minipage}
  7097. &
  7098. $\Rightarrow$
  7099. &
  7100. \begin{minipage}{0.6\textwidth}
  7101. \begin{lstlisting}
  7102. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7103. (let ([tmp2 (project |$e'_2$| Integer)])
  7104. (vector-ref tmp1 tmp2)))
  7105. \end{lstlisting}
  7106. \end{minipage}
  7107. \\[2ex]\hline
  7108. \begin{minipage}{0.25\textwidth}
  7109. \begin{lstlisting}
  7110. (if |$e_1$| |$e_2$| |$e_3$|)
  7111. \end{lstlisting}
  7112. \end{minipage}
  7113. &
  7114. $\Rightarrow$
  7115. &
  7116. \begin{minipage}{0.6\textwidth}
  7117. \begin{lstlisting}
  7118. (if (eq? |$e'_1$| (inject #f Boolean))
  7119. |$e'_3$|
  7120. |$e'_2$|)
  7121. \end{lstlisting}
  7122. \end{minipage}
  7123. \\[2ex]\hline
  7124. \begin{minipage}{0.25\textwidth}
  7125. \begin{lstlisting}
  7126. (eq? |$e_1$| |$e_2$|)
  7127. \end{lstlisting}
  7128. \end{minipage}
  7129. &
  7130. $\Rightarrow$
  7131. &
  7132. \begin{minipage}{0.6\textwidth}
  7133. \begin{lstlisting}
  7134. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7135. \end{lstlisting}
  7136. \end{minipage}
  7137. \\[2ex]\hline
  7138. \end{tabular}
  7139. \caption{Compiling $R_7$ to $R_6$.}
  7140. \label{fig:compile-r7-r6}
  7141. \end{figure}
  7142. \begin{exercise}\normalfont
  7143. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7144. Create tests for $R_7$ by adapting all of your previous test programs
  7145. by removing type annotations. Add 5 more tests programs that
  7146. specifically rely on the language being dynamically typed. That is,
  7147. they should not be legal programs in a statically typed language, but
  7148. nevertheless, they should be valid $R_7$ programs that run to
  7149. completion without error.
  7150. \end{exercise}
  7151. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7152. \chapter{Gradual Typing}
  7153. \label{ch:gradual-typing}
  7154. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7155. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7156. \chapter{Parametric Polymorphism}
  7157. \label{ch:parametric-polymorphism}
  7158. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7159. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7160. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7161. \chapter{High-level Optimization}
  7162. \label{ch:high-level-optimization}
  7163. This chapter will present a procedure inlining pass based on the
  7164. algorithm of \citet{Waddell:1997fk}.
  7165. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7166. \chapter{Appendix}
  7167. \section{Interpreters}
  7168. \label{appendix:interp}
  7169. We provide several interpreters in the \key{interp.rkt} file. The
  7170. \key{interp-scheme} function takes an AST in one of the Racket-like
  7171. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7172. the program, returning the result value. The \key{interp-C} function
  7173. interprets an AST for a program in one of the C-like languages ($C_0,
  7174. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7175. for an x86 program.
  7176. \section{Utility Functions}
  7177. \label{appendix:utilities}
  7178. The utility function described in this section can be found in the
  7179. \key{utilities.rkt} file.
  7180. The \key{read-program} function takes a file path and parses that file
  7181. (it must be a Racket program) into an abstract syntax tree with a
  7182. \key{Program} node at the top.
  7183. The \key{parse-program} function takes an S-expression representation
  7184. of an AST and converts it into the struct-based representation.
  7185. The \key{assert} function displays the error message \key{msg} if the
  7186. Boolean \key{bool} is false.
  7187. \begin{lstlisting}
  7188. (define (assert msg bool) ...)
  7189. \end{lstlisting}
  7190. The \key{lookup} function takes a key and an association list (a list
  7191. of key-value pairs), and returns the first value that is associated
  7192. with the given key, if there is one. If not, an error is triggered.
  7193. The association list may contain both immutable pairs (built with
  7194. \key{cons}) and mutable pairs (built with \key{mcons}).
  7195. The \key{map2} function ...
  7196. %% \subsection{Graphs}
  7197. %% \begin{itemize}
  7198. %% \item The \code{make-graph} function takes a list of vertices
  7199. %% (symbols) and returns a graph.
  7200. %% \item The \code{add-edge} function takes a graph and two vertices and
  7201. %% adds an edge to the graph that connects the two vertices. The graph
  7202. %% is updated in-place. There is no return value for this function.
  7203. %% \item The \code{adjacent} function takes a graph and a vertex and
  7204. %% returns the set of vertices that are adjacent to the given
  7205. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7206. %% used with functions from the \code{racket/set} module.
  7207. %% \item The \code{vertices} function takes a graph and returns the list
  7208. %% of vertices in the graph.
  7209. %% \end{itemize}
  7210. \subsection{Testing}
  7211. The \key{interp-tests} function takes a compiler name (a string), a
  7212. description of the passes, an interpreter for the source language, a
  7213. test family name (a string), and a list of test numbers, and runs the
  7214. compiler passes and the interpreters to check whether the passes
  7215. correct. The description of the passes is a list with one entry per
  7216. pass. An entry is a list with three things: a string giving the name
  7217. of the pass, the function that implements the pass (a translator from
  7218. AST to AST), and a function that implements the interpreter (a
  7219. function from AST to result value) for the language of the output of
  7220. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7221. good choice. The \key{interp-tests} function assumes that the
  7222. subdirectory \key{tests} has a collection of Scheme programs whose names
  7223. all start with the family name, followed by an underscore and then the
  7224. test number, ending in \key{.scm}. Also, for each Scheme program there
  7225. is a file with the same number except that it ends with \key{.in} that
  7226. provides the input for the Scheme program.
  7227. \begin{lstlisting}
  7228. (define (interp-tests name passes test-family test-nums) ...)
  7229. \end{lstlisting}
  7230. The compiler-tests function takes a compiler name (a string) a
  7231. description of the passes (as described above for
  7232. \code{interp-tests}), a test family name (a string), and a list of
  7233. test numbers (see the comment for interp-tests), and runs the compiler
  7234. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7235. machine code. It runs the machine code and checks that the output is
  7236. 42.
  7237. \begin{lstlisting}
  7238. (define (compiler-tests name passes test-family test-nums) ...)
  7239. \end{lstlisting}
  7240. The compile-file function takes a description of the compiler passes
  7241. (see the comment for \key{interp-tests}) and returns a function that,
  7242. given a program file name (a string ending in \key{.scm}), applies all
  7243. of the passes and writes the output to a file whose name is the same
  7244. as the program file name but with \key{.scm} replaced with \key{.s}.
  7245. \begin{lstlisting}
  7246. (define (compile-file passes)
  7247. (lambda (prog-file-name) ...))
  7248. \end{lstlisting}
  7249. \section{x86 Instruction Set Quick-Reference}
  7250. \label{sec:x86-quick-reference}
  7251. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7252. do. We write $A \to B$ to mean that the value of $A$ is written into
  7253. location $B$. Address offsets are given in bytes. The instruction
  7254. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7255. registers (such as $\%rax$), or memory references (such as
  7256. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7257. reference per instruction. Other operands must be immediates or
  7258. registers.
  7259. \begin{table}[tbp]
  7260. \centering
  7261. \begin{tabular}{l|l}
  7262. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7263. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7264. \texttt{negq} $A$ & $- A \to A$ \\
  7265. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7266. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7267. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7268. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7269. \texttt{retq} & Pops the return address and jumps to it \\
  7270. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7271. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7272. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7273. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7274. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7275. matches the condition code of the instruction, otherwise go to the
  7276. next instructions. The condition codes are \key{e} for ``equal'',
  7277. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7278. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7279. \texttt{jl} $L$ & \\
  7280. \texttt{jle} $L$ & \\
  7281. \texttt{jg} $L$ & \\
  7282. \texttt{jge} $L$ & \\
  7283. \texttt{jmp} $L$ & Jump to label $L$ \\
  7284. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7285. \texttt{movzbq} $A$, $B$ &
  7286. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7287. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7288. and the extra bytes of $B$ are set to zero.} \\
  7289. & \\
  7290. & \\
  7291. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7292. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7293. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7294. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7295. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7296. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7297. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7298. description of the condition codes. $A$ must be a single byte register
  7299. (e.g., \texttt{al} or \texttt{cl}).} \\
  7300. \texttt{setl} $A$ & \\
  7301. \texttt{setle} $A$ & \\
  7302. \texttt{setg} $A$ & \\
  7303. \texttt{setge} $A$ &
  7304. \end{tabular}
  7305. \vspace{5pt}
  7306. \caption{Quick-reference for the x86 instructions used in this book.}
  7307. \label{tab:x86-instr}
  7308. \end{table}
  7309. \bibliographystyle{plainnat}
  7310. \bibliography{all}
  7311. \end{document}
  7312. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7313. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7314. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7315. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7316. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7317. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7318. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7319. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7320. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7321. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7322. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7323. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7324. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7325. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7326. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7327. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7328. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7329. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7330. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7331. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7332. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7333. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7334. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7335. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7336. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7337. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7338. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7339. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7340. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7341. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7342. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7343. % LocalWords: struct symtab