book.tex 300 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898
  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},
  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. We use \emph{abstract syntax trees} (ASTs), which are data
  261. structures in computer memory, in contrast to how programs are
  262. typically stored in text files on disk, as \emph{concrete syntax}.
  263. %
  264. ASTs can be represented in many different ways, depending on the programming
  265. language used to write the compiler.
  266. %
  267. We use Racket's \code{struct} feature to conveniently represent
  268. ASTs (Section~\ref{sec:ast}). We use grammars to defined the abstract
  269. syntax of programming languages (Section~\ref{sec:grammar}) and
  270. pattern matching to inspect individual nodes in an AST
  271. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  272. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  273. chapter provides an brief introduction to these ideas.
  274. \section{Abstract Syntax Trees and Racket Structures}
  275. \label{sec:ast}
  276. The primary data structure that is commonly used for representing
  277. programs is the \emph{abstract syntax tree} (AST). When considering
  278. some part of a program, a compiler needs to ask what kind of thing it
  279. is and what sub-parts it contains. For example, the program on the
  280. left corresponds to the AST on the right.
  281. \begin{center}
  282. \begin{minipage}{0.4\textwidth}
  283. \begin{lstlisting}
  284. (+ (read) (- 8))
  285. \end{lstlisting}
  286. \end{minipage}
  287. \begin{minipage}{0.4\textwidth}
  288. \begin{equation}
  289. \begin{tikzpicture}
  290. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  291. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  292. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  293. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  294. \draw[->] (plus) to (read);
  295. \draw[->] (plus) to (minus);
  296. \draw[->] (minus) to (8);
  297. \end{tikzpicture}
  298. \label{eq:arith-prog}
  299. \end{equation}
  300. \end{minipage}
  301. \end{center}
  302. We shall use the standard terminology for trees: each circle above is
  303. called a \emph{node}. The arrows connect a node to its \emph{children}
  304. (which are also nodes). The top-most node is the \emph{root}. Every
  305. node except for the root has a \emph{parent} (the node it is the child
  306. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  307. it is an \emph{internal} node.
  308. %% Recall that an \emph{symbolic expression} (S-expression) is either
  309. %% \begin{enumerate}
  310. %% \item an atom, or
  311. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  312. %% where $e_1$ and $e_2$ are each an S-expression.
  313. %% \end{enumerate}
  314. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  315. %% null value \code{'()}, etc. We can create an S-expression in Racket
  316. %% simply by writing a backquote (called a quasi-quote in Racket)
  317. %% followed by the textual representation of the S-expression. It is
  318. %% quite common to use S-expressions to represent a list, such as $a, b
  319. %% ,c$ in the following way:
  320. %% \begin{lstlisting}
  321. %% `(a . (b . (c . ())))
  322. %% \end{lstlisting}
  323. %% Each element of the list is in the first slot of a pair, and the
  324. %% second slot is either the rest of the list or the null value, to mark
  325. %% the end of the list. Such lists are so common that Racket provides
  326. %% special notation for them that removes the need for the periods
  327. %% and so many parenthesis:
  328. %% \begin{lstlisting}
  329. %% `(a b c)
  330. %% \end{lstlisting}
  331. %% The following expression creates an S-expression that represents AST
  332. %% \eqref{eq:arith-prog}.
  333. %% \begin{lstlisting}
  334. %% `(+ (read) (- 8))
  335. %% \end{lstlisting}
  336. %% When using S-expressions to represent ASTs, the convention is to
  337. %% represent each AST node as a list and to put the operation symbol at
  338. %% the front of the list. The rest of the list contains the children. So
  339. %% in the above case, the root AST node has operation \code{`+} and its
  340. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  341. %% diagram \eqref{eq:arith-prog}.
  342. %% To build larger S-expressions one often needs to splice together
  343. %% several smaller S-expressions. Racket provides the comma operator to
  344. %% splice an S-expression into a larger one. For example, instead of
  345. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  346. %% we could have first created an S-expression for AST
  347. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  348. %% S-expression.
  349. %% \begin{lstlisting}
  350. %% (define ast1.4 `(- 8))
  351. %% (define ast1.1 `(+ (read) ,ast1.4))
  352. %% \end{lstlisting}
  353. %% In general, the Racket expression that follows the comma (splice)
  354. %% can be any expression that produces an S-expression.
  355. We define a Racket \code{struct} for each kind of node. For this
  356. chapter we require just two kinds of nodes: one for integer constants
  357. and one for primitive operations. The following is the \code{struct}
  358. definition for integer constants.
  359. \begin{lstlisting}
  360. (struct Int (value))
  361. \end{lstlisting}
  362. An integer node includes just one thing: the integer value.
  363. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  364. \begin{lstlisting}
  365. (define eight (Int 8))
  366. \end{lstlisting}
  367. We say that the value created by \code{(Int 8)} is an
  368. \emph{instance} of the \code{Int} structure.
  369. The following is the \code{struct} definition for primitives operations.
  370. \begin{lstlisting}
  371. (struct Prim (op arg*))
  372. \end{lstlisting}
  373. A primitive operation node includes an operator symbol \code{op}
  374. and a list of children \code{arg*}. For example, to create
  375. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  376. \begin{lstlisting}
  377. (define neg-eight (Prim '- (list eight)))
  378. \end{lstlisting}
  379. Primitive operations may have zero or more children. The \code{read}
  380. operator has zero children:
  381. \begin{lstlisting}
  382. (define rd (Prim 'read '()))
  383. \end{lstlisting}
  384. whereas the addition operator has two children:
  385. \begin{lstlisting}
  386. (define ast1.1 (Prim '+ (list rd neg-eight)))
  387. \end{lstlisting}
  388. We have made a design choice regarding the \code{Prim} structure.
  389. Instead of using one structure for many different operations
  390. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  391. structure for each operation, as follows.
  392. \begin{lstlisting}
  393. (struct Read ())
  394. (struct Add (left right))
  395. (struct Neg (value))
  396. \end{lstlisting}
  397. The reason we choose to use just one structure is that in many parts
  398. of the compiler, the code for the different primitive operators is the
  399. same, so we might as well just write that code once, which is enabled
  400. by using a single structure.
  401. When compiling a program such as \eqref{eq:arith-prog}, we need to
  402. know that the operation associated with the root node is addition and
  403. that it has two children: \texttt{read} and a negation. The AST data
  404. structure directly supports these queries, as we shall see in
  405. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  406. in compilers.
  407. In this book, we often write down the concrete syntax of a program
  408. even when we really have in mind the AST because the concrete syntax
  409. is more concise. We recommend that, in your mind, you always think of
  410. programs as abstract syntax trees.
  411. \section{Grammars}
  412. \label{sec:grammar}
  413. A programming language can be thought of as a \emph{set} of programs.
  414. The set is typically infinite (one can always create larger and larger
  415. programs), so one cannot simply describe a language by listing all of
  416. the programs in the language. Instead we write down a set of rules, a
  417. \emph{grammar}, for building programs. Grammars are often used to
  418. define the concrete syntax of a language, but they can also be used to
  419. describe the abstract syntax. We shall write our rules in a variant of
  420. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  421. example, we describe a small language, named $R_0$, that consists of
  422. integers and arithmetic operations.
  423. The first grammar rule says that an instance of the \code{Int}
  424. structure is an expression:
  425. \begin{equation}
  426. \Exp ::= \INT{\Int} \label{eq:arith-int}
  427. \end{equation}
  428. %
  429. Each rule has a left-hand-side and a right-hand-side. The way to read
  430. a rule is that if you have all the program parts on the
  431. right-hand-side, then you can create an AST node and categorize it
  432. according to the left-hand-side.
  433. %
  434. A name such as $\Exp$ that is
  435. defined by the grammar rules is a \emph{non-terminal}.
  436. %
  437. The name $\Int$ is a also a non-terminal, but instead of defining it
  438. with a grammar rule, we define it with the following explanation. We
  439. make the simplifying design decision that all of the languages in this
  440. book only handle machine-representable integers. On most modern
  441. machines this corresponds to integers represented with 64-bits, i.e.,
  442. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  443. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  444. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  445. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  446. that the sequence of decimals represent an integer in range $-2^{62}$
  447. to $2^{62}-1$.
  448. The second grammar rule is the \texttt{read} operation that receives
  449. an input integer from the user of the program.
  450. \begin{equation}
  451. \Exp ::= \READ{} \label{eq:arith-read}
  452. \end{equation}
  453. The third rule says that, given an $\Exp$ node, you can build another
  454. $\Exp$ node by negating it.
  455. \begin{equation}
  456. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  457. \end{equation}
  458. Symbols in typewriter font such as \key{-} and \key{read} are
  459. \emph{terminal} symbols and must literally appear in the program for
  460. the rule to be applicable.
  461. We can apply the rules to build ASTs in the $R_0$
  462. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  463. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  464. an $\Exp$.
  465. \begin{center}
  466. \begin{minipage}{0.4\textwidth}
  467. \begin{lstlisting}
  468. (Prim '- (list (Int 8)))
  469. \end{lstlisting}
  470. \end{minipage}
  471. \begin{minipage}{0.25\textwidth}
  472. \begin{equation}
  473. \begin{tikzpicture}
  474. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  475. \node[draw, circle] (8) at (0, -1.2) {$8$};
  476. \draw[->] (minus) to (8);
  477. \end{tikzpicture}
  478. \label{eq:arith-neg8}
  479. \end{equation}
  480. \end{minipage}
  481. \end{center}
  482. The next grammar rule defines addition expressions:
  483. \begin{equation}
  484. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  485. \end{equation}
  486. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  487. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  488. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  489. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  490. to show that
  491. \begin{lstlisting}
  492. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  493. \end{lstlisting}
  494. is an $\Exp$ in the $R_0$ language.
  495. If you have an AST for which the above rules do not apply, then the
  496. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  497. is not in $R_0$ because there are no rules for \code{+} with only one
  498. argument, nor for \key{-} with two arguments. Whenever we define a
  499. language with a grammar, the language only includes those programs
  500. that are justified by the rules.
  501. The last grammar rule for $R_0$ states that there is a \code{Program}
  502. node to mark the top of the whole program:
  503. \[
  504. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  505. \]
  506. The \code{Program} structure is defined as follows
  507. \begin{lstlisting}
  508. (struct Program (info body))
  509. \end{lstlisting}
  510. where \code{body} is an expression. In later chapters, the \code{info}
  511. part will be used to store auxilliary information but for now it is
  512. just the empty list.
  513. The \code{read-program} function provided in \code{utilities.rkt}
  514. reads programs in from a file (the sequence of characters in the
  515. concrete syntax of Racket) and parses them into the abstract syntax
  516. tree. The concrete syntax does not include a \key{program} form; that
  517. is added by the \code{read-program} function as it creates the
  518. AST. See the description of \code{read-program} in
  519. Appendix~\ref{appendix:utilities} for more details.
  520. It is common to have many rules with the same left-hand side, such as
  521. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  522. for gathering several rules, as shown in
  523. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  524. called an {\em alternative}.
  525. \begin{figure}[tp]
  526. \fbox{
  527. \begin{minipage}{0.96\textwidth}
  528. \[
  529. \begin{array}{rcl}
  530. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  531. &\mid& \ADD{\Exp}{\Exp} \\
  532. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  533. \end{array}
  534. \]
  535. \end{minipage}
  536. }
  537. \caption{The abstract syntax of $R_0$, a language of integer arithmetic.}
  538. \label{fig:r0-syntax}
  539. \end{figure}
  540. \section{Pattern Matching}
  541. \label{sec:pattern-matching}
  542. As mentioned above, compilers often need to access the children of an
  543. AST node. Racket provides the \texttt{match} form to access the parts
  544. of a structure. Consider the following example and the output on the
  545. right.
  546. \begin{center}
  547. \begin{minipage}{0.5\textwidth}
  548. \begin{lstlisting}
  549. (match ast1.1
  550. [(Prim op (list child1 child2))
  551. (print op)])
  552. \end{lstlisting}
  553. \end{minipage}
  554. \vrule
  555. \begin{minipage}{0.25\textwidth}
  556. \begin{lstlisting}
  557. '+
  558. \end{lstlisting}
  559. \end{minipage}
  560. \end{center}
  561. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  562. parts to the three variables \texttt{op}, \texttt{child1}, and
  563. \texttt{child2}. In general, a match clause consists of a
  564. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  565. that may also contain pattern-variables (each one preceded by a comma).
  566. %
  567. The pattern is not the same thing as a quasiquote expression used to
  568. \emph{construct} ASTs, however, the similarity is intentional:
  569. constructing and deconstructing ASTs uses similar syntax.
  570. %
  571. While the pattern uses a restricted syntax, the body of the match
  572. clause may contain any Racket code whatsoever.
  573. A \code{match} form may contain several clauses, as in the following
  574. function \code{leaf?} that recognizes when an $R_0$ node is
  575. a leaf. The \code{match} proceeds through the clauses in order,
  576. checking whether the pattern can match the input AST. The
  577. body of the first clause that matches is executed. The output of
  578. \code{leaf?} for several ASTs is shown on the right.
  579. \begin{center}
  580. \begin{minipage}{0.6\textwidth}
  581. \begin{lstlisting}
  582. (define (leaf? arith)
  583. (match arith
  584. [(Int n) #t]
  585. [(Prim 'read '()) #t]
  586. [(Prim '- (list c1)) #f]
  587. [(Prim '+ (list c1 c2)) #f]))
  588. (leaf? (Prim 'read '()))
  589. (leaf? (Prim '- (list (Int 8))))
  590. (leaf? (Int 8))
  591. \end{lstlisting}
  592. \end{minipage}
  593. \vrule
  594. \begin{minipage}{0.25\textwidth}
  595. \begin{lstlisting}
  596. #t
  597. #f
  598. #t
  599. \end{lstlisting}
  600. \end{minipage}
  601. \end{center}
  602. When writing a \code{match}, we always refer to the grammar definition
  603. for the language and identify which non-terminal we're expecting to
  604. match against, then we make sure that 1) we have one clause for each
  605. alternative of that non-terminal and 2) that the pattern in each
  606. clause corresponds to the corresponding right-hand side of a grammar
  607. rule. For the \code{match} in the \code{leaf?} function, we refer to
  608. the grammar for $R_0$ in Figure~\ref{fig:r0-syntax}. The $\Exp$
  609. non-terminal has 4 alternatives, so the \code{match} has 4 clauses.
  610. The pattern in each clause corresponds to the right-hand side of a
  611. grammar rule. For example, the pattern \code{(Prim '+ (list c1 c2))}
  612. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When translating
  613. from grammars to patterns, replace non-terminals such as $\Exp$ with
  614. pattern variables (e.g. \code{c1} and \code{c2}).
  615. \section{Recursion}
  616. \label{sec:recursion}
  617. Programs are inherently recursive. For example, an $R_0$ expression is
  618. often made of smaller expressions. Thus, the natural way to process an
  619. entire program is with a recursive function. As a first example of
  620. such a recursive function, we define \texttt{exp?} below, which takes
  621. an arbitrary S-expression and determines whether or not it is an $R_0$
  622. expression. As discussed in the previous section, each match clause
  623. corresponds to one grammar rule. The body of each clause makes a
  624. recursive call for each child node. This kind of recursive function is
  625. so common that it has a name: \emph{structural recursion}. In
  626. general, when a recursive function is defined using a sequence of
  627. match clauses that correspond to a grammar, and the body of each
  628. clause makes a recursive call on each child node, then we say the
  629. function is defined by structural recursion\footnote{This principle of
  630. structuring code according to the data definition is advocated in
  631. the book \emph{How to Design Programs}
  632. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  633. define a second function, named \code{R0?}, that determines whether an
  634. S-expression is an $R_0$ program. In general we can expect to write
  635. one recursive function to handle each non-terminal in the grammar.
  636. %
  637. \begin{center}
  638. \begin{minipage}{0.7\textwidth}
  639. \begin{lstlisting}
  640. (define (exp? ast)
  641. (match ast
  642. [(Int n) #t]
  643. [(Prim 'read '()) #t]
  644. [(Prim '- (list e)) (exp? e)]
  645. [(Prim '+ (list e1 e2))
  646. (and (exp? e1) (exp? e2))]
  647. [else #f]))
  648. (define (R0? ast)
  649. (match ast
  650. [(Program '() e) (exp? e)]
  651. [else #f]))
  652. (R0? (Program '() ast1.1)
  653. (R0? (Program '()
  654. (Prim '- (list (Prim 'read '())
  655. (Prim '+ (list (Num 8)))))))
  656. \end{lstlisting}
  657. \end{minipage}
  658. \vrule
  659. \begin{minipage}{0.25\textwidth}
  660. \begin{lstlisting}
  661. #t
  662. #f
  663. \end{lstlisting}
  664. \end{minipage}
  665. \end{center}
  666. You may be tempted to merge the two functions into one, like this:
  667. \begin{center}
  668. \begin{minipage}{0.5\textwidth}
  669. \begin{lstlisting}
  670. (define (R0? ast)
  671. (match ast
  672. [(Int n) #t]
  673. [(Prim 'read '()) #t]
  674. [(Prim '- (list e)) (R0? e)]
  675. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  676. [(Program '() e) (R0? e)]
  677. [else #f]))
  678. \end{lstlisting}
  679. \end{minipage}
  680. \end{center}
  681. %
  682. Sometimes such a trick will save a few lines of code, especially when it comes
  683. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  684. recommended because it can get you into trouble.
  685. %
  686. For instance, the above function is subtly wrong:
  687. \lstinline{(R0? (Program '() (Program '() (Int 3))))} will return true, when it
  688. should return false.
  689. %% NOTE FIXME - must check for consistency on this issue throughout.
  690. \section{Interpreters}
  691. \label{sec:interp-R0}
  692. The meaning, or semantics, of a program is typically defined in the
  693. specification of the language. For example, the Scheme language is
  694. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  695. defined in its reference manual~\citep{plt-tr}. In this book we use an
  696. interpreter to define the meaning of each language that we consider,
  697. following Reynolds' advice in this
  698. regard~\citep{reynolds72:_def_interp}. An interpreter that is
  699. designated (by some people) as the definition of a language is called
  700. a \emph{definitional interpreter}. Here we warm up by creating a
  701. definitional interpreter for the $R_0$ language, which serves as a
  702. second example of structural recursion. The \texttt{interp-R0}
  703. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  704. function is a match on the input program followed by a call to the
  705. \lstinline{interp-exp} helper function, which in turn has one match
  706. clause per grammar rule for $R_0$ expressions.
  707. \begin{figure}[tbp]
  708. \begin{lstlisting}
  709. (define (interp-exp e)
  710. (match e
  711. [(Int n) n]
  712. [(Prim 'read '())
  713. (define r (read))
  714. (cond [(fixnum? r) r]
  715. [else (error 'interp-R1 "expected an integer" r)])]
  716. [(Prim '- (list e))
  717. (define v (interp-exp e))
  718. (fx- 0 v)]
  719. [(Prim '+ (list e1 e2))
  720. (define v1 (interp-exp e1))
  721. (define v2 (interp-exp e2))
  722. (fx+ v1 v2)]
  723. )))
  724. (define (interp-R0 p)
  725. (match p
  726. [(Program '() e) (interp-exp e)]
  727. ))
  728. \end{lstlisting}
  729. \caption{Interpreter for the $R_0$ language.}
  730. \label{fig:interp-R0}
  731. \end{figure}
  732. Let us consider the result of interpreting a few $R_0$ programs. The
  733. following program adds two integers.
  734. \begin{lstlisting}
  735. (+ 10 32)
  736. \end{lstlisting}
  737. The result is \key{42}. We wrote the above program in concrete syntax,
  738. whereas the parsed abstract syntax is:
  739. \begin{lstlisting}
  740. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  741. \end{lstlisting}
  742. The next example demonstrates that expressions may be nested within
  743. each other, in this case nesting several additions and negations.
  744. \begin{lstlisting}
  745. (+ 10 (- (+ 12 20)))
  746. \end{lstlisting}
  747. What is the result of the above program?
  748. As mentioned previously, the $R_0$ language does not support
  749. arbitrarily-large integers, but only $63$-bit integers, so we
  750. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  751. in Racket.
  752. Suppose $n = 999999999999999999$, which indeed fits in $63$-bits.
  753. What happens when we run the following program in our interpreter?
  754. \begin{lstlisting}
  755. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  756. \end{lstlisting}
  757. It produces an error:
  758. \begin{lstlisting}
  759. fx+: result is not a fixnum
  760. \end{lstlisting}
  761. We establish the convention that if running the definitional
  762. interpreter on a program produces an error, then the meaning of that
  763. program is \emph{unspecified}. That means a compiler for the language
  764. is under no obligations regarding that program; it may or may not
  765. produce an executable, and if it does, that executable can do
  766. anything. This convention applies to the languages defined in this
  767. book, as a way to simplify the student's task of implementing them,
  768. but this convention is not applicable to all programming languages.
  769. Moving on to the last feature of the $R_0$ language, the \key{read}
  770. operation prompts the user of the program for an integer. Recall that
  771. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  772. \code{8}. So if we run
  773. \begin{lstlisting}
  774. (interp-R0 ast1.1)
  775. \end{lstlisting}
  776. and the input the integer \code{50} we get the answer to life, the
  777. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  778. Guide to the Galaxy} by Douglas Adams.}
  779. We include the \key{read} operation in $R_0$ so a clever student
  780. cannot implement a compiler for $R_0$ that simply runs the interpreter
  781. during compilation to obtain the output and then generates the trivial
  782. code to produce the output. (Yes, a clever student did this in a
  783. previous version of the course.)
  784. The job of a compiler is to translate a program in one language into a
  785. program in another language so that the output program behaves the
  786. same way as the input program does according to its definitional
  787. interpreter. This idea is depicted in the following diagram. Suppose
  788. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  789. interpreter for each language. Suppose that the compiler translates
  790. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  791. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  792. respective interpreters with input $i$ should yield the same output
  793. $o$.
  794. \begin{equation} \label{eq:compile-correct}
  795. \begin{tikzpicture}[baseline=(current bounding box.center)]
  796. \node (p1) at (0, 0) {$P_1$};
  797. \node (p2) at (3, 0) {$P_2$};
  798. \node (o) at (3, -2.5) {$o$};
  799. \path[->] (p1) edge [above] node {compile} (p2);
  800. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  801. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  802. \end{tikzpicture}
  803. \end{equation}
  804. In the next section we see our first example of a compiler.
  805. \section{Example Compiler: a Partial Evaluator}
  806. \label{sec:partial-evaluation}
  807. In this section we consider a compiler that translates $R_0$
  808. programs into $R_0$ programs that may be more efficient, that is,
  809. this compiler is an optimizer. Our optimizer will accomplish this by
  810. trying to eagerly compute the parts of the program that do not depend
  811. on any inputs. For example, given the following program
  812. \begin{lstlisting}
  813. (+ (read) (- (+ 5 3)))
  814. \end{lstlisting}
  815. our compiler will translate it into the program
  816. \begin{lstlisting}
  817. (+ (read) -8)
  818. \end{lstlisting}
  819. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  820. evaluator for the $R_0$ language. The output of the partial evaluator
  821. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  822. recursion over $\Exp$ is captured in the \code{pe-exp} function
  823. whereas the code for partially evaluating the negation and addition
  824. operations is factored into two separate helper functions:
  825. \code{pe-neg} and \code{pe-add}. The input to these helper
  826. functions is the output of partially evaluating the children.
  827. \begin{figure}[tbp]
  828. \begin{lstlisting}
  829. (define (pe-neg r)
  830. (match r
  831. [(Int n) (Int (fx- 0 n))]
  832. [else (Prim '- (list r))]))
  833. (define (pe-add r1 r2)
  834. (match* (r1 r2)
  835. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  836. [(_ _) (Prim '+ (list r1 r2))]))
  837. (define (pe-exp e)
  838. (match e
  839. [(Int n) (Int n)]
  840. [(Prim 'read '()) (Prim 'read '())]
  841. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  842. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  843. ))
  844. (define (pe-R0 p)
  845. (match p
  846. [(Program info e) (Program info (pe-exp e))]
  847. ))
  848. \end{lstlisting}
  849. \caption{A partial evaluator for $R_0$ expressions.}
  850. \label{fig:pe-arith}
  851. \end{figure}
  852. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  853. arguments are integers and if they are, perform the appropriate
  854. arithmetic. Otherwise, they use quasiquote to create an AST node for
  855. the operation (either negation or addition) and use comma to splice in
  856. the children.
  857. To gain some confidence that the partial evaluator is correct, we can
  858. test whether it produces programs that get the same result as the
  859. input programs. That is, we can test whether it satisfies Diagram
  860. \eqref{eq:compile-correct}. The following code runs the partial
  861. evaluator on several examples and tests the output program. The
  862. \texttt{parse-program} and \texttt{assert} functions are defined in
  863. Appendix~\ref{appendix:utilities}.\\
  864. \begin{minipage}{1.0\textwidth}
  865. \begin{lstlisting}
  866. (define (test-pe p)
  867. (assert "testing pe-R0"
  868. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  869. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  870. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  871. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  872. \end{lstlisting}
  873. \end{minipage}
  874. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  875. \chapter{Integers and Variables}
  876. \label{ch:int-exp}
  877. This chapter is about compiling the subset of Racket that includes
  878. integer arithmetic and local variable binding, which we name $R_1$, to
  879. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  880. to x86-64 simply as x86. The chapter begins with a description of the
  881. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  882. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  883. discuss only what is needed for compiling $R_1$. We introduce more of
  884. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  885. reflect on their differences and come up with a plan to break down the
  886. translation from $R_1$ to x86 into a handful of steps
  887. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  888. chapter give detailed hints regarding each step
  889. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  890. to give enough hints that the well-prepared reader, together with a
  891. few friends, can implement a compiler from $R_1$ to x86 in a couple
  892. weeks while at the same time leaving room for some fun and creativity.
  893. To give the reader a feeling for the scale of this first compiler, the
  894. instructor solution for the $R_1$ compiler is less than 500 lines of
  895. code.
  896. \section{The $R_1$ Language}
  897. \label{sec:s0}
  898. The $R_1$ language extends the $R_0$ language
  899. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  900. the $R_1$ language is defined by the grammar in
  901. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  902. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  903. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  904. the $R_1$ language includes the \key{Program} struct to mark the top
  905. of the program. The $\itm{info}$ field of the \key{Program} struct
  906. contains an \emph{association list} (a list of key-value pairs) that
  907. is used to communicate auxiliary data from one compiler pass the
  908. next. Despite the simplicity of the $R_1$ language, it is rich enough
  909. to exhibit several compilation techniques.
  910. \begin{figure}[btp]
  911. \centering
  912. \fbox{
  913. \begin{minipage}{0.96\textwidth}
  914. \[
  915. \begin{array}{rcl}
  916. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  917. &\mid& \ADD{\Exp}{\Exp}
  918. \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  919. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  920. \end{array}
  921. \]
  922. \end{minipage}
  923. }
  924. \caption{The abstract syntax of $R_1$, a language of integers and variables.}
  925. \label{fig:r1-syntax}
  926. \end{figure}
  927. Let us dive further into the syntax and semantics of the $R_1$
  928. language. The \key{Let} feature defines a variable for use within its
  929. body and initializes the variable with the value of an expression.
  930. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  931. The concrete syntax for \key{Let} is
  932. \begin{lstlisting}
  933. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  934. \end{lstlisting}
  935. For example, the following program initializes \code{x} to $32$ and then
  936. evaluates the body \code{(+ 10 x)}, producing $42$.
  937. \begin{lstlisting}
  938. (let ([x (+ 12 20)]) (+ 10 x))
  939. \end{lstlisting}
  940. When there are multiple \key{let}'s for the same variable, the closest
  941. enclosing \key{let} is used. That is, variable definitions overshadow
  942. prior definitions. Consider the following program with two \key{let}'s
  943. that define variables named \code{x}. Can you figure out the result?
  944. \begin{lstlisting}
  945. (let ([x 32]) (+ (let ([x 10]) x) x))
  946. \end{lstlisting}
  947. For the purposes of depicting which variable uses correspond to which
  948. definitions, the following shows the \code{x}'s annotated with
  949. subscripts to distinguish them. Double check that your answer for the
  950. above is the same as your answer for this annotated version of the
  951. program.
  952. \begin{lstlisting}
  953. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  954. \end{lstlisting}
  955. The initializing expression is always evaluated before the body of the
  956. \key{let}, so in the following, the \key{read} for \code{x} is
  957. performed before the \key{read} for \code{y}. Given the input
  958. $52$ then $10$, the following produces $42$ (not $-42$).
  959. \begin{lstlisting}
  960. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  961. \end{lstlisting}
  962. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  963. $R_1$ language. It extends the interpreter for $R_0$ with two new
  964. \key{match} clauses for variables and for \key{let}. For \key{let},
  965. we need a way to communicate the value of a variable to all the uses
  966. of a variable. To accomplish this, we maintain a mapping from
  967. variables to values, which is called an \emph{environment}. For
  968. simplicity, here we use an association list to represent the
  969. environment. The \code{interp-R1} function takes the current
  970. environment, \code{env}, as an extra parameter. When the interpreter
  971. encounters a variable, it finds the corresponding value using the
  972. \code{lookup} function (Appendix~\ref{appendix:utilities}). When the
  973. interpreter encounters a \key{Let}, it evaluates the initializing
  974. expression, extends the environment with the result value bound to the
  975. variable, then evaluates the body of the \key{Let}.
  976. \begin{figure}[tbp]
  977. \begin{lstlisting}
  978. (define (interp-exp env)
  979. (lambda (e)
  980. (match e
  981. [(Int n) n]
  982. [(Prim 'read '())
  983. (define r (read))
  984. (cond [(fixnum? r) r]
  985. [else (error 'interp-R1 "expected an integer" r)])]
  986. [(Prim '- (list e))
  987. (define v ((interp-exp env) e))
  988. (fx- 0 v)]
  989. [(Prim '+ (list e1 e2))
  990. (define v1 ((interp-exp env) e1))
  991. (define v2 ((interp-exp env) e2))
  992. (fx+ v1 v2)]
  993. [(Var x) (lookup x env)]
  994. [(Let x e body)
  995. (define new-env (cons (cons x ((interp-exp env) e)) env))
  996. ((interp-exp new-env) body)]
  997. )))
  998. (define (interp-R1 p)
  999. (match p
  1000. [(Program info e) ((interp-exp '()) e)]
  1001. ))
  1002. \end{lstlisting}
  1003. \caption{Interpreter for the $R_1$ language.}
  1004. \label{fig:interp-R1}
  1005. \end{figure}
  1006. The goal for this chapter is to implement a compiler that translates
  1007. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1008. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1009. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1010. is, they both output the same integer $n$. We depict this correctness
  1011. criteria in the following diagram.
  1012. \[
  1013. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1014. \node (p1) at (0, 0) {$P_1$};
  1015. \node (p2) at (4, 0) {$P_2$};
  1016. \node (o) at (4, -2) {$n$};
  1017. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1018. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1019. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1020. \end{tikzpicture}
  1021. \]
  1022. In the next section we introduce enough of the x86 assembly
  1023. language to compile $R_1$.
  1024. \section{The x86 Assembly Language}
  1025. \label{sec:x86}
  1026. Figure~\ref{fig:x86-a} defines the concrete syntax for the subset of
  1027. the x86 assembly language needed for this chapter.
  1028. %
  1029. An x86 program is a sequence of instructions. The program is stored in
  1030. the computer's memory and the computer has a \emph{program counter}
  1031. that points to the address of the next instruction to be executed. For
  1032. most instructions, once the instruction is executed, the program
  1033. counter is incremented to point to the immediately following
  1034. instruction in memory. Most x86 instructions take two operands, where
  1035. each operand is either an integer constant (called \emph{immediate
  1036. value}), a \emph{register}, or a \emph{memory} location. A register
  1037. is a special kind of variable. Each one holds a 64-bit value; there
  1038. are 16 registers in the computer and their names are given in
  1039. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  1040. addresses to 64-bit values%
  1041. \footnote{This simple story suffices for describing how sequential
  1042. programs access memory but is not sufficient for multi-threaded
  1043. programs. However, multi-threaded execution is beyond the scope of
  1044. this book.}.
  1045. %
  1046. We use the AT\&T syntax expected by the GNU assembler, which comes
  1047. with the \key{gcc} compiler that we use for compiling assembly code to
  1048. machine code.
  1049. %
  1050. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1051. the x86 instructions used in this book.
  1052. % to do: finish treatment of imulq
  1053. % it's needed for vector's in R6/R7
  1054. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1055. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1056. && \key{r8} \mid \key{r9} \mid \key{r10}
  1057. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1058. \mid \key{r14} \mid \key{r15}}
  1059. \begin{figure}[tp]
  1060. \fbox{
  1061. \begin{minipage}{0.96\textwidth}
  1062. \[
  1063. \begin{array}{lcl}
  1064. \Reg &::=& \allregisters{} \\
  1065. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  1066. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  1067. \key{subq} \; \Arg, \Arg \mid
  1068. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  1069. && \key{callq} \; \mathit{label} \mid
  1070. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1071. \Prog &::= & \key{.globl main}\\
  1072. & & \key{main:} \; \Instr^{+}
  1073. \end{array}
  1074. \]
  1075. \end{minipage}
  1076. }
  1077. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1078. \label{fig:x86-a}
  1079. \end{figure}
  1080. An immediate value is written using the notation \key{\$}$n$ where $n$
  1081. is an integer.
  1082. %
  1083. A register is written with a \key{\%} followed by the register name,
  1084. such as \key{\%rax}.
  1085. %
  1086. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1087. which obtains the address stored in register $r$ and then adds $n$
  1088. bytes to the address. The resulting address is used to either load or
  1089. store to memory depending on whether it occurs as a source or
  1090. destination argument of an instruction.
  1091. An arithmetic instruction such as $\key{addq}\,s,\,d$ reads from the
  1092. source $s$ and destination $d$, applies the arithmetic operation, then
  1093. writes the result back to the destination $d$.
  1094. %
  1095. The move instruction $\key{movq}\,s\,d$ reads from $s$ and stores the
  1096. result in $d$.
  1097. %
  1098. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1099. specified by the label. We discuss procedure calls in more detail
  1100. later in this chapter and in Chapter~\ref{ch:functions}.
  1101. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1102. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1103. \key{main} procedure is externally visible, which is necessary so
  1104. that the operating system can call it. The label \key{main:}
  1105. indicates the beginning of the \key{main} procedure which is where
  1106. the operating system starts executing this program. The instruction
  1107. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1108. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1109. $10$ in \key{rax} and puts the result, $42$, back into
  1110. \key{rax}.
  1111. %
  1112. The last instruction, \key{retq}, finishes the \key{main} function by
  1113. returning the integer in \key{rax} to the operating system. The
  1114. operating system interprets this integer as the program's exit
  1115. code. By convention, an exit code of 0 indicates that a program
  1116. completed successfully, and all other exit codes indicate various
  1117. errors. Nevertheless, we return the result of the program as the exit
  1118. code.
  1119. %\begin{wrapfigure}{r}{2.25in}
  1120. \begin{figure}[tbp]
  1121. \begin{lstlisting}
  1122. .globl main
  1123. main:
  1124. movq $10, %rax
  1125. addq $32, %rax
  1126. retq
  1127. \end{lstlisting}
  1128. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1129. \label{fig:p0-x86}
  1130. %\end{wrapfigure}
  1131. \end{figure}
  1132. Unfortunately, x86 varies in a couple ways depending on what operating
  1133. system it is assembled in. The code examples shown here are correct on
  1134. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1135. labels like \key{main} must be prefixed with an underscore, as in
  1136. \key{\_main}.
  1137. We exhibit the use of memory for storing intermediate results in the
  1138. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1139. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1140. region of memory called the \emph{procedure call stack} (or
  1141. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1142. for each procedure call. The memory layout for an individual frame is
  1143. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1144. \emph{stack pointer} and points to the item at the top of the
  1145. stack. The stack grows downward in memory, so we increase the size of
  1146. the stack by subtracting from the stack pointer. Some operating
  1147. systems require the frame size to be a multiple of 16 bytes. In the
  1148. context of a procedure call, the \emph{return address} is the next
  1149. instruction after the call instruction on the caller side. During a
  1150. function call, the return address is pushed onto the stack. The
  1151. register \key{rbp} is the \emph{base pointer} which serves two
  1152. purposes: 1) it saves the location of the stack pointer for the
  1153. calling procedure and 2) it is used to access variables associated
  1154. with the current procedure. The base pointer of the calling procedure
  1155. is pushed onto the stack after the return address. We number the
  1156. variables from $1$ to $n$. Variable $1$ is stored at address
  1157. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1158. \begin{figure}[tbp]
  1159. \begin{lstlisting}
  1160. start:
  1161. movq $10, -8(%rbp)
  1162. negq -8(%rbp)
  1163. movq -8(%rbp), %rax
  1164. addq $52, %rax
  1165. jmp conclusion
  1166. .globl main
  1167. main:
  1168. pushq %rbp
  1169. movq %rsp, %rbp
  1170. subq $16, %rsp
  1171. jmp start
  1172. conclusion:
  1173. addq $16, %rsp
  1174. popq %rbp
  1175. retq
  1176. \end{lstlisting}
  1177. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1178. \label{fig:p1-x86}
  1179. \end{figure}
  1180. \begin{figure}[tbp]
  1181. \centering
  1182. \begin{tabular}{|r|l|} \hline
  1183. Position & Contents \\ \hline
  1184. 8(\key{\%rbp}) & return address \\
  1185. 0(\key{\%rbp}) & old \key{rbp} \\
  1186. -8(\key{\%rbp}) & variable $1$ \\
  1187. -16(\key{\%rbp}) & variable $2$ \\
  1188. \ldots & \ldots \\
  1189. 0(\key{\%rsp}) & variable $n$\\ \hline
  1190. \end{tabular}
  1191. \caption{Memory layout of a frame.}
  1192. \label{fig:frame}
  1193. \end{figure}
  1194. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1195. three instructions are the typical \emph{prelude} for a procedure.
  1196. The instruction \key{pushq \%rbp} saves the base pointer for the
  1197. caller onto the stack and subtracts $8$ from the stack pointer. The
  1198. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1199. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1200. stack pointer down to make enough room for storing variables. This
  1201. program needs one variable ($8$ bytes) but because the frame size is
  1202. required to be a multiple of 16 bytes, the space for variables is
  1203. rounded to 16 bytes.
  1204. The four instructions under the label \code{start} carry out the work
  1205. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1206. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1207. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1208. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1209. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1210. \key{rax}, at which point \key{rax} contains $42$.
  1211. The three instructions under the label \code{conclusion} are the
  1212. typical \emph{finale} of a procedure. The first two instructions are
  1213. necessary to get the state of the machine back to where it was at the
  1214. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1215. moves the stack pointer back to point at the old base pointer. The
  1216. amount added here needs to match the amount that was subtracted in the
  1217. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1218. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1219. instruction, \key{retq}, jumps back to the procedure that called this
  1220. one and adds 8 to the stack pointer, which returns the stack pointer
  1221. to where it was prior to the procedure call.
  1222. The compiler will need a convenient representation for manipulating
  1223. x86 programs, so we define an abstract syntax for x86 in
  1224. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1225. a subscript $0$ because later we introduce extended versions of this
  1226. assembly language. The main difference compared to the concrete syntax
  1227. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1228. instructions to appear anywhere, but instead organizes instructions
  1229. into groups called \emph{blocks} and associates a label with every
  1230. block, which is why the \key{CFG} struct (for control-flow graph)
  1231. includes an association list mapping labels to blocks. The reason for
  1232. this organization becomes apparent in Chapter~\ref{ch:bool-types} when
  1233. we introduce conditional branching.
  1234. \begin{figure}[tp]
  1235. \fbox{
  1236. \begin{minipage}{0.96\textwidth}
  1237. \[
  1238. \begin{array}{lcl}
  1239. \itm{reg} &::=& \allregisters{} \\
  1240. \Arg &::=& \IMM{\Int} \mid \REG{\itm{reg}}
  1241. \mid \DEREF{\itm{reg}}{\Int} \\
  1242. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg} \\
  1243. &\mid& \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1244. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}\\
  1245. &\mid& \UNIINSTR{\code{'negq}}{\Arg}\\
  1246. &\mid& \CALLQ{\itm{label}} \mid \RETQ{} \\
  1247. &\mid& \PUSHQ{\Arg} \mid \POPQ{\Arg} \\
  1248. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1249. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1250. \end{array}
  1251. \]
  1252. \end{minipage}
  1253. }
  1254. \caption{Abstract syntax for $x86_0$ assembly.}
  1255. \label{fig:x86-ast-a}
  1256. \end{figure}
  1257. \section{Planning the trip to x86 via the $C_0$ language}
  1258. \label{sec:plan-s0-x86}
  1259. To compile one language to another it helps to focus on the
  1260. differences between the two languages because the compiler will need
  1261. to bridge those differences. What are the differences between $R_1$
  1262. and x86 assembly? Here are some of the most important ones:
  1263. \begin{enumerate}
  1264. \item[(a)] x86 arithmetic instructions typically have two arguments
  1265. and update the second argument in place. In contrast, $R_1$
  1266. arithmetic operations take two arguments and produce a new value.
  1267. An x86 instruction may have at most one memory-accessing argument.
  1268. Furthermore, some instructions place special restrictions on their
  1269. arguments.
  1270. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1271. whereas x86 instructions restrict their arguments to be integers
  1272. constants, registers, and memory locations.
  1273. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1274. sequence of instructions and jumps to labeled positions, whereas in
  1275. $R_1$ the order of evaluation is a left-to-right depth-first
  1276. traversal of the abstract syntax tree.
  1277. \item[(d)] An $R_1$ program can have any number of variables whereas
  1278. x86 has 16 registers and the procedure calls stack.
  1279. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1280. same name. The registers and memory locations of x86 all have unique
  1281. names or addresses.
  1282. \end{enumerate}
  1283. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1284. the problem into several steps, dealing with the above differences one
  1285. at a time. Each of these steps is called a \emph{pass} of the
  1286. compiler.
  1287. %
  1288. This terminology comes from each step traverses (i.e. passes over) the
  1289. AST of the program.
  1290. %
  1291. We begin by sketching how we might implement each pass, and give them
  1292. names. We then figure out an ordering of the passes and the
  1293. input/output language for each pass. The very first pass has $R_1$ as
  1294. its input language and the last pass has x86 as its output
  1295. language. In between we can choose whichever language is most
  1296. convenient for expressing the output of each pass, whether that be
  1297. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1298. Finally, to implement each pass we write one recursive function per
  1299. non-terminal in the grammar of the input language of the pass.
  1300. \begin{description}
  1301. \item[Pass \key{select-instructions}] To handle the difference between
  1302. $R_1$ operations and x86 instructions we convert each $R_1$
  1303. operation to a short sequence of instructions that accomplishes the
  1304. same task.
  1305. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1306. subexpression (i.e. operator and operand, and hence the name
  1307. \key{opera*}) is an \emph{atomic} expression (a variable or
  1308. integer), we introduce temporary variables to hold the results
  1309. of subexpressions.
  1310. \item[Pass \key{explicate-control}] To make the execution order of the
  1311. program explicit, we convert from the abstract syntax tree
  1312. representation into a \emph{control-flow graph} in which each node
  1313. contains a sequence of statements and the edges between nodes say
  1314. where to go at the end of the sequence.
  1315. \item[Pass \key{assign-homes}] To handle the difference between the
  1316. variables in $R_1$ versus the registers and stack locations in x86,
  1317. we assignment of each variable to a register or stack location.
  1318. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1319. by renaming every variable to a unique name, so that shadowing no
  1320. longer occurs.
  1321. \end{description}
  1322. The next question is: in what order should we apply these passes? This
  1323. question can be challenging because it is difficult to know ahead of
  1324. time which orders will be better (easier to implement, produce more
  1325. efficient code, etc.) so oftentimes trial-and-error is
  1326. involved. Nevertheless, we can try to plan ahead and make educated
  1327. choices regarding the ordering.
  1328. Let us consider the ordering of \key{uniquify} and
  1329. \key{remove-complex-opera*}. The assignment of subexpressions to
  1330. temporary variables involves introducing new variables and moving
  1331. subexpressions, which might change the shadowing of variables and
  1332. inadvertently change the behavior of the program. But if we apply
  1333. \key{uniquify} first, this will not be an issue. Of course, this means
  1334. that in \key{remove-complex-opera*}, we need to ensure that the
  1335. temporary variables that it creates are unique.
  1336. What should be the ordering of \key{explicate-control} with respect to
  1337. \key{uniquify}? The \key{uniquify} pass should come first because
  1338. \key{explicate-control} changes all the \key{let}-bound variables to
  1339. become local variables whose scope is the entire program, which would
  1340. confuse variables with the same name.
  1341. %
  1342. Likewise, we place \key{explicate-control} after
  1343. \key{remove-complex-opera*} because \key{explicate-control} removes
  1344. the \key{let} form, but it is convenient to use \key{let} in the
  1345. output of \key{remove-complex-opera*}.
  1346. %
  1347. Regarding \key{assign-homes}, it is helpful to place
  1348. \key{explicate-control} first because \key{explicate-control} changes
  1349. \key{let}-bound variables into program-scope variables. This means
  1350. that the \key{assign-homes} pass can read off the variables from the
  1351. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1352. entire program in search of \key{let}-bound variables.
  1353. Last, we need to decide on the ordering of \key{select-instructions}
  1354. and \key{assign-homes}. These two passes are intertwined, creating a
  1355. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1356. have already determined which instructions will be used, because x86
  1357. instructions have restrictions about which of their arguments can be
  1358. registers versus stack locations. One might want to give preferential
  1359. treatment to variables that occur in register-argument positions. On
  1360. the other hand, it may turn out to be impossible to make sure that all
  1361. such variables are assigned to registers, and then one must redo the
  1362. selection of instructions. Some compilers handle this problem by
  1363. iteratively repeating these two passes until a good solution is found.
  1364. We shall use a simpler approach in which \key{select-instructions}
  1365. comes first, followed by the \key{assign-homes}, then a third
  1366. pass named \key{patch-instructions} that uses a reserved register to
  1367. patch-up outstanding problems regarding instructions with too many
  1368. memory accesses. The disadvantage of this approach is some programs
  1369. may not execute as efficiently as they would if we used the iterative
  1370. approach and used all of the registers for variables.
  1371. \begin{figure}[tbp]
  1372. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1373. \node (R1) at (0,2) {\large $R_1$};
  1374. \node (R1-2) at (3,2) {\large $R_1$};
  1375. \node (R1-3) at (6,2) {\large $R_1$};
  1376. %\node (C0-1) at (6,0) {\large $C_0$};
  1377. \node (C0-2) at (3,0) {\large $C_0$};
  1378. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1379. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1380. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1381. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1382. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1383. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1384. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1385. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1386. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1387. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1388. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1389. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1390. \end{tikzpicture}
  1391. \caption{Overview of the passes for compiling $R_1$. }
  1392. \label{fig:R1-passes}
  1393. \end{figure}
  1394. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1395. passes in the form of a graph. Each pass is an edge and the
  1396. input/output language of each pass is a node in the graph. The output
  1397. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1398. are still in the $R_1$ language, but the output of the pass
  1399. \key{explicate-control} is in a different language $C_0$ that is
  1400. designed to make the order of evaluation explicit in its syntax, which
  1401. we introduce in the next section. The \key{select-instruction} pass
  1402. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1403. \key{patch-instructions} passes input and output variants of x86
  1404. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1405. \key{print-x86}, which converts from the abstract syntax of
  1406. $\text{x86}_0$ to the concrete syntax of x86.
  1407. In the next sections we discuss the $C_0$ language and the
  1408. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1409. remainder of this chapter gives hints regarding the implementation of
  1410. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1411. \subsection{The $C_0$ Intermediate Language}
  1412. The output of \key{explicate-control} is similar to the $C$
  1413. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1414. categories for expressions and statements, so we name it $C_0$. The
  1415. concrete syntax for $C_0$ is define din
  1416. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1417. is defined in Figure~\ref{fig:c0-syntax}.
  1418. %
  1419. The $C_0$ language supports the same operators as $R_1$ but the
  1420. arguments of operators are restricted to atomic expressions (variables
  1421. and integers), thanks to the \key{remove-complex-opera*} pass. In the
  1422. literature this style of intermediate language is called
  1423. administrative normal form, or ANF for
  1424. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{Let}
  1425. expressions, $C_0$ has assignment statements which can be executed in
  1426. sequence using the \key{Seq} form. A sequence of statements always
  1427. ends with \key{Return}, a guarantee that is baked into the grammar
  1428. rules for the \itm{tail} non-terminal. The naming of this non-terminal
  1429. comes from the term \emph{tail position}, which refers to an
  1430. expression that is the last one to execute within a function. (A
  1431. expression in tail position may contain subexpressions, and those may
  1432. or may not be in tail position depending on the kind of expression.)
  1433. A $C_0$ program consists of a control-flow graph (represented as an
  1434. association list mapping labels to tails). This is more general than
  1435. necessary for the present chapter, as we do not yet need to introduce
  1436. \key{goto} for jumping to labels, but it saves us from having to
  1437. change the syntax of the program construct in
  1438. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1439. \key{start}, and the whole program is its tail.
  1440. %
  1441. The $\itm{info}$ field of the \key{Program} form, after the
  1442. \key{explicate-control} pass, contains a mapping from the symbol
  1443. \key{locals} to a list of variables, that is, a list of all the
  1444. variables used in the program. At the start of the program, these
  1445. variables are uninitialized; they become initialized on their first
  1446. assignment.
  1447. \begin{figure}[tbp]
  1448. \fbox{
  1449. \begin{minipage}{0.96\textwidth}
  1450. \[
  1451. \begin{array}{lcl}
  1452. \Arg &::=& \Int \mid \Var \\
  1453. \Exp &::=& \Arg \mid \key{(read)} \mid \key{(-}~\Arg\key{)} \mid \key{(+}~\Arg~\Arg\key{)}\\
  1454. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1455. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1456. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1457. \end{array}
  1458. \]
  1459. \end{minipage}
  1460. }
  1461. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1462. \label{fig:c0-concrete-syntax}
  1463. \end{figure}
  1464. \begin{figure}[tbp]
  1465. \fbox{
  1466. \begin{minipage}{0.96\textwidth}
  1467. \[
  1468. \begin{array}{lcl}
  1469. \Arg &::=& \INT{\Int} \mid \VAR{\Var} \\
  1470. \Exp &::=& \Arg \mid \READ{} \mid \NEG{\Arg} \\
  1471. &\mid& \ADD{\Arg}{\Arg}\\
  1472. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1473. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1474. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1475. \end{array}
  1476. \]
  1477. \end{minipage}
  1478. }
  1479. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1480. \label{fig:c0-syntax}
  1481. \end{figure}
  1482. %% The \key{select-instructions} pass is optimistic in the sense that it
  1483. %% treats variables as if they were all mapped to registers. The
  1484. %% \key{select-instructions} pass generates a program that consists of
  1485. %% x86 instructions but that still uses variables, so it is an
  1486. %% intermediate language that is technically different than x86, which
  1487. %% explains the asterisks in the diagram above.
  1488. %% In this Chapter we shall take the easy road to implementing
  1489. %% \key{assign-homes} and simply map all variables to stack locations.
  1490. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1491. %% smarter approach in which we make a best-effort to map variables to
  1492. %% registers, resorting to the stack only when necessary.
  1493. %% Once variables have been assigned to their homes, we can finalize the
  1494. %% instruction selection by dealing with an idiosyncrasy of x86
  1495. %% assembly. Many x86 instructions have two arguments but only one of the
  1496. %% arguments may be a memory reference (and the stack is a part of
  1497. %% memory). Because some variables may get mapped to stack locations,
  1498. %% some of our generated instructions may violate this restriction. The
  1499. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1500. %% replacing every violating instruction with a short sequence of
  1501. %% instructions that use the \key{rax} register. Once we have implemented
  1502. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1503. %% need to patch instructions will be relatively rare.
  1504. \subsection{The dialects of x86}
  1505. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1506. the pass \key{select-instructions}. It extends $x86_0$ with an
  1507. unbounded number of program-scope variables and has looser rules
  1508. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1509. output of \key{print-x86}, is the concrete syntax for x86.
  1510. \section{Uniquify Variables}
  1511. \label{sec:uniquify-s0}
  1512. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1513. programs in which every \key{let} uses a unique variable name. For
  1514. example, the \code{uniquify} pass should translate the program on the
  1515. left into the program on the right. \\
  1516. \begin{tabular}{lll}
  1517. \begin{minipage}{0.4\textwidth}
  1518. \begin{lstlisting}
  1519. (let ([x 32])
  1520. (+ (let ([x 10]) x) x))
  1521. \end{lstlisting}
  1522. \end{minipage}
  1523. &
  1524. $\Rightarrow$
  1525. &
  1526. \begin{minipage}{0.4\textwidth}
  1527. \begin{lstlisting}
  1528. (let ([x.1 32])
  1529. (+ (let ([x.2 10]) x.2) x.1))
  1530. \end{lstlisting}
  1531. \end{minipage}
  1532. \end{tabular} \\
  1533. %
  1534. The following is another example translation, this time of a program
  1535. with a \key{let} nested inside the initializing expression of another
  1536. \key{let}.\\
  1537. \begin{tabular}{lll}
  1538. \begin{minipage}{0.4\textwidth}
  1539. \begin{lstlisting}
  1540. (let ([x (let ([x 4])
  1541. (+ x 1))])
  1542. (+ x 2))
  1543. \end{lstlisting}
  1544. \end{minipage}
  1545. &
  1546. $\Rightarrow$
  1547. &
  1548. \begin{minipage}{0.4\textwidth}
  1549. \begin{lstlisting}
  1550. (let ([x.2 (let ([x.1 4])
  1551. (+ x.1 1))])
  1552. (+ x.2 2))
  1553. \end{lstlisting}
  1554. \end{minipage}
  1555. \end{tabular}
  1556. We recommend implementing \code{uniquify} by creating a function named
  1557. \code{uniquify-exp} that is structurally recursive function and mostly
  1558. just copies the input program. However, when encountering a \key{let},
  1559. it should generate a unique name for the variable (the Racket function
  1560. \code{gensym} is handy for this) and associate the old name with the
  1561. new unique name in an association list. The \code{uniquify-exp}
  1562. function will need to access this association list when it gets to a
  1563. variable reference, so we add another parameter to \code{uniquify-exp}
  1564. for the association list. It is quite common for a compiler pass to
  1565. need a map to store extra information about variables. Such maps are
  1566. traditionally called \emph{symbol tables}.
  1567. The skeleton of the \code{uniquify-exp} function is shown in
  1568. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1569. convenient to partially apply it to a symbol table and then apply it
  1570. to different expressions, as in the last clause for primitive
  1571. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1572. is useful for applying a function to each element of a list to produce
  1573. a new list.
  1574. \begin{exercise}
  1575. \normalfont % I don't like the italics for exercises. -Jeremy
  1576. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1577. implement the clauses for variables and for the \key{let} form.
  1578. \end{exercise}
  1579. \begin{figure}[tbp]
  1580. \begin{lstlisting}
  1581. (define (uniquify-exp symtab)
  1582. (lambda (e)
  1583. (match e
  1584. [(Var x) ___]
  1585. [(Int n) (Int n)]
  1586. [(Let x e body) ___]
  1587. [(Prim op es)
  1588. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1589. )))
  1590. (define (uniquify p)
  1591. (match p
  1592. [(Program info e)
  1593. (Program info ((uniquify-exp '()) e))]
  1594. )))
  1595. \end{lstlisting}
  1596. \caption{Skeleton for the \key{uniquify} pass.}
  1597. \label{fig:uniquify-s0}
  1598. \end{figure}
  1599. \begin{exercise}
  1600. \normalfont % I don't like the italics for exercises. -Jeremy
  1601. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1602. and checking whether the output programs produce the same result as
  1603. the input programs. The $R_1$ programs should be designed to test the
  1604. most interesting parts of the \key{uniquify} pass, that is, the
  1605. programs should include \key{let} forms, variables, and variables
  1606. that overshadow each other. The five programs should be in a
  1607. subdirectory named \key{tests} and they should have the same file name
  1608. except for a different integer at the end of the name, followed by the
  1609. ending \key{.rkt}. Use the \key{interp-tests} function
  1610. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1611. your \key{uniquify} pass on the example programs. See the
  1612. \key{run-tests.rkt} script in the student support code for an example
  1613. of how to use \key{interp-tests}.
  1614. \end{exercise}
  1615. \section{Remove Complex Operands}
  1616. \label{sec:remove-complex-opera-r1}
  1617. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1618. $R_1$ programs in which the arguments of operations are atomic
  1619. expressions. Put another way, this pass removes complex operands,
  1620. such as the expression \code{(- 10)} in the program below. This is
  1621. accomplished by introducing a new \key{let}-bound variable, binding
  1622. the complex operand to the new variable, and then using the new
  1623. variable in place of the complex operand, as shown in the output of
  1624. \code{remove-complex-opera*} on the right.\\
  1625. \begin{tabular}{lll}
  1626. \begin{minipage}{0.4\textwidth}
  1627. % s0_19.rkt
  1628. \begin{lstlisting}
  1629. (+ 52 (- 10))
  1630. \end{lstlisting}
  1631. \end{minipage}
  1632. &
  1633. $\Rightarrow$
  1634. &
  1635. \begin{minipage}{0.4\textwidth}
  1636. \begin{lstlisting}
  1637. (let ([tmp.1 (- 10)])
  1638. (+ 52 tmp.1))
  1639. \end{lstlisting}
  1640. \end{minipage}
  1641. \end{tabular}
  1642. We recommend implementing this pass with two mutually recursive
  1643. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1644. \code{rco-atom} to subexpressions that need to become atomic and to
  1645. apply \code{rco-exp} to subexpressions that can be atomic or complex.
  1646. Both functions take an $R_1$ expression as input. The \code{rco-exp}
  1647. function returns an expression. The \code{rco-atom} function returns
  1648. two things: an atomic expression and association list mapping
  1649. temporary variables to complex subexpressions. You can return multiple
  1650. things from a function using Racket's \key{values} form and you can
  1651. receive multiple things from a function call using the
  1652. \key{define-values} form. If you are not familiar with these features,
  1653. review the Racket documentation. Also, the \key{for/lists} form is
  1654. useful for applying a function to each element of a list, in the case
  1655. where the function returns multiple values.
  1656. The following shows the output of \code{rco-atom} on the expression
  1657. \code{(- 10)} (using concrete syntax to be concise).
  1658. \begin{tabular}{lll}
  1659. \begin{minipage}{0.4\textwidth}
  1660. \begin{lstlisting}
  1661. (- 10)
  1662. \end{lstlisting}
  1663. \end{minipage}
  1664. &
  1665. $\Rightarrow$
  1666. &
  1667. \begin{minipage}{0.4\textwidth}
  1668. \begin{lstlisting}
  1669. tmp.1
  1670. ((tmp.1 . (- 10)))
  1671. \end{lstlisting}
  1672. \end{minipage}
  1673. \end{tabular}
  1674. Take special care of programs such as the next one that \key{let}-bind
  1675. variables with integers or other variables. You should leave them
  1676. unchanged, as shown in to the program on the right \\
  1677. \begin{tabular}{lll}
  1678. \begin{minipage}{0.4\textwidth}
  1679. % s0_20.rkt
  1680. \begin{lstlisting}
  1681. (let ([a 42])
  1682. (let ([b a])
  1683. b))
  1684. \end{lstlisting}
  1685. \end{minipage}
  1686. &
  1687. $\Rightarrow$
  1688. &
  1689. \begin{minipage}{0.4\textwidth}
  1690. \begin{lstlisting}
  1691. (let ([a 42])
  1692. (let ([b a])
  1693. b))
  1694. \end{lstlisting}
  1695. \end{minipage}
  1696. \end{tabular} \\
  1697. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1698. produce the following output.\\
  1699. \begin{minipage}{0.4\textwidth}
  1700. \begin{lstlisting}
  1701. (let ([tmp.1 42])
  1702. (let ([a tmp.1])
  1703. (let ([tmp.2 a])
  1704. (let ([b tmp.2])
  1705. b))))
  1706. \end{lstlisting}
  1707. \end{minipage}
  1708. \begin{exercise}
  1709. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1710. it on all of the example programs that you created to test the
  1711. \key{uniquify} pass and create three new example programs that are
  1712. designed to exercise the interesting code in the
  1713. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1714. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1715. your passes on the example programs.
  1716. \end{exercise}
  1717. \section{Explicate Control}
  1718. \label{sec:explicate-control-r1}
  1719. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1720. programs that make the order of execution explicit in their
  1721. syntax. For now this amounts to flattening \key{let} constructs into a
  1722. sequence of assignment statements. For example, consider the following
  1723. $R_1$ program.\\
  1724. % s0_11.rkt
  1725. \begin{minipage}{0.96\textwidth}
  1726. \begin{lstlisting}
  1727. (let ([y (let ([x 20])
  1728. (+ x (let ([x 22]) x)))])
  1729. y)
  1730. \end{lstlisting}
  1731. \end{minipage}\\
  1732. %
  1733. The output of the previous pass and of \code{explicate-control} is
  1734. shown below. Recall that the right-hand-side of a \key{let} executes
  1735. before its body, so the order of evaluation for this program is to
  1736. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1737. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1738. output of \code{explicate-control} makes this ordering explicit.\\
  1739. \begin{tabular}{lll}
  1740. \begin{minipage}{0.4\textwidth}
  1741. \begin{lstlisting}
  1742. (let ([y (let ([x.1 20])
  1743. (let ([x.2 22])
  1744. (+ x.1 x.2)))])
  1745. y)
  1746. \end{lstlisting}
  1747. \end{minipage}
  1748. &
  1749. $\Rightarrow$
  1750. &
  1751. \begin{minipage}{0.4\textwidth}
  1752. \begin{lstlisting}
  1753. locals: y x.1 x.2
  1754. start:
  1755. x.1 = 20;
  1756. x.2 = 22;
  1757. y = (+ x.1 x.2);
  1758. return y;
  1759. \end{lstlisting}
  1760. \end{minipage}
  1761. \end{tabular}
  1762. We recommend implementing \code{explicate-control} using two mutually
  1763. recursive functions: \code{explicate-tail} and
  1764. \code{explicate-assign}. The first function should be applied to
  1765. expressions in tail position whereas the second should be applied to
  1766. expressions that occur on the right-hand-side of a \key{let}. The
  1767. \code{explicate-tail} function takes an $R_1$ expression as input and
  1768. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1769. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1770. function takes an $R_1$ expression, the variable that it is to be
  1771. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1772. assignment (e.g., the code generated for the body of the \key{let}).
  1773. It returns a $\Tail$ and a list of variables. The top-level
  1774. \code{explicate-control} function should invoke \code{explicate-tail}
  1775. on the body of the \key{program} and then associate the \code{locals}
  1776. symbol with the resulting list of variables in the $\itm{info}$ field,
  1777. as in the above example.
  1778. %% \section{Uncover Locals}
  1779. %% \label{sec:uncover-locals-r1}
  1780. %% The pass \code{uncover-locals} simply collects all of the variables in
  1781. %% the program and places then in the $\itm{info}$ of the program
  1782. %% construct. Here is the output for the example program of the last
  1783. %% section.
  1784. %% \begin{minipage}{0.4\textwidth}
  1785. %% \begin{lstlisting}
  1786. %% (program ((locals . (x.1 x.2 y)))
  1787. %% ((start .
  1788. %% (seq (assign x.1 20)
  1789. %% (seq (assign x.2 22)
  1790. %% (seq (assign y (+ x.1 x.2))
  1791. %% (return y)))))))
  1792. %% \end{lstlisting}
  1793. %% \end{minipage}
  1794. \section{Select Instructions}
  1795. \label{sec:select-r1}
  1796. In the \code{select-instructions} pass we begin the work of
  1797. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1798. this pass is a variable of x86 that still uses variables, so we add an
  1799. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1800. syntax of Figure~\ref{fig:x86-ast-a}. We recommend implementing the
  1801. \code{select-instructions} in terms of three auxiliary functions, one
  1802. for each of the non-terminals of $C_0$: $\Arg$, $\Stmt$, and $\Tail$.
  1803. The cases for $\Arg$ are straightforward, variables stay
  1804. the same and integer constants are changed to immediates:
  1805. $\INT{n}$ changes to $\IMM{n}$.
  1806. Next we consider the cases for $\Stmt$, starting with arithmetic
  1807. operations. For example, in $C_0$ an addition operation can take the
  1808. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1809. need to use the \key{addq} instruction which does an in-place
  1810. update. So we must first move \code{10} to \code{x}. \\
  1811. \begin{tabular}{lll}
  1812. \begin{minipage}{0.4\textwidth}
  1813. \begin{lstlisting}
  1814. x = (+ 10 32);
  1815. \end{lstlisting}
  1816. \end{minipage}
  1817. &
  1818. $\Rightarrow$
  1819. &
  1820. \begin{minipage}{0.4\textwidth}
  1821. \begin{lstlisting}
  1822. movq $10 x
  1823. addq $32 x
  1824. \end{lstlisting}
  1825. \end{minipage}
  1826. \end{tabular} \\
  1827. %
  1828. There are cases that require special care to avoid generating
  1829. needlessly complicated code. If one of the arguments of the addition
  1830. is the same as the left-hand side of the assignment, then there is no
  1831. need for the extra move instruction. For example, the following
  1832. assignment statement can be translated into a single \key{addq}
  1833. instruction.\\
  1834. \begin{tabular}{lll}
  1835. \begin{minipage}{0.4\textwidth}
  1836. \begin{lstlisting}
  1837. x = (+ 10 x);
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. &
  1841. $\Rightarrow$
  1842. &
  1843. \begin{minipage}{0.4\textwidth}
  1844. \begin{lstlisting}
  1845. addq $10 x
  1846. \end{lstlisting}
  1847. \end{minipage}
  1848. \end{tabular} \\
  1849. The \key{read} operation does not have a direct counterpart in x86
  1850. assembly, so we have instead implemented this functionality in the C
  1851. language, with the function \code{read\_int} in the file
  1852. \code{runtime.c}. In general, we refer to all of the functionality in
  1853. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1854. for short. When compiling your generated x86 assembly code, you need
  1855. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1856. using \code{gcc} option \code{-c}) and link it into the
  1857. executable. For our purposes of code generation, all you need to do is
  1858. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1859. (for left-hand side) into a call to the \code{read\_int} function
  1860. followed by a move from \code{rax} to the left-hand side. The move
  1861. from \code{rax} is needed because the return value from
  1862. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1863. \begin{tabular}{lll}
  1864. \begin{minipage}{0.4\textwidth}
  1865. \begin{lstlisting}
  1866. |$\itm{lhs}$| = (read);
  1867. \end{lstlisting}
  1868. \end{minipage}
  1869. &
  1870. $\Rightarrow$
  1871. &
  1872. \begin{minipage}{0.4\textwidth}
  1873. \begin{lstlisting}
  1874. callq read_int
  1875. movq %rax |$\itm{lhs}$|
  1876. \end{lstlisting}
  1877. \end{minipage}
  1878. \end{tabular} \\
  1879. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1880. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1881. assignment to the \key{rax} register followed by a jump to the
  1882. conclusion of the program (so the conclusion needs to be labeled).
  1883. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1884. recursively and append the resulting instructions.
  1885. \begin{exercise}
  1886. \normalfont
  1887. Implement the \key{select-instructions} pass and test it on all of the
  1888. example programs that you created for the previous passes and create
  1889. three new example programs that are designed to exercise all of the
  1890. interesting code in this pass. Use the \key{interp-tests} function
  1891. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1892. your passes on the example programs.
  1893. \end{exercise}
  1894. \section{Assign Homes}
  1895. \label{sec:assign-r1}
  1896. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1897. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1898. Thus, the \key{assign-homes} pass is responsible for placing all of
  1899. the program variables in registers or on the stack. For runtime
  1900. efficiency, it is better to place variables in registers, but as there
  1901. are only 16 registers, some programs must necessarily place some
  1902. variables on the stack. In this chapter we focus on the mechanics of
  1903. placing variables on the stack. We study an algorithm for placing
  1904. variables in registers in Chapter~\ref{ch:register-allocation-r1}.
  1905. Consider again the following $R_1$ program.
  1906. % s0_20.rkt
  1907. \begin{lstlisting}
  1908. (program ()
  1909. (let ([a 42])
  1910. (let ([b a])
  1911. b)))
  1912. \end{lstlisting}
  1913. For reference, we repeat the output of \code{select-instructions} on
  1914. the left and show the output of \code{assign-homes} on the right.
  1915. Recall that \key{explicate-control} associated the list of
  1916. variables with the \code{locals} symbol in the program's $\itm{info}$
  1917. field, so \code{assign-homes} has convenient access to the them. In
  1918. this example, we assign variable \code{a} to stack location
  1919. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1920. \begin{tabular}{l}
  1921. \begin{minipage}{0.4\textwidth}
  1922. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1923. (program ((locals . (a b)))
  1924. ((start .
  1925. (block ()
  1926. (movq (int 42) (var a))
  1927. (movq (var a) (var b))
  1928. (movq (var b) (reg rax))
  1929. (jmp conclusion)))))
  1930. \end{lstlisting}
  1931. \end{minipage}
  1932. {$\Rightarrow$}
  1933. \begin{minipage}{0.4\textwidth}
  1934. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1935. (program ((stack-space . 16))
  1936. ((start .
  1937. (block ()
  1938. (movq (int 42) (deref rbp -8))
  1939. (movq (deref rbp -8) (deref rbp -16))
  1940. (movq (deref rbp -16) (reg rax))
  1941. (jmp conclusion)))))
  1942. \end{lstlisting}
  1943. \end{minipage}
  1944. \end{tabular} \\
  1945. In the process of assigning variables to stack locations, it is
  1946. convenient to compute and store the size of the frame (in bytes) in
  1947. the $\itm{info}$ field of the \key{program} node, with the key
  1948. \code{stack-space}, which will be needed later to generate the
  1949. procedure conclusion. Some operating systems place restrictions on
  1950. the frame size. For example, Mac OS X requires the frame size to be a
  1951. multiple of 16 bytes.
  1952. \begin{exercise}
  1953. \normalfont Implement the \key{assign-homes} pass and test it on all
  1954. of the example programs that you created for the previous passes pass.
  1955. We recommend that \key{assign-homes} take an extra parameter that is a
  1956. mapping of variable names to homes (stack locations for now). Use the
  1957. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1958. \key{utilities.rkt} to test your passes on the example programs.
  1959. \end{exercise}
  1960. \section{Patch Instructions}
  1961. \label{sec:patch-s0}
  1962. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  1963. programs to $\text{x86}_0$ programs by making sure that each
  1964. instruction adheres to the restrictions of the x86 assembly language.
  1965. In particular, at most one argument of an instruction may be a memory
  1966. reference.
  1967. We return to the following running example.
  1968. % s0_20.rkt
  1969. \begin{lstlisting}
  1970. (let ([a 42])
  1971. (let ([b a])
  1972. b))
  1973. \end{lstlisting}
  1974. After the \key{assign-homes} pass, the above program has been translated to
  1975. the following. \\
  1976. \begin{minipage}{0.5\textwidth}
  1977. \begin{lstlisting}
  1978. (program ((stack-space . 16))
  1979. ((start .
  1980. (block ()
  1981. (movq (int 42) (deref rbp -8))
  1982. (movq (deref rbp -8) (deref rbp -16))
  1983. (movq (deref rbp -16) (reg rax))
  1984. (jmp conclusion)))))
  1985. \end{lstlisting}
  1986. \end{minipage}\\
  1987. The second \key{movq} instruction is problematic because both
  1988. arguments are stack locations. We suggest fixing this problem by
  1989. moving from the source location to the register \key{rax} and then
  1990. from \key{rax} to the destination location, as follows.
  1991. \begin{lstlisting}
  1992. (movq (deref rbp -8) (reg rax))
  1993. (movq (reg rax) (deref rbp -16))
  1994. \end{lstlisting}
  1995. \begin{exercise}
  1996. \normalfont
  1997. Implement the \key{patch-instructions} pass and test it on all of the
  1998. example programs that you created for the previous passes and create
  1999. three new example programs that are designed to exercise all of the
  2000. interesting code in this pass. Use the \key{interp-tests} function
  2001. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2002. your passes on the example programs.
  2003. \end{exercise}
  2004. \section{Print x86}
  2005. \label{sec:print-x86}
  2006. The last step of the compiler from $R_1$ to x86 is to convert the
  2007. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  2008. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  2009. \key{format} and \key{string-append} functions are useful in this
  2010. regard. The main work that this step needs to perform is to create the
  2011. \key{main} function and the standard instructions for its prelude and
  2012. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2013. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2014. variables, so we suggest computing it in the \key{assign-homes} pass
  2015. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2016. of the \key{program} node.
  2017. %% Your compiled code should print the result of the program's execution
  2018. %% by using the \code{print\_int} function provided in
  2019. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2020. %% far, this final result should be stored in the \key{rax} register.
  2021. %% We'll talk more about how to perform function calls with arguments in
  2022. %% general later on, but for now, place the following after the compiled
  2023. %% code for the $R_1$ program but before the conclusion:
  2024. %% \begin{lstlisting}
  2025. %% movq %rax, %rdi
  2026. %% callq print_int
  2027. %% \end{lstlisting}
  2028. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2029. %% stores the first argument to be passed into \key{print\_int}.
  2030. If you want your program to run on Mac OS X, your code needs to
  2031. determine whether or not it is running on a Mac, and prefix
  2032. underscores to labels like \key{main}. You can determine the platform
  2033. with the Racket call \code{(system-type 'os)}, which returns
  2034. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2035. %% In addition to
  2036. %% placing underscores on \key{main}, you need to put them in front of
  2037. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2038. %% \_print\_int}).
  2039. \begin{exercise}
  2040. \normalfont Implement the \key{print-x86} pass and test it on all of
  2041. the example programs that you created for the previous passes. Use the
  2042. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2043. \key{utilities.rkt} to test your complete compiler on the example
  2044. programs. See the \key{run-tests.rkt} script in the student support
  2045. code for an example of how to use \key{compiler-tests}. Also, remember
  2046. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2047. \key{gcc}.
  2048. \end{exercise}
  2049. \section{Challenge: Partial Evaluator for $R_1$}
  2050. \label{sec:pe-R1}
  2051. This section describes optional challenge exercises that involve
  2052. adapting and improving the partial evaluator for $R_0$ that was
  2053. introduced in Section~\ref{sec:partial-evaluation}.
  2054. \begin{exercise}\label{ex:pe-R1}
  2055. \normalfont
  2056. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2057. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2058. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2059. and variables to the $R_0$ language, so you will need to add cases for
  2060. them in the \code{pe-exp} function. Also, note that the \key{program}
  2061. form changes slightly to include an $\itm{info}$ field. Once
  2062. complete, add the partial evaluation pass to the front of your
  2063. compiler and make sure that your compiler still passes all of the
  2064. tests.
  2065. \end{exercise}
  2066. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2067. \begin{exercise}
  2068. \normalfont
  2069. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2070. \code{pe-add} auxiliary functions with functions that know more about
  2071. arithmetic. For example, your partial evaluator should translate
  2072. \begin{lstlisting}
  2073. (+ 1 (+ (read) 1))
  2074. \end{lstlisting}
  2075. into
  2076. \begin{lstlisting}
  2077. (+ 2 (read))
  2078. \end{lstlisting}
  2079. To accomplish this, the \code{pe-exp} function should produce output
  2080. in the form of the $\itm{residual}$ non-terminal of the following
  2081. grammar.
  2082. \[
  2083. \begin{array}{lcl}
  2084. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2085. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2086. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2087. \end{array}
  2088. \]
  2089. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2090. that their inputs are $\itm{residual}$ expressions and they should
  2091. return $\itm{residual}$ expressions. Once the improvements are
  2092. complete, make sure that your compiler still passes all of the tests.
  2093. After all, fast code is useless if it produces incorrect results!
  2094. \end{exercise}
  2095. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2096. \chapter{Register Allocation}
  2097. \label{ch:register-allocation-r1}
  2098. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2099. make our life easier. However, we can improve the performance of the
  2100. generated code if we instead place some variables into registers. The
  2101. CPU can access a register in a single cycle, whereas accessing the
  2102. stack takes many cycles if the relevant data is in cache or many more
  2103. to access main memory if the data is not in cache.
  2104. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2105. serves as a running example. We show the source program and also the
  2106. output of instruction selection. At that point the program is almost
  2107. x86 assembly but not quite; it still contains variables instead of
  2108. stack locations or registers.
  2109. \begin{figure}
  2110. \begin{minipage}{0.45\textwidth}
  2111. Example $R_1$ program:
  2112. % s0_22.rkt
  2113. \begin{lstlisting}
  2114. (program ()
  2115. (let ([v 1])
  2116. (let ([w 46])
  2117. (let ([x (+ v 7)])
  2118. (let ([y (+ 4 x)])
  2119. (let ([z (+ x w)])
  2120. (+ z (- y))))))))
  2121. \end{lstlisting}
  2122. \end{minipage}
  2123. \begin{minipage}{0.45\textwidth}
  2124. After instruction selection:
  2125. \begin{lstlisting}
  2126. (program
  2127. ((locals . (v w x y z t.1)))
  2128. ((start .
  2129. (block ()
  2130. (movq (int 1) (var v))
  2131. (movq (int 46) (var w))
  2132. (movq (var v) (var x))
  2133. (addq (int 7) (var x))
  2134. (movq (var x) (var y))
  2135. (addq (int 4) (var y))
  2136. (movq (var x) (var z))
  2137. (addq (var w) (var z))
  2138. (movq (var y) (var t.1))
  2139. (negq (var t.1))
  2140. (movq (var z) (reg rax))
  2141. (addq (var t.1) (reg rax))
  2142. (jmp conclusion)))))
  2143. \end{lstlisting}
  2144. \end{minipage}
  2145. \caption{An example program for register allocation.}
  2146. \label{fig:reg-eg}
  2147. \end{figure}
  2148. The goal of register allocation is to fit as many variables into
  2149. registers as possible. A program sometimes has more variables than
  2150. registers, so we cannot map each variable to a different
  2151. register. Fortunately, it is common for different variables to be
  2152. needed during different periods of time during program execution, and
  2153. in such cases several variables can be mapped to the same register.
  2154. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2155. After the variable \code{x} is moved to \code{z} it is no longer
  2156. needed. Variable \code{y}, on the other hand, is used only after this
  2157. point, so \code{x} and \code{y} could share the same register. The
  2158. topic of Section~\ref{sec:liveness-analysis-r1} is how we compute
  2159. where a variable is needed. Once we have that information, we compute
  2160. which variables are needed at the same time, i.e., which ones
  2161. \emph{interfere}, and represent this relation as graph whose vertices
  2162. are variables and edges indicate when two variables interfere with
  2163. each other (Section~\ref{sec:build-interference}). We then model
  2164. register allocation as a graph coloring problem, which we discuss in
  2165. Section~\ref{sec:graph-coloring}.
  2166. In the event that we run out of registers despite these efforts, we
  2167. place the remaining variables on the stack, similar to what we did in
  2168. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  2169. that is assigned to a stack location, it has been \emph{spilled}. The
  2170. process of spilling variables is handled as part of the graph coloring
  2171. process described in \ref{sec:graph-coloring}.
  2172. \section{Registers and Calling Conventions}
  2173. \label{sec:calling-conventions}
  2174. As we perform register allocation, we will need to be aware of the
  2175. conventions that govern the way in which registers interact with
  2176. function calls. The convention for x86 is that the caller is
  2177. responsible for freeing up some registers, the \emph{caller-saved
  2178. registers}, prior to the function call, and the callee is
  2179. responsible for saving and restoring some other registers, the
  2180. \emph{callee-saved registers}, before and after using them. The
  2181. caller-saved registers are
  2182. \begin{lstlisting}
  2183. rax rdx rcx rsi rdi r8 r9 r10 r11
  2184. \end{lstlisting}
  2185. while the callee-saved registers are
  2186. \begin{lstlisting}
  2187. rsp rbp rbx r12 r13 r14 r15
  2188. \end{lstlisting}
  2189. Another way to think about this caller/callee convention is the
  2190. following. The caller should assume that all the caller-saved registers
  2191. get overwritten with arbitrary values by the callee. On the other
  2192. hand, the caller can safely assume that all the callee-saved registers
  2193. contain the same values after the call that they did before the call.
  2194. The callee can freely use any of the caller-saved registers. However,
  2195. if the callee wants to use a callee-saved register, the callee must
  2196. arrange to put the original value back in the register prior to
  2197. returning to the caller, which is usually accomplished by saving and
  2198. restoring the value from the stack.
  2199. \section{Liveness Analysis}
  2200. \label{sec:liveness-analysis-r1}
  2201. A variable is \emph{live} if the variable is used at some later point
  2202. in the program and there is not an intervening assignment to the
  2203. variable.
  2204. %
  2205. To understand the latter condition, consider the following code
  2206. fragment in which there are two writes to \code{b}. Are \code{a} and
  2207. \code{b} both live at the same time?
  2208. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2209. (movq (int 5) (var a))
  2210. (movq (int 30) (var b))
  2211. (movq (var a) (var c))
  2212. (movq (int 10) (var b))
  2213. (addq (var b) (var c))
  2214. \end{lstlisting}
  2215. The answer is no because the value \code{30} written to \code{b} on
  2216. line 2 is never used. The variable \code{b} is read on line 5 and
  2217. there is an intervening write to \code{b} on line 4, so the read on
  2218. line 5 receives the value written on line 4, not line 2.
  2219. The live variables can be computed by traversing the instruction
  2220. sequence back to front (i.e., backwards in execution order). Let
  2221. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2222. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2223. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2224. variables before instruction $I_k$. The live variables after an
  2225. instruction are always the same as the live variables before the next
  2226. instruction.
  2227. \begin{equation*}
  2228. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2229. \end{equation*}
  2230. To start things off, there are no live variables after the last
  2231. instruction, so
  2232. \begin{equation*}
  2233. L_{\mathsf{after}}(n) = \emptyset
  2234. \end{equation*}
  2235. We then apply the following rule repeatedly, traversing the
  2236. instruction sequence back to front.
  2237. \begin{equation*}
  2238. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2239. \end{equation*}
  2240. where $W(k)$ are the variables written to by instruction $I_k$ and
  2241. $R(k)$ are the variables read by instruction $I_k$.
  2242. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2243. for the running example, with each instruction aligned with its
  2244. $L_{\mathtt{after}}$ set to make the figure easy to read.
  2245. \margincomment{JM: I think you should walk through the explanation of this formula,
  2246. connecting it back to the example from before. \\
  2247. JS: Agreed.}
  2248. \begin{figure}[tbp]
  2249. \hspace{20pt}
  2250. \begin{minipage}{0.45\textwidth}
  2251. \begin{lstlisting}[numbers=left]
  2252. (block ()
  2253. (movq (int 1) (var v))
  2254. (movq (int 46) (var w))
  2255. (movq (var v) (var x))
  2256. (addq (int 7) (var x))
  2257. (movq (var x) (var y))
  2258. (addq (int 4) (var y))
  2259. (movq (var x) (var z))
  2260. (addq (var w) (var z))
  2261. (movq (var y) (var t.1))
  2262. (negq (var t.1))
  2263. (movq (var z) (reg rax))
  2264. (addq (var t.1) (reg rax))
  2265. (jmp conclusion))
  2266. \end{lstlisting}
  2267. \end{minipage}
  2268. \vrule\hspace{10pt}
  2269. \begin{minipage}{0.45\textwidth}
  2270. \begin{lstlisting}
  2271. |$\{\}$|
  2272. |$\{v \}$|
  2273. |$\{v,w\}$|
  2274. |$\{w,x\}$|
  2275. |$\{w,x\}$|
  2276. |$\{w,x,y\}$|
  2277. |$\{w,x,y\}$|
  2278. |$\{w,y,z\}$|
  2279. |$\{y,z\}$|
  2280. |$\{z,t.1\}$|
  2281. |$\{z,t.1\}$|
  2282. |$\{t.1\}$|
  2283. |$\{\}$|
  2284. |$\{\}$|
  2285. \end{lstlisting}
  2286. \end{minipage}
  2287. \caption{An example block annotated with live-after sets.}
  2288. \label{fig:live-eg}
  2289. \end{figure}
  2290. \begin{exercise}\normalfont
  2291. Implement the compiler pass named \code{uncover-live} that computes
  2292. the live-after sets. We recommend storing the live-after sets (a list
  2293. of lists of variables) in the $\itm{info}$ field of the \key{block}
  2294. construct.
  2295. %
  2296. We recommend organizing your code to use a helper function that takes
  2297. a list of instructions and an initial live-after set (typically empty)
  2298. and returns the list of live-after sets.
  2299. %
  2300. We recommend creating helper functions to 1) compute the set of
  2301. variables that appear in an argument (of an instruction), 2) compute
  2302. the variables read by an instruction which corresponds to the $R$
  2303. function discussed above, and 3) the variables written by an
  2304. instruction which corresponds to $W$.
  2305. \end{exercise}
  2306. \section{Building the Interference Graph}
  2307. \label{sec:build-interference}
  2308. Based on the liveness analysis, we know where each variable is needed.
  2309. However, during register allocation, we need to answer questions of
  2310. the specific form: are variables $u$ and $v$ live at the same time?
  2311. (And therefore cannot be assigned to the same register.) To make this
  2312. question easier to answer, we create an explicit data structure, an
  2313. \emph{interference graph}. An interference graph is an undirected
  2314. graph that has an edge between two variables if they are live at the
  2315. same time, that is, if they interfere with each other.
  2316. The most obvious way to compute the interference graph is to look at
  2317. the set of live variables between each statement in the program, and
  2318. add an edge to the graph for every pair of variables in the same set.
  2319. This approach is less than ideal for two reasons. First, it can be
  2320. rather expensive because it takes $O(n^2)$ time to look at every pair
  2321. in a set of $n$ live variables. Second, there is a special case in
  2322. which two variables that are live at the same time do not actually
  2323. interfere with each other: when they both contain the same value
  2324. because we have assigned one to the other.
  2325. A better way to compute the interference graph is to focus on the
  2326. writes. That is, for each instruction, create an edge between the
  2327. variable being written to and all the \emph{other} live variables.
  2328. (One should not create self edges.) For a \key{callq} instruction,
  2329. think of all caller-saved registers as being written to, so and edge
  2330. must be added between every live variable and every caller-saved
  2331. register. For \key{movq}, we deal with the above-mentioned special
  2332. case by not adding an edge between a live variable $v$ and destination
  2333. $d$ if $v$ matches the source of the move. So we have the following
  2334. three rules.
  2335. \begin{enumerate}
  2336. \item If instruction $I_k$ is an arithmetic instruction such as
  2337. (\key{addq} $s$\, $d$), then add the edge $(d,v)$ for every $v \in
  2338. L_{\mathsf{after}}(k)$ unless $v = d$.
  2339. \item If instruction $I_k$ is of the form (\key{callq}
  2340. $\mathit{label}$), then add an edge $(r,v)$ for every caller-saved
  2341. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2342. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  2343. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2344. d$ or $v = s$.
  2345. \end{enumerate}
  2346. \margincomment{JM: I think you could give examples of each one of these
  2347. using the example program and use those to help explain why these
  2348. rules are correct.\\
  2349. JS: Agreed.}
  2350. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2351. the following interference for the instruction at the specified line
  2352. number.
  2353. \begin{quote}
  2354. Line 2: no interference,\\
  2355. Line 3: $w$ interferes with $v$,\\
  2356. Line 4: $x$ interferes with $w$,\\
  2357. Line 5: $x$ interferes with $w$,\\
  2358. Line 6: $y$ interferes with $w$,\\
  2359. Line 7: $y$ interferes with $w$ and $x$,\\
  2360. Line 8: $z$ interferes with $w$ and $y$,\\
  2361. Line 9: $z$ interferes with $y$, \\
  2362. Line 10: $t.1$ interferes with $z$, \\
  2363. Line 11: $t.1$ interferes with $z$, \\
  2364. Line 12: no interference, \\
  2365. Line 13: no interference. \\
  2366. Line 14: no interference.
  2367. \end{quote}
  2368. The resulting interference graph is shown in
  2369. Figure~\ref{fig:interfere}.
  2370. \begin{figure}[tbp]
  2371. \large
  2372. \[
  2373. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2374. \node (v) at (0,0) {$v$};
  2375. \node (w) at (2,0) {$w$};
  2376. \node (x) at (4,0) {$x$};
  2377. \node (t1) at (6,-2) {$t.1$};
  2378. \node (y) at (2,-2) {$y$};
  2379. \node (z) at (4,-2) {$z$};
  2380. \draw (v) to (w);
  2381. \foreach \i in {w,x,y}
  2382. {
  2383. \foreach \j in {w,x,y}
  2384. {
  2385. \draw (\i) to (\j);
  2386. }
  2387. }
  2388. \draw (z) to (w);
  2389. \draw (z) to (y);
  2390. \draw (t1) to (z);
  2391. \end{tikzpicture}
  2392. \]
  2393. \caption{The interference graph of the example program.}
  2394. \label{fig:interfere}
  2395. \end{figure}
  2396. %% Our next concern is to choose a data structure for representing the
  2397. %% interference graph. There are many choices for how to represent a
  2398. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2399. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2400. %% data structure is to study the algorithm that uses the data structure,
  2401. %% determine what operations need to be performed, and then choose the
  2402. %% data structure that provide the most efficient implementations of
  2403. %% those operations. Often times the choice of data structure can have an
  2404. %% effect on the time complexity of the algorithm, as it does here. If
  2405. %% you skim the next section, you will see that the register allocation
  2406. %% algorithm needs to ask the graph for all of its vertices and, given a
  2407. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2408. %% correct choice of graph representation is that of an adjacency
  2409. %% list. There are helper functions in \code{utilities.rkt} for
  2410. %% representing graphs using the adjacency list representation:
  2411. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2412. %% (Appendix~\ref{appendix:utilities}).
  2413. %% %
  2414. %% \margincomment{\footnotesize To do: change to use the
  2415. %% Racket graph library. \\ --Jeremy}
  2416. %% %
  2417. %% In particular, those functions use a hash table to map each vertex to
  2418. %% the set of adjacent vertices, and the sets are represented using
  2419. %% Racket's \key{set}, which is also a hash table.
  2420. \begin{exercise}\normalfont
  2421. Implement the compiler pass named \code{build-interference} according
  2422. to the algorithm suggested above. We recommend using the Racket
  2423. \code{graph} package to create and inspect the interference graph.
  2424. The output graph of this pass should be stored in the $\itm{info}$
  2425. field of the program, under the key \code{conflicts}.
  2426. \end{exercise}
  2427. \section{Graph Coloring via Sudoku}
  2428. \label{sec:graph-coloring}
  2429. We now come to the main event, mapping variables to registers (or to
  2430. stack locations in the event that we run out of registers). We need
  2431. to make sure not to map two variables to the same register if the two
  2432. variables interfere with each other. In terms of the interference
  2433. graph, this means that adjacent vertices must be mapped to different
  2434. registers. If we think of registers as colors, the register
  2435. allocation problem becomes the widely-studied graph coloring
  2436. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2437. The reader may be more familiar with the graph coloring problem than he
  2438. or she realizes; the popular game of Sudoku is an instance of the
  2439. graph coloring problem. The following describes how to build a graph
  2440. out of an initial Sudoku board.
  2441. \begin{itemize}
  2442. \item There is one vertex in the graph for each Sudoku square.
  2443. \item There is an edge between two vertices if the corresponding squares
  2444. are in the same row, in the same column, or if the squares are in
  2445. the same $3\times 3$ region.
  2446. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2447. \item Based on the initial assignment of numbers to squares in the
  2448. Sudoku board, assign the corresponding colors to the corresponding
  2449. vertices in the graph.
  2450. \end{itemize}
  2451. If you can color the remaining vertices in the graph with the nine
  2452. colors, then you have also solved the corresponding game of Sudoku.
  2453. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2454. the corresponding graph with colored vertices. We map the Sudoku
  2455. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2456. sampling of the vertices (those that are colored) because showing
  2457. edges for all of the vertices would make the graph unreadable.
  2458. \begin{figure}[tbp]
  2459. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2460. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2461. \caption{A Sudoku game board and the corresponding colored graph.}
  2462. \label{fig:sudoku-graph}
  2463. \end{figure}
  2464. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2465. strategies to come up with an algorithm for allocating registers. For
  2466. example, one of the basic techniques for Sudoku is called Pencil
  2467. Marks. The idea is that you use a process of elimination to determine
  2468. what numbers no longer make sense for a square, and write down those
  2469. numbers in the square (writing very small). For example, if the number
  2470. $1$ is assigned to a square, then by process of elimination, you can
  2471. write the pencil mark $1$ in all the squares in the same row, column,
  2472. and region. Many Sudoku computer games provide automatic support for
  2473. Pencil Marks.
  2474. %
  2475. The Pencil Marks technique corresponds to the notion of color
  2476. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2477. vertex, in Sudoku terms, is the set of colors that are no longer
  2478. available. In graph terminology, we have the following definition:
  2479. \begin{equation*}
  2480. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2481. \text{ and } \mathrm{color}(v) = c \}
  2482. \end{equation*}
  2483. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2484. edge with $u$.
  2485. Using the Pencil Marks technique leads to a simple strategy for
  2486. filling in numbers: if there is a square with only one possible number
  2487. left, then write down that number! But what if there are no squares
  2488. with only one possibility left? One brute-force approach is to just
  2489. make a guess. If that guess ultimately leads to a solution, great. If
  2490. not, backtrack to the guess and make a different guess. One good
  2491. thing about Pencil Marks is that it reduces the degree of branching in
  2492. the search tree. Nevertheless, backtracking can be horribly time
  2493. consuming. One way to reduce the amount of backtracking is to use the
  2494. most-constrained-first heuristic. That is, when making a guess, always
  2495. choose a square with the fewest possibilities left (the vertex with
  2496. the highest saturation). The idea is that choosing highly constrained
  2497. squares earlier rather than later is better because later there may
  2498. not be any possibilities.
  2499. In some sense, register allocation is easier than Sudoku because we
  2500. can always cheat and add more numbers by mapping variables to the
  2501. stack. We say that a variable is \emph{spilled} when we decide to map
  2502. it to a stack location. We would like to minimize the time needed to
  2503. color the graph, and backtracking is expensive. Thus, it makes sense
  2504. to keep the most-constrained-first heuristic but drop the backtracking
  2505. in favor of greedy search (guess and just keep going).
  2506. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2507. greedy algorithm for register allocation based on saturation and the
  2508. most-constrained-first heuristic, which is roughly equivalent to the
  2509. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2510. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2511. as in Sudoku, the algorithm represents colors with integers, with the
  2512. first $k$ colors corresponding to the $k$ registers in a given machine
  2513. and the rest of the integers corresponding to stack locations.
  2514. \begin{figure}[btp]
  2515. \centering
  2516. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2517. Algorithm: DSATUR
  2518. Input: a graph |$G$|
  2519. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2520. |$W \gets \mathit{vertices}(G)$|
  2521. while |$W \neq \emptyset$| do
  2522. pick a vertex |$u$| from |$W$| with the highest saturation,
  2523. breaking ties randomly
  2524. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2525. |$\mathrm{color}[u] \gets c$|
  2526. |$W \gets W - \{u\}$|
  2527. \end{lstlisting}
  2528. \caption{The saturation-based greedy graph coloring algorithm.}
  2529. \label{fig:satur-algo}
  2530. \end{figure}
  2531. With this algorithm in hand, let us return to the running example and
  2532. consider how to color the interference graph in
  2533. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2534. register allocation because we use it to patch instructions, so we
  2535. remove that vertex from the graph. Initially, all of the vertices are
  2536. not yet colored and they are unsaturated, so we annotate each of them
  2537. with a dash for their color and an empty set for the saturation.
  2538. \[
  2539. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2540. \node (v) at (0,0) {$v:-,\{\}$};
  2541. \node (w) at (3,0) {$w:-,\{\}$};
  2542. \node (x) at (6,0) {$x:-,\{\}$};
  2543. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2544. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2545. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2546. \draw (v) to (w);
  2547. \foreach \i in {w,x,y}
  2548. {
  2549. \foreach \j in {w,x,y}
  2550. {
  2551. \draw (\i) to (\j);
  2552. }
  2553. }
  2554. \draw (z) to (w);
  2555. \draw (z) to (y);
  2556. \draw (t1) to (z);
  2557. \end{tikzpicture}
  2558. \]
  2559. We select a maximally saturated vertex and color it $0$. In this case we
  2560. have a 7-way tie, so we arbitrarily pick $t.1$. The then mark color $0$
  2561. as no longer available for $z$ because it interferes
  2562. with $t.1$.
  2563. \[
  2564. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2565. \node (v) at (0,0) {$v:-,\{\}$};
  2566. \node (w) at (3,0) {$w:-,\{\}$};
  2567. \node (x) at (6,0) {$x:-,\{\}$};
  2568. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2569. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2570. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2571. \draw (v) to (w);
  2572. \foreach \i in {w,x,y}
  2573. {
  2574. \foreach \j in {w,x,y}
  2575. {
  2576. \draw (\i) to (\j);
  2577. }
  2578. }
  2579. \draw (z) to (w);
  2580. \draw (z) to (y);
  2581. \draw (t1) to (z);
  2582. \end{tikzpicture}
  2583. \]
  2584. Now we repeat the process, selecting another maximally saturated
  2585. vertex, which in this case is $z$. We color $z$ with $1$.
  2586. \[
  2587. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2588. \node (v) at (0,0) {$v:-,\{\}$};
  2589. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2590. \node (x) at (6,0) {$x:-,\{\}$};
  2591. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2592. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2593. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2594. \draw (t1) to (z);
  2595. \draw (v) to (w);
  2596. \foreach \i in {w,x,y}
  2597. {
  2598. \foreach \j in {w,x,y}
  2599. {
  2600. \draw (\i) to (\j);
  2601. }
  2602. }
  2603. \draw (z) to (w);
  2604. \draw (z) to (y);
  2605. \end{tikzpicture}
  2606. \]
  2607. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2608. first available color, which is $0$.
  2609. \[
  2610. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2611. \node (v) at (0,0) {$v:-,\{\}$};
  2612. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2613. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2614. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2615. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2616. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2617. \draw (t1) to (z);
  2618. \draw (v) to (w);
  2619. \foreach \i in {w,x,y}
  2620. {
  2621. \foreach \j in {w,x,y}
  2622. {
  2623. \draw (\i) to (\j);
  2624. }
  2625. }
  2626. \draw (z) to (w);
  2627. \draw (z) to (y);
  2628. \end{tikzpicture}
  2629. \]
  2630. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2631. \[
  2632. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2633. \node (v) at (0,0) {$v:-,\{2\}$};
  2634. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2635. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2636. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2637. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2638. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2639. \draw (t1) to (z);
  2640. \draw (v) to (w);
  2641. \foreach \i in {w,x,y}
  2642. {
  2643. \foreach \j in {w,x,y}
  2644. {
  2645. \draw (\i) to (\j);
  2646. }
  2647. }
  2648. \draw (z) to (w);
  2649. \draw (z) to (y);
  2650. \end{tikzpicture}
  2651. \]
  2652. Now $x$ has the highest saturation, so we color it $1$.
  2653. \[
  2654. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2655. \node (v) at (0,0) {$v:-,\{2\}$};
  2656. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2657. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2658. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2659. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2660. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2661. \draw (t1) to (z);
  2662. \draw (v) to (w);
  2663. \foreach \i in {w,x,y}
  2664. {
  2665. \foreach \j in {w,x,y}
  2666. {
  2667. \draw (\i) to (\j);
  2668. }
  2669. }
  2670. \draw (z) to (w);
  2671. \draw (z) to (y);
  2672. \end{tikzpicture}
  2673. \]
  2674. In the last step of the algorithm, we color $v$ with $0$.
  2675. \[
  2676. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2677. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2678. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2679. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2680. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2681. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2682. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2683. \draw (t1) to (z);
  2684. \draw (v) to (w);
  2685. \foreach \i in {w,x,y}
  2686. {
  2687. \foreach \j in {w,x,y}
  2688. {
  2689. \draw (\i) to (\j);
  2690. }
  2691. }
  2692. \draw (z) to (w);
  2693. \draw (z) to (y);
  2694. \end{tikzpicture}
  2695. \]
  2696. With the coloring complete, we can finalize the assignment of
  2697. variables to registers and stack locations. Recall that if we have $k$
  2698. registers, we map the first $k$ colors to registers and the rest to
  2699. stack locations. Suppose for the moment that we have just one
  2700. register to use for register allocation, \key{rcx}. Then the following
  2701. is the mapping of colors to registers and stack allocations.
  2702. \[
  2703. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2704. \]
  2705. Putting this mapping together with the above coloring of the variables, we
  2706. arrive at the assignment:
  2707. \begin{gather*}
  2708. \{ v \mapsto \key{\%rcx}, \,
  2709. w \mapsto \key{-16(\%rbp)}, \,
  2710. x \mapsto \key{-8(\%rbp)}, \\
  2711. y \mapsto \key{\%rcx}, \,
  2712. z\mapsto \key{-8(\%rbp)},
  2713. t.1\mapsto \key{\%rcx} \}
  2714. \end{gather*}
  2715. Applying this assignment to our running example, on the left, yields
  2716. the program on the right.\\
  2717. % why frame size of 32? -JGS
  2718. \begin{minipage}{0.4\textwidth}
  2719. \begin{lstlisting}
  2720. (block ()
  2721. (movq (int 1) (var v))
  2722. (movq (int 46) (var w))
  2723. (movq (var v) (var x))
  2724. (addq (int 7) (var x))
  2725. (movq (var x) (var y))
  2726. (addq (int 4) (var y))
  2727. (movq (var x) (var z))
  2728. (addq (var w) (var z))
  2729. (movq (var y) (var t.1))
  2730. (negq (var t.1))
  2731. (movq (var z) (reg rax))
  2732. (addq (var t.1) (reg rax))
  2733. (jmp conclusion))
  2734. \end{lstlisting}
  2735. \end{minipage}
  2736. $\Rightarrow$
  2737. \begin{minipage}{0.45\textwidth}
  2738. \begin{lstlisting}
  2739. (block ()
  2740. (movq (int 1) (reg rcx))
  2741. (movq (int 46) (deref rbp -16))
  2742. (movq (reg rcx) (deref rbp -8))
  2743. (addq (int 7) (deref rbp -8))
  2744. (movq (deref rbp -8) (reg rcx))
  2745. (addq (int 4) (reg rcx))
  2746. (movq (deref rbp -8) (deref rbp -8))
  2747. (addq (deref rbp -16) (deref rbp -8))
  2748. (movq (reg rcx) (reg rcx))
  2749. (negq (reg rcx))
  2750. (movq (deref rbp -8) (reg rax))
  2751. (addq (reg rcx) (reg rax))
  2752. (jmp conclusion))
  2753. \end{lstlisting}
  2754. \end{minipage}
  2755. The resulting program is almost an x86 program. The remaining step
  2756. is to apply the patch instructions pass. In this example, the trivial
  2757. move of \code{-8(\%rbp)} to itself is deleted and the addition of
  2758. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2759. \code{rax} as follows.
  2760. \begin{lstlisting}
  2761. (movq (deref rbp -16) (reg rax)
  2762. (addq (reg rax) (deref rbp -8))
  2763. \end{lstlisting}
  2764. An overview of all of the passes involved in register allocation is
  2765. shown in Figure~\ref{fig:reg-alloc-passes}.
  2766. \begin{figure}[tbp]
  2767. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2768. \node (R1) at (0,2) {\large $R_1$};
  2769. \node (R1-2) at (3,2) {\large $R_1$};
  2770. \node (R1-3) at (6,2) {\large $R_1$};
  2771. \node (C0-1) at (6,0) {\large $C_0$};
  2772. \node (C0-2) at (3,0) {\large $C_0$};
  2773. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2774. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2775. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2776. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2777. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2778. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2779. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2780. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2781. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2782. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2783. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2784. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2785. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2786. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2787. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2788. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2789. \end{tikzpicture}
  2790. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2791. \label{fig:reg-alloc-passes}
  2792. \end{figure}
  2793. \begin{exercise}\normalfont
  2794. Implement the pass \code{allocate-registers}, which should come
  2795. after the \code{build-interference} pass. The three new passes,
  2796. \code{uncover-live}, \code{build-interference}, and
  2797. \code{allocate-registers} replace the \code{assign-homes} pass of
  2798. Section~\ref{sec:assign-r1}.
  2799. We recommend that you create a helper function named
  2800. \code{color-graph} that takes an interference graph and a list of
  2801. all the variables in the program. This function should return a
  2802. mapping of variables to their colors (represented as natural
  2803. numbers). By creating this helper function, you will be able to
  2804. reuse it in Chapter~\ref{ch:functions} when you add support for
  2805. functions.
  2806. Once you have obtained the coloring from \code{color-graph}, you can
  2807. assign the variables to registers or stack locations and then reuse
  2808. code from the \code{assign-homes} pass from
  2809. Section~\ref{sec:assign-r1} to replace the variables with their
  2810. assigned location.
  2811. Test your updated compiler by creating new example programs that
  2812. exercise all of the register allocation algorithm, such as forcing
  2813. variables to be spilled to the stack.
  2814. \end{exercise}
  2815. \section{Print x86 and Conventions for Registers}
  2816. \label{sec:print-x86-reg-alloc}
  2817. Recall the \code{print-x86} pass generates the prelude and
  2818. conclusion instructions for the \code{main} function.
  2819. %
  2820. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2821. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2822. reason for this is that our \code{main} function must adhere to the
  2823. x86 calling conventions that we described in
  2824. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2825. function needs to restore (in the conclusion) any callee-saved
  2826. registers that get used during register allocation. The simplest
  2827. approach is to save and restore all of the callee-saved registers. The
  2828. more efficient approach is to keep track of which callee-saved
  2829. registers were used and only save and restore them. Either way, make
  2830. sure to take this use of stack space into account when you are
  2831. calculating the size of the frame. Also, don't forget that the size of
  2832. the frame needs to be a multiple of 16 bytes.
  2833. \section{Challenge: Move Biasing$^{*}$}
  2834. \label{sec:move-biasing}
  2835. This section describes an optional enhancement to register allocation
  2836. for those students who are looking for an extra challenge or who have
  2837. a deeper interest in register allocation.
  2838. We return to the running example, but we remove the supposition that
  2839. we only have one register to use. So we have the following mapping of
  2840. color numbers to registers.
  2841. \[
  2842. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2843. \]
  2844. Using the same assignment that was produced by register allocator
  2845. described in the last section, we get the following program.
  2846. \begin{minipage}{0.45\textwidth}
  2847. \begin{lstlisting}
  2848. (block ()
  2849. (movq (int 1) (var v))
  2850. (movq (int 46) (var w))
  2851. (movq (var v) (var x))
  2852. (addq (int 7) (var x))
  2853. (movq (var x) (var y))
  2854. (addq (int 4) (var y))
  2855. (movq (var x) (var z))
  2856. (addq (var w) (var z))
  2857. (movq (var y) (var t.1))
  2858. (negq (var t.1))
  2859. (movq (var z) (reg rax))
  2860. (addq (var t.1) (reg rax))
  2861. (jmp conclusion))
  2862. \end{lstlisting}
  2863. \end{minipage}
  2864. $\Rightarrow$
  2865. \begin{minipage}{0.45\textwidth}
  2866. \begin{lstlisting}
  2867. (block ()
  2868. (movq (int 1) (reg rbx))
  2869. (movq (int 46) (reg rdx))
  2870. (movq (reg rbx) (reg rcx))
  2871. (addq (int 7) (reg rcx))
  2872. (movq (reg rcx) (reg rbx))
  2873. (addq (int 4) (reg rbx))
  2874. (movq (reg rcx) (reg rcx))
  2875. (addq (reg rdx) (reg rcx))
  2876. (movq (reg rbx) (reg rbx))
  2877. (negq (reg rbx))
  2878. (movq (reg rcx) (reg rax))
  2879. (addq (reg rbx) (reg rax))
  2880. (jmp conclusion))
  2881. \end{lstlisting}
  2882. \end{minipage}
  2883. While this allocation is quite good, we could do better. For example,
  2884. the variables \key{v} and \key{x} ended up in different registers, but
  2885. if they had been placed in the same register, then the move from
  2886. \key{v} to \key{x} could be removed.
  2887. We say that two variables $p$ and $q$ are \emph{move related} if they
  2888. participate together in a \key{movq} instruction, that is, \key{movq}
  2889. $p$, $q$ or \key{movq} $q$, $p$. When the register allocator chooses a
  2890. color for a variable, it should prefer a color that has already been
  2891. used for a move-related variable (assuming that they do not
  2892. interfere). Of course, this preference should not override the
  2893. preference for registers over stack locations, but should only be used
  2894. as a tie breaker when choosing between registers or when choosing
  2895. between stack locations.
  2896. We recommend that you represent the move relationships in a graph,
  2897. similar to how we represented interference. The following is the
  2898. \emph{move graph} for our running example.
  2899. \[
  2900. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2901. \node (v) at (0,0) {$v$};
  2902. \node (w) at (3,0) {$w$};
  2903. \node (x) at (6,0) {$x$};
  2904. \node (y) at (3,-1.5) {$y$};
  2905. \node (z) at (6,-1.5) {$z$};
  2906. \node (t1) at (9,-1.5) {$t.1$};
  2907. \draw[bend left=15] (t1) to (y);
  2908. \draw[bend left=15] (v) to (x);
  2909. \draw (x) to (y);
  2910. \draw (x) to (z);
  2911. \end{tikzpicture}
  2912. \]
  2913. Now we replay the graph coloring, pausing to see the coloring of $x$
  2914. and $v$. So we have the following coloring and the most saturated
  2915. vertex is $x$.
  2916. \[
  2917. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2918. \node (v) at (0,0) {$v:-,\{2\}$};
  2919. \node (w) at (3,0) {$w:2,\{0,1\}$};
  2920. \node (x) at (6,0) {$x:-,\{0,2\}$};
  2921. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2922. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2923. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2924. \draw (t1) to (z);
  2925. \draw (v) to (w);
  2926. \foreach \i in {w,x,y}
  2927. {
  2928. \foreach \j in {w,x,y}
  2929. {
  2930. \draw (\i) to (\j);
  2931. }
  2932. }
  2933. \draw (z) to (w);
  2934. \draw (z) to (y);
  2935. \end{tikzpicture}
  2936. \]
  2937. Last time we chose to color $x$ with $1$,
  2938. %
  2939. which so happens to be the color of $z$, and $x$ is move related to
  2940. $z$. This was rather lucky, and if the program had been a little
  2941. different, and say $z$ had been already assigned to $2$, then $x$
  2942. would still get $1$ and our luck would have run out. With move
  2943. biasing, we use the fact that $x$ and $z$ are move related to
  2944. influence the choice of color for $x$, in this case choosing $1$
  2945. because that's the color of $z$.
  2946. \[
  2947. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2948. \node (v) at (0,0) {$v:-,\{2\}$};
  2949. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2950. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2951. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2952. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2953. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2954. \draw (t1) to (z);
  2955. \draw (v) to (w);
  2956. \foreach \i in {w,x,y}
  2957. {
  2958. \foreach \j in {w,x,y}
  2959. {
  2960. \draw (\i) to (\j);
  2961. }
  2962. }
  2963. \draw (z) to (w);
  2964. \draw (z) to (y);
  2965. \end{tikzpicture}
  2966. \]
  2967. Next we consider coloring the variable $v$, and we just need to avoid
  2968. choosing $2$ because of the interference with $w$. Last time we choose
  2969. the color $0$, simply because it was the lowest, but this time we know
  2970. that $v$ is move related to $x$, so we choose the color $1$.
  2971. \[
  2972. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2973. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  2974. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2975. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2976. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2977. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2978. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2979. \draw (t1) to (z);
  2980. \draw (v) to (w);
  2981. \foreach \i in {w,x,y}
  2982. {
  2983. \foreach \j in {w,x,y}
  2984. {
  2985. \draw (\i) to (\j);
  2986. }
  2987. }
  2988. \draw (z) to (w);
  2989. \draw (z) to (y);
  2990. \end{tikzpicture}
  2991. \]
  2992. We apply this register assignment to the running example, on the left,
  2993. to obtain the code on right.
  2994. \begin{minipage}{0.45\textwidth}
  2995. \begin{lstlisting}
  2996. (block ()
  2997. (movq (int 1) (var v))
  2998. (movq (int 46) (var w))
  2999. (movq (var v) (var x))
  3000. (addq (int 7) (var x))
  3001. (movq (var x) (var y))
  3002. (addq (int 4) (var y))
  3003. (movq (var x) (var z))
  3004. (addq (var w) (var z))
  3005. (movq (var y) (var t.1))
  3006. (negq (var t.1))
  3007. (movq (var z) (reg rax))
  3008. (addq (var t.1) (reg rax))
  3009. (jmp conclusion))
  3010. \end{lstlisting}
  3011. \end{minipage}
  3012. $\Rightarrow$
  3013. \begin{minipage}{0.45\textwidth}
  3014. \begin{lstlisting}
  3015. (block ()
  3016. (movq (int 1) (reg rcx))
  3017. (movq (int 46) (reg rbx))
  3018. (movq (reg rcx) (reg rcx))
  3019. (addq (int 7) (reg rcx))
  3020. (movq (reg rcx) (reg rdx))
  3021. (addq (int 4) (reg rdx))
  3022. (movq (reg rcx) (reg rcx))
  3023. (addq (reg rbx) (reg rcx))
  3024. (movq (reg rdx) (reg rbx))
  3025. (negq (reg rbx))
  3026. (movq (reg rcx) (reg rax))
  3027. (addq (reg rbx) (reg rax))
  3028. (jmp conclusion))
  3029. \end{lstlisting}
  3030. \end{minipage}
  3031. The \code{patch-instructions} then removes the trivial moves from
  3032. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3033. result.
  3034. \begin{minipage}{0.45\textwidth}
  3035. \begin{lstlisting}
  3036. (block ()
  3037. (movq (int 1) (reg rcx))
  3038. (movq (int 46) (reg rbx))
  3039. (addq (int 7) (reg rcx))
  3040. (movq (reg rcx) (reg rdx))
  3041. (addq (int 4) (reg rdx))
  3042. (addq (reg rbx) (reg rcx))
  3043. (movq (reg rdx) (reg rbx))
  3044. (negq (reg rbx))
  3045. (movq (reg rcx) (reg rax))
  3046. (addq (reg rbx) (reg rax))
  3047. (jmp conclusion))
  3048. \end{lstlisting}
  3049. \end{minipage}
  3050. \begin{exercise}\normalfont
  3051. Change your implementation of \code{allocate-registers} to take move
  3052. biasing into account. Make sure that your compiler still passes all of
  3053. the previous tests. Create two new tests that include at least one
  3054. opportunity for move biasing and visually inspect the output x86
  3055. programs to make sure that your move biasing is working properly.
  3056. \end{exercise}
  3057. \margincomment{\footnotesize To do: another neat challenge would be to do
  3058. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3059. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3060. \chapter{Booleans and Control Flow}
  3061. \label{ch:bool-types}
  3062. The $R_0$ and $R_1$ languages only had a single kind of value, the
  3063. integers. In this Chapter we add a second kind of value, the Booleans,
  3064. to create the $R_2$ language. The Boolean values \emph{true} and
  3065. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3066. Racket. We also introduce several operations that involve Booleans
  3067. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  3068. \key{if} expression. With the addition of \key{if} expressions,
  3069. programs can have non-trivial control flow which has an impact on
  3070. several parts of the compiler. Also, because we now have two kinds of
  3071. values, we need to worry about programs that apply an operation to the
  3072. wrong kind of value, such as \code{(not 1)}.
  3073. There are two language design options for such situations. One option
  3074. is to signal an error and the other is to provide a wider
  3075. interpretation of the operation. The Racket language uses a mixture of
  3076. these two options, depending on the operation and the kind of
  3077. value. For example, the result of \code{(not 1)} in Racket is
  3078. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  3079. the other hand, \code{(car 1)} results in a run-time error in Racket
  3080. stating that \code{car} expects a pair.
  3081. The Typed Racket language makes similar design choices as Racket,
  3082. except much of the error detection happens at compile time instead of
  3083. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3084. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3085. reports a compile-time error because Typed Racket expects the type of
  3086. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3087. For the $R_2$ language we choose to be more like Typed Racket in that
  3088. we shall perform type checking during compilation. In
  3089. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3090. is, how to compile a dynamically typed language like Racket. The
  3091. $R_2$ language is a subset of Typed Racket but by no means includes
  3092. all of Typed Racket. Furthermore, for many of the operations we shall
  3093. take a narrower interpretation than Typed Racket, for example,
  3094. rejecting \code{(not 1)}.
  3095. This chapter is organized as follows. We begin by defining the syntax
  3096. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3097. then introduce the idea of type checking and build a type checker for
  3098. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3099. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3100. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  3101. how our compiler passes need to change to accommodate Booleans and
  3102. conditional control flow.
  3103. \section{The $R_2$ Language}
  3104. \label{sec:r2-lang}
  3105. The syntax of the $R_2$ language is defined in
  3106. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray),
  3107. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  3108. \code{if} expression. Also, we expand the operators to include
  3109. subtraction, \key{and}, \key{or} and \key{not}, the \key{eq?}
  3110. operations for comparing two integers or two Booleans, and the
  3111. \key{<}, \key{<=}, \key{>}, and \key{>=} operations for comparing
  3112. integers.
  3113. \begin{figure}[tp]
  3114. \centering
  3115. \fbox{
  3116. \begin{minipage}{0.96\textwidth}
  3117. \[
  3118. \begin{array}{lcl}
  3119. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3120. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \mid (\key{-}\;\Exp\;\Exp) \\
  3121. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  3122. &\mid& \key{\#t} \mid \key{\#f}
  3123. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3124. \mid (\key{not}\;\Exp) \\
  3125. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  3126. R_2 &::=& (\key{program} \; \itm{info}\; \Exp)
  3127. \end{array}
  3128. \]
  3129. \end{minipage}
  3130. }
  3131. \caption{The syntax of $R_2$, extending $R_1$
  3132. (Figure~\ref{fig:r1-syntax}) with Booleans and conditionals.}
  3133. \label{fig:r2-syntax}
  3134. \end{figure}
  3135. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3136. the parts that are the same as the interpreter for $R_1$
  3137. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3138. simply evaluate to themselves. The conditional expression $(\key{if}\,
  3139. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  3140. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3141. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3142. operations \code{not} and \code{and} behave as you might expect, but
  3143. note that the \code{and} operation is short-circuiting. That is, given
  3144. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3145. evaluated if $e_1$ evaluates to \code{\#f}.
  3146. With the addition of the comparison operations, there are quite a few
  3147. primitive operations and the interpreter code for them is somewhat
  3148. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  3149. parts into the \code{interp-op} function and the similar parts into
  3150. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  3151. use \code{interp-op} for the \code{and} operation because of the
  3152. short-circuiting behavior in the order of evaluation of its arguments.
  3153. \begin{figure}[tbp]
  3154. \begin{lstlisting}
  3155. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  3156. (define (interp-op op)
  3157. (match op
  3158. ...
  3159. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3160. ['eq? (lambda (v1 v2)
  3161. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3162. (and (boolean? v1) (boolean? v2)))
  3163. (eq? v1 v2)]))]
  3164. ['< (lambda (v1 v2)
  3165. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3166. ['<= (lambda (v1 v2)
  3167. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3168. ['> (lambda (v1 v2)
  3169. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3170. ['>= (lambda (v1 v2)
  3171. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3172. [else (error 'interp-op "unknown operator")]))
  3173. (define (interp-exp env)
  3174. (lambda (e)
  3175. (define recur (interp-exp env))
  3176. (match e
  3177. ...
  3178. [(? boolean?) e]
  3179. [`(if ,cnd ,thn ,els)
  3180. (define b (recur cnd))
  3181. (match b
  3182. [#t (recur thn)]
  3183. [#f (recur els)])]
  3184. [`(and ,e1 ,e2)
  3185. (define v1 (recur e1))
  3186. (match v1
  3187. [#t (match (recur e2) [#t #t] [#f #f])]
  3188. [#f #f])]
  3189. [`(,op ,args ...)
  3190. #:when (set-member? primitives op)
  3191. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3192. )))
  3193. (define (interp-R2 env)
  3194. (lambda (p)
  3195. (match p
  3196. [`(program ,info ,e)
  3197. ((interp-exp '()) e)])))
  3198. \end{lstlisting}
  3199. \caption{Interpreter for the $R_2$ language.}
  3200. \label{fig:interp-R2}
  3201. \end{figure}
  3202. \section{Type Checking $R_2$ Programs}
  3203. \label{sec:type-check-r2}
  3204. It is helpful to think about type checking in two complementary
  3205. ways. A type checker predicts the \emph{type} of value that will be
  3206. produced by each expression in the program. For $R_2$, we have just
  3207. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3208. predict that
  3209. \begin{lstlisting}
  3210. (+ 10 (- (+ 12 20)))
  3211. \end{lstlisting}
  3212. produces an \key{Integer} while
  3213. \begin{lstlisting}
  3214. (and (not #f) #t)
  3215. \end{lstlisting}
  3216. produces a \key{Boolean}.
  3217. As mentioned at the beginning of this chapter, a type checker also
  3218. rejects programs that apply operators to the wrong type of value. Our
  3219. type checker for $R_2$ will signal an error for the following
  3220. expression because, as we have seen above, the expression \code{(+ 10
  3221. ...)} has type \key{Integer}, and we require the argument of a
  3222. \code{not} to have type \key{Boolean}.
  3223. \begin{lstlisting}
  3224. (not (+ 10 (- (+ 12 20))))
  3225. \end{lstlisting}
  3226. The type checker for $R_2$ is best implemented as a structurally
  3227. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3228. many of the clauses for the \code{type-check-exp} function. Given an
  3229. input expression \code{e}, the type checker either returns the type
  3230. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3231. the type of an integer literal is \code{Integer} and the type of a
  3232. Boolean literal is \code{Boolean}. To handle variables, the type
  3233. checker, like the interpreter, uses an association list. However, in
  3234. this case the association list maps variables to types instead of
  3235. values. Consider the clause for \key{let}. We type check the
  3236. initializing expression to obtain its type \key{T} and then associate
  3237. type \code{T} with the variable \code{x}. When the type checker
  3238. encounters the use of a variable, it can find its type in the
  3239. association list.
  3240. \begin{figure}[tbp]
  3241. \begin{lstlisting}
  3242. (define (type-check-exp env)
  3243. (lambda (e)
  3244. (define recur (type-check-exp env))
  3245. (match e
  3246. [(? fixnum?) 'Integer]
  3247. [(? boolean?) 'Boolean]
  3248. [(? symbol? x) (dict-ref env x)]
  3249. [`(read) 'Integer]
  3250. [`(let ([,x ,e]) ,body)
  3251. (define T (recur e))
  3252. (define new-env (cons (cons x T) env))
  3253. (type-check-exp new-env body)]
  3254. ...
  3255. [`(not ,e)
  3256. (match (recur e)
  3257. ['Boolean 'Boolean]
  3258. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  3259. ...
  3260. )))
  3261. (define (type-check-R2 env)
  3262. (lambda (e)
  3263. (match e
  3264. [`(program ,info ,body)
  3265. (define ty ((type-check-exp '()) body))
  3266. `(program ,info ,body)]
  3267. )))
  3268. \end{lstlisting}
  3269. \caption{Skeleton of a type checker for the $R_2$ language.}
  3270. \label{fig:type-check-R2}
  3271. \end{figure}
  3272. %% To print the resulting value correctly, the overall type of the
  3273. %% program must be threaded through the remainder of the passes. We can
  3274. %% store the type within the \key{program} form as shown in Figure
  3275. %% \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3276. %% intermediate language produced by the type checker, which we define as
  3277. %% follows: \\[1ex]
  3278. %% \fbox{
  3279. %% \begin{minipage}{0.87\textwidth}
  3280. %% \[
  3281. %% \begin{array}{lcl}
  3282. %% R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3283. %% \end{array}
  3284. %% \]
  3285. %% \end{minipage}
  3286. %% }
  3287. \begin{exercise}\normalfont
  3288. Complete the implementation of \code{type-check-R2} and test it on 10
  3289. new example programs in $R_2$ that you choose based on how thoroughly
  3290. they test the type checking algorithm. Half of the example programs
  3291. should have a type error, to make sure that your type checker properly
  3292. rejects them. The other half of the example programs should not have
  3293. type errors. Your testing should check that the result of the type
  3294. checker agrees with the value returned by the interpreter, that is, if
  3295. the type checker returns \key{Integer}, then the interpreter should
  3296. return an integer. Likewise, if the type checker returns
  3297. \key{Boolean}, then the interpreter should return \code{\#t} or
  3298. \code{\#f}. Note that if your type checker does not signal an error
  3299. for a program, then interpreting that program should not encounter an
  3300. error. If it does, there is something wrong with your type checker.
  3301. \end{exercise}
  3302. \section{Shrink the $R_2$ Language}
  3303. \label{sec:shrink-r2}
  3304. The $R_2$ language includes several operators that are easily
  3305. expressible in terms of other operators. For example, subtraction is
  3306. expressible in terms of addition and negation.
  3307. \[
  3308. (\key{-}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3309. \]
  3310. Several of the comparison operations are expressible in terms of
  3311. less-than and logical negation.
  3312. \[
  3313. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad
  3314. \LET{t_1}{e_1}{(\key{not}\;(\key{<}\;e_2\;t_1))}
  3315. \]
  3316. By performing these translations near the front-end of the compiler,
  3317. the later passes of the compiler will not need to deal with these
  3318. constructs, making those passes shorter. On the other hand, sometimes
  3319. these translations make it more difficult to generate the most
  3320. efficient code with respect to the number of instructions. However,
  3321. these differences typically do not affect the number of accesses to
  3322. memory, which is the primary factor that determines execution time on
  3323. modern computer architectures.
  3324. \begin{exercise}\normalfont
  3325. Implement the pass \code{shrink} that removes subtraction,
  3326. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3327. by translating them to other constructs in $R_2$. Create tests to
  3328. make sure that the behavior of all of these constructs stays the
  3329. same after translation.
  3330. \end{exercise}
  3331. \section{XOR, Comparisons, and Control Flow in x86}
  3332. \label{sec:x86-1}
  3333. To implement the new logical operations, the comparison operations,
  3334. and the \key{if} expression, we need to delve further into the x86
  3335. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3336. larger subset of x86 that includes instructions for logical
  3337. operations, comparisons, and jumps.
  3338. One small challenge is that x86 does not provide an instruction that
  3339. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3340. However, the \code{xorq} instruction can be used to encode \code{not}.
  3341. The \key{xorq} instruction takes two arguments, performs a pairwise
  3342. exclusive-or operation on each bit of its arguments, and writes the
  3343. results into its second argument. Recall the truth table for
  3344. exclusive-or:
  3345. \begin{center}
  3346. \begin{tabular}{l|cc}
  3347. & 0 & 1 \\ \hline
  3348. 0 & 0 & 1 \\
  3349. 1 & 1 & 0
  3350. \end{tabular}
  3351. \end{center}
  3352. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3353. in row of the table for the bit $1$, the result is the opposite of the
  3354. second bit. Thus, the \code{not} operation can be implemented by
  3355. \code{xorq} with $1$ as the first argument: $0001
  3356. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3357. 0001 = 0000$.
  3358. \begin{figure}[tp]
  3359. \fbox{
  3360. \begin{minipage}{0.96\textwidth}
  3361. \[
  3362. \begin{array}{lcl}
  3363. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3364. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3365. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3366. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3367. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3368. (\key{subq} \; \Arg\; \Arg) \mid
  3369. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3370. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3371. (\key{pushq}\;\Arg) \mid
  3372. (\key{popq}\;\Arg) \mid
  3373. (\key{retq})} \\
  3374. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3375. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3376. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3377. \mid (\key{jmp} \; \itm{label})
  3378. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3379. &\mid& (\key{label} \; \itm{label}) \\
  3380. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3381. \end{array}
  3382. \]
  3383. \end{minipage}
  3384. }
  3385. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3386. \label{fig:x86-1}
  3387. \end{figure}
  3388. Next we consider the x86 instructions that are relevant for
  3389. compiling the comparison operations. The \key{cmpq} instruction
  3390. compares its two arguments to determine whether one argument is less
  3391. than, equal, or greater than the other argument. The \key{cmpq}
  3392. instruction is unusual regarding the order of its arguments and where
  3393. the result is placed. The argument order is backwards: if you want to
  3394. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3395. \key{cmpq} is placed in the special EFLAGS register. This register
  3396. cannot be accessed directly but it can be queried by a number of
  3397. instructions, including the \key{set} instruction. The \key{set}
  3398. instruction puts a \key{1} or \key{0} into its destination depending
  3399. on whether the comparison came out according to the condition code
  3400. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3401. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3402. The set instruction has an annoying quirk in that its destination
  3403. argument must be single byte register, such as \code{al}, which is
  3404. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3405. instruction can then be used to move from a single byte register to a
  3406. normal 64-bit register.
  3407. For compiling the \key{if} expression, the x86 instructions for
  3408. jumping are relevant. The \key{jmp} instruction updates the program
  3409. counter to point to the instruction after the indicated label. The
  3410. \key{jmp-if} instruction updates the program counter to point to the
  3411. instruction after the indicated label depending on whether the result
  3412. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3413. the \key{jmp-if} instruction falls through to the next
  3414. instruction. Because the \key{jmp-if} instruction relies on the EFLAGS
  3415. register, it is quite common for the \key{jmp-if} to be immediately
  3416. preceded by a \key{cmpq} instruction, to set the EFLAGS register.
  3417. Our abstract syntax for \key{jmp-if} differs from the concrete syntax
  3418. for x86 to separate the instruction name from the condition code. For
  3419. example, \code{(jmp-if le foo)} corresponds to \code{jle foo}.
  3420. \section{The $C_1$ Intermediate Language}
  3421. \label{sec:c1}
  3422. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3423. language, but we need to grow that intermediate language to handle the
  3424. new features in $R_2$: Booleans and conditional expressions.
  3425. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3426. logic and comparison operators to the $\Exp$ non-terminal, the
  3427. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3428. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3429. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3430. goto's in the grammar for $\Tail$. This means that a sequence of
  3431. statements may now end with a \code{goto} or a conditional
  3432. \code{goto}, which jumps to one of two labeled pieces of code
  3433. depending on the outcome of the comparison. In
  3434. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3435. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3436. and \key{goto}'s.
  3437. \begin{figure}[tp]
  3438. \fbox{
  3439. \begin{minipage}{0.96\textwidth}
  3440. \[
  3441. \begin{array}{lcl}
  3442. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3443. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3444. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3445. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3446. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3447. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  3448. &\mid& (\key{goto}\,\itm{label}) \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})} \\
  3449. C_1 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  3450. \end{array}
  3451. \]
  3452. \end{minipage}
  3453. }
  3454. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3455. \label{fig:c1-syntax}
  3456. \end{figure}
  3457. \section{Explicate Control}
  3458. \label{sec:explicate-control-r2}
  3459. Recall that the purpose of \code{explicate-control} is to make the
  3460. order of evaluation explicit in the syntax of the program. With the
  3461. addition of \key{if} in $R_2$, things get more interesting.
  3462. As a motivating example, consider the following program that has an
  3463. \key{if} expression nested in the predicate of another \key{if}.
  3464. % s1_38.rkt
  3465. \begin{lstlisting}
  3466. (program ()
  3467. (if (if (eq? (read) 1)
  3468. (eq? (read) 0)
  3469. (eq? (read) 2))
  3470. (+ 10 32)
  3471. (+ 700 77)))
  3472. \end{lstlisting}
  3473. %
  3474. The naive way to compile \key{if} and \key{eq?} would be to handle
  3475. each of them in isolation, regardless of their context. Each
  3476. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3477. by a couple instructions to move the result from the EFLAGS register
  3478. into a general purpose register or stack location. Each \key{if} would
  3479. be translated into the combination of a \key{cmpq} and \key{jmp-if}.
  3480. However, if we take context into account we can do better and reduce
  3481. the use of \key{cmpq} and EFLAG-accessing instructions.
  3482. One idea is to try and reorganize the code at the level of $R_2$,
  3483. pushing the outer \key{if} inside the inner one. This would yield the
  3484. following code.
  3485. \begin{lstlisting}
  3486. (if (eq? (read) 1)
  3487. (if (eq? (read) 0)
  3488. (+ 10 32)
  3489. (+ 700 77))
  3490. (if (eq? (read) 2))
  3491. (+ 10 32)
  3492. (+ 700 77))
  3493. \end{lstlisting}
  3494. Unfortunately, this approach duplicates the two branches, and a
  3495. compiler must never duplicate code!
  3496. We need a way to perform the above transformation, but without
  3497. duplicating code. The solution is straightforward if we think at the
  3498. level of x86 assembly: we can label the code for each of the branches
  3499. and insert \key{goto}'s in all the places that need to execute the
  3500. branches. Put another way, we need to move away from abstract syntax
  3501. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3502. use a standard program representation called a \emph{control flow
  3503. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3504. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3505. each edge represents a jump to another block. The \key{program}
  3506. construct of $C_0$ and $C_1$ represents a control flow graph as an
  3507. association list mapping labels to basic blocks. Each block is
  3508. represented by the $\Tail$ non-terminal.
  3509. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3510. \code{remove-complex-opera*} pass and then the
  3511. \code{explicate-control} pass on the example program. We shall walk
  3512. through the output program and then discuss the algorithm.
  3513. %
  3514. Following the order of evaluation in the output of
  3515. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3516. comparison to \code{1} from the predicate of the inner \key{if}. In
  3517. the output of \code{explicate-control}, in the \code{start} block,
  3518. this becomes a \code{(read)} followed by a conditional goto to either
  3519. \code{block61} or \code{block62}. Each of these contains the
  3520. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3521. 1)}, respectively. Regarding \code{block61}, we start with the
  3522. \code{(read)} and comparison to \code{0} and then have a conditional
  3523. goto, either to \code{block59} or \code{block60}, which indirectly
  3524. take us to \code{block55} and \code{block56}, the two branches of the
  3525. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3526. story for \code{block62} is similar.
  3527. \begin{figure}[tbp]
  3528. \begin{tabular}{lll}
  3529. \begin{minipage}{0.4\textwidth}
  3530. \begin{lstlisting}
  3531. (program ()
  3532. (if (if (eq? (read) 1)
  3533. (eq? (read) 0)
  3534. (eq? (read) 2))
  3535. (+ 10 32)
  3536. (+ 700 77)))
  3537. \end{lstlisting}
  3538. \hspace{40pt}$\Downarrow$
  3539. \begin{lstlisting}
  3540. (program ()
  3541. (if (if (let ([tmp52 (read)])
  3542. (eq? tmp52 1))
  3543. (let ([tmp53 (read)])
  3544. (eq? tmp53 0))
  3545. (let ([tmp54 (read)])
  3546. (eq? tmp54 2)))
  3547. (+ 10 32)
  3548. (+ 700 77)))
  3549. \end{lstlisting}
  3550. \end{minipage}
  3551. &
  3552. $\Rightarrow$
  3553. &
  3554. \begin{minipage}{0.55\textwidth}
  3555. \begin{lstlisting}
  3556. (program ()
  3557. ((block62 .
  3558. (seq (assign tmp54 (read))
  3559. (if (eq? tmp54 2)
  3560. (goto block59)
  3561. (goto block60))))
  3562. (block61 .
  3563. (seq (assign tmp53 (read))
  3564. (if (eq? tmp53 0)
  3565. (goto block57)
  3566. (goto block58))))
  3567. (block60 . (goto block56))
  3568. (block59 . (goto block55))
  3569. (block58 . (goto block56))
  3570. (block57 . (goto block55))
  3571. (block56 . (return (+ 700 77)))
  3572. (block55 . (return (+ 10 32)))
  3573. (start .
  3574. (seq (assign tmp52 (read))
  3575. (if (eq? tmp52 1)
  3576. (goto block61)
  3577. (goto block62))))))
  3578. \end{lstlisting}
  3579. \end{minipage}
  3580. \end{tabular}
  3581. \caption{Example translation from $R_2$ to $C_1$
  3582. via the \code{explicate-control}.}
  3583. \label{fig:explicate-control-s1-38}
  3584. \end{figure}
  3585. The nice thing about the output of \code{explicate-control} is that
  3586. there are no unnecessary uses of \code{eq?} and every use of
  3587. \code{eq?} is part of a conditional jump. The down-side of this output
  3588. is that it includes trivial blocks, such as \code{block57} through
  3589. \code{block60}, that only jump to another block. We discuss a solution
  3590. to this problem in Section~\ref{sec:opt-jumps}.
  3591. Recall that in Section~\ref{sec:explicate-control-r1} we implement the
  3592. \code{explicate-control} pass for $R_1$ using two mutually recursive
  3593. functions, \code{explicate-tail} and
  3594. \code{explicate-assign}. The former function translated
  3595. expressions in tail position whereas the later function translated
  3596. expressions on the right-hand-side of a \key{let}. With the addition
  3597. of \key{if} expression in $R_2$ we have a new kind of context to deal
  3598. with: the predicate position of the \key{if}. So we shall need another
  3599. function, \code{explicate-pred}, that takes an $R_2$
  3600. expression and two pieces of $C_1$ code (two $\Tail$'s) for the
  3601. then-branch and else-branch. The output of
  3602. \code{explicate-pred} is a $C_1$ $\Tail$. However, these
  3603. three functions also need to construct the control-flow graph, which we
  3604. recommend they do via updates to a global variable. Next we consider
  3605. the specific additions to the tail and assign functions, and some of
  3606. cases for the pred function.
  3607. The \code{explicate-tail} function needs an additional case
  3608. for \key{if}. The branches of the \key{if} inherit the current
  3609. context, so they are in tail position. Let $B_1$ be the result of
  3610. \code{explicate-tail} on the $\itm{thn}$ branch and $B_2$ be
  3611. the result of apply \code{explicate-tail} to the $\itm{else}$
  3612. branch. Then the \key{if} translates to the block $B_3$ which is the
  3613. result of applying \code{explicate-pred} to the predicate
  3614. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3615. \[
  3616. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3617. \]
  3618. Next we consider the case for \key{if} in the
  3619. \code{explicate-assign} function. So the context of the
  3620. \key{if} is an assignment to some variable $x$ and then the control
  3621. continues to some block $B_1$. The code that we generate for both the
  3622. $\itm{thn}$ and $\itm{els}$ branches shall both need to continue to
  3623. $B_1$, so we add $B_1$ to the control flow graph with a fresh label
  3624. $\ell_1$. Again, the branches of the \key{if} inherit the current
  3625. context, so that are in assignment positions. Let $B_2$ be the result
  3626. of applying \code{explicate-assign} to the $\itm{thn}$ branch,
  3627. variable $x$, and the block \code{(goto $\ell_1$)}. Let $B_3$ be the
  3628. result of applying \code{explicate-assign} to the $\itm{else}$
  3629. branch, variable $x$, and the block \code{(goto $\ell_1$)}. The
  3630. \key{if} translates to the block $B_4$ which is the result of applying
  3631. \code{explicate-pred} to the predicate $\itm{cnd}$ and the
  3632. blocks $B_2$ and $B_3$.
  3633. \[
  3634. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3635. \]
  3636. The function \code{explicate-pred} will need a case for every
  3637. expression that can have type \code{Boolean}. We detail a few cases
  3638. here and leave the rest for the reader. The input to this function is
  3639. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3640. enclosing \key{if}. One of the base cases of this function is when the
  3641. expression is a less-than comparison. We translate it to a
  3642. conditional \code{goto}. We need labels for the two branches $B_1$ and
  3643. $B_2$, so we add them to the control flow graph and obtain some labels
  3644. $\ell_1$ and $\ell_2$. The translation of the less-than comparison is
  3645. as follows.
  3646. \[
  3647. (\key{<}\;e_1\;e_2) \quad\Rightarrow\quad
  3648. (\key{if}\;(\key{<}\;e_1\;e_2)\;(\key{goto}\;\ell_1)\;(\key{goto}\;\ell_2))
  3649. \]
  3650. The case for \key{if} in \code{explicate-pred} is particularly
  3651. illuminating, as it deals with the challenges that we discussed above
  3652. regarding the example of the nested \key{if} expressions. Again, we
  3653. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3654. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3655. and $\itm{els}$ of the current \key{if} inherit their context from the
  3656. current one, i.e., predicate context. So we apply
  3657. \code{explicate-pred} to $\itm{thn}$ with the two blocks
  3658. \code{(goto $\ell_1$)} and \code{(goto $\ell_2$)}, to obtain $B_3$.
  3659. Similarly for the $\itm{els}$ branch, to obtain $B_4$.
  3660. Finally, we apply \code{explicate-pred} to
  3661. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3662. to obtain the result $B_5$.
  3663. \[
  3664. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3665. \quad\Rightarrow\quad
  3666. B_5
  3667. \]
  3668. \begin{exercise}\normalfont
  3669. Implement the pass \code{explicate-code} by adding the cases for
  3670. \key{if} to the functions for tail and assignment contexts, and
  3671. implement the function for predicate contexts. Create test cases
  3672. that exercise all of the new cases in the code for this pass.
  3673. \end{exercise}
  3674. \section{Select Instructions}
  3675. \label{sec:select-r2}
  3676. Recall that the \code{select-instructions} pass lowers from our
  3677. $C$-like intermediate representation to the pseudo-x86 language, which
  3678. is suitable for conducting register allocation. The pass is
  3679. implemented using three auxiliary functions, one for each of the
  3680. non-terminals $\Arg$, $\Stmt$, and $\Tail$.
  3681. For $\Arg$, we have new cases for the Booleans. We take the usual
  3682. approach of encoding them as integers, with true as 1 and false as 0.
  3683. \[
  3684. \key{\#t} \Rightarrow \key{1}
  3685. \qquad
  3686. \key{\#f} \Rightarrow \key{0}
  3687. \]
  3688. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3689. be implemented in terms of \code{xorq} as we discussed at the
  3690. beginning of this section. Given an assignment \code{(assign
  3691. $\itm{lhs}$ (not $\Arg$))}, if the left-hand side $\itm{lhs}$ is
  3692. the same as $\Arg$, then just the \code{xorq} suffices:
  3693. \[
  3694. (\key{assign}\; x\; (\key{not}\; x))
  3695. \quad\Rightarrow\quad
  3696. ((\key{xorq}\;(\key{int}\;1)\;x'))
  3697. \]
  3698. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3699. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3700. $\Arg$. Then we have
  3701. \[
  3702. (\key{assign}\; \itm{lhs}\; (\key{not}\; \Arg))
  3703. \quad\Rightarrow\quad
  3704. ((\key{movq}\; \Arg'\; \itm{lhs}') \; (\key{xorq}\;(\key{int}\;1)\;\itm{lhs}'))
  3705. \]
  3706. Next consider the cases for \code{eq?} and less-than comparison.
  3707. Translating these operations to x86 is slightly involved due to the
  3708. unusual nature of the \key{cmpq} instruction discussed above. We
  3709. recommend translating an assignment from \code{eq?} into the following
  3710. sequence of three instructions. \\
  3711. \begin{tabular}{lll}
  3712. \begin{minipage}{0.4\textwidth}
  3713. \begin{lstlisting}
  3714. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3715. \end{lstlisting}
  3716. \end{minipage}
  3717. &
  3718. $\Rightarrow$
  3719. &
  3720. \begin{minipage}{0.4\textwidth}
  3721. \begin{lstlisting}
  3722. (cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3723. (set e (byte-reg al))
  3724. (movzbq (byte-reg al) |$\itm{lhs}'$|)
  3725. \end{lstlisting}
  3726. \end{minipage}
  3727. \end{tabular} \\
  3728. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3729. \key{goto} and conditional \key{goto}. Both are straightforward
  3730. to handle. A \key{goto} becomes a jump instruction.
  3731. \[
  3732. (\key{goto}\; \ell) \quad \Rightarrow \quad ((\key{jmp} \;\ell))
  3733. \]
  3734. A conditional \key{goto} becomes a compare instruction followed
  3735. by a conditional jump (for ``then'') and the fall-through is
  3736. to a regular jump (for ``else'').\\
  3737. \begin{tabular}{lll}
  3738. \begin{minipage}{0.4\textwidth}
  3739. \begin{lstlisting}
  3740. (if (eq? |$\Arg_1$| |$\Arg_2$|)
  3741. (goto |$\ell_1$|)
  3742. (goto |$\ell_2$|))
  3743. \end{lstlisting}
  3744. \end{minipage}
  3745. &
  3746. $\Rightarrow$
  3747. &
  3748. \begin{minipage}{0.4\textwidth}
  3749. \begin{lstlisting}
  3750. ((cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3751. (jmp-if e |$\ell_1$|)
  3752. (jmp |$\ell_2$|))
  3753. \end{lstlisting}
  3754. \end{minipage}
  3755. \end{tabular} \\
  3756. \begin{exercise}\normalfont
  3757. Expand your \code{select-instructions} pass to handle the new features
  3758. of the $R_2$ language. Test the pass on all the examples you have
  3759. created and make sure that you have some test programs that use the
  3760. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3761. the output using the \code{interp-x86} interpreter
  3762. (Appendix~\ref{appendix:interp}).
  3763. \end{exercise}
  3764. \section{Register Allocation}
  3765. \label{sec:register-allocation-r2}
  3766. The changes required for $R_2$ affect the liveness analysis, building
  3767. the interference graph, and assigning homes, but the graph coloring
  3768. algorithm itself does not need to change.
  3769. \subsection{Liveness Analysis}
  3770. \label{sec:liveness-analysis-r2}
  3771. Recall that for $R_1$ we implemented liveness analysis for a single
  3772. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3773. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3774. now produces many basic blocks arranged in a control-flow graph. The
  3775. first question we need to consider is in what order should we process
  3776. the basic blocks? Recall that to perform liveness analysis, we need to
  3777. know the live-after set. If a basic block has no successor blocks,
  3778. then it has an empty live-after set and we can immediately apply
  3779. liveness analysis to it. If a basic block has some successors, then we
  3780. need to complete liveness analysis on those blocks first.
  3781. Furthermore, we know that the control flow graph does not contain any
  3782. cycles (it is a DAG, that is, a directed acyclic graph)\footnote{If we
  3783. were to add loops to the language, then the CFG could contain cycles
  3784. and we would instead need to use the classic worklist algorithm for
  3785. computing the fixed point of the liveness
  3786. analysis~\citep{Aho:1986qf}.}. What all this amounts to is that we
  3787. need to process the basic blocks in reverse topological order. We
  3788. recommend using the \code{tsort} and \code{transpose} functions of the
  3789. Racket \code{graph} package to obtain this ordering.
  3790. The next question is how to compute the live-after set of a block
  3791. given the live-before sets of all its successor blocks. During
  3792. compilation we do not know which way the branch will go, so we do not
  3793. know which of the successor's live-before set to use. The solution
  3794. comes from the observation that there is no harm in identifying more
  3795. variables as live than absolutely necessary. Thus, we can take the
  3796. union of the live-before sets from all the successors to be the
  3797. live-after set for the block. Once we have computed the live-after
  3798. set, we can proceed to perform liveness analysis on the block just as
  3799. we did in Section~\ref{sec:liveness-analysis-r1}.
  3800. The helper functions for computing the variables in an instruction's
  3801. argument and for computing the variables read-from ($R$) or written-to
  3802. ($W$) by an instruction need to be updated to handle the new kinds of
  3803. arguments and instructions in x86$_1$.
  3804. \subsection{Build Interference}
  3805. \label{sec:build-interference-r2}
  3806. Many of the new instructions in x86$_1$ can be handled in the same way
  3807. as the instructions in x86$_0$. Thus, if your code was already quite
  3808. general, it will not need to be changed to handle the new
  3809. instructions. If not, I recommend that you change your code to be more
  3810. general. The \key{movzbq} instruction should be handled like the
  3811. \key{movq} instruction.
  3812. %% \subsection{Assign Homes}
  3813. %% \label{sec:assign-homes-r2}
  3814. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3815. %% to be updated to handle the \key{if} statement, simply by recursively
  3816. %% processing the child nodes. Hopefully your code already handles the
  3817. %% other new instructions, but if not, you can generalize your code.
  3818. \begin{exercise}\normalfont
  3819. Update the \code{register-allocation} pass so that it works for $R_2$
  3820. and test your compiler using your previously created programs on the
  3821. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3822. \end{exercise}
  3823. %% \section{Lower Conditionals (New Pass)}
  3824. %% \label{sec:lower-conditionals}
  3825. %% In the \code{select-instructions} pass we decided to procrastinate in
  3826. %% the lowering of the \key{if} statement, thereby making liveness
  3827. %% analysis easier. Now we need to make up for that and turn the \key{if}
  3828. %% statement into the appropriate instruction sequence. The following
  3829. %% translation gives the general idea. If the condition is true, we need
  3830. %% to execute the $\itm{thns}$ branch and otherwise we need to execute
  3831. %% the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3832. %% jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3833. %% is appropriate for the comparison operator \itm{cmp}. If the
  3834. %% condition is false, we fall through to the $\itm{elss}$ branch. At the
  3835. %% end of the $\itm{elss}$ branch we need to take care to not fall
  3836. %% through to the $\itm{thns}$ branch. So we jump to the
  3837. %% $\itm{endlabel}$. All of the labels in the generated code should be
  3838. %% created with \code{gensym}.
  3839. %% \begin{tabular}{lll}
  3840. %% \begin{minipage}{0.4\textwidth}
  3841. %% \begin{lstlisting}
  3842. %% (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3843. %% \end{lstlisting}
  3844. %% \end{minipage}
  3845. %% &
  3846. %% $\Rightarrow$
  3847. %% &
  3848. %% \begin{minipage}{0.4\textwidth}
  3849. %% \begin{lstlisting}
  3850. %% (cmpq |$\Arg_2$| |$\Arg_1$|)
  3851. %% (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3852. %% |$\itm{elss}$|
  3853. %% (jmp |$\itm{endlabel}$|)
  3854. %% (label |$\itm{thenlabel}$|)
  3855. %% |$\itm{thns}$|
  3856. %% (label |$\itm{endlabel}$|)
  3857. %% \end{lstlisting}
  3858. %% \end{minipage}
  3859. %% \end{tabular}
  3860. %% \begin{exercise}\normalfont
  3861. %% Implement the \code{lower-conditionals} pass. Test your compiler using
  3862. %% your previously created programs on the \code{interp-x86} interpreter
  3863. %% (Appendix~\ref{appendix:interp}).
  3864. %% \end{exercise}
  3865. \section{Patch Instructions}
  3866. The second argument of the \key{cmpq} instruction must not be an
  3867. immediate value (such as a literal integer). So if you are comparing
  3868. two immediates, we recommend inserting a \key{movq} instruction to put
  3869. the second argument in \key{rax}.
  3870. %
  3871. The second argument of the \key{movzbq} must be a register.
  3872. %
  3873. There are no special restrictions on the x86 instructions
  3874. \key{jmp-if}, \key{jmp}, and \key{label}.
  3875. \begin{exercise}\normalfont
  3876. Update \code{patch-instructions} to handle the new x86 instructions.
  3877. Test your compiler using your previously created programs on the
  3878. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3879. \end{exercise}
  3880. \section{An Example Translation}
  3881. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3882. $R_2$ translated to x86, showing the results of
  3883. \code{explicate-control}, \code{select-instructions}, and the final
  3884. x86 assembly code.
  3885. \begin{figure}[tbp]
  3886. \begin{tabular}{lll}
  3887. \begin{minipage}{0.5\textwidth}
  3888. % s1_20.rkt
  3889. \begin{lstlisting}
  3890. (program ()
  3891. (if (eq? (read) 1) 42 0))
  3892. \end{lstlisting}
  3893. $\Downarrow$
  3894. \begin{lstlisting}
  3895. (program ()
  3896. ((block32 . (return 0))
  3897. (block31 . (return 42))
  3898. (start .
  3899. (seq (assign tmp30 (read))
  3900. (if (eq? tmp30 1)
  3901. (goto block31)
  3902. (goto block32))))))
  3903. \end{lstlisting}
  3904. $\Downarrow$
  3905. \begin{lstlisting}
  3906. (program ((locals . (tmp30)))
  3907. ((block32 .
  3908. (block ()
  3909. (movq (int 0) (reg rax))
  3910. (jmp conclusion)))
  3911. (block31 .
  3912. (block ()
  3913. (movq (int 42) (reg rax))
  3914. (jmp conclusion)))
  3915. (start .
  3916. (block ()
  3917. (callq read_int)
  3918. (movq (reg rax) (var tmp30))
  3919. (cmpq (int 1) (var tmp30))
  3920. (jmp-if e block31)
  3921. (jmp block32)))))
  3922. \end{lstlisting}
  3923. \end{minipage}
  3924. &
  3925. $\Rightarrow$
  3926. \begin{minipage}{0.4\textwidth}
  3927. \begin{lstlisting}
  3928. _block31:
  3929. movq $42, %rax
  3930. jmp _conclusion
  3931. _block32:
  3932. movq $0, %rax
  3933. jmp _conclusion
  3934. _start:
  3935. callq _read_int
  3936. movq %rax, %rcx
  3937. cmpq $1, %rcx
  3938. je _block31
  3939. jmp _block32
  3940. .globl _main
  3941. _main:
  3942. pushq %rbp
  3943. movq %rsp, %rbp
  3944. pushq %r12
  3945. pushq %rbx
  3946. pushq %r13
  3947. pushq %r14
  3948. subq $0, %rsp
  3949. jmp _start
  3950. _conclusion:
  3951. addq $0, %rsp
  3952. popq %r14
  3953. popq %r13
  3954. popq %rbx
  3955. popq %r12
  3956. popq %rbp
  3957. retq
  3958. \end{lstlisting}
  3959. \end{minipage}
  3960. \end{tabular}
  3961. \caption{Example compilation of an \key{if} expression to x86.}
  3962. \label{fig:if-example-x86}
  3963. \end{figure}
  3964. \begin{figure}[p]
  3965. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3966. \node (R2) at (0,2) {\large $R_2$};
  3967. \node (R2-2) at (3,2) {\large $R_2$};
  3968. \node (R2-3) at (6,2) {\large $R_2$};
  3969. \node (R2-4) at (9,2) {\large $R_2$};
  3970. \node (R2-5) at (12,2) {\large $R_2$};
  3971. \node (C1-1) at (6,0) {\large $C_1$};
  3972. \node (C1-2) at (3,0) {\large $C_1$};
  3973. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3974. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3975. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3976. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  3977. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3978. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3979. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  3980. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  3981. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  3982. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  3983. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  3984. \path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  3985. \path[->,bend right=15] (C1-2) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3986. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3987. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3988. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3989. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  3990. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  3991. \end{tikzpicture}
  3992. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3993. \label{fig:R2-passes}
  3994. \end{figure}
  3995. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  3996. compilation of $R_2$.
  3997. \section{Challenge: Optimize Jumps$^{*}$}
  3998. \label{sec:opt-jumps}
  3999. UNDER CONSTRUCTION
  4000. %% \section{Challenge: Optimizing Conditions$^{*}$}
  4001. %% \label{sec:opt-if}
  4002. %% A close inspection of the x86 code generated in
  4003. %% Figure~\ref{fig:if-example-x86} reveals some redundant computation
  4004. %% regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  4005. %% twice using \key{cmpq} as follows.
  4006. %% % Wierd LaTeX bug if I remove the following. -Jeremy
  4007. %% % Does it have to do with page breaks?
  4008. %% \begin{lstlisting}
  4009. %% \end{lstlisting}
  4010. %% \begin{lstlisting}
  4011. %% cmpq $1, %rcx
  4012. %% sete %al
  4013. %% movzbq %al, %rcx
  4014. %% cmpq $1, %rcx
  4015. %% je then21288
  4016. %% \end{lstlisting}
  4017. %% The reason for this non-optimal code has to do with the \code{flatten}
  4018. %% pass earlier in this Chapter. We recommended flattening the condition
  4019. %% to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  4020. %% is already an \code{eq?} test, then we would like to use that
  4021. %% directly. In fact, for many of the expressions of Boolean type, we can
  4022. %% generate more optimized code. For example, if the condition is
  4023. %% \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  4024. %% all. If the condition is a \code{let}, we can optimize based on the
  4025. %% form of its body. If the condition is a \code{not}, then we can flip
  4026. %% the two branches.
  4027. %% %
  4028. %% \margincomment{\tiny We could do even better by converting to basic
  4029. %% blocks.\\ --Jeremy}
  4030. %% %
  4031. %% On the other hand, if the condition is a \code{and}
  4032. %% or another \code{if}, we should flatten them into an $\Arg$ to avoid
  4033. %% code duplication.
  4034. %% Figure~\ref{fig:opt-if} shows an example program and the result of
  4035. %% applying the above suggested optimizations.
  4036. %% \begin{exercise}\normalfont
  4037. %% Change the \code{flatten} pass to improve the code that gets
  4038. %% generated for \code{if} expressions. We recommend writing a helper
  4039. %% function that recursively traverses the condition of the \code{if}.
  4040. %% \end{exercise}
  4041. %% \begin{figure}[tbp]
  4042. %% \begin{tabular}{lll}
  4043. %% \begin{minipage}{0.5\textwidth}
  4044. %% \begin{lstlisting}
  4045. %% (program
  4046. %% (if (let ([x 1])
  4047. %% (not (eq? x (read))))
  4048. %% 777
  4049. %% 42))
  4050. %% \end{lstlisting}
  4051. %% $\Downarrow$
  4052. %% \begin{lstlisting}
  4053. %% (program (x.1 if.2 tmp.3)
  4054. %% (type Integer)
  4055. %% (assign x.1 1)
  4056. %% (assign tmp.3 (read))
  4057. %% (if (eq? x.1 tmp.3)
  4058. %% ((assign if.2 42))
  4059. %% ((assign if.2 777)))
  4060. %% (return if.2))
  4061. %% \end{lstlisting}
  4062. %% $\Downarrow$
  4063. %% \begin{lstlisting}
  4064. %% (program (x.1 if.2 tmp.3)
  4065. %% (type Integer)
  4066. %% (movq (int 1) (var x.1))
  4067. %% (callq read_int)
  4068. %% (movq (reg rax) (var tmp.3))
  4069. %% (if (eq? (var x.1) (var tmp.3))
  4070. %% ((movq (int 42) (var if.2)))
  4071. %% ((movq (int 777) (var if.2))))
  4072. %% (movq (var if.2) (reg rax)))
  4073. %% \end{lstlisting}
  4074. %% \end{minipage}
  4075. %% &
  4076. %% $\Rightarrow$
  4077. %% \begin{minipage}{0.4\textwidth}
  4078. %% \begin{lstlisting}
  4079. %% .globl _main
  4080. %% _main:
  4081. %% pushq %rbp
  4082. %% movq %rsp, %rbp
  4083. %% pushq %r13
  4084. %% pushq %r14
  4085. %% pushq %r12
  4086. %% pushq %rbx
  4087. %% subq $0, %rsp
  4088. %% movq $1, %rbx
  4089. %% callq _read_int
  4090. %% movq %rax, %rcx
  4091. %% cmpq %rcx, %rbx
  4092. %% je then35989
  4093. %% movq $777, %rbx
  4094. %% jmp if_end35990
  4095. %% then35989:
  4096. %% movq $42, %rbx
  4097. %% if_end35990:
  4098. %% movq %rbx, %rax
  4099. %% movq %rax, %rdi
  4100. %% callq _print_int
  4101. %% movq $0, %rax
  4102. %% addq $0, %rsp
  4103. %% popq %rbx
  4104. %% popq %r12
  4105. %% popq %r14
  4106. %% popq %r13
  4107. %% popq %rbp
  4108. %% retq
  4109. %% \end{lstlisting}
  4110. %% \end{minipage}
  4111. %% \end{tabular}
  4112. %% \caption{Example program with optimized conditionals.}
  4113. %% \label{fig:opt-if}
  4114. %% \end{figure}
  4115. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4116. \chapter{Tuples and Garbage Collection}
  4117. \label{ch:tuples}
  4118. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4119. things to discuss in this chapter. \\ --Jeremy}
  4120. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4121. all the IR grammars are spelled out! \\ --Jeremy}
  4122. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4123. but keep type annotations on vector creation and local variables, function
  4124. parameters, etc. \\ --Jeremy}
  4125. \margincomment{\scriptsize Be more explicit about how to deal with
  4126. the root stack. \\ --Jeremy}
  4127. In this chapter we study the implementation of mutable tuples (called
  4128. ``vectors'' in Racket). This language feature is the first to use the
  4129. computer's \emph{heap} because the lifetime of a Racket tuple is
  4130. indefinite, that is, a tuple lives forever from the programmer's
  4131. viewpoint. Of course, from an implementer's viewpoint, it is important
  4132. to reclaim the space associated with a tuple when it is no longer
  4133. needed, which is why we also study \emph{garbage collection}
  4134. techniques in this chapter.
  4135. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4136. interpreter and type checker. The $R_3$ language extends the $R_2$
  4137. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4138. ``void'' value. The reason for including the later is that the
  4139. \code{vector-set!} operation returns a value of type
  4140. \code{Void}\footnote{This may sound contradictory, but Racket's
  4141. \code{Void} type corresponds to what is more commonly called the
  4142. \code{Unit} type. This type is inhabited by a single value that is
  4143. usually written \code{unit} or \code{()}\citep{Pierce:2002hj}.}.
  4144. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4145. copying live objects back and forth between two halves of the
  4146. heap. The garbage collector requires coordination with the compiler so
  4147. that it can see all of the \emph{root} pointers, that is, pointers in
  4148. registers or on the procedure call stack.
  4149. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4150. discuss all the necessary changes and additions to the compiler
  4151. passes, including a new compiler pass named \code{expose-allocation}.
  4152. \section{The $R_3$ Language}
  4153. \label{sec:r3}
  4154. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  4155. includes three new forms for creating a tuple, reading an element of a
  4156. tuple, and writing to an element of a tuple. The program in
  4157. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4158. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  4159. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  4160. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  4161. ``then'' branch is taken. The element at index $0$ of \code{t} is
  4162. $40$, to which we add the $2$, the element at index $0$ of the
  4163. 1-tuple.
  4164. \begin{figure}[tbp]
  4165. \begin{lstlisting}
  4166. (let ([t (vector 40 #t (vector 2))])
  4167. (if (vector-ref t 1)
  4168. (+ (vector-ref t 0)
  4169. (vector-ref (vector-ref t 2) 0))
  4170. 44))
  4171. \end{lstlisting}
  4172. \caption{Example program that creates tuples and reads from them.}
  4173. \label{fig:vector-eg}
  4174. \end{figure}
  4175. \begin{figure}[tbp]
  4176. \centering
  4177. \fbox{
  4178. \begin{minipage}{0.96\textwidth}
  4179. \[
  4180. \begin{array}{lcl}
  4181. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4182. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4183. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4184. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4185. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4186. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4187. \mid (\key{and}\;\Exp\;\Exp)
  4188. \mid (\key{or}\;\Exp\;\Exp)
  4189. \mid (\key{not}\;\Exp) } \\
  4190. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4191. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4192. &\mid& (\key{vector}\;\Exp^{+})
  4193. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4194. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4195. &\mid& (\key{void}) \\
  4196. R_3 &::=& (\key{program} \; \Exp)
  4197. \end{array}
  4198. \]
  4199. \end{minipage}
  4200. }
  4201. \caption{The syntax of $R_3$, extending $R_2$
  4202. (Figure~\ref{fig:r2-syntax}) with tuples.}
  4203. \label{fig:r3-syntax}
  4204. \end{figure}
  4205. Tuples are our first encounter with heap-allocated data, which raises
  4206. several interesting issues. First, variable binding performs a
  4207. shallow-copy when dealing with tuples, which means that different
  4208. variables can refer to the same tuple, i.e., different variables can
  4209. be \emph{aliases} for the same thing. Consider the following example
  4210. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4211. the mutation through \code{t2} is visible when referencing the tuple
  4212. from \code{t1}, so the result of this program is \code{42}.
  4213. \begin{lstlisting}
  4214. (let ([t1 (vector 3 7)])
  4215. (let ([t2 t1])
  4216. (let ([_ (vector-set! t2 0 42)])
  4217. (vector-ref t1 0))))
  4218. \end{lstlisting}
  4219. The next issue concerns the lifetime of tuples. Of course, they are
  4220. created by the \code{vector} form, but when does their lifetime end?
  4221. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4222. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4223. is not tied to any notion of static scoping. For example, the
  4224. following program returns \code{3} even though the variable \code{t}
  4225. goes out of scope prior to accessing the vector.
  4226. \begin{lstlisting}
  4227. (vector-ref
  4228. (let ([t (vector 3 7)])
  4229. t)
  4230. 0)
  4231. \end{lstlisting}
  4232. From the perspective of programmer-observable behavior, tuples live
  4233. forever. Of course, if they really lived forever, then many programs
  4234. would run out of memory.\footnote{The $R_3$ language does not have
  4235. looping or recursive function, so it is nigh impossible to write a
  4236. program in $R_3$ that will run out of memory. However, we add
  4237. recursive functions in the next Chapter!} A Racket implementation
  4238. must therefore perform automatic garbage collection.
  4239. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4240. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4241. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4242. operations in Racket. One subtle point is that the \code{vector-set!}
  4243. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4244. can be passed around just like other values inside an $R_3$ program,
  4245. but there are no operations specific to the the \code{\#<void>} value
  4246. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4247. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4248. otherwise.
  4249. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$ , which
  4250. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4251. need to know which variables are pointers into the heap, that is,
  4252. which variables are vectors. Also, when allocating a vector, we shall
  4253. need to know which elements of the vector are pointers. We can obtain
  4254. this information during type checking and when we uncover local
  4255. variables. The type checker in Figure~\ref{fig:typecheck-R3} not only
  4256. computes the type of an expression, it also wraps every sub-expression
  4257. $e$ with the form $(\key{has-type}\; e\; T)$, where $T$ is $e$'s
  4258. type. Subsequently, in the \code{uncover-locals} pass
  4259. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4260. propagated to all variables (including the temporaries generated by
  4261. \code{remove-complex-opera*}).
  4262. \begin{figure}[tbp]
  4263. \begin{lstlisting}
  4264. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4265. (define (interp-op op)
  4266. (match op
  4267. ...
  4268. ['vector vector]
  4269. ['vector-ref vector-ref]
  4270. ['vector-set! vector-set!]
  4271. [else (error 'interp-op "unknown operator")]))
  4272. (define (interp-R3 env)
  4273. (lambda (e)
  4274. (match e
  4275. ...
  4276. [else (error 'interp-R3 "unrecognized expression")]
  4277. )))
  4278. \end{lstlisting}
  4279. \caption{Interpreter for the $R_3$ language.}
  4280. \label{fig:interp-R3}
  4281. \end{figure}
  4282. \begin{figure}[tbp]
  4283. \begin{lstlisting}
  4284. (define (type-check-exp env)
  4285. (lambda (e)
  4286. (define recur (type-check-exp env))
  4287. (match e
  4288. ...
  4289. ['(void) (values '(has-type (void) Void) 'Void)]
  4290. [`(vector ,es ...)
  4291. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4292. (recur e)))
  4293. (let ([t `(Vector ,@t*)])
  4294. (debug "vector/type-check-exp finished vector" t)
  4295. (values `(has-type (vector ,@e*) ,t) t))]
  4296. [`(vector-ref ,e ,i)
  4297. (define-values (e^ t) (recur e))
  4298. (match t
  4299. [`(Vector ,ts ...)
  4300. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4301. (error 'type-check-exp "invalid index ~a" i))
  4302. (let ([t (list-ref ts i)])
  4303. (values `(has-type (vector-ref ,e^ (has-type ,i Integer)) ,t)
  4304. t))]
  4305. [else (error "expected a vector in vector-ref, not" t)])]
  4306. [`(eq? ,arg1 ,arg2)
  4307. (define-values (e1 t1) (recur arg1))
  4308. (define-values (e2 t2) (recur arg2))
  4309. (match* (t1 t2)
  4310. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  4311. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  4312. [(other wise) ((super type-check-exp env) e)])]
  4313. ...
  4314. )))
  4315. \end{lstlisting}
  4316. \caption{Type checker for the $R_3$ language.}
  4317. \label{fig:typecheck-R3}
  4318. \end{figure}
  4319. \section{Garbage Collection}
  4320. \label{sec:GC}
  4321. Here we study a relatively simple algorithm for garbage collection
  4322. that is the basis of state-of-the-art garbage
  4323. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4324. particular, we describe a two-space copying
  4325. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4326. perform the
  4327. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4328. coarse-grained depiction of what happens in a two-space collector,
  4329. showing two time steps, prior to garbage collection on the top and
  4330. after garbage collection on the bottom. In a two-space collector, the
  4331. heap is divided into two parts, the FromSpace and the
  4332. ToSpace. Initially, all allocations go to the FromSpace until there is
  4333. not enough room for the next allocation request. At that point, the
  4334. garbage collector goes to work to make more room.
  4335. The garbage collector must be careful not to reclaim tuples that will
  4336. be used by the program in the future. Of course, it is impossible in
  4337. general to predict what a program will do, but we can over approximate
  4338. the will-be-used tuples by preserving all tuples that could be
  4339. accessed by \emph{any} program given the current computer state. A
  4340. program could access any tuple whose address is in a register or on
  4341. the procedure call stack. These addresses are called the \emph{root
  4342. set}. In addition, a program could access any tuple that is
  4343. transitively reachable from the root set. Thus, it is safe for the
  4344. garbage collector to reclaim the tuples that are not reachable in this
  4345. way.
  4346. So the goal of the garbage collector is twofold:
  4347. \begin{enumerate}
  4348. \item preserve all tuple that are reachable from the root set via a
  4349. path of pointers, that is, the \emph{live} tuples, and
  4350. \item reclaim the memory of everything else, that is, the
  4351. \emph{garbage}.
  4352. \end{enumerate}
  4353. A copying collector accomplishes this by copying all of the live
  4354. objects from the FromSpace into the ToSpace and then performs a slight
  4355. of hand, treating the ToSpace as the new FromSpace and the old
  4356. FromSpace as the new ToSpace. In the example of
  4357. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4358. root set, one in a register and two on the stack. All of the live
  4359. objects have been copied to the ToSpace (the right-hand side of
  4360. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4361. pointer relationships. For example, the pointer in the register still
  4362. points to a 2-tuple whose first element is a 3-tuple and second
  4363. element is a 2-tuple. There are four tuples that are not reachable
  4364. from the root set and therefore do not get copied into the ToSpace.
  4365. (The situation in Figure~\ref{fig:copying-collector}, with a
  4366. cycle, cannot be created by a well-typed program in $R_3$. However,
  4367. creating cycles will be possible once we get to $R_6$. We design
  4368. the garbage collector to deal with cycles to begin with, so we will
  4369. not need to revisit this issue.)
  4370. \begin{figure}[tbp]
  4371. \centering
  4372. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4373. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4374. \caption{A copying collector in action.}
  4375. \label{fig:copying-collector}
  4376. \end{figure}
  4377. There are many alternatives to copying collectors (and their older
  4378. siblings, the generational collectors) when its comes to garbage
  4379. collection, such as mark-and-sweep and reference counting. The
  4380. strengths of copying collectors are that allocation is fast (just a
  4381. test and pointer increment), there is no fragmentation, cyclic garbage
  4382. is collected, and the time complexity of collection only depends on
  4383. the amount of live data, and not on the amount of
  4384. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4385. copying collectors is that they use a lot of space, though that
  4386. problem is ameliorated in generational collectors. Racket and Scheme
  4387. programs tend to allocate many small objects and generate a lot of
  4388. garbage, so copying and generational collectors are a good fit. Of
  4389. course, garbage collection is an active research topic, especially
  4390. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4391. continuously developing new techniques and revisiting old
  4392. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4393. \subsection{Graph Copying via Cheney's Algorithm}
  4394. \label{sec:cheney}
  4395. Let us take a closer look at how the copy works. The allocated objects
  4396. and pointers can be viewed as a graph and we need to copy the part of
  4397. the graph that is reachable from the root set. To make sure we copy
  4398. all of the reachable vertices in the graph, we need an exhaustive
  4399. graph traversal algorithm, such as depth-first search or breadth-first
  4400. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4401. take into account the possibility of cycles by marking which vertices
  4402. have already been visited, so as to ensure termination of the
  4403. algorithm. These search algorithms also use a data structure such as a
  4404. stack or queue as a to-do list to keep track of the vertices that need
  4405. to be visited. We shall use breadth-first search and a trick due to
  4406. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4407. copying tuples into the ToSpace.
  4408. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4409. copy progresses. The queue is represented by a chunk of contiguous
  4410. memory at the beginning of the ToSpace, using two pointers to track
  4411. the front and the back of the queue. The algorithm starts by copying
  4412. all tuples that are immediately reachable from the root set into the
  4413. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4414. old tuple to indicate that it has been visited. (We discuss the
  4415. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4416. inside the copied tuples in the queue still point back to the
  4417. FromSpace. Once the initial queue has been created, the algorithm
  4418. enters a loop in which it repeatedly processes the tuple at the front
  4419. of the queue and pops it off the queue. To process a tuple, the
  4420. algorithm copies all the tuple that are directly reachable from it to
  4421. the ToSpace, placing them at the back of the queue. The algorithm then
  4422. updates the pointers in the popped tuple so they point to the newly
  4423. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4424. step we copy the tuple whose second element is $42$ to the back of the
  4425. queue. The other pointer goes to a tuple that has already been copied,
  4426. so we do not need to copy it again, but we do need to update the
  4427. pointer to the new location. This can be accomplished by storing a
  4428. \emph{forwarding} pointer to the new location in the old tuple, back
  4429. when we initially copied the tuple into the ToSpace. This completes
  4430. one step of the algorithm. The algorithm continues in this way until
  4431. the front of the queue is empty, that is, until the front catches up
  4432. with the back.
  4433. \begin{figure}[tbp]
  4434. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4435. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4436. \label{fig:cheney}
  4437. \end{figure}
  4438. \subsection{Data Representation}
  4439. \label{sec:data-rep-gc}
  4440. The garbage collector places some requirements on the data
  4441. representations used by our compiler. First, the garbage collector
  4442. needs to distinguish between pointers and other kinds of data. There
  4443. are several ways to accomplish this.
  4444. \begin{enumerate}
  4445. \item Attached a tag to each object that identifies what type of
  4446. object it is~\citep{McCarthy:1960dz}.
  4447. \item Store different types of objects in different
  4448. regions~\citep{Steele:1977ab}.
  4449. \item Use type information from the program to either generate
  4450. type-specific code for collecting or to generate tables that can
  4451. guide the
  4452. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4453. \end{enumerate}
  4454. Dynamically typed languages, such as Lisp, need to tag objects
  4455. anyways, so option 1 is a natural choice for those languages.
  4456. However, $R_3$ is a statically typed language, so it would be
  4457. unfortunate to require tags on every object, especially small and
  4458. pervasive objects like integers and Booleans. Option 3 is the
  4459. best-performing choice for statically typed languages, but comes with
  4460. a relatively high implementation complexity. To keep this chapter to a
  4461. 2-week time budget, we recommend a combination of options 1 and 2,
  4462. with separate strategies used for the stack and the heap.
  4463. Regarding the stack, we recommend using a separate stack for
  4464. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4465. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4466. local variable needs to be spilled and is of type \code{(Vector
  4467. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4468. of the normal procedure call stack. Furthermore, we always spill
  4469. vector-typed variables if they are live during a call to the
  4470. collector, thereby ensuring that no pointers are in registers during a
  4471. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4472. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4473. layout using a root stack. The root stack contains the two pointers
  4474. from the regular stack and also the pointer in the second
  4475. register.
  4476. \begin{figure}[tbp]
  4477. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4478. \caption{Maintaining a root stack to facilitate garbage collection.}
  4479. \label{fig:shadow-stack}
  4480. \end{figure}
  4481. The problem of distinguishing between pointers and other kinds of data
  4482. also arises inside of each tuple. We solve this problem by attaching a
  4483. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4484. in on the tags for two of the tuples in the example from
  4485. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4486. in a big-endian way, from right-to-left, with bit location 0 (the
  4487. least significant bit) on the far right, which corresponds to the
  4488. directional of the x86 shifting instructions \key{salq} (shift
  4489. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4490. specifying which elements of the tuple are pointers, the part labeled
  4491. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4492. a pointer and a 0 bit indicates some other kind of data. The pointer
  4493. mask starts at bit location 7. We have limited tuples to a maximum
  4494. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4495. tag also contains two other pieces of information. The length of the
  4496. tuple (number of elements) is stored in bits location 1 through
  4497. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4498. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4499. has not yet been copied. If the bit has value 0 then the entire tag
  4500. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4501. always zero anyways because our tuples are 8-byte aligned.)
  4502. \begin{figure}[tbp]
  4503. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4504. \caption{Representation for tuples in the heap.}
  4505. \label{fig:tuple-rep}
  4506. \end{figure}
  4507. \subsection{Implementation of the Garbage Collector}
  4508. \label{sec:organize-gz}
  4509. The implementation of the garbage collector needs to do a lot of
  4510. bit-level data manipulation and we need to link it with our
  4511. compiler-generated x86 code. Thus, we recommend implementing the
  4512. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4513. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4514. interface to the garbage collector. The \code{initialize} function
  4515. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4516. function is meant to be called near the beginning of \code{main},
  4517. before the rest of the program executes. The \code{initialize}
  4518. function puts the address of the beginning of the FromSpace into the
  4519. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4520. points to the address that is 1-past the last element of the
  4521. FromSpace. (We use half-open intervals to represent chunks of
  4522. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4523. points to the first element of the root stack.
  4524. As long as there is room left in the FromSpace, your generated code
  4525. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4526. %
  4527. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4528. --Jeremy}
  4529. %
  4530. The amount of room left in FromSpace is the difference between the
  4531. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4532. function should be called when there is not enough room left in the
  4533. FromSpace for the next allocation. The \code{collect} function takes
  4534. a pointer to the current top of the root stack (one past the last item
  4535. that was pushed) and the number of bytes that need to be
  4536. allocated. The \code{collect} function performs the copying collection
  4537. and leaves the heap in a state such that the next allocation will
  4538. succeed.
  4539. \begin{figure}[tbp]
  4540. \begin{lstlisting}
  4541. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4542. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4543. int64_t* free_ptr;
  4544. int64_t* fromspace_begin;
  4545. int64_t* fromspace_end;
  4546. int64_t** rootstack_begin;
  4547. \end{lstlisting}
  4548. \caption{The compiler's interface to the garbage collector.}
  4549. \label{fig:gc-header}
  4550. \end{figure}
  4551. \begin{exercise}
  4552. In the file \code{runtime.c} you will find the implementation of
  4553. \code{initialize} and a partial implementation of \code{collect}.
  4554. The \code{collect} function calls another function, \code{cheney},
  4555. to perform the actual copy, and that function is left to the reader
  4556. to implement. The following is the prototype for \code{cheney}.
  4557. \begin{lstlisting}
  4558. static void cheney(int64_t** rootstack_ptr);
  4559. \end{lstlisting}
  4560. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4561. rootstack (which is an array of pointers). The \code{cheney} function
  4562. also communicates with \code{collect} through the global
  4563. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4564. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4565. the ToSpace:
  4566. \begin{lstlisting}
  4567. static int64_t* tospace_begin;
  4568. static int64_t* tospace_end;
  4569. \end{lstlisting}
  4570. The job of the \code{cheney} function is to copy all the live
  4571. objects (reachable from the root stack) into the ToSpace, update
  4572. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4573. update the root stack so that it points to the objects in the
  4574. ToSpace, and finally to swap the global pointers for the FromSpace
  4575. and ToSpace.
  4576. \end{exercise}
  4577. %% \section{Compiler Passes}
  4578. %% \label{sec:code-generation-gc}
  4579. The introduction of garbage collection has a non-trivial impact on our
  4580. compiler passes. We introduce one new compiler pass called
  4581. \code{expose-allocation} and make non-trivial changes to
  4582. \code{type-check}, \code{flatten}, \code{select-instructions},
  4583. \code{allocate-registers}, and \code{print-x86}. The following
  4584. program will serve as our running example. It creates two tuples, one
  4585. nested inside the other. Both tuples have length one. The example then
  4586. accesses the element in the inner tuple tuple via two vector
  4587. references.
  4588. % tests/s2_17.rkt
  4589. \begin{lstlisting}
  4590. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4591. \end{lstlisting}
  4592. Next we proceed to discuss the new \code{expose-allocation} pass.
  4593. \section{Expose Allocation}
  4594. \label{sec:expose-allocation}
  4595. The pass \code{expose-allocation} lowers the \code{vector} creation
  4596. form into a conditional call to the collector followed by the
  4597. allocation. We choose to place the \code{expose-allocation} pass
  4598. before \code{flatten} because \code{expose-allocation} introduces new
  4599. variables, which can be done locally with \code{let}, but \code{let}
  4600. is gone after \code{flatten}. In the following, we show the
  4601. transformation for the \code{vector} form into let-bindings for the
  4602. initializing expressions, by a conditional \code{collect}, an
  4603. \code{allocate}, and the initialization of the vector.
  4604. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4605. total bytes need to be allocated for the vector, which is 8 for the
  4606. tag plus \itm{len} times 8.)
  4607. \begin{lstlisting}
  4608. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4609. |$\Longrightarrow$|
  4610. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4611. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4612. (global-value fromspace_end))
  4613. (void)
  4614. (collect |\itm{bytes}|))])
  4615. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4616. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4617. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4618. |$v$|) ... )))) ...)
  4619. \end{lstlisting}
  4620. (In the above, we suppressed all of the \code{has-type} forms in the
  4621. output for the sake of readability.) The placement of the initializing
  4622. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4623. the sequence of \code{vector-set!}'s is important, as those expressions
  4624. may trigger garbage collection and we do not want an allocated but
  4625. uninitialized tuple to be present during a garbage collection.
  4626. The output of \code{expose-allocation} is a language that extends
  4627. $R_3$ with the three new forms that we use above in the translation of
  4628. \code{vector}.
  4629. \[
  4630. \begin{array}{lcl}
  4631. \Exp &::=& \cdots
  4632. \mid (\key{collect} \,\itm{int})
  4633. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4634. \mid (\key{global-value} \,\itm{name})
  4635. \end{array}
  4636. \]
  4637. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4638. %% the beginning of the program which will instruct the garbage collector
  4639. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4640. %% two arguments of \code{initialize} specify the initial allocated space
  4641. %% for the root stack and for the heap.
  4642. %
  4643. %% The \code{expose-allocation} pass annotates all of the local variables
  4644. %% in the \code{program} form with their type.
  4645. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4646. \code{expose-allocation} pass on our running example.
  4647. \begin{figure}[tbp]
  4648. \begin{lstlisting}
  4649. (program ()
  4650. (vector-ref
  4651. (vector-ref
  4652. (let ((vecinit48
  4653. (let ((vecinit44 42))
  4654. (let ((collectret46
  4655. (if (<
  4656. (+ (global-value free_ptr) 16)
  4657. (global-value fromspace_end))
  4658. (void)
  4659. (collect 16))))
  4660. (let ((alloc43 (allocate 1 (Vector Integer))))
  4661. (let ((initret45 (vector-set! alloc43 0 vecinit44)))
  4662. alloc43))))))
  4663. (let ((collectret50
  4664. (if (< (+ (global-value free_ptr) 16)
  4665. (global-value fromspace_end))
  4666. (void)
  4667. (collect 16))))
  4668. (let ((alloc47 (allocate 1 (Vector (Vector Integer)))))
  4669. (let ((initret49 (vector-set! alloc47 0 vecinit48)))
  4670. alloc47))))
  4671. 0)
  4672. 0))
  4673. \end{lstlisting}
  4674. \caption{Output of the \code{expose-allocation} pass, minus
  4675. all of the \code{has-type} forms.}
  4676. \label{fig:expose-alloc-output}
  4677. \end{figure}
  4678. %\clearpage
  4679. \section{Explicate Control and the $C_2$ language}
  4680. \label{sec:explicate-control-r3}
  4681. \begin{figure}[tp]
  4682. \fbox{
  4683. \begin{minipage}{0.96\textwidth}
  4684. \[
  4685. \begin{array}{lcl}
  4686. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4687. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4688. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4689. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4690. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4691. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4692. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4693. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4694. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4695. \mid (\key{collect} \,\itm{int}) \\
  4696. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4697. &\mid& \gray{(\key{goto}\,\itm{label})
  4698. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4699. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4700. \end{array}
  4701. \]
  4702. \end{minipage}
  4703. }
  4704. \caption{The $C_2$ language, extending $C_1$
  4705. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4706. \label{fig:c2-syntax}
  4707. \end{figure}
  4708. The output of \code{explicate-control} is a program in the
  4709. intermediate language $C_2$, whose syntax is defined in
  4710. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4711. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4712. \key{global-value} expressions and the \code{collect} statement. The
  4713. \code{explicate-control} pass can treat these new forms much like the
  4714. other forms.
  4715. \section{Uncover Locals}
  4716. \label{sec:uncover-locals-r3}
  4717. Recall that the \code{uncover-locals} function collects all of the
  4718. local variables so that it can store them in the $\itm{info}$ field of
  4719. the \code{program} form. Also recall that we need to know the types of
  4720. all the local variables for purposes of identifying the root set for
  4721. the garbage collector. Thus, we change \code{uncover-locals} to
  4722. collect not just the variables, but the variables and their types in
  4723. the form of an association list. Thanks to the \code{has-type} forms,
  4724. the types are readily available. Figure~\ref{fig:uncover-locals-r3}
  4725. lists the output of the \code{uncover-locals} pass on the running
  4726. example.
  4727. \begin{figure}[tbp]
  4728. \begin{lstlisting}
  4729. (program
  4730. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4731. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4732. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4733. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4734. (tmp52 . Integer) (tmp57 . (Vector Integer))
  4735. (vecinit44 . Integer) (tmp56 . Integer) (initret49 . Void)
  4736. (collectret50 . Void))))
  4737. ((block63 . (seq (collect 16) (goto block61)))
  4738. (block62 . (seq (assign collectret46 (void)) (goto block61)))
  4739. (block61 . (seq (assign alloc43 (allocate 1 (Vector Integer)))
  4740. (seq (assign initret45 (vector-set! alloc43 0 vecinit44))
  4741. (seq (assign vecinit48 alloc43)
  4742. (seq (assign tmp54 (global-value free_ptr))
  4743. (seq (assign tmp55 (+ tmp54 16))
  4744. (seq (assign tmp56 (global-value fromspace_end))
  4745. (if (< tmp55 tmp56) (goto block59) (goto block60)))))))))
  4746. (block60 . (seq (collect 16) (goto block58)))
  4747. (block59 . (seq (assign collectret50 (void)) (goto block58)))
  4748. (block58 . (seq (assign alloc47 (allocate 1 (Vector (Vector Integer))))
  4749. (seq (assign initret49 (vector-set! alloc47 0 vecinit48))
  4750. (seq (assign tmp57 (vector-ref alloc47 0))
  4751. (return (vector-ref tmp57 0))))))
  4752. (start . (seq (assign vecinit44 42)
  4753. (seq (assign tmp51 (global-value free_ptr))
  4754. (seq (assign tmp52 (+ tmp51 16))
  4755. (seq (assign tmp53 (global-value fromspace_end))
  4756. (if (< tmp52 tmp53) (goto block62) (goto block63)))))))))
  4757. \end{lstlisting}
  4758. \caption{Output of \code{uncover-locals} for the running example.}
  4759. \label{fig:uncover-locals-r3}
  4760. \end{figure}
  4761. \clearpage
  4762. \section{Select Instructions}
  4763. \label{sec:select-instructions-gc}
  4764. %% void (rep as zero)
  4765. %% allocate
  4766. %% collect (callq collect)
  4767. %% vector-ref
  4768. %% vector-set!
  4769. %% global-value (postpone)
  4770. In this pass we generate x86 code for most of the new operations that
  4771. were needed to compile tuples, including \code{allocate},
  4772. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4773. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4774. The \code{vector-ref} and \code{vector-set!} forms translate into
  4775. \code{movq} instructions with the appropriate \key{deref}. (The
  4776. plus one is to get past the tag at the beginning of the tuple
  4777. representation.)
  4778. \begin{lstlisting}
  4779. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4780. |$\Longrightarrow$|
  4781. (movq |$\itm{vec}'$| (reg r11))
  4782. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4783. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4784. |$\Longrightarrow$|
  4785. (movq |$\itm{vec}'$| (reg r11))
  4786. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4787. (movq (int 0) |$\itm{lhs}$|)
  4788. \end{lstlisting}
  4789. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4790. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4791. register \code{r11} ensures that offsets are only performed with
  4792. register operands. This requires removing \code{r11} from
  4793. consideration by the register allocating.
  4794. We compile the \code{allocate} form to operations on the
  4795. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4796. is the next free address in the FromSpace, so we move it into the
  4797. \itm{lhs} and then move it forward by enough space for the tuple being
  4798. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4799. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4800. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4801. how the tag is organized. We recommend using the Racket operations
  4802. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4803. The type annotation in the \code{vector} form is used to determine the
  4804. pointer mask region of the tag.
  4805. \begin{lstlisting}
  4806. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4807. |$\Longrightarrow$|
  4808. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4809. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4810. (movq |$\itm{lhs}'$| (reg r11))
  4811. (movq (int |$\itm{tag}$|) (deref r11 0))
  4812. \end{lstlisting}
  4813. The \code{collect} form is compiled to a call to the \code{collect}
  4814. function in the runtime. The arguments to \code{collect} are the top
  4815. of the root stack and the number of bytes that need to be allocated.
  4816. We shall use a dedicated register, \code{r15}, to store the pointer to
  4817. the top of the root stack. So \code{r15} is not available for use by
  4818. the register allocator.
  4819. \begin{lstlisting}
  4820. (collect |$\itm{bytes}$|)
  4821. |$\Longrightarrow$|
  4822. (movq (reg r15) (reg rdi))
  4823. (movq |\itm{bytes}| (reg rsi))
  4824. (callq collect)
  4825. \end{lstlisting}
  4826. \begin{figure}[tp]
  4827. \fbox{
  4828. \begin{minipage}{0.96\textwidth}
  4829. \[
  4830. \begin{array}{lcl}
  4831. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4832. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4833. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4834. \mid (\key{global-value}\; \itm{name}) \\
  4835. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4836. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4837. (\key{subq} \; \Arg\; \Arg) \mid
  4838. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4839. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4840. (\key{pushq}\;\Arg) \mid
  4841. (\key{popq}\;\Arg) \mid
  4842. (\key{retq})} \\
  4843. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4844. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4845. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4846. \mid (\key{jmp} \; \itm{label})
  4847. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  4848. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  4849. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4850. \end{array}
  4851. \]
  4852. \end{minipage}
  4853. }
  4854. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4855. \label{fig:x86-2}
  4856. \end{figure}
  4857. The syntax of the $x86_2$ language is defined in
  4858. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4859. of the form for global variables.
  4860. %
  4861. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4862. \code{select-instructions} pass on the running example.
  4863. \begin{figure}[tbp]
  4864. \centering
  4865. \begin{minipage}{0.75\textwidth}
  4866. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4867. (program
  4868. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4869. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4870. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4871. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4872. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  4873. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  4874. ((block63 . (block ()
  4875. (movq (reg r15) (reg rdi))
  4876. (movq (int 16) (reg rsi))
  4877. (callq collect)
  4878. (jmp block61)))
  4879. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  4880. (block61 . (block ()
  4881. (movq (global-value free_ptr) (var alloc43))
  4882. (addq (int 16) (global-value free_ptr))
  4883. (movq (var alloc43) (reg r11))
  4884. (movq (int 3) (deref r11 0))
  4885. (movq (var alloc43) (reg r11))
  4886. (movq (var vecinit44) (deref r11 8))
  4887. (movq (int 0) (var initret45))
  4888. (movq (var alloc43) (var vecinit48))
  4889. (movq (global-value free_ptr) (var tmp54))
  4890. (movq (var tmp54) (var tmp55))
  4891. (addq (int 16) (var tmp55))
  4892. (movq (global-value fromspace_end) (var tmp56))
  4893. (cmpq (var tmp56) (var tmp55))
  4894. (jmp-if l block59)
  4895. (jmp block60)))
  4896. (block60 . (block ()
  4897. (movq (reg r15) (reg rdi))
  4898. (movq (int 16) (reg rsi))
  4899. (callq collect)
  4900. (jmp block58))
  4901. (block59 . (block ()
  4902. (movq (int 0) (var collectret50))
  4903. (jmp block58)))
  4904. (block58 . (block ()
  4905. (movq (global-value free_ptr) (var alloc47))
  4906. (addq (int 16) (global-value free_ptr))
  4907. (movq (var alloc47) (reg r11))
  4908. (movq (int 131) (deref r11 0))
  4909. (movq (var alloc47) (reg r11))
  4910. (movq (var vecinit48) (deref r11 8))
  4911. (movq (int 0) (var initret49))
  4912. (movq (var alloc47) (reg r11))
  4913. (movq (deref r11 8) (var tmp57))
  4914. (movq (var tmp57) (reg r11))
  4915. (movq (deref r11 8) (reg rax))
  4916. (jmp conclusion)))
  4917. (start . (block ()
  4918. (movq (int 42) (var vecinit44))
  4919. (movq (global-value free_ptr) (var tmp51))
  4920. (movq (var tmp51) (var tmp52))
  4921. (addq (int 16) (var tmp52))
  4922. (movq (global-value fromspace_end) (var tmp53))
  4923. (cmpq (var tmp53) (var tmp52))
  4924. (jmp-if l block62)
  4925. (jmp block63))))))
  4926. \end{lstlisting}
  4927. \end{minipage}
  4928. \caption{Output of the \code{select-instructions} pass.}
  4929. \label{fig:select-instr-output-gc}
  4930. \end{figure}
  4931. \clearpage
  4932. \section{Register Allocation}
  4933. \label{sec:reg-alloc-gc}
  4934. As discussed earlier in this chapter, the garbage collector needs to
  4935. access all the pointers in the root set, that is, all variables that
  4936. are vectors. It will be the responsibility of the register allocator
  4937. to make sure that:
  4938. \begin{enumerate}
  4939. \item the root stack is used for spilling vector-typed variables, and
  4940. \item if a vector-typed variable is live during a call to the
  4941. collector, it must be spilled to ensure it is visible to the
  4942. collector.
  4943. \end{enumerate}
  4944. The later responsibility can be handled during construction of the
  4945. inference graph, by adding interference edges between the call-live
  4946. vector-typed variables and all the callee-saved registers. (They
  4947. already interfere with the caller-saved registers.) The type
  4948. information for variables is in the \code{program} form, so we
  4949. recommend adding another parameter to the \code{build-interference}
  4950. function to communicate this association list.
  4951. The spilling of vector-typed variables to the root stack can be
  4952. handled after graph coloring, when choosing how to assign the colors
  4953. (integers) to registers and stack locations. The \code{program} output
  4954. of this pass changes to also record the number of spills to the root
  4955. stack.
  4956. % build-interference
  4957. %
  4958. % callq
  4959. % extra parameter for var->type assoc. list
  4960. % update 'program' and 'if'
  4961. % allocate-registers
  4962. % allocate spilled vectors to the rootstack
  4963. % don't change color-graph
  4964. \section{Print x86}
  4965. \label{sec:print-x86-gc}
  4966. \margincomment{\scriptsize We need to show the translation to x86 and what
  4967. to do about global-value. \\ --Jeremy}
  4968. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4969. \code{print-x86} pass on the running example. In the prelude and
  4970. conclusion of the \code{main} function, we treat the root stack very
  4971. much like the regular stack in that we move the root stack pointer
  4972. (\code{r15}) to make room for all of the spills to the root stack,
  4973. except that the root stack grows up instead of down. For the running
  4974. example, there was just one spill so we increment \code{r15} by 8
  4975. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  4976. One issue that deserves special care is that there may be a call to
  4977. \code{collect} prior to the initializing assignments for all the
  4978. variables in the root stack. We do not want the garbage collector to
  4979. accidentally think that some uninitialized variable is a pointer that
  4980. needs to be followed. Thus, we zero-out all locations on the root
  4981. stack in the prelude of \code{main}. In
  4982. Figure~\ref{fig:print-x86-output-gc}, the instruction
  4983. %
  4984. \lstinline{movq $0, (%r15)}
  4985. %
  4986. accomplishes this task. The garbage collector tests each root to see
  4987. if it is null prior to dereferencing it.
  4988. \begin{figure}[htbp]
  4989. \begin{minipage}[t]{0.5\textwidth}
  4990. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4991. _block58:
  4992. movq _free_ptr(%rip), %rcx
  4993. addq $16, _free_ptr(%rip)
  4994. movq %rcx, %r11
  4995. movq $131, 0(%r11)
  4996. movq %rcx, %r11
  4997. movq -8(%r15), %rax
  4998. movq %rax, 8(%r11)
  4999. movq $0, %rdx
  5000. movq %rcx, %r11
  5001. movq 8(%r11), %rcx
  5002. movq %rcx, %r11
  5003. movq 8(%r11), %rax
  5004. jmp _conclusion
  5005. _block59:
  5006. movq $0, %rcx
  5007. jmp _block58
  5008. _block62:
  5009. movq $0, %rcx
  5010. jmp _block61
  5011. _block60:
  5012. movq %r15, %rdi
  5013. movq $16, %rsi
  5014. callq _collect
  5015. jmp _block58
  5016. _block63:
  5017. movq %r15, %rdi
  5018. movq $16, %rsi
  5019. callq _collect
  5020. jmp _block61
  5021. _start:
  5022. movq $42, %rbx
  5023. movq _free_ptr(%rip), %rdx
  5024. addq $16, %rdx
  5025. movq _fromspace_end(%rip), %rcx
  5026. cmpq %rcx, %rdx
  5027. jl _block62
  5028. jmp _block63
  5029. \end{lstlisting}
  5030. \end{minipage}
  5031. \begin{minipage}[t]{0.45\textwidth}
  5032. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5033. _block61:
  5034. movq _free_ptr(%rip), %rcx
  5035. addq $16, _free_ptr(%rip)
  5036. movq %rcx, %r11
  5037. movq $3, 0(%r11)
  5038. movq %rcx, %r11
  5039. movq %rbx, 8(%r11)
  5040. movq $0, %rdx
  5041. movq %rcx, -8(%r15)
  5042. movq _free_ptr(%rip), %rcx
  5043. addq $16, %rcx
  5044. movq _fromspace_end(%rip), %rdx
  5045. cmpq %rdx, %rcx
  5046. jl _block59
  5047. jmp _block60
  5048. .globl _main
  5049. _main:
  5050. pushq %rbp
  5051. movq %rsp, %rbp
  5052. pushq %r12
  5053. pushq %rbx
  5054. pushq %r13
  5055. pushq %r14
  5056. subq $0, %rsp
  5057. movq $16384, %rdi
  5058. movq $16, %rsi
  5059. callq _initialize
  5060. movq _rootstack_begin(%rip), %r15
  5061. movq $0, (%r15)
  5062. addq $8, %r15
  5063. jmp _start
  5064. _conclusion:
  5065. subq $8, %r15
  5066. addq $0, %rsp
  5067. popq %r14
  5068. popq %r13
  5069. popq %rbx
  5070. popq %r12
  5071. popq %rbp
  5072. retq
  5073. \end{lstlisting}
  5074. \end{minipage}
  5075. \caption{Output of the \code{print-x86} pass.}
  5076. \label{fig:print-x86-output-gc}
  5077. \end{figure}
  5078. \margincomment{\scriptsize Suggest an implementation strategy
  5079. in which the students first do the code gen and test that
  5080. without GC (just use a big heap), then after that is debugged,
  5081. implement the GC. \\ --Jeremy}
  5082. \begin{figure}[p]
  5083. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5084. \node (R3) at (0,2) {\large $R_3$};
  5085. \node (R3-2) at (3,2) {\large $R_3$};
  5086. \node (R3-3) at (6,2) {\large $R_3$};
  5087. \node (R3-4) at (9,2) {\large $R_3$};
  5088. \node (R3-5) at (12,2) {\large $R_3$};
  5089. \node (C2-4) at (3,0) {\large $C_2$};
  5090. \node (C2-3) at (6,0) {\large $C_2$};
  5091. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5092. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5093. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5094. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5095. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5096. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5097. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5098. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5099. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5100. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5101. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5102. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5103. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5104. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5105. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5106. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5107. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5108. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5109. \end{tikzpicture}
  5110. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5111. \label{fig:R3-passes}
  5112. \end{figure}
  5113. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5114. for the compilation of $R_3$.
  5115. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5116. \chapter{Functions}
  5117. \label{ch:functions}
  5118. This chapter studies the compilation of functions at the level of
  5119. abstraction of the C language. This corresponds to a subset of Typed
  5120. Racket in which only top-level function definitions are allowed. These
  5121. kind of functions are an important stepping stone to implementing
  5122. lexically-scoped functions in the form of \key{lambda} abstractions,
  5123. which is the topic of Chapter~\ref{ch:lambdas}.
  5124. \section{The $R_4$ Language}
  5125. The syntax for function definitions and function application is shown
  5126. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5127. Programs in $R_4$ start with zero or more function definitions. The
  5128. function names from these definitions are in-scope for the entire
  5129. program, including all other function definitions (so the ordering of
  5130. function definitions does not matter). The syntax for function
  5131. application does not include an explicit keyword, which is error prone
  5132. when using \code{match}. To alleviate this problem, we change the
  5133. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5134. during type checking.
  5135. Functions are first-class in the sense that a function pointer is data
  5136. and can be stored in memory or passed as a parameter to another
  5137. function. Thus, we introduce a function type, written
  5138. \begin{lstlisting}
  5139. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5140. \end{lstlisting}
  5141. for a function whose $n$ parameters have the types $\Type_1$ through
  5142. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5143. these functions (with respect to Racket functions) is that they are
  5144. not lexically scoped. That is, the only external entities that can be
  5145. referenced from inside a function body are other globally-defined
  5146. functions. The syntax of $R_4$ prevents functions from being nested
  5147. inside each other.
  5148. \begin{figure}[tp]
  5149. \centering
  5150. \fbox{
  5151. \begin{minipage}{0.96\textwidth}
  5152. \[
  5153. \begin{array}{lcl}
  5154. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5155. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5156. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5157. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5158. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5159. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5160. \mid (\key{and}\;\Exp\;\Exp)
  5161. \mid (\key{or}\;\Exp\;\Exp)
  5162. \mid (\key{not}\;\Exp)} \\
  5163. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5164. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5165. (\key{vector-ref}\;\Exp\;\Int)} \\
  5166. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5167. &\mid& (\Exp \; \Exp^{*}) \\
  5168. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5169. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5170. \end{array}
  5171. \]
  5172. \end{minipage}
  5173. }
  5174. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5175. with functions.}
  5176. \label{fig:r4-syntax}
  5177. \end{figure}
  5178. The program in Figure~\ref{fig:r4-function-example} is a
  5179. representative example of defining and using functions in $R_4$. We
  5180. define a function \code{map-vec} that applies some other function
  5181. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5182. vector containing the results. We also define a function \code{add1}
  5183. that does what its name suggests. The program then applies
  5184. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5185. \code{(vector 1 42)}, from which we return the \code{42}.
  5186. \begin{figure}[tbp]
  5187. \begin{lstlisting}
  5188. (program ()
  5189. (define (map-vec [f : (Integer -> Integer)]
  5190. [v : (Vector Integer Integer)])
  5191. : (Vector Integer Integer)
  5192. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5193. (define (add1 [x : Integer]) : Integer
  5194. (+ x 1))
  5195. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5196. )
  5197. \end{lstlisting}
  5198. \caption{Example of using functions in $R_4$.}
  5199. \label{fig:r4-function-example}
  5200. \end{figure}
  5201. The definitional interpreter for $R_4$ is in
  5202. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5203. responsible for setting up the mutual recursion between the top-level
  5204. function definitions. We use the classic back-patching approach that
  5205. uses mutable variables and makes two passes over the function
  5206. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5207. top-level environment using a mutable cons cell for each function
  5208. definition. Note that the \code{lambda} value for each function is
  5209. incomplete; it does not yet include the environment. Once the
  5210. top-level environment is constructed, we then iterate over it and
  5211. update the \code{lambda} value's to use the top-level environment.
  5212. \begin{figure}[tp]
  5213. \begin{lstlisting}
  5214. (define (interp-exp env)
  5215. (lambda (e)
  5216. (define recur (interp-exp env))
  5217. (match e
  5218. ...
  5219. [`(,fun ,args ...)
  5220. (define arg-vals (for/list ([e args]) (recur e)))
  5221. (define fun-val (recur fun))
  5222. (match fun-val
  5223. [`(lambda (,xs ...) ,body ,fun-env)
  5224. (define new-env (append (map cons xs arg-vals) fun-env))
  5225. ((interp-exp new-env) body)]
  5226. [else (error "interp-exp, expected function, not" fun-val)])]
  5227. [else (error 'interp-exp "unrecognized expression")]
  5228. )))
  5229. (define (interp-def d)
  5230. (match d
  5231. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5232. (mcons f `(lambda ,xs ,body ()))]
  5233. ))
  5234. (define (interp-R4 p)
  5235. (match p
  5236. [`(program ,ds ... ,body)
  5237. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5238. (for/list ([b top-level])
  5239. (set-mcdr! b (match (mcdr b)
  5240. [`(lambda ,xs ,body ())
  5241. `(lambda ,xs ,body ,top-level)])))
  5242. ((interp-exp top-level) body))]
  5243. ))
  5244. \end{lstlisting}
  5245. \caption{Interpreter for the $R_4$ language.}
  5246. \label{fig:interp-R4}
  5247. \end{figure}
  5248. \section{Functions in x86}
  5249. \label{sec:fun-x86}
  5250. \margincomment{\tiny Make sure callee-saved registers are discussed
  5251. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5252. \margincomment{\tiny Talk about the return address on the
  5253. stack and what callq and retq does.\\ --Jeremy }
  5254. The x86 architecture provides a few features to support the
  5255. implementation of functions. We have already seen that x86 provides
  5256. labels so that one can refer to the location of an instruction, as is
  5257. needed for jump instructions. Labels can also be used to mark the
  5258. beginning of the instructions for a function. Going further, we can
  5259. obtain the address of a label by using the \key{leaq} instruction and
  5260. \key{rip}-relative addressing. For example, the following puts the
  5261. address of the \code{add1} label into the \code{rbx} register.
  5262. \begin{lstlisting}
  5263. leaq add1(%rip), %rbx
  5264. \end{lstlisting}
  5265. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5266. instruction for jumping to a function whose location is given by a
  5267. label. Here we instead will be jumping to a function whose location is
  5268. given by an address, that is, we need to make an \emph{indirect
  5269. function call}. The x86 syntax is to give the register name prefixed
  5270. with an asterisk.
  5271. \begin{lstlisting}
  5272. callq *%rbx
  5273. \end{lstlisting}
  5274. \subsection{Calling Conventions}
  5275. The \code{callq} instruction provides partial support for implementing
  5276. functions, but it does not handle (1) parameter passing, (2) saving
  5277. and restoring frames on the procedure call stack, or (3) determining
  5278. how registers are shared by different functions. These issues require
  5279. coordination between the caller and the callee, which is often
  5280. assembly code written by different programmers or generated by
  5281. different compilers. As a result, people have developed
  5282. \emph{conventions} that govern how functions calls are performed.
  5283. Here we shall use the same conventions used by the \code{gcc}
  5284. compiler~\citep{Matz:2013aa}.
  5285. Regarding (1) parameter passing, the convention is to use the
  5286. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5287. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5288. than six arguments, then the convention is to use space on the frame
  5289. of the caller for the rest of the arguments. However, to ease the
  5290. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5291. we shall arrange to never have more than six arguments.
  5292. %
  5293. The register \code{rax} is for the return value of the function.
  5294. Regarding (2) frames and the procedure call stack, the convention is
  5295. that the stack grows down, with each function call using a chunk of
  5296. space called a frame. The caller sets the stack pointer, register
  5297. \code{rsp}, to the last data item in its frame. The callee must not
  5298. change anything in the caller's frame, that is, anything that is at or
  5299. above the stack pointer. The callee is free to use locations that are
  5300. below the stack pointer.
  5301. Regarding (3) the sharing of registers between different functions,
  5302. recall from Section~\ref{sec:calling-conventions} that the registers
  5303. are divided into two groups, the caller-saved registers and the
  5304. callee-saved registers. The caller should assume that all the
  5305. caller-saved registers get overwritten with arbitrary values by the
  5306. callee. Thus, the caller should either 1) not put values that are live
  5307. across a call in caller-saved registers, or 2) save and restore values
  5308. that are live across calls. We shall recommend option 1). On the flip
  5309. side, if the callee wants to use a callee-saved register, the callee
  5310. must save the contents of those registers on their stack frame and
  5311. then put them back prior to returning to the caller. The base
  5312. pointer, register \code{rbp}, is used as a point-of-reference within a
  5313. frame, so that each local variable can be accessed at a fixed offset
  5314. from the base pointer.
  5315. %
  5316. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5317. frames.
  5318. %% If we were to use stack arguments, they would be between the
  5319. %% caller locals and the callee return address.
  5320. \begin{figure}[tbp]
  5321. \centering
  5322. \begin{tabular}{r|r|l|l} \hline
  5323. Caller View & Callee View & Contents & Frame \\ \hline
  5324. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5325. 0(\key{\%rbp}) & & old \key{rbp} \\
  5326. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5327. \ldots & & \ldots \\
  5328. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5329. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5330. \ldots & & \ldots \\
  5331. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5332. %% & & \\
  5333. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5334. %% & \ldots & \ldots \\
  5335. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5336. \hline
  5337. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5338. & 0(\key{\%rbp}) & old \key{rbp} \\
  5339. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5340. & \ldots & \ldots \\
  5341. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5342. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5343. & \ldots & \ldots \\
  5344. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5345. \end{tabular}
  5346. \caption{Memory layout of caller and callee frames.}
  5347. \label{fig:call-frames}
  5348. \end{figure}
  5349. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5350. %% local variables and for storing the values of callee-saved registers
  5351. %% (we shall refer to all of these collectively as ``locals''), and that
  5352. %% at the beginning of a function we move the stack pointer \code{rsp}
  5353. %% down to make room for them.
  5354. %% We recommend storing the local variables
  5355. %% first and then the callee-saved registers, so that the local variables
  5356. %% can be accessed using \code{rbp} the same as before the addition of
  5357. %% functions.
  5358. %% To make additional room for passing arguments, we shall
  5359. %% move the stack pointer even further down. We count how many stack
  5360. %% arguments are needed for each function call that occurs inside the
  5361. %% body of the function and find their maximum. Adding this number to the
  5362. %% number of locals gives us how much the \code{rsp} should be moved at
  5363. %% the beginning of the function. In preparation for a function call, we
  5364. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5365. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5366. %% so on.
  5367. %% Upon calling the function, the stack arguments are retrieved by the
  5368. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5369. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5370. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5371. %% the layout of the caller and callee frames. Notice how important it is
  5372. %% that we correctly compute the maximum number of arguments needed for
  5373. %% function calls; if that number is too small then the arguments and
  5374. %% local variables will smash into each other!
  5375. \subsection{Efficient Tail Calls}
  5376. \label{sec:tail-call}
  5377. In general, the amount of stack space used by a program is determined
  5378. by the longest chain of nested function calls. That is, if function
  5379. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5380. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5381. $n$ can grow quite large in the case of recursive or mutually
  5382. recursive functions. However, in some cases we can arrange to use only
  5383. constant space, i.e. $O(1)$, instead of $O(n)$.
  5384. If a function call is the last action in a function body, then that
  5385. call is said to be a \emph{tail call}. In such situations, the frame
  5386. of the caller is no longer needed, so we can pop the caller's frame
  5387. before making the tail call. With this approach, a recursive function
  5388. that only makes tail calls will only use $O(1)$ stack space.
  5389. Functional languages like Racket typically rely heavily on recursive
  5390. functions, so they typically guarantee that all tail calls will be
  5391. optimized in this way.
  5392. However, some care is needed with regards to argument passing in tail
  5393. calls. As mentioned above, for arguments beyond the sixth, the
  5394. convention is to use space in the caller's frame for passing
  5395. arguments. But here we've popped the caller's frame and can no longer
  5396. use it. Another alternative is to use space in the callee's frame for
  5397. passing arguments. However, this option is also problematic because
  5398. the caller and callee's frame overlap in memory. As we begin to copy
  5399. the arguments from their sources in the caller's frame, the target
  5400. locations in the callee's frame might overlap with the sources for
  5401. later arguments! We solve this problem by not using the stack for
  5402. parameter passing but instead use the heap, as we describe in the
  5403. Section~\ref{sec:limit-functions-r4}.
  5404. As mentioned above, for a tail call we pop the caller's frame prior to
  5405. making the tail call. The instructions for popping a frame are the
  5406. instructions that we usually place in the conclusion of a
  5407. function. Thus, we also need to place such code immediately before
  5408. each tail call. These instructions include restoring the callee-saved
  5409. registers, so it is good that the argument passing registers are all
  5410. caller-saved registers.
  5411. One last note regarding which instruction to use to make the tail
  5412. call. When the callee is finished, it should not return to the current
  5413. function, but it should return to the function that called the current
  5414. one. Thus, the return address that is already on the stack is the
  5415. right one, and we should not use \key{callq} to make the tail call, as
  5416. that would unnecessarily overwrite the return address. Instead we can
  5417. simply use the \key{jmp} instruction. Like the indirect function call,
  5418. we write an indirect jump with a register prefixed with an asterisk.
  5419. We recommend using \code{rax} to hold the jump target because the
  5420. preceding ``conclusion'' overwrites just about everything else.
  5421. \begin{lstlisting}
  5422. jmp *%rax
  5423. \end{lstlisting}
  5424. %% Now that we have a good understanding of functions as they appear in
  5425. %% $R_4$ and the support for functions in x86, we need to plan the
  5426. %% changes to our compiler, that is, do we need any new passes and/or do
  5427. %% we need to change any existing passes? Also, do we need to add new
  5428. %% kinds of AST nodes to any of the intermediate languages?
  5429. \section{Shrink $R_4$}
  5430. \label{sec:shrink-r4}
  5431. The \code{shrink} pass performs a couple minor modifications to the
  5432. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5433. field to each function definition:
  5434. \begin{lstlisting}
  5435. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5436. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5437. \end{lstlisting}
  5438. and introduces an explicit \code{main} function.\\
  5439. \begin{tabular}{lll}
  5440. \begin{minipage}{0.45\textwidth}
  5441. \begin{lstlisting}
  5442. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5443. \end{lstlisting}
  5444. \end{minipage}
  5445. &
  5446. $\Rightarrow$
  5447. &
  5448. \begin{minipage}{0.45\textwidth}
  5449. \begin{lstlisting}
  5450. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5451. \end{lstlisting}
  5452. \end{minipage}
  5453. \end{tabular} \\
  5454. where $\itm{mainDef}$ is
  5455. \begin{lstlisting}
  5456. (define (main) : Integer () |$\Exp'$|)
  5457. \end{lstlisting}
  5458. \section{Reveal Functions}
  5459. \label{sec:reveal-functions-r4}
  5460. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5461. compilation because it conflates the use of function names and local
  5462. variables. This is a problem because we need to compile the use of a
  5463. function name differently than the use of a local variable; we need to
  5464. use \code{leaq} to convert the function name (a label in x86) to an
  5465. address in a register. Thus, it is a good idea to create a new pass
  5466. that changes function references from just a symbol $f$ to
  5467. \code{(fun-ref $f$)}. A good name for this pass is
  5468. \code{reveal-functions} and the output language, $F_1$, is defined in
  5469. Figure~\ref{fig:f1-syntax}.
  5470. \begin{figure}[tp]
  5471. \centering
  5472. \fbox{
  5473. \begin{minipage}{0.96\textwidth}
  5474. \[
  5475. \begin{array}{lcl}
  5476. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5477. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5478. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5479. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5480. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5481. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5482. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5483. (\key{vector-ref}\;\Exp\;\Int)} \\
  5484. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5485. (\key{app}\; \Exp \; \Exp^{*})} \\
  5486. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5487. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5488. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5489. \end{array}
  5490. \]
  5491. \end{minipage}
  5492. }
  5493. \caption{The $F_1$ language, an extension of $R_4$
  5494. (Figure~\ref{fig:r4-syntax}).}
  5495. \label{fig:f1-syntax}
  5496. \end{figure}
  5497. %% Distinguishing between calls in tail position and non-tail position
  5498. %% requires the pass to have some notion of context. We recommend using
  5499. %% two mutually recursive functions, one for processing expressions in
  5500. %% tail position and another for the rest.
  5501. Placing this pass after \code{uniquify} is a good idea, because it
  5502. will make sure that there are no local variables and functions that
  5503. share the same name. On the other hand, \code{reveal-functions} needs
  5504. to come before the \code{explicate-control} pass because that pass
  5505. will help us compile \code{fun-ref} into assignment statements.
  5506. \section{Limit Functions}
  5507. \label{sec:limit-functions-r4}
  5508. This pass transforms functions so that they have at most six
  5509. parameters and transforms all function calls so that they pass at most
  5510. six arguments. A simple strategy for imposing an argument limit of
  5511. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5512. into a vector, making that subsequent vector the $n$th argument.
  5513. \begin{tabular}{lll}
  5514. \begin{minipage}{0.2\textwidth}
  5515. \begin{lstlisting}
  5516. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5517. \end{lstlisting}
  5518. \end{minipage}
  5519. &
  5520. $\Rightarrow$
  5521. &
  5522. \begin{minipage}{0.4\textwidth}
  5523. \begin{lstlisting}
  5524. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5525. \end{lstlisting}
  5526. \end{minipage}
  5527. \end{tabular}
  5528. In the body of the function, all occurrences of the $i$th argument in
  5529. which $i>5$ must be replaced with a \code{vector-ref}.
  5530. \section{Remove Complex Operators and Operands}
  5531. \label{sec:rco-r4}
  5532. The primary decisions to make for this pass is whether to classify
  5533. \code{fun-ref} and \code{app} as either simple or complex
  5534. expressions. Recall that a simple expression will eventually end up as
  5535. just an ``immediate'' argument of an x86 instruction. Function
  5536. application will be translated to a sequence of instructions, so
  5537. \code{app} must be classified as complex expression. Regarding
  5538. \code{fun-ref}, as discussed above, the function label needs to
  5539. be converted to an address using the \code{leaq} instruction. Thus,
  5540. even though \code{fun-ref} seems rather simple, it needs to be
  5541. classified as a complex expression so that we generate an assignment
  5542. statement with a left-hand side that can serve as the target of the
  5543. \code{leaq}.
  5544. \section{Explicate Control and the $C_3$ language}
  5545. \label{sec:explicate-control-r4}
  5546. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5547. \key{explicate-control}. The three mutually recursive functions for
  5548. this pass, for assignment, tail, and predicate contexts, must all be
  5549. updated with cases for \code{fun-ref} and \code{app}. In
  5550. assignment and predicate contexts, \code{app} becomes \code{call},
  5551. whereas in tail position \code{app} becomes \code{tailcall}. We
  5552. recommend defining a new function for processing function definitions.
  5553. This code is similar to the case for \code{program} in $R_3$. The
  5554. top-level \code{explicate-control} function that handles the
  5555. \code{program} form of $R_4$ can then apply this new function to all
  5556. the function definitions.
  5557. \begin{figure}[tp]
  5558. \fbox{
  5559. \begin{minipage}{0.96\textwidth}
  5560. \[
  5561. \begin{array}{lcl}
  5562. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5563. \\
  5564. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5565. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5566. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5567. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5568. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5569. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5570. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5571. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5572. \mid (\key{collect} \,\itm{int}) }\\
  5573. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5574. &\mid& \gray{(\key{goto}\,\itm{label})
  5575. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5576. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5577. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5578. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5579. \end{array}
  5580. \]
  5581. \end{minipage}
  5582. }
  5583. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5584. \label{fig:c3-syntax}
  5585. \end{figure}
  5586. \section{Uncover Locals}
  5587. \label{sec:uncover-locals-r4}
  5588. The function for processing $\Tail$ should be updated with a case for
  5589. \code{tailcall}. We also recommend creating a new function for
  5590. processing function definitions. Each function definition in $C_3$ has
  5591. its own set of local variables, so the code for function definitions
  5592. should be similar to the case for the \code{program} form in $C_2$.
  5593. \section{Select Instructions}
  5594. \label{sec:select-r4}
  5595. The output of select instructions is a program in the x86$_3$
  5596. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5597. \begin{figure}[tp]
  5598. \fbox{
  5599. \begin{minipage}{0.96\textwidth}
  5600. \[
  5601. \begin{array}{lcl}
  5602. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  5603. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  5604. &\mid& \gray{ (\key{byte-reg}\; \itm{register})
  5605. \mid (\key{global-value}\; \itm{name}) } \\
  5606. &\mid& (\key{fun-ref}\; \itm{label})\\
  5607. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5608. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5609. (\key{subq} \; \Arg\; \Arg) \mid
  5610. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5611. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5612. (\key{pushq}\;\Arg) \mid
  5613. (\key{popq}\;\Arg) \mid
  5614. (\key{retq}) } \\
  5615. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5616. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5617. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5618. \mid (\key{jmp} \; \itm{label})
  5619. \mid (\key{j}\itm{cc} \; \itm{label})
  5620. \mid (\key{label} \; \itm{label}) } \\
  5621. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5622. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5623. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5624. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5625. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5626. \end{array}
  5627. \]
  5628. \end{minipage}
  5629. }
  5630. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5631. \label{fig:x86-3}
  5632. \end{figure}
  5633. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5634. as follows: \\
  5635. \begin{tabular}{lll}
  5636. \begin{minipage}{0.45\textwidth}
  5637. \begin{lstlisting}
  5638. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5639. \end{lstlisting}
  5640. \end{minipage}
  5641. &
  5642. $\Rightarrow$
  5643. &
  5644. \begin{minipage}{0.4\textwidth}
  5645. \begin{lstlisting}
  5646. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5647. \end{lstlisting}
  5648. \end{minipage}
  5649. \end{tabular} \\
  5650. Regarding function definitions, we need to remove their parameters and
  5651. instead perform parameter passing in terms of the conventions
  5652. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5653. in the argument passing registers, and inside the function we should
  5654. generate a \code{movq} instruction for each parameter, to move the
  5655. argument value from the appropriate register to a new local variable
  5656. with the same name as the old parameter.
  5657. Next, consider the compilation of function calls, which have the
  5658. following form upon input to \code{select-instructions}.
  5659. \begin{lstlisting}
  5660. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5661. \end{lstlisting}
  5662. In the mirror image of handling the parameters of function
  5663. definitions, the arguments \itm{args} need to be moved to the argument
  5664. passing registers.
  5665. %
  5666. Once the instructions for parameter passing have been generated, the
  5667. function call itself can be performed with an indirect function call,
  5668. for which I recommend creating the new instruction
  5669. \code{indirect-callq}. Of course, the return value from the function
  5670. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5671. \begin{lstlisting}
  5672. (indirect-callq |\itm{fun}|)
  5673. (movq (reg rax) |\itm{lhs}|)
  5674. \end{lstlisting}
  5675. Regarding tail calls, the parameter passing is the same as non-tail
  5676. calls: generate instructions to move the arguments into to the
  5677. argument passing registers. After that we need to pop the frame from
  5678. the procedure call stack. However, we do not yet know how big the
  5679. frame is; that gets determined during register allocation. So instead
  5680. of generating those instructions here, we invent a new instruction
  5681. that means ``pop the frame and then do an indirect jump'', which we
  5682. name \code{tail-jmp}.
  5683. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5684. using the label \code{start} for the initial block of a program, and
  5685. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5686. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5687. can be compiled to an assignment to \code{rax} followed by a jump to
  5688. \code{conclusion}. With the addition of function definitions, we will
  5689. have a starting block and conclusion for each function, but their
  5690. labels need to be unique. We recommend prepending the function's name
  5691. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5692. labels. (Alternatively, one could \code{gensym} labels for the start
  5693. and conclusion and store them in the $\itm{info}$ field of the
  5694. function definition.)
  5695. \section{Uncover Live}
  5696. %% The rest of the passes need only minor modifications to handle the new
  5697. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5698. %% \code{leaq}.
  5699. Inside \code{uncover-live}, when computing the $W$ set (written
  5700. variables) for an \code{indirect-callq} instruction, we recommend
  5701. including all the caller-saved registers, which will have the affect
  5702. of making sure that no caller-saved register actually needs to be
  5703. saved.
  5704. \section{Build Interference Graph}
  5705. With the addition of function definitions, we compute an interference
  5706. graph for each function (not just one for the whole program).
  5707. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5708. spill vector-typed variables that are live during a call to the
  5709. \code{collect}. With the addition of functions to our language, we
  5710. need to revisit this issue. Many functions will perform allocation and
  5711. therefore have calls to the collector inside of them. Thus, we should
  5712. not only spill a vector-typed variable when it is live during a call
  5713. to \code{collect}, but we should spill the variable if it is live
  5714. during any function call. Thus, in the \code{build-interference} pass,
  5715. we recommend adding interference edges between call-live vector-typed
  5716. variables and the callee-saved registers (in addition to the usual
  5717. addition of edges between call-live variables and the caller-saved
  5718. registers).
  5719. \section{Patch Instructions}
  5720. In \code{patch-instructions}, you should deal with the x86
  5721. idiosyncrasy that the destination argument of \code{leaq} must be a
  5722. register. Additionally, you should ensure that the argument of
  5723. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5724. code generation more convenient, because we will be trampling many
  5725. registers before the tail call (as explained below).
  5726. \section{Print x86}
  5727. For the \code{print-x86} pass, we recommend the following translations:
  5728. \begin{lstlisting}
  5729. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5730. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5731. \end{lstlisting}
  5732. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5733. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5734. is what we will want to do, but before the jump we need to pop the
  5735. current frame. So we need to restore the state of the registers to the
  5736. point they were at when the current function was called. This
  5737. sequence of instructions is the same as the code for the conclusion of
  5738. a function.
  5739. Note that your \code{print-x86} pass needs to add the code for saving
  5740. and restoring callee-saved registers, if you have not already
  5741. implemented that. This is necessary when generating code for function
  5742. definitions.
  5743. \section{An Example Translation}
  5744. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5745. function in $R_4$ to x86. The figure also includes the results of the
  5746. \code{explicate-control} and \code{select-instructions} passes. We
  5747. have omitted the \code{has-type} AST nodes for readability. Can you
  5748. see any ways to improve the translation?
  5749. \begin{figure}[tbp]
  5750. \begin{tabular}{ll}
  5751. \begin{minipage}{0.45\textwidth}
  5752. % s3_2.rkt
  5753. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5754. (program
  5755. (define (add [x : Integer]
  5756. [y : Integer])
  5757. : Integer (+ x y))
  5758. (add 40 2))
  5759. \end{lstlisting}
  5760. $\Downarrow$
  5761. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5762. (program ()
  5763. (define (add86 [x87 : Integer]
  5764. [y88 : Integer]) : Integer ()
  5765. ((add86start . (return (+ x87 y88)))))
  5766. (define (main) : Integer ()
  5767. ((mainstart .
  5768. (seq (assign tmp89 (fun-ref add86))
  5769. (tailcall tmp89 40 2))))))
  5770. \end{lstlisting}
  5771. \end{minipage}
  5772. &
  5773. $\Rightarrow$
  5774. \begin{minipage}{0.5\textwidth}
  5775. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5776. (program ()
  5777. (define (add86)
  5778. ((locals (x87 . Integer) (y88 . Integer))
  5779. (num-params . 2))
  5780. ((add86start .
  5781. (block ()
  5782. (movq (reg rcx) (var x87))
  5783. (movq (reg rdx) (var y88))
  5784. (movq (var x87) (reg rax))
  5785. (addq (var y88) (reg rax))
  5786. (jmp add86conclusion)))))
  5787. (define (main)
  5788. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5789. (num-params . 0))
  5790. ((mainstart .
  5791. (block ()
  5792. (leaq (fun-ref add86) (var tmp89))
  5793. (movq (int 40) (reg rcx))
  5794. (movq (int 2) (reg rdx))
  5795. (tail-jmp (var tmp89))))))
  5796. \end{lstlisting}
  5797. $\Downarrow$
  5798. \end{minipage}
  5799. \end{tabular}
  5800. \begin{tabular}{lll}
  5801. \begin{minipage}{0.3\textwidth}
  5802. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5803. _add90start:
  5804. movq %rcx, %rsi
  5805. movq %rdx, %rcx
  5806. movq %rsi, %rax
  5807. addq %rcx, %rax
  5808. jmp _add90conclusion
  5809. .globl _add90
  5810. .align 16
  5811. _add90:
  5812. pushq %rbp
  5813. movq %rsp, %rbp
  5814. pushq %r12
  5815. pushq %rbx
  5816. pushq %r13
  5817. pushq %r14
  5818. subq $0, %rsp
  5819. jmp _add90start
  5820. _add90conclusion:
  5821. addq $0, %rsp
  5822. popq %r14
  5823. popq %r13
  5824. popq %rbx
  5825. popq %r12
  5826. subq $0, %r15
  5827. popq %rbp
  5828. retq
  5829. \end{lstlisting}
  5830. \end{minipage}
  5831. &
  5832. \begin{minipage}{0.3\textwidth}
  5833. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5834. _mainstart:
  5835. leaq _add90(%rip), %rsi
  5836. movq $40, %rcx
  5837. movq $2, %rdx
  5838. movq %rsi, %rax
  5839. addq $0, %rsp
  5840. popq %r14
  5841. popq %r13
  5842. popq %rbx
  5843. popq %r12
  5844. subq $0, %r15
  5845. popq %rbp
  5846. jmp *%rax
  5847. .globl _main
  5848. .align 16
  5849. _main:
  5850. pushq %rbp
  5851. movq %rsp, %rbp
  5852. pushq %r12
  5853. pushq %rbx
  5854. pushq %r13
  5855. pushq %r14
  5856. subq $0, %rsp
  5857. movq $16384, %rdi
  5858. movq $16, %rsi
  5859. callq _initialize
  5860. movq _rootstack_begin(%rip), %r15
  5861. jmp _mainstart
  5862. \end{lstlisting}
  5863. \end{minipage}
  5864. &
  5865. \begin{minipage}{0.3\textwidth}
  5866. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5867. _mainconclusion:
  5868. addq $0, %rsp
  5869. popq %r14
  5870. popq %r13
  5871. popq %rbx
  5872. popq %r12
  5873. subq $0, %r15
  5874. popq %rbp
  5875. retq
  5876. \end{lstlisting}
  5877. \end{minipage}
  5878. \end{tabular}
  5879. \caption{Example compilation of a simple function to x86.}
  5880. \label{fig:add-fun}
  5881. \end{figure}
  5882. \begin{exercise}\normalfont
  5883. Expand your compiler to handle $R_4$ as outlined in this chapter.
  5884. Create 5 new programs that use functions, including examples that pass
  5885. functions and return functions from other functions and including
  5886. recursive functions. Test your compiler on these new programs and all
  5887. of your previously created test programs.
  5888. \end{exercise}
  5889. \begin{figure}[p]
  5890. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5891. \node (R4) at (0,2) {\large $R_4$};
  5892. \node (R4-2) at (3,2) {\large $R_4$};
  5893. \node (R4-3) at (6,2) {\large $R_4$};
  5894. \node (F1-1) at (12,0) {\large $F_1$};
  5895. \node (F1-2) at (9,0) {\large $F_1$};
  5896. \node (F1-3) at (6,0) {\large $F_1$};
  5897. \node (F1-4) at (3,0) {\large $F_1$};
  5898. \node (C3-1) at (6,-2) {\large $C_3$};
  5899. \node (C3-2) at (3,-2) {\large $C_3$};
  5900. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5901. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5902. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5903. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  5904. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5905. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5906. \path[->,bend left=15] (R4) edge [above] node
  5907. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  5908. \path[->,bend left=15] (R4-2) edge [above] node
  5909. {\ttfamily\footnotesize uniquify} (R4-3);
  5910. \path[->,bend left=15] (R4-3) edge [right] node
  5911. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  5912. \path[->,bend left=15] (F1-1) edge [below] node
  5913. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  5914. \path[->,bend right=15] (F1-2) edge [above] node
  5915. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  5916. \path[->,bend right=15] (F1-3) edge [above] node
  5917. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  5918. \path[->,bend left=15] (F1-4) edge [right] node
  5919. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  5920. \path[->,bend left=15] (C3-1) edge [below] node
  5921. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  5922. \path[->,bend right=15] (C3-2) edge [left] node
  5923. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5924. \path[->,bend left=15] (x86-2) edge [left] node
  5925. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5926. \path[->,bend right=15] (x86-2-1) edge [below] node
  5927. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5928. \path[->,bend right=15] (x86-2-2) edge [left] node
  5929. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5930. \path[->,bend left=15] (x86-3) edge [above] node
  5931. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  5932. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5933. \end{tikzpicture}
  5934. \caption{Diagram of the passes for $R_4$, a language with functions.}
  5935. \label{fig:R4-passes}
  5936. \end{figure}
  5937. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  5938. the compilation of $R_4$.
  5939. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5940. \chapter{Lexically Scoped Functions}
  5941. \label{ch:lambdas}
  5942. This chapter studies lexically scoped functions as they appear in
  5943. functional languages such as Racket. By lexical scoping we mean that a
  5944. function's body may refer to variables whose binding site is outside
  5945. of the function, in an enclosing scope.
  5946. %
  5947. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5948. anonymous function defined using the \key{lambda} form. The body of
  5949. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5950. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5951. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5952. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5953. returned from the function \code{f}. Below the definition of \code{f},
  5954. we have two calls to \code{f} with different arguments for \code{x},
  5955. first \code{5} then \code{3}. The functions returned from \code{f} are
  5956. bound to variables \code{g} and \code{h}. Even though these two
  5957. functions were created by the same \code{lambda}, they are really
  5958. different functions because they use different values for
  5959. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5960. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5961. the result of this program is \code{42}.
  5962. \begin{figure}[btp]
  5963. % s4_6.rkt
  5964. \begin{lstlisting}
  5965. (define (f [x : Integer]) : (Integer -> Integer)
  5966. (let ([y 4])
  5967. (lambda: ([z : Integer]) : Integer
  5968. (+ x (+ y z)))))
  5969. (let ([g (f 5)])
  5970. (let ([h (f 3)])
  5971. (+ (g 11) (h 15))))
  5972. \end{lstlisting}
  5973. \caption{Example of a lexically scoped function.}
  5974. \label{fig:lexical-scoping}
  5975. \end{figure}
  5976. \section{The $R_5$ Language}
  5977. The syntax for this language with anonymous functions and lexical
  5978. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5979. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5980. for function application. In this chapter we shall describe how to
  5981. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5982. into a combination of functions (as in $R_4$) and tuples (as in
  5983. $R_3$).
  5984. \begin{figure}[tp]
  5985. \centering
  5986. \fbox{
  5987. \begin{minipage}{0.96\textwidth}
  5988. \[
  5989. \begin{array}{lcl}
  5990. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5991. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5992. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5993. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5994. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  5995. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  5996. &\mid& \gray{\key{\#t} \mid \key{\#f}
  5997. \mid (\key{and}\;\Exp\;\Exp)
  5998. \mid (\key{or}\;\Exp\;\Exp)
  5999. \mid (\key{not}\;\Exp) } \\
  6000. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6001. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6002. (\key{vector-ref}\;\Exp\;\Int)} \\
  6003. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6004. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6005. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6006. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6007. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6008. \end{array}
  6009. \]
  6010. \end{minipage}
  6011. }
  6012. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6013. with \key{lambda}.}
  6014. \label{fig:r5-syntax}
  6015. \end{figure}
  6016. To compile lexically-scoped functions to top-level function
  6017. definitions, the compiler will need to provide special treatment to
  6018. variable occurrences such as \code{x} and \code{y} in the body of the
  6019. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6020. of $R_4$ may not refer to variables defined outside the function. To
  6021. identify such variable occurrences, we review the standard notion of
  6022. free variable.
  6023. \begin{definition}
  6024. A variable is \emph{free with respect to an expression} $e$ if the
  6025. variable occurs inside $e$ but does not have an enclosing binding in
  6026. $e$.
  6027. \end{definition}
  6028. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6029. free with respect to the expression \code{(+ x (+ y z))}. On the
  6030. other hand, only \code{x} and \code{y} are free with respect to the
  6031. following expression because \code{z} is bound by the \code{lambda}.
  6032. \begin{lstlisting}
  6033. (lambda: ([z : Integer]) : Integer
  6034. (+ x (+ y z)))
  6035. \end{lstlisting}
  6036. Once we have identified the free variables of a \code{lambda}, we need
  6037. to arrange for some way to transport, at runtime, the values of those
  6038. variables from the point where the \code{lambda} was created to the
  6039. point where the \code{lambda} is applied. Referring again to
  6040. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6041. needs to be used in the application of \code{g} to \code{11}, but the
  6042. binding of \code{x} to \code{3} needs to be used in the application of
  6043. \code{h} to \code{15}. An efficient solution to the problem, due to
  6044. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6045. free variables together with the function pointer for the lambda's
  6046. code, an arrangement called a \emph{flat closure} (which we shorten to
  6047. just ``closure'') . Fortunately, we have all the ingredients to make
  6048. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6049. Chapter~\ref{ch:functions} gave us function pointers. The function
  6050. pointer shall reside at index $0$ and the values for free variables
  6051. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6052. the two closures created by the two calls to \code{f} in
  6053. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6054. the same \key{lambda}, they share the same function pointer but differ
  6055. in the values for the free variable \code{x}.
  6056. \begin{figure}[tbp]
  6057. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6058. \caption{Example closure representation for the \key{lambda}'s
  6059. in Figure~\ref{fig:lexical-scoping}.}
  6060. \label{fig:closures}
  6061. \end{figure}
  6062. \section{Interpreting $R_5$}
  6063. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6064. $R_5$. The clause for \key{lambda} saves the current environment
  6065. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6066. the environment from the \key{lambda}, the \code{lam-env}, when
  6067. interpreting the body of the \key{lambda}. The \code{lam-env}
  6068. environment is extended with the mapping of parameters to argument
  6069. values.
  6070. \begin{figure}[tbp]
  6071. \begin{lstlisting}
  6072. (define (interp-exp env)
  6073. (lambda (e)
  6074. (define recur (interp-exp env))
  6075. (match e
  6076. ...
  6077. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6078. `(lambda ,xs ,body ,env)]
  6079. [`(app ,fun ,args ...)
  6080. (define fun-val ((interp-exp env) fun))
  6081. (define arg-vals (map (interp-exp env) args))
  6082. (match fun-val
  6083. [`(lambda (,xs ...) ,body ,lam-env)
  6084. (define new-env (append (map cons xs arg-vals) lam-env))
  6085. ((interp-exp new-env) body)]
  6086. [else (error "interp-exp, expected function, not" fun-val)])]
  6087. [else (error 'interp-exp "unrecognized expression")]
  6088. )))
  6089. \end{lstlisting}
  6090. \caption{Interpreter for $R_5$.}
  6091. \label{fig:interp-R5}
  6092. \end{figure}
  6093. \section{Type Checking $R_5$}
  6094. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6095. \key{lambda} form. The body of the \key{lambda} is checked in an
  6096. environment that includes the current environment (because it is
  6097. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6098. require the body's type to match the declared return type.
  6099. \begin{figure}[tbp]
  6100. \begin{lstlisting}
  6101. (define (typecheck-R5 env)
  6102. (lambda (e)
  6103. (match e
  6104. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6105. (define new-env (append (map cons xs Ts) env))
  6106. (define bodyT ((typecheck-R5 new-env) body))
  6107. (cond [(equal? rT bodyT)
  6108. `(,@Ts -> ,rT)]
  6109. [else
  6110. (error "mismatch in return type" bodyT rT)])]
  6111. ...
  6112. )))
  6113. \end{lstlisting}
  6114. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6115. \label{fig:typecheck-R5}
  6116. \end{figure}
  6117. \section{Closure Conversion}
  6118. The compiling of lexically-scoped functions into top-level function
  6119. definitions is accomplished in the pass \code{convert-to-closures}
  6120. that comes after \code{reveal-functions} and before
  6121. \code{limit-functions}.
  6122. As usual, we shall implement the pass as a recursive function over the
  6123. AST. All of the action is in the clauses for \key{lambda} and
  6124. \key{app}. We transform a \key{lambda} expression into an expression
  6125. that creates a closure, that is, creates a vector whose first element
  6126. is a function pointer and the rest of the elements are the free
  6127. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6128. generated to identify the function.
  6129. \begin{tabular}{lll}
  6130. \begin{minipage}{0.4\textwidth}
  6131. \begin{lstlisting}
  6132. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6133. \end{lstlisting}
  6134. \end{minipage}
  6135. &
  6136. $\Rightarrow$
  6137. &
  6138. \begin{minipage}{0.4\textwidth}
  6139. \begin{lstlisting}
  6140. (vector |\itm{name}| |\itm{fvs}| ...)
  6141. \end{lstlisting}
  6142. \end{minipage}
  6143. \end{tabular} \\
  6144. %
  6145. In addition to transforming each \key{lambda} into a \key{vector}, we
  6146. must create a top-level function definition for each \key{lambda}, as
  6147. shown below.\\
  6148. \begin{minipage}{0.8\textwidth}
  6149. \begin{lstlisting}
  6150. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6151. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6152. ...
  6153. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6154. |\itm{body'}|)...))
  6155. \end{lstlisting}
  6156. \end{minipage}\\
  6157. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6158. parameters are the normal parameters of the \key{lambda}. The types
  6159. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6160. underscore is a dummy type because it is rather difficult to give a
  6161. type to the function in the closure's type, and it does not matter.
  6162. The sequence of \key{let} forms bind the free variables to their
  6163. values obtained from the closure.
  6164. We transform function application into code that retrieves the
  6165. function pointer from the closure and then calls the function, passing
  6166. in the closure as the first argument. We bind $e'$ to a temporary
  6167. variable to avoid code duplication.
  6168. \begin{tabular}{lll}
  6169. \begin{minipage}{0.3\textwidth}
  6170. \begin{lstlisting}
  6171. (app |$e$| |\itm{es}| ...)
  6172. \end{lstlisting}
  6173. \end{minipage}
  6174. &
  6175. $\Rightarrow$
  6176. &
  6177. \begin{minipage}{0.5\textwidth}
  6178. \begin{lstlisting}
  6179. (let ([|\itm{tmp}| |$e'$|])
  6180. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6181. \end{lstlisting}
  6182. \end{minipage}
  6183. \end{tabular} \\
  6184. There is also the question of what to do with top-level function
  6185. definitions. To maintain a uniform translation of function
  6186. application, we turn function references into closures.
  6187. \begin{tabular}{lll}
  6188. \begin{minipage}{0.3\textwidth}
  6189. \begin{lstlisting}
  6190. (fun-ref |$f$|)
  6191. \end{lstlisting}
  6192. \end{minipage}
  6193. &
  6194. $\Rightarrow$
  6195. &
  6196. \begin{minipage}{0.5\textwidth}
  6197. \begin{lstlisting}
  6198. (vector (fun-ref |$f$|))
  6199. \end{lstlisting}
  6200. \end{minipage}
  6201. \end{tabular} \\
  6202. %
  6203. The top-level function definitions need to be updated as well to take
  6204. an extra closure parameter.
  6205. \section{An Example Translation}
  6206. \label{sec:example-lambda}
  6207. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6208. conversion for the example program demonstrating lexical scoping that
  6209. we discussed at the beginning of this chapter.
  6210. \begin{figure}[h]
  6211. \begin{minipage}{0.8\textwidth}
  6212. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6213. (program
  6214. (define (f [x : Integer]) : (Integer -> Integer)
  6215. (let ([y 4])
  6216. (lambda: ([z : Integer]) : Integer
  6217. (+ x (+ y z)))))
  6218. (let ([g (f 5)])
  6219. (let ([h (f 3)])
  6220. (+ (g 11) (h 15)))))
  6221. \end{lstlisting}
  6222. $\Downarrow$
  6223. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6224. (program (type Integer)
  6225. (define (f (x : Integer)) : (Integer -> Integer)
  6226. (let ((y 4))
  6227. (lambda: ((z : Integer)) : Integer
  6228. (+ x (+ y z)))))
  6229. (let ((g (app (fun-ref f) 5)))
  6230. (let ((h (app (fun-ref f) 3)))
  6231. (+ (app g 11) (app h 15)))))
  6232. \end{lstlisting}
  6233. $\Downarrow$
  6234. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6235. (program (type Integer)
  6236. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6237. (let ((y 4))
  6238. (vector (fun-ref lam.1) x y)))
  6239. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6240. (let ((x (vector-ref clos.2 1)))
  6241. (let ((y (vector-ref clos.2 2)))
  6242. (+ x (+ y z)))))
  6243. (let ((g (let ((t.1 (vector (fun-ref f))))
  6244. (app (vector-ref t.1 0) t.1 5))))
  6245. (let ((h (let ((t.2 (vector (fun-ref f))))
  6246. (app (vector-ref t.2 0) t.2 3))))
  6247. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6248. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6249. \end{lstlisting}
  6250. \end{minipage}
  6251. \caption{Example of closure conversion.}
  6252. \label{fig:lexical-functions-example}
  6253. \end{figure}
  6254. \begin{figure}[p]
  6255. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6256. \node (R4) at (0,2) {\large $R_4$};
  6257. \node (R4-2) at (3,2) {\large $R_4$};
  6258. \node (R4-3) at (6,2) {\large $R_4$};
  6259. \node (F1-1) at (12,0) {\large $F_1$};
  6260. \node (F1-2) at (9,0) {\large $F_1$};
  6261. \node (F1-3) at (6,0) {\large $F_1$};
  6262. \node (F1-4) at (3,0) {\large $F_1$};
  6263. \node (F1-5) at (0,0) {\large $F_1$};
  6264. \node (C3-1) at (6,-2) {\large $C_3$};
  6265. \node (C3-2) at (3,-2) {\large $C_3$};
  6266. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6267. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6268. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6269. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6270. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6271. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6272. \path[->,bend left=15] (R4) edge [above] node
  6273. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6274. \path[->,bend left=15] (R4-2) edge [above] node
  6275. {\ttfamily\footnotesize uniquify} (R4-3);
  6276. \path[->] (R4-3) edge [right] node
  6277. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6278. \path[->,bend left=15] (F1-1) edge [below] node
  6279. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6280. \path[->,bend right=15] (F1-2) edge [above] node
  6281. {\ttfamily\footnotesize limit-functions} (F1-3);
  6282. \path[->,bend right=15] (F1-3) edge [above] node
  6283. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6284. \path[->,bend right=15] (F1-4) edge [above] node
  6285. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6286. \path[->] (F1-5) edge [left] node
  6287. {\ttfamily\footnotesize explicate-control} (C3-1);
  6288. \path[->,bend left=15] (C3-1) edge [below] node
  6289. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6290. \path[->,bend right=15] (C3-2) edge [left] node
  6291. {\ttfamily\footnotesize select-instr.} (x86-2);
  6292. \path[->,bend left=15] (x86-2) edge [left] node
  6293. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6294. \path[->,bend right=15] (x86-2-1) edge [below] node
  6295. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6296. \path[->,bend right=15] (x86-2-2) edge [left] node
  6297. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6298. \path[->,bend left=15] (x86-3) edge [above] node
  6299. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6300. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6301. \end{tikzpicture}
  6302. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6303. functions.}
  6304. \label{fig:R5-passes}
  6305. \end{figure}
  6306. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6307. for the compilation of $R_5$.
  6308. \begin{exercise}\normalfont
  6309. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6310. Create 5 new programs that use \key{lambda} functions and make use of
  6311. lexical scoping. Test your compiler on these new programs and all of
  6312. your previously created test programs.
  6313. \end{exercise}
  6314. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6315. \chapter{Dynamic Typing}
  6316. \label{ch:type-dynamic}
  6317. In this chapter we discuss the compilation of a dynamically typed
  6318. language, named $R_7$, that is a subset of the Racket
  6319. language. (Recall that in the previous chapters we have studied
  6320. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6321. languages, an expression may produce values of differing
  6322. type. Consider the following example with a conditional expression
  6323. that may return a Boolean or an integer depending on the input to the
  6324. program.
  6325. \begin{lstlisting}
  6326. (not (if (eq? (read) 1) #f 0))
  6327. \end{lstlisting}
  6328. Languages that allow expressions to produce different kinds of values
  6329. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6330. such as subtype polymorphism and parametric
  6331. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6332. talking about here does not have a special name, but it is the usual
  6333. kind that arises in dynamically typed languages.
  6334. Another characteristic of dynamically typed languages is that
  6335. primitive operations, such as \code{not}, are often defined to operate
  6336. on many different types of values. In fact, in Racket, the \code{not}
  6337. operator produces a result for any kind of value: given \code{\#f} it
  6338. returns \code{\#t} and given anything else it returns \code{\#f}.
  6339. Furthermore, even when primitive operations restrict their inputs to
  6340. values of a certain type, this restriction is enforced at runtime
  6341. instead of during compilation. For example, the following vector
  6342. reference results in a run-time contract violation.
  6343. \begin{lstlisting}
  6344. (vector-ref (vector 42) #t)
  6345. \end{lstlisting}
  6346. \begin{figure}[tp]
  6347. \centering
  6348. \fbox{
  6349. \begin{minipage}{0.97\textwidth}
  6350. \[
  6351. \begin{array}{rcl}
  6352. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6353. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6354. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6355. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6356. &\mid& \key{\#t} \mid \key{\#f}
  6357. \mid (\key{and}\;\Exp\;\Exp)
  6358. \mid (\key{or}\;\Exp\;\Exp)
  6359. \mid (\key{not}\;\Exp) \\
  6360. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6361. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6362. (\key{vector-ref}\;\Exp\;\Exp) \\
  6363. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6364. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6365. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6366. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6367. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6368. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6369. \end{array}
  6370. \]
  6371. \end{minipage}
  6372. }
  6373. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6374. \label{fig:r7-syntax}
  6375. \end{figure}
  6376. The syntax of $R_7$, our subset of Racket, is defined in
  6377. Figure~\ref{fig:r7-syntax}.
  6378. %
  6379. The definitional interpreter for $R_7$ is given in
  6380. Figure~\ref{fig:interp-R7}.
  6381. \begin{figure}[tbp]
  6382. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6383. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6384. (define (valid-op? op) (member op '(+ - and or not)))
  6385. (define (interp-r7 env)
  6386. (lambda (ast)
  6387. (define recur (interp-r7 env))
  6388. (match ast
  6389. [(? symbol?) (lookup ast env)]
  6390. [(? integer?) `(inject ,ast Integer)]
  6391. [#t `(inject #t Boolean)]
  6392. [#f `(inject #f Boolean)]
  6393. [`(read) `(inject ,(read-fixnum) Integer)]
  6394. [`(lambda (,xs ...) ,body)
  6395. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6396. [`(define (,f ,xs ...) ,body)
  6397. (mcons f `(lambda ,xs ,body))]
  6398. [`(program ,ds ... ,body)
  6399. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6400. (for/list ([b top-level])
  6401. (set-mcdr! b (match (mcdr b)
  6402. [`(lambda ,xs ,body)
  6403. `(inject (lambda ,xs ,body ,top-level)
  6404. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6405. ((interp-r7 top-level) body))]
  6406. [`(vector ,(app recur elts) ...)
  6407. (define tys (map get-tagged-type elts))
  6408. `(inject ,(apply vector elts) (Vector ,@tys))]
  6409. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6410. (match v1
  6411. [`(inject ,vec ,ty)
  6412. (vector-set! vec n v2)
  6413. `(inject (void) Void)])]
  6414. [`(vector-ref ,(app recur v) ,n)
  6415. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6416. [`(let ([,x ,(app recur v)]) ,body)
  6417. ((interp-r7 (cons (cons x v) env)) body)]
  6418. [`(,op ,es ...) #:when (valid-op? op)
  6419. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6420. [`(eq? ,(app recur l) ,(app recur r))
  6421. `(inject ,(equal? l r) Boolean)]
  6422. [`(if ,(app recur q) ,t ,f)
  6423. (match q
  6424. [`(inject #f Boolean) (recur f)]
  6425. [else (recur t)])]
  6426. [`(,(app recur f-val) ,(app recur vs) ...)
  6427. (match f-val
  6428. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6429. (define new-env (append (map cons xs vs) lam-env))
  6430. ((interp-r7 new-env) body)]
  6431. [else (error "interp-r7, expected function, not" f-val)])])))
  6432. \end{lstlisting}
  6433. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6434. \label{fig:interp-R7}
  6435. \end{figure}
  6436. Let us consider how we might compile $R_7$ to x86, thinking about the
  6437. first example above. Our bit-level representation of the Boolean
  6438. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6439. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6440. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6441. general, cannot be determined at compile time, but depends on the
  6442. runtime type of its input, as in the example above that depends on the
  6443. result of \code{(read)}.
  6444. The way around this problem is to include information about a value's
  6445. runtime type in the value itself, so that this information can be
  6446. inspected by operators such as \code{not}. In particular, we shall
  6447. steal the 3 right-most bits from our 64-bit values to encode the
  6448. runtime type. We shall use $001$ to identify integers, $100$ for
  6449. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6450. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6451. define the following auxiliary function.
  6452. \begin{align*}
  6453. \itm{tagof}(\key{Integer}) &= 001 \\
  6454. \itm{tagof}(\key{Boolean}) &= 100 \\
  6455. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6456. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6457. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6458. \itm{tagof}(\key{Void}) &= 101
  6459. \end{align*}
  6460. (We shall say more about the new \key{Vectorof} type shortly.)
  6461. This stealing of 3 bits comes at some
  6462. price: our integers are reduced to ranging from $-2^{60}$ to
  6463. $2^{60}$. The stealing does not adversely affect vectors and
  6464. procedures because those values are addresses, and our addresses are
  6465. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6466. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6467. bits with the tag and we can simply zero-out the tag to recover the
  6468. original address.
  6469. In some sense, these tagged values are a new kind of value. Indeed,
  6470. we can extend our \emph{typed} language with tagged values by adding a
  6471. new type to classify them, called \key{Any}, and with operations for
  6472. creating and using tagged values, yielding the $R_6$ language that we
  6473. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6474. fundamental support for polymorphism and runtime types that we need to
  6475. support dynamic typing.
  6476. There is an interesting interaction between tagged values and garbage
  6477. collection. A variable of type \code{Any} might refer to a vector and
  6478. therefore it might be a root that needs to be inspected and copied
  6479. during garbage collection. Thus, we need to treat variables of type
  6480. \code{Any} in a similar way to variables of type \code{Vector} for
  6481. purposes of register allocation, which we discuss in
  6482. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6483. variable of type \code{Any} is spilled, it must be spilled to the root
  6484. stack. But this means that the garbage collector needs to be able to
  6485. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6486. value that points to a tuple, and (3) a tagged value that is not a
  6487. tuple. We enable this differentiation by choosing not to use the tag
  6488. $000$. Instead, that bit pattern is reserved for identifying plain old
  6489. pointers to tuples. On the other hand, if one of the first three bits
  6490. is set, then we have a tagged value, and inspecting the tag can
  6491. differentiation between vectors ($010$) and the other kinds of values.
  6492. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6493. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6494. extend our compiler to handle the new features of $R_6$
  6495. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6496. \ref{sec:register-allocation-r6}).
  6497. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6498. \label{sec:r6-lang}
  6499. \begin{figure}[tp]
  6500. \centering
  6501. \fbox{
  6502. \begin{minipage}{0.97\textwidth}
  6503. \[
  6504. \begin{array}{lcl}
  6505. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6506. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6507. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6508. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6509. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6510. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6511. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6512. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6513. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6514. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6515. \mid (\key{and}\;\Exp\;\Exp)
  6516. \mid (\key{or}\;\Exp\;\Exp)
  6517. \mid (\key{not}\;\Exp)} \\
  6518. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6519. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6520. (\key{vector-ref}\;\Exp\;\Int)} \\
  6521. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6522. &\mid& \gray{(\Exp \; \Exp^{*})
  6523. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6524. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6525. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6526. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6527. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6528. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6529. \end{array}
  6530. \]
  6531. \end{minipage}
  6532. }
  6533. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6534. with \key{Any}.}
  6535. \label{fig:r6-syntax}
  6536. \end{figure}
  6537. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6538. $(\key{inject}\; e\; T)$ form converts the value produced by
  6539. expression $e$ of type $T$ into a tagged value. The
  6540. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6541. expression $e$ into a value of type $T$ or else halts the program if
  6542. the type tag is equivalent to $T$. We treat
  6543. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6544. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6545. Note that in both \key{inject} and
  6546. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6547. which simplifies the implementation and corresponds with what is
  6548. needed for compiling untyped Racket. The type predicates,
  6549. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6550. if the tag corresponds to the predicate, and return \key{\#t}
  6551. otherwise.
  6552. %
  6553. Selections from the type checker for $R_6$ are shown in
  6554. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6555. Figure~\ref{fig:interp-R6}.
  6556. \begin{figure}[btp]
  6557. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6558. (define (flat-ty? ty) ...)
  6559. (define (typecheck-R6 env)
  6560. (lambda (e)
  6561. (define recur (typecheck-R6 env))
  6562. (match e
  6563. [`(inject ,e ,ty)
  6564. (unless (flat-ty? ty)
  6565. (error "may only inject a value of flat type, not ~a" ty))
  6566. (define-values (new-e e-ty) (recur e))
  6567. (cond
  6568. [(equal? e-ty ty)
  6569. (values `(inject ,new-e ,ty) 'Any)]
  6570. [else
  6571. (error "inject expected ~a to have type ~a" e ty)])]
  6572. [`(project ,e ,ty)
  6573. (unless (flat-ty? ty)
  6574. (error "may only project to a flat type, not ~a" ty))
  6575. (define-values (new-e e-ty) (recur e))
  6576. (cond
  6577. [(equal? e-ty 'Any)
  6578. (values `(project ,new-e ,ty) ty)]
  6579. [else
  6580. (error "project expected ~a to have type Any" e)])]
  6581. [`(vector-ref ,e ,i)
  6582. (define-values (new-e e-ty) (recur e))
  6583. (match e-ty
  6584. [`(Vector ,ts ...) ...]
  6585. [`(Vectorof ,ty)
  6586. (unless (exact-nonnegative-integer? i)
  6587. (error 'type-check "invalid index ~a" i))
  6588. (values `(vector-ref ,new-e ,i) ty)]
  6589. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6590. ...
  6591. )))
  6592. \end{lstlisting}
  6593. \caption{Type checker for parts of the $R_6$ language.}
  6594. \label{fig:typecheck-R6}
  6595. \end{figure}
  6596. % to do: add rules for vector-ref, etc. for Vectorof
  6597. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6598. \begin{figure}[btp]
  6599. \begin{lstlisting}
  6600. (define primitives (set 'boolean? ...))
  6601. (define (interp-op op)
  6602. (match op
  6603. ['boolean? (lambda (v)
  6604. (match v
  6605. [`(tagged ,v1 Boolean) #t]
  6606. [else #f]))]
  6607. ...))
  6608. ;; Equivalence of flat types
  6609. (define (tyeq? t1 t2)
  6610. (match `(,t1 ,t2)
  6611. [`((Vectorof Any) (Vector ,t2s ...))
  6612. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6613. [`((Vector ,t1s ...) (Vectorof Any))
  6614. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6615. [else (equal? t1 t2)]))
  6616. (define (interp-R6 env)
  6617. (lambda (ast)
  6618. (match ast
  6619. [`(inject ,e ,t)
  6620. `(tagged ,((interp-R6 env) e) ,t)]
  6621. [`(project ,e ,t2)
  6622. (define v ((interp-R6 env) e))
  6623. (match v
  6624. [`(tagged ,v1 ,t1)
  6625. (cond [(tyeq? t1 t2)
  6626. v1]
  6627. [else
  6628. (error "in project, type mismatch" t1 t2)])]
  6629. [else
  6630. (error "in project, expected tagged value" v)])]
  6631. ...)))
  6632. \end{lstlisting}
  6633. \caption{Interpreter for $R_6$.}
  6634. \label{fig:interp-R6}
  6635. \end{figure}
  6636. %\clearpage
  6637. \section{Shrinking $R_6$}
  6638. \label{sec:shrink-r6}
  6639. In the \code{shrink} pass we recommend compiling \code{project} into
  6640. an explicit \code{if} expression that uses three new operations:
  6641. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6642. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6643. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6644. value from a tagged value. Finally, the \code{exit} operation ends the
  6645. execution of the program by invoking the operating system's
  6646. \code{exit} function. So the translation for \code{project} is as
  6647. follows. (We have omitted the \code{has-type} AST nodes to make this
  6648. output more readable.)
  6649. \begin{tabular}{lll}
  6650. \begin{minipage}{0.3\textwidth}
  6651. \begin{lstlisting}
  6652. (project |$e$| |$\Type$|)
  6653. \end{lstlisting}
  6654. \end{minipage}
  6655. &
  6656. $\Rightarrow$
  6657. &
  6658. \begin{minipage}{0.5\textwidth}
  6659. \begin{lstlisting}
  6660. (let ([|$\itm{tmp}$| |$e'$|])
  6661. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6662. (value-of-any |$\itm{tmp}$|)
  6663. (exit)))
  6664. \end{lstlisting}
  6665. \end{minipage}
  6666. \end{tabular} \\
  6667. Similarly, we recommend translating the type predicates
  6668. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6669. \section{Instruction Selection for $R_6$}
  6670. \label{sec:select-r6}
  6671. \paragraph{Inject}
  6672. We recommend compiling an \key{inject} as follows if the type is
  6673. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6674. destination to the left by the number of bits specified its source
  6675. argument (in this case $3$, the length of the tag) and it preserves
  6676. the sign of the integer. We use the \key{orq} instruction to combine
  6677. the tag and the value to form the tagged value. \\
  6678. \begin{tabular}{lll}
  6679. \begin{minipage}{0.4\textwidth}
  6680. \begin{lstlisting}
  6681. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6682. \end{lstlisting}
  6683. \end{minipage}
  6684. &
  6685. $\Rightarrow$
  6686. &
  6687. \begin{minipage}{0.5\textwidth}
  6688. \begin{lstlisting}
  6689. (movq |$e'$| |\itm{lhs}'|)
  6690. (salq (int 3) |\itm{lhs}'|)
  6691. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6692. \end{lstlisting}
  6693. \end{minipage}
  6694. \end{tabular} \\
  6695. The instruction selection for vectors and procedures is different
  6696. because their is no need to shift them to the left. The rightmost 3
  6697. bits are already zeros as described above. So we just combine the
  6698. value and the tag using \key{orq}. \\
  6699. \begin{tabular}{lll}
  6700. \begin{minipage}{0.4\textwidth}
  6701. \begin{lstlisting}
  6702. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6703. \end{lstlisting}
  6704. \end{minipage}
  6705. &
  6706. $\Rightarrow$
  6707. &
  6708. \begin{minipage}{0.5\textwidth}
  6709. \begin{lstlisting}
  6710. (movq |$e'$| |\itm{lhs}'|)
  6711. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6712. \end{lstlisting}
  6713. \end{minipage}
  6714. \end{tabular}
  6715. \paragraph{Tag of Any}
  6716. Recall that the \code{tag-of-any} operation extracts the type tag from
  6717. a value of type \code{Any}. The type tag is the bottom three bits, so
  6718. we obtain the tag by taking the bitwise-and of the value with $111$
  6719. ($7$ in decimal).
  6720. \begin{tabular}{lll}
  6721. \begin{minipage}{0.4\textwidth}
  6722. \begin{lstlisting}
  6723. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6724. \end{lstlisting}
  6725. \end{minipage}
  6726. &
  6727. $\Rightarrow$
  6728. &
  6729. \begin{minipage}{0.5\textwidth}
  6730. \begin{lstlisting}
  6731. (movq |$e'$| |\itm{lhs}'|)
  6732. (andq (int 7) |\itm{lhs}'|)
  6733. \end{lstlisting}
  6734. \end{minipage}
  6735. \end{tabular}
  6736. \paragraph{Value of Any}
  6737. Like \key{inject}, the instructions for \key{value-of-any} are
  6738. different depending on whether the type $T$ is a pointer (vector or
  6739. procedure) or not (Integer or Boolean). The following shows the
  6740. instruction selection for Integer and Boolean. We produce an untagged
  6741. value by shifting it to the right by 3 bits.
  6742. %
  6743. \\
  6744. \begin{tabular}{lll}
  6745. \begin{minipage}{0.4\textwidth}
  6746. \begin{lstlisting}
  6747. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6748. \end{lstlisting}
  6749. \end{minipage}
  6750. &
  6751. $\Rightarrow$
  6752. &
  6753. \begin{minipage}{0.5\textwidth}
  6754. \begin{lstlisting}
  6755. (movq |$e'$| |\itm{lhs}'|)
  6756. (sarq (int 3) |\itm{lhs}'|)
  6757. \end{lstlisting}
  6758. \end{minipage}
  6759. \end{tabular} \\
  6760. %
  6761. In the case for vectors and procedures, there is no need to
  6762. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6763. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6764. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6765. \code{movq} into the destination $\itm{lhs}$. We then generate
  6766. \code{andq} with the tagged value to get the desired result. \\
  6767. %
  6768. \begin{tabular}{lll}
  6769. \begin{minipage}{0.4\textwidth}
  6770. \begin{lstlisting}
  6771. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6772. \end{lstlisting}
  6773. \end{minipage}
  6774. &
  6775. $\Rightarrow$
  6776. &
  6777. \begin{minipage}{0.5\textwidth}
  6778. \begin{lstlisting}
  6779. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6780. (andq |$e'$| |\itm{lhs}'|)
  6781. \end{lstlisting}
  6782. \end{minipage}
  6783. \end{tabular}
  6784. %% \paragraph{Type Predicates} We leave it to the reader to
  6785. %% devise a sequence of instructions to implement the type predicates
  6786. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6787. \section{Register Allocation for $R_6$}
  6788. \label{sec:register-allocation-r6}
  6789. As mentioned above, a variable of type \code{Any} might refer to a
  6790. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6791. of type \code{Any} in the same way that it treats variables of type
  6792. \code{Vector} for purposes of garbage collection. In particular,
  6793. \begin{itemize}
  6794. \item If a variable of type \code{Any} is live during a function call,
  6795. then it must be spilled. One way to accomplish this is to augment
  6796. the pass \code{build-interference} to mark all variables that are
  6797. live after a \code{callq} as interfering with all the registers.
  6798. \item If a variable of type \code{Any} is spilled, it must be spilled
  6799. to the root stack instead of the normal procedure call stack.
  6800. \end{itemize}
  6801. \begin{exercise}\normalfont
  6802. Expand your compiler to handle $R_6$ as discussed in the last few
  6803. sections. Create 5 new programs that use the \code{Any} type and the
  6804. new operations (\code{inject}, \code{project}, \code{boolean?},
  6805. etc.). Test your compiler on these new programs and all of your
  6806. previously created test programs.
  6807. \end{exercise}
  6808. \section{Compiling $R_7$ to $R_6$}
  6809. \label{sec:compile-r7}
  6810. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6811. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6812. given a subexpression $e$ of $R_7$, the pass will produce an
  6813. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6814. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6815. the Boolean \code{\#t}, which must be injected to produce an
  6816. expression of type \key{Any}.
  6817. %
  6818. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6819. addition, is representative of compilation for many operations: the
  6820. arguments have type \key{Any} and must be projected to \key{Integer}
  6821. before the addition can be performed.
  6822. The compilation of \key{lambda} (third row of
  6823. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6824. produce type annotations: we simply use \key{Any}.
  6825. %
  6826. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  6827. has to account for some differences in behavior between $R_7$ and
  6828. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  6829. kind of values can be used in various places. For example, the
  6830. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  6831. the arguments need not be of the same type (but in that case, the
  6832. result will be \code{\#f}).
  6833. \begin{figure}[btp]
  6834. \centering
  6835. \begin{tabular}{|lll|} \hline
  6836. \begin{minipage}{0.25\textwidth}
  6837. \begin{lstlisting}
  6838. #t
  6839. \end{lstlisting}
  6840. \end{minipage}
  6841. &
  6842. $\Rightarrow$
  6843. &
  6844. \begin{minipage}{0.6\textwidth}
  6845. \begin{lstlisting}
  6846. (inject #t Boolean)
  6847. \end{lstlisting}
  6848. \end{minipage}
  6849. \\[2ex]\hline
  6850. \begin{minipage}{0.25\textwidth}
  6851. \begin{lstlisting}
  6852. (+ |$e_1$| |$e_2$|)
  6853. \end{lstlisting}
  6854. \end{minipage}
  6855. &
  6856. $\Rightarrow$
  6857. &
  6858. \begin{minipage}{0.6\textwidth}
  6859. \begin{lstlisting}
  6860. (inject
  6861. (+ (project |$e'_1$| Integer)
  6862. (project |$e'_2$| Integer))
  6863. Integer)
  6864. \end{lstlisting}
  6865. \end{minipage}
  6866. \\[2ex]\hline
  6867. \begin{minipage}{0.25\textwidth}
  6868. \begin{lstlisting}
  6869. (lambda (|$x_1 \ldots$|) |$e$|)
  6870. \end{lstlisting}
  6871. \end{minipage}
  6872. &
  6873. $\Rightarrow$
  6874. &
  6875. \begin{minipage}{0.6\textwidth}
  6876. \begin{lstlisting}
  6877. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  6878. (Any|$\ldots$|Any -> Any))
  6879. \end{lstlisting}
  6880. \end{minipage}
  6881. \\[2ex]\hline
  6882. \begin{minipage}{0.25\textwidth}
  6883. \begin{lstlisting}
  6884. (app |$e_0$| |$e_1 \ldots e_n$|)
  6885. \end{lstlisting}
  6886. \end{minipage}
  6887. &
  6888. $\Rightarrow$
  6889. &
  6890. \begin{minipage}{0.6\textwidth}
  6891. \begin{lstlisting}
  6892. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6893. |$e'_1 \ldots e'_n$|)
  6894. \end{lstlisting}
  6895. \end{minipage}
  6896. \\[2ex]\hline
  6897. \begin{minipage}{0.25\textwidth}
  6898. \begin{lstlisting}
  6899. (vector-ref |$e_1$| |$e_2$|)
  6900. \end{lstlisting}
  6901. \end{minipage}
  6902. &
  6903. $\Rightarrow$
  6904. &
  6905. \begin{minipage}{0.6\textwidth}
  6906. \begin{lstlisting}
  6907. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6908. (let ([tmp2 (project |$e'_2$| Integer)])
  6909. (vector-ref tmp1 tmp2)))
  6910. \end{lstlisting}
  6911. \end{minipage}
  6912. \\[2ex]\hline
  6913. \begin{minipage}{0.25\textwidth}
  6914. \begin{lstlisting}
  6915. (if |$e_1$| |$e_2$| |$e_3$|)
  6916. \end{lstlisting}
  6917. \end{minipage}
  6918. &
  6919. $\Rightarrow$
  6920. &
  6921. \begin{minipage}{0.6\textwidth}
  6922. \begin{lstlisting}
  6923. (if (eq? |$e'_1$| (inject #f Boolean))
  6924. |$e'_3$|
  6925. |$e'_2$|)
  6926. \end{lstlisting}
  6927. \end{minipage}
  6928. \\[2ex]\hline
  6929. \begin{minipage}{0.25\textwidth}
  6930. \begin{lstlisting}
  6931. (eq? |$e_1$| |$e_2$|)
  6932. \end{lstlisting}
  6933. \end{minipage}
  6934. &
  6935. $\Rightarrow$
  6936. &
  6937. \begin{minipage}{0.6\textwidth}
  6938. \begin{lstlisting}
  6939. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6940. \end{lstlisting}
  6941. \end{minipage}
  6942. \\[2ex]\hline
  6943. \end{tabular}
  6944. \caption{Compiling $R_7$ to $R_6$.}
  6945. \label{fig:compile-r7-r6}
  6946. \end{figure}
  6947. \begin{exercise}\normalfont
  6948. Expand your compiler to handle $R_7$ as outlined in this chapter.
  6949. Create tests for $R_7$ by adapting all of your previous test programs
  6950. by removing type annotations. Add 5 more tests programs that
  6951. specifically rely on the language being dynamically typed. That is,
  6952. they should not be legal programs in a statically typed language, but
  6953. nevertheless, they should be valid $R_7$ programs that run to
  6954. completion without error.
  6955. \end{exercise}
  6956. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6957. \chapter{Gradual Typing}
  6958. \label{ch:gradual-typing}
  6959. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  6960. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6961. \chapter{Parametric Polymorphism}
  6962. \label{ch:parametric-polymorphism}
  6963. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  6964. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  6965. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6966. \chapter{High-level Optimization}
  6967. \label{ch:high-level-optimization}
  6968. This chapter will present a procedure inlining pass based on the
  6969. algorithm of \citet{Waddell:1997fk}.
  6970. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6971. \chapter{Appendix}
  6972. \section{Interpreters}
  6973. \label{appendix:interp}
  6974. We provide several interpreters in the \key{interp.rkt} file. The
  6975. \key{interp-scheme} function takes an AST in one of the Racket-like
  6976. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  6977. the program, returning the result value. The \key{interp-C} function
  6978. interprets an AST for a program in one of the C-like languages ($C_0,
  6979. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  6980. for an x86 program.
  6981. \section{Utility Functions}
  6982. \label{appendix:utilities}
  6983. The utility function described in this section can be found in the
  6984. \key{utilities.rkt} file.
  6985. The \key{read-program} function takes a file path and parses that file
  6986. (it must be a Racket program) into an abstract syntax tree (as an
  6987. S-expression) with a \key{program} AST at the top.
  6988. The \key{assert} function displays the error message \key{msg} if the
  6989. Boolean \key{bool} is false.
  6990. \begin{lstlisting}
  6991. (define (assert msg bool) ...)
  6992. \end{lstlisting}
  6993. The \key{lookup} function takes a key and an association list (a list
  6994. of key-value pairs), and returns the first value that is associated
  6995. with the given key, if there is one. If not, an error is triggered.
  6996. The association list may contain both immutable pairs (built with
  6997. \key{cons}) and mutable pairs (built with \key{mcons}).
  6998. The \key{map2} function ...
  6999. %% \subsection{Graphs}
  7000. %% \begin{itemize}
  7001. %% \item The \code{make-graph} function takes a list of vertices
  7002. %% (symbols) and returns a graph.
  7003. %% \item The \code{add-edge} function takes a graph and two vertices and
  7004. %% adds an edge to the graph that connects the two vertices. The graph
  7005. %% is updated in-place. There is no return value for this function.
  7006. %% \item The \code{adjacent} function takes a graph and a vertex and
  7007. %% returns the set of vertices that are adjacent to the given
  7008. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7009. %% used with functions from the \code{racket/set} module.
  7010. %% \item The \code{vertices} function takes a graph and returns the list
  7011. %% of vertices in the graph.
  7012. %% \end{itemize}
  7013. \subsection{Testing}
  7014. The \key{interp-tests} function takes a compiler name (a string), a
  7015. description of the passes, an interpreter for the source language, a
  7016. test family name (a string), and a list of test numbers, and runs the
  7017. compiler passes and the interpreters to check whether the passes
  7018. correct. The description of the passes is a list with one entry per
  7019. pass. An entry is a list with three things: a string giving the name
  7020. of the pass, the function that implements the pass (a translator from
  7021. AST to AST), and a function that implements the interpreter (a
  7022. function from AST to result value) for the language of the output of
  7023. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7024. good choice. The \key{interp-tests} function assumes that the
  7025. subdirectory \key{tests} has a collection of Scheme programs whose names
  7026. all start with the family name, followed by an underscore and then the
  7027. test number, ending in \key{.scm}. Also, for each Scheme program there
  7028. is a file with the same number except that it ends with \key{.in} that
  7029. provides the input for the Scheme program.
  7030. \begin{lstlisting}
  7031. (define (interp-tests name passes test-family test-nums) ...)
  7032. \end{lstlisting}
  7033. The compiler-tests function takes a compiler name (a string) a
  7034. description of the passes (as described above for
  7035. \code{interp-tests}), a test family name (a string), and a list of
  7036. test numbers (see the comment for interp-tests), and runs the compiler
  7037. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7038. machine code. It runs the machine code and checks that the output is
  7039. 42.
  7040. \begin{lstlisting}
  7041. (define (compiler-tests name passes test-family test-nums) ...)
  7042. \end{lstlisting}
  7043. The compile-file function takes a description of the compiler passes
  7044. (see the comment for \key{interp-tests}) and returns a function that,
  7045. given a program file name (a string ending in \key{.scm}), applies all
  7046. of the passes and writes the output to a file whose name is the same
  7047. as the program file name but with \key{.scm} replaced with \key{.s}.
  7048. \begin{lstlisting}
  7049. (define (compile-file passes)
  7050. (lambda (prog-file-name) ...))
  7051. \end{lstlisting}
  7052. \section{x86 Instruction Set Quick-Reference}
  7053. \label{sec:x86-quick-reference}
  7054. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7055. do. We write $A \to B$ to mean that the value of $A$ is written into
  7056. location $B$. Address offsets are given in bytes. The instruction
  7057. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7058. registers (such as $\%rax$), or memory references (such as
  7059. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7060. reference per instruction. Other operands must be immediates or
  7061. registers.
  7062. \begin{table}[tbp]
  7063. \centering
  7064. \begin{tabular}{l|l}
  7065. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7066. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7067. \texttt{negq} $A$ & $- A \to A$ \\
  7068. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7069. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7070. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7071. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7072. \texttt{retq} & Pops the return address and jumps to it \\
  7073. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7074. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7075. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7076. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7077. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7078. matches the condition code of the instruction, otherwise go to the
  7079. next instructions. The condition codes are \key{e} for ``equal'',
  7080. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7081. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7082. \texttt{jl} $L$ & \\
  7083. \texttt{jle} $L$ & \\
  7084. \texttt{jg} $L$ & \\
  7085. \texttt{jge} $L$ & \\
  7086. \texttt{jmp} $L$ & Jump to label $L$ \\
  7087. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7088. \texttt{movzbq} $A$, $B$ &
  7089. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7090. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7091. and the extra bytes of $B$ are set to zero.} \\
  7092. & \\
  7093. & \\
  7094. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7095. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7096. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7097. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7098. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7099. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7100. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7101. description of the condition codes. $A$ must be a single byte register
  7102. (e.g., \texttt{al} or \texttt{cl}).} \\
  7103. \texttt{setl} $A$ & \\
  7104. \texttt{setle} $A$ & \\
  7105. \texttt{setg} $A$ & \\
  7106. \texttt{setge} $A$ &
  7107. \end{tabular}
  7108. \vspace{5pt}
  7109. \caption{Quick-reference for the x86 instructions used in this book.}
  7110. \label{tab:x86-instr}
  7111. \end{table}
  7112. \bibliographystyle{plainnat}
  7113. \bibliography{all}
  7114. \end{document}
  7115. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7116. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7117. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7118. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7119. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7120. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7121. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7122. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7123. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7124. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7125. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7126. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7127. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7128. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7129. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7130. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7131. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7132. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7133. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7134. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7135. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7136. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7137. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7138. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7139. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7140. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7141. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7142. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7143. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7144. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7145. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge