book.tex 288 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * alternative back ends (ARM, LLVM)
  5. %% * lazy evaluation
  6. %% * gradual typing
  7. %% * continuations, exceptions
  8. %% * self hosting
  9. %% * I/O
  10. %% * foreign function interface
  11. %% * quasi-quote and unquote
  12. %% * macros (perhaps too difficult?)
  13. %% * alternative garbage collector
  14. %% * alternative register allocator
  15. %% * parametric polymorphism
  16. %% * type classes (perhaps too difficulty?)
  17. %% * loops (too easy? combine with something else?)
  18. %% * loop optimization
  19. %% * records and subtyping
  20. %% * object-oriented features
  21. %% - objects, object types, and structural subtyping (e.g. Abadi and Cardelli)
  22. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  23. %% * multi-threading, fork join, futures, implicit parallelism
  24. %% * dataflow analysis, type analysis and specialization
  25. \documentclass[11pt]{book}
  26. \usepackage[T1]{fontenc}
  27. \usepackage[utf8]{inputenc}
  28. \usepackage{lmodern}
  29. \usepackage{hyperref}
  30. \usepackage{graphicx}
  31. \usepackage[english]{babel}
  32. \usepackage{listings}
  33. \usepackage{amsmath}
  34. \usepackage{amsthm}
  35. \usepackage{amssymb}
  36. \usepackage{natbib}
  37. \usepackage{stmaryrd}
  38. \usepackage{xypic}
  39. \usepackage{semantic}
  40. \usepackage{wrapfig}
  41. \usepackage{multirow}
  42. \usepackage{color}
  43. \definecolor{lightgray}{gray}{1}
  44. \newcommand{\black}[1]{{\color{black} #1}}
  45. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  46. %% For pictures
  47. \usepackage{tikz}
  48. \usetikzlibrary{arrows.meta}
  49. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  50. % Computer Modern is already the default. -Jeremy
  51. %\renewcommand{\ttdefault}{cmtt}
  52. \definecolor{comment-red}{rgb}{0.8,0,0}
  53. \if{0}
  54. % Peanut gallery comments:
  55. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  56. \newcommand{\margincomment}[1]{\marginpar{#1}}
  57. \else
  58. \newcommand{\rn}[1]{}
  59. \newcommand{\margincomment}[1]{}
  60. \fi
  61. \lstset{%
  62. language=Lisp,
  63. basicstyle=\ttfamily\small,
  64. escapechar=|,
  65. columns=flexible,
  66. moredelim=[is][\color{red}]{~}{~}
  67. }
  68. \newtheorem{theorem}{Theorem}
  69. \newtheorem{lemma}[theorem]{Lemma}
  70. \newtheorem{corollary}[theorem]{Corollary}
  71. \newtheorem{proposition}[theorem]{Proposition}
  72. \newtheorem{constraint}[theorem]{Constraint}
  73. \newtheorem{definition}[theorem]{Definition}
  74. \newtheorem{exercise}[theorem]{Exercise}
  75. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  76. % 'dedication' environment: To add a dedication paragraph at the start of book %
  77. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  78. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  79. \newenvironment{dedication}
  80. {
  81. \cleardoublepage
  82. \thispagestyle{empty}
  83. \vspace*{\stretch{1}}
  84. \hfill\begin{minipage}[t]{0.66\textwidth}
  85. \raggedright
  86. }
  87. {
  88. \end{minipage}
  89. \vspace*{\stretch{3}}
  90. \clearpage
  91. }
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. % Chapter quote at the start of chapter %
  94. % Source: http://tex.stackexchange.com/a/53380 %
  95. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  96. \makeatletter
  97. \renewcommand{\@chapapp}{}% Not necessary...
  98. \newenvironment{chapquote}[2][2em]
  99. {\setlength{\@tempdima}{#1}%
  100. \def\chapquote@author{#2}%
  101. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  102. \itshape}
  103. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  104. \makeatother
  105. \input{defs}
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \title{\Huge \textbf{Essentials of Compilation} \\
  108. \huge An Incremental Approach}
  109. \author{\textsc{Jeremy G. Siek, Ryan R. Newton} \\
  110. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  111. Indiana University \\
  112. \\
  113. with contributions from: \\
  114. Carl Factora \\
  115. Andre Kuhlenschmidt \\
  116. Michael M. Vitousek \\
  117. Michael Vollmer \\
  118. Ryan Scott \\
  119. Cameron Swords
  120. }
  121. \begin{document}
  122. \frontmatter
  123. \maketitle
  124. \begin{dedication}
  125. This book is dedicated to the programming language wonks at Indiana
  126. University.
  127. \end{dedication}
  128. \tableofcontents
  129. \listoffigures
  130. %\listoftables
  131. \mainmatter
  132. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  133. \chapter*{Preface}
  134. The tradition of compiler writing at Indiana University goes back to
  135. research and courses about programming languages by Daniel Friedman in
  136. the 1970's and 1980's. Dan had conducted research on lazy
  137. evaluation~\citep{Friedman:1976aa} in the context of
  138. Lisp~\citep{McCarthy:1960dz} and then studied
  139. continuations~\citep{Felleisen:kx} and
  140. macros~\citep{Kohlbecker:1986dk} in the context of the
  141. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  142. of those courses, Kent Dybvig, went on to build Chez
  143. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  144. compiler for Scheme. After completing his Ph.D. at the University of
  145. North Carolina, Kent returned to teach at Indiana University.
  146. Throughout the 1990's and 2000's, Kent continued development of Chez
  147. Scheme and taught the compiler course.
  148. The compiler course evolved to incorporate novel pedagogical ideas
  149. while also including elements of effective real-world compilers. One
  150. of Dan's ideas was to split the compiler into many small ``passes'' so
  151. that the code for each pass would be easy to understood in isolation.
  152. (In contrast, most compilers of the time were organized into only a
  153. few monolithic passes for reasons of compile-time efficiency.) Kent,
  154. with later help from his students Dipanwita Sarkar and Andrew Keep,
  155. developed infrastructure to support this approach and evolved the
  156. course, first to use micro-sized passes and then into even smaller
  157. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  158. student in this compiler course in the early 2000's, as part of his
  159. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  160. the course immensely!
  161. One of Jeremy's classmates, Abdulaziz Ghuloum, observed that the
  162. front-to-back organization of the course made it difficult for
  163. students to understand the rationale for the compiler
  164. design. Abdulaziz proposed an incremental approach in which the
  165. students build the compiler in stages; they start by implementing a
  166. complete compiler for a very small subset of the input language, then
  167. in each subsequent stage they add a feature to the input language and
  168. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  169. In this way, the students see how the language features motivate
  170. aspects of the compiler design.
  171. After graduating from Indiana University in 2005, Jeremy went on to
  172. teach at the University of Colorado. He adapted the nano pass and
  173. incremental approaches to compiling a subset of the Python
  174. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  175. on the surface but there is a large overlap in the compiler techniques
  176. required for the two languages. Thus, Jeremy was able to teach much of
  177. the same content from the Indiana compiler course. He very much
  178. enjoyed teaching the course organized in this way, and even better,
  179. many of the students learned a lot and got excited about compilers.
  180. Jeremy returned to teach at Indiana University in 2013. In his
  181. absence the compiler course had switched from the front-to-back
  182. organization to a back-to-front organization. Seeing how well the
  183. incremental approach worked at Colorado, he started porting and
  184. adapting the structure of the Colorado course back into the land of
  185. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  186. the course is now about compiling a subset of Racket (and Typed
  187. Racket) to the x86 assembly language. The compiler is implemented in
  188. Racket 7.1~\citep{plt-tr}.
  189. This is the textbook for the incremental version of the compiler
  190. course at Indiana University (Spring 2016 - present) and it is the
  191. first open textbook for an Indiana compiler course. With this book we
  192. hope to make the Indiana compiler course available to people that have
  193. not had the chance to study in Bloomington in person. Many of the
  194. compiler design decisions in this book are drawn from the assignment
  195. descriptions of \cite{Dybvig:2010aa}. We have captured what we think are
  196. the most important topics from \cite{Dybvig:2010aa} but we have omitted
  197. topics that we think are less interesting conceptually and we have made
  198. simplifications to reduce complexity. In this way, this book leans
  199. more towards pedagogy than towards the absolute efficiency of the
  200. generated code. Also, the book differs in places where we saw the
  201. opportunity to make the topics more fun, such as in relating register
  202. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  203. \section*{Prerequisites}
  204. The material in this book is challenging but rewarding. It is meant to
  205. prepare students for a lifelong career in programming languages. We do
  206. not recommend this book for students who want to dabble in programming
  207. languages.
  208. The book uses the Racket language both for the implementation of the
  209. compiler and for the language that is compiled, so a student should be
  210. proficient with Racket (or Scheme) prior to reading this book. There
  211. are many other excellent resources for learning Scheme and
  212. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  213. is helpful but not necessary for the student to have prior exposure to
  214. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  215. obtain from a computer systems
  216. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  217. parts of x86-64 assembly language that are needed.
  218. %\section*{Structure of book}
  219. % You might want to add short description about each chapter in this book.
  220. %\section*{About the companion website}
  221. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  222. %\begin{itemize}
  223. % \item A link to (freely downlodable) latest version of this document.
  224. % \item Link to download LaTeX source for this document.
  225. % \item Miscellaneous material (e.g. suggested readings etc).
  226. %\end{itemize}
  227. \section*{Acknowledgments}
  228. Many people have contributed to the ideas, techniques, organization,
  229. and teaching of the materials in this book. We especially thank the
  230. following people.
  231. \begin{itemize}
  232. \item Bor-Yuh Evan Chang
  233. \item Kent Dybvig
  234. \item Daniel P. Friedman
  235. \item Ronald Garcia
  236. \item Abdulaziz Ghuloum
  237. \item Jay McCarthy
  238. \item Dipanwita Sarkar
  239. \item Andrew Keep
  240. \item Oscar Waddell
  241. \item Michael Wollowski
  242. \end{itemize}
  243. \mbox{}\\
  244. \noindent Jeremy G. Siek \\
  245. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  246. %\noindent Spring 2016
  247. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  248. \chapter{Preliminaries}
  249. \label{ch:trees-recur}
  250. In this chapter, we review the basic tools that are needed for implementing a
  251. compiler. We use abstract syntax trees (ASTs), which refer to data structures in
  252. the compilers memory, rather than programs as they are stored on disk, in
  253. \emph{concrete syntax}.
  254. %
  255. ASTs can be represented in many different ways, depending on the programming
  256. language used to write the compiler.
  257. %
  258. Because this book uses Racket (\url{http://racket-lang.org}), a
  259. descendant of Lisp, we use S-expressions to represent programs
  260. (Section~\ref{sec:ast}). We use grammars to defined programming languages
  261. (Section~\ref{sec:grammar}) and pattern matching to inspect
  262. individual nodes in an AST (Section~\ref{sec:pattern-matching}). We
  263. use recursion to construct and deconstruct entire ASTs
  264. (Section~\ref{sec:recursion}). This chapter provides an brief
  265. introduction to these ideas.
  266. \section{Abstract Syntax Trees and S-expressions}
  267. \label{sec:ast}
  268. The primary data structure that is commonly used for representing
  269. programs is the \emph{abstract syntax tree} (AST). When considering
  270. some part of a program, a compiler needs to ask what kind of part it
  271. is and what sub-parts it has. For example, the program on the left,
  272. represented by an S-expression, corresponds to the AST on the right.
  273. \begin{center}
  274. \begin{minipage}{0.4\textwidth}
  275. \begin{lstlisting}
  276. (+ (read) (- 8))
  277. \end{lstlisting}
  278. \end{minipage}
  279. \begin{minipage}{0.4\textwidth}
  280. \begin{equation}
  281. \begin{tikzpicture}
  282. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  283. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  284. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  285. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  286. \draw[->] (plus) to (read);
  287. \draw[->] (plus) to (minus);
  288. \draw[->] (minus) to (8);
  289. \end{tikzpicture}
  290. \label{eq:arith-prog}
  291. \end{equation}
  292. \end{minipage}
  293. \end{center}
  294. We shall use the standard terminology for trees: each circle above is
  295. called a \emph{node}. The arrows connect a node to its \emph{children}
  296. (which are also nodes). The top-most node is the \emph{root}. Every
  297. node except for the root has a \emph{parent} (the node it is the child
  298. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  299. it is an \emph{internal} node.
  300. Recall that an \emph{symbolic expression} (S-expression) is either
  301. \begin{enumerate}
  302. \item an atom, or
  303. \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  304. where $e_1$ and $e_2$ are each an S-expression.
  305. \end{enumerate}
  306. An \emph{atom} can be a symbol, such as \code{`hello}, a number, the null
  307. value \code{'()}, etc.
  308. We can create an S-expression in Racket simply by writing a backquote
  309. (called a quasi-quote in Racket).
  310. followed by the textual representation of the S-expression.
  311. It is quite common to use S-expressions
  312. to represent a list, such as $a, b ,c$ in the following way:
  313. \begin{lstlisting}
  314. `(a . (b . (c . ())))
  315. \end{lstlisting}
  316. Each element of the list is in the first slot of a pair, and the
  317. second slot is either the rest of the list or the null value, to mark
  318. the end of the list. Such lists are so common that Racket provides
  319. special notation for them that removes the need for the periods
  320. and so many parenthesis:
  321. \begin{lstlisting}
  322. `(a b c)
  323. \end{lstlisting}
  324. For another example,
  325. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  326. by the following Racket expression:
  327. \begin{center}
  328. \texttt{`(+ (read) (- 8))}
  329. \end{center}
  330. When using S-expressions to represent ASTs, the convention is to
  331. represent each AST node as a list and to put the operation symbol at
  332. the front of the list. The rest of the list contains the children. So
  333. in the above case, the root AST node has operation \code{`+} and its
  334. two children are \code{`(read)} and \code{`(- 8)}, just as in the
  335. diagram \eqref{eq:arith-prog}.
  336. To build larger S-expressions one often needs to splice together
  337. several smaller S-expressions. Racket provides the comma operator to
  338. splice an S-expression into a larger one. For example, instead of
  339. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  340. we could have first created an S-expression for AST
  341. \eqref{eq:arith-neg8} and then spliced that into the addition
  342. S-expression.
  343. \begin{lstlisting}
  344. (define ast1.4 `(- 8))
  345. (define ast1.1 `(+ (read) ,ast1.4))
  346. \end{lstlisting}
  347. In general, the Racket expression that follows the comma (splice)
  348. can be any expression that computes an S-expression.
  349. When deciding how to compile program \eqref{eq:arith-prog}, we need to
  350. know that the operation associated with the root node is addition and
  351. that it has two children: \texttt{read} and a negation. The AST data
  352. structure directly supports these queries, as we shall see in
  353. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  354. in compilers. In this book, we will often write down the S-expression
  355. representation of a program even when we really have in mind the AST
  356. because the S-expression is more concise. We recommend that, in your
  357. mind, you always think of programs as abstract syntax trees.
  358. \section{Grammars}
  359. \label{sec:grammar}
  360. A programming language can be thought of as a \emph{set} of programs.
  361. The set is typically infinite (one can always create larger and larger
  362. programs), so one cannot simply describe a language by listing all of
  363. the programs in the language. Instead we write down a set of rules, a
  364. \emph{grammar}, for building programs. We shall write our rules in a
  365. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  366. As an example, we describe a small language, named $R_0$, of
  367. integers and arithmetic operations. The first rule says that any
  368. integer is an expression, $\Exp$, in the language:
  369. \begin{equation}
  370. \Exp ::= \Int \label{eq:arith-int}
  371. \end{equation}
  372. %
  373. Each rule has a left-hand-side and a right-hand-side. The way to read
  374. a rule is that if you have all the program parts on the
  375. right-hand-side, then you can create an AST node and categorize it
  376. according to the left-hand-side.
  377. %
  378. A name such as $\Exp$ that is
  379. defined by the grammar rules is a \emph{non-terminal}.
  380. %
  381. The name $\Int$ is a also a non-terminal, however,
  382. we do not define $\Int$ because the
  383. reader already knows what an integer is.
  384. %
  385. Further, we make the simplifying design decision that all of the languages in
  386. this book only handle machine-representable integers. On most modern machines
  387. this corresponds to integers represented with 64-bits, i.e., the in range
  388. $-2^{63}$ to $2^{63}-1$.
  389. %
  390. However, we restrict this range further to match the Racket \texttt{fixnum}
  391. datatype, which allows 63-bit integers on a 64-bit machine.
  392. The second grammar rule is the \texttt{read} operation that receives
  393. an input integer from the user of the program.
  394. \begin{equation}
  395. \Exp ::= (\key{read}) \label{eq:arith-read}
  396. \end{equation}
  397. The third rule says that, given an $\Exp$ node, you can build another
  398. $\Exp$ node by negating it.
  399. \begin{equation}
  400. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  401. \end{equation}
  402. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  403. and must literally appear in the program for the rule to be
  404. applicable.
  405. We can apply the rules to build ASTs in the $R_0$
  406. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  407. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  408. an $\Exp$.
  409. \begin{center}
  410. \begin{minipage}{0.25\textwidth}
  411. \begin{lstlisting}
  412. (- 8)
  413. \end{lstlisting}
  414. \end{minipage}
  415. \begin{minipage}{0.25\textwidth}
  416. \begin{equation}
  417. \begin{tikzpicture}
  418. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  419. \node[draw, circle] (8) at (0, -1.2) {$8$};
  420. \draw[->] (minus) to (8);
  421. \end{tikzpicture}
  422. \label{eq:arith-neg8}
  423. \end{equation}
  424. \end{minipage}
  425. \end{center}
  426. The following grammar rule defines addition expressions:
  427. \begin{equation}
  428. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  429. \end{equation}
  430. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  431. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  432. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  433. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  434. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  435. If you have an AST for which the above rules do not apply, then the
  436. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  437. not in $R_0$ because there are no rules for \key{+} with only one
  438. argument, nor for \key{-} with two arguments. Whenever we define a
  439. language with a grammar, we implicitly mean for the language to be the
  440. smallest set of programs that are justified by the rules. That is, the
  441. language only includes those programs that the rules allow.
  442. The last grammar rule for $R_0$ states that there is a \key{program}
  443. node to mark the top of the whole program:
  444. \[
  445. R_0 ::= (\key{program} \; \Exp)
  446. \]
  447. The \code{read-program} function provided in \code{utilities.rkt}
  448. reads programs in from a file (the sequence of characters in the
  449. concrete syntax of Racket) and parses them into the abstract syntax
  450. tree. The concrete syntax does not include a \key{program} form; that
  451. is added by the \code{read-program} function as it creates the
  452. AST. See the description of \code{read-program} in
  453. Appendix~\ref{appendix:utilities} for more details.
  454. It is common to have many rules with the same left-hand side, such as
  455. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  456. for gathering several rules, as shown in
  457. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  458. called an {\em alternative}.
  459. \begin{figure}[tp]
  460. \fbox{
  461. \begin{minipage}{0.96\textwidth}
  462. \[
  463. \begin{array}{rcl}
  464. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  465. (\key{+} \; \Exp \; \Exp) \\
  466. R_0 &::=& (\key{program} \; \Exp)
  467. \end{array}
  468. \]
  469. \end{minipage}
  470. }
  471. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  472. \label{fig:r0-syntax}
  473. \end{figure}
  474. \section{Pattern Matching}
  475. \label{sec:pattern-matching}
  476. As mentioned above, one of the operations that a compiler needs to
  477. perform on an AST is to access the children of a node. Racket
  478. provides the \texttt{match} form to access the parts of an
  479. S-expression. Consider the following example and the output on the
  480. right.
  481. \begin{center}
  482. \begin{minipage}{0.5\textwidth}
  483. \begin{lstlisting}
  484. (match ast1.1
  485. [`(,op ,child1 ,child2)
  486. (print op) (newline)
  487. (print child1) (newline)
  488. (print child2)])
  489. \end{lstlisting}
  490. \end{minipage}
  491. \vrule
  492. \begin{minipage}{0.25\textwidth}
  493. \begin{lstlisting}
  494. '+
  495. '(read)
  496. '(- 8)
  497. \end{lstlisting}
  498. \end{minipage}
  499. \end{center}
  500. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  501. parts to the three variables \texttt{op}, \texttt{child1}, and
  502. \texttt{child2}. In general, a match clause consists of a
  503. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  504. that may contain pattern-variables (each one preceded by a comma).
  505. %
  506. The pattern is not the same thing as a quasiquote expression used to
  507. \emph{construct} ASTs, however, the similarity is intentional: constructing and
  508. deconstructing ASTs uses similar syntax.
  509. %
  510. While the pattern uses a restricted syntax,
  511. the body of the match clause may contain any Racket code whatsoever.
  512. A \texttt{match} form may contain several clauses, as in the following
  513. function \texttt{leaf?} that recognizes when an $R_0$ node is
  514. a leaf. The \texttt{match} proceeds through the clauses in order,
  515. checking whether the pattern can match the input S-expression. The
  516. body of the first clause that matches is executed. The output of
  517. \texttt{leaf?} for several S-expressions is shown on the right. In the
  518. below \texttt{match}, we see another form of pattern: the \texttt{(?
  519. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  520. S-expression to see if it is a machine-representable integer.
  521. \begin{center}
  522. \begin{minipage}{0.5\textwidth}
  523. \begin{lstlisting}
  524. (define (leaf? arith)
  525. (match arith
  526. [(? fixnum?) #t]
  527. [`(read) #t]
  528. [`(- ,c1) #f]
  529. [`(+ ,c1 ,c2) #f]))
  530. (leaf? `(read))
  531. (leaf? `(- 8))
  532. (leaf? `(+ (read) (- 8)))
  533. \end{lstlisting}
  534. \end{minipage}
  535. \vrule
  536. \begin{minipage}{0.25\textwidth}
  537. \begin{lstlisting}
  538. #t
  539. #f
  540. #f
  541. \end{lstlisting}
  542. \end{minipage}
  543. \end{center}
  544. \section{Recursion}
  545. \label{sec:recursion}
  546. Programs are inherently recursive in that an $R_0$ expression ($\Exp$)
  547. is made up of smaller expressions. Thus, the natural way to process an
  548. entire program is with a recursive function. As a first example of
  549. such a function, we define \texttt{exp?} below, which takes an
  550. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  551. sexp} is an $R_0$ expression. Note that each match clause
  552. corresponds to one grammar rule the body of each clause makes a
  553. recursive call for each child node. This pattern of recursive function
  554. is so common that it has a name, \emph{structural recursion}. In
  555. general, when a recursive function is defined using a sequence of
  556. match clauses that correspond to a grammar, and each clause body makes
  557. a recursive call on each child node, then we say the function is
  558. defined by structural recursion. Below we also define a second
  559. function, named \code{R0?}, determines whether an S-expression is an
  560. $R_0$ program.
  561. %
  562. \begin{center}
  563. \begin{minipage}{0.7\textwidth}
  564. \begin{lstlisting}
  565. (define (exp? sexp)
  566. (match sexp
  567. [(? fixnum?) #t]
  568. [`(read) #t]
  569. [`(- ,e) (exp? e)]
  570. [`(+ ,e1 ,e2)
  571. (and (exp? e1) (exp? e2))]
  572. [else #f]))
  573. (define (R0? sexp)
  574. (match sexp
  575. [`(program ,e) (exp? e)]
  576. [else #f]))
  577. (R0? `(program (+ (read) (- 8))))
  578. (R0? `(program (- (read) (+ 8))))
  579. \end{lstlisting}
  580. \end{minipage}
  581. \vrule
  582. \begin{minipage}{0.25\textwidth}
  583. \begin{lstlisting}
  584. #t
  585. #f
  586. \end{lstlisting}
  587. \end{minipage}
  588. \end{center}
  589. Indeed, the structural recursion follows the grammar itself. We can
  590. generally expect to write a recursive function to handle each
  591. non-terminal in the grammar.\footnote{This principle of structuring
  592. code according to the data definition is advocated in the book
  593. \emph{How to Design Programs}
  594. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}
  595. You may be tempted to write the program with just one function, like this:
  596. \begin{center}
  597. \begin{minipage}{0.5\textwidth}
  598. \begin{lstlisting}
  599. (define (R0? sexp)
  600. (match sexp
  601. [(? fixnum?) #t]
  602. [`(read) #t]
  603. [`(- ,e) (R0? e)]
  604. [`(+ ,e1 ,e2) (and (R0? e1) (R0? e2))]
  605. [`(program ,e) (R0? e)]
  606. [else #f]))
  607. \end{lstlisting}
  608. \end{minipage}
  609. \end{center}
  610. %
  611. Sometimes such a trick will save a few lines of code, especially when it comes
  612. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  613. recommended because it can get you into trouble.
  614. %
  615. For instance, the above function is subtly wrong:
  616. \lstinline{(R0? `(program (program 3)))} will return true, when it
  617. should return false.
  618. %% NOTE FIXME - must check for consistency on this issue throughout.
  619. \section{Interpreters}
  620. \label{sec:interp-R0}
  621. The meaning, or semantics, of a program is typically defined in the
  622. specification of the language. For example, the Scheme language is
  623. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  624. defined in its reference manual~\citep{plt-tr}. In this book we use an
  625. interpreter to define the meaning of each language that we consider,
  626. following Reynold's advice in this
  627. regard~\citep{reynolds72:_def_interp}. Here we warm up by writing an
  628. interpreter for the $R_0$ language, which serves as a second example
  629. of structural recursion. The \texttt{interp-R0} function is defined in
  630. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  631. input program \texttt{p} and then a call to the \lstinline{interp-exp}
  632. helper function, which in turn has one match clause per grammar rule
  633. for $R_0$ expressions.
  634. \begin{figure}[tbp]
  635. \begin{lstlisting}
  636. (define (interp-exp e)
  637. (match e
  638. [(? fixnum?) e]
  639. [`(read)
  640. (let ([r (read)])
  641. (cond [(fixnum? r) r]
  642. [else (error 'interp-R0 "input not an integer" r)]))]
  643. [`(- ,e1) (fx- 0 (interp-exp e1))]
  644. [`(+ ,e1 ,e2) (fx+ (interp-exp e1) (interp-exp e2))]
  645. ))
  646. (define (interp-R0 p)
  647. (match p
  648. [`(program ,e) (interp-exp e)]))
  649. \end{lstlisting}
  650. \caption{Interpreter for the $R_0$ language.}
  651. \label{fig:interp-R0}
  652. \end{figure}
  653. Let us consider the result of interpreting a few $R_0$ programs. The
  654. following program simply adds two integers.
  655. \begin{lstlisting}
  656. (+ 10 32)
  657. \end{lstlisting}
  658. The result is \key{42}, as you might have expected. Here we have written the
  659. program in concrete syntax, whereas the parsed abstract syntax would be the
  660. slightly different: \lstinline{(program (+ 10 32))}.
  661. The next example demonstrates that expressions may be nested within
  662. each other, in this case nesting several additions and negations.
  663. \begin{lstlisting}
  664. (+ 10 (- (+ 12 20)))
  665. \end{lstlisting}
  666. What is the result of the above program?
  667. As mentioned previously, the $R0$ language does not support
  668. arbitrarily-large integers, but only $63$-bit integers, so we
  669. interpret the arithmetic operations of $R0$ using fixnum arithmetic.
  670. What happens when we run the following program?
  671. \begin{lstlisting}
  672. (define large 999999999999999999)
  673. (interp-R0 `(program (+ (+ (+ ,large ,large) (+ ,large ,large))
  674. (+ (+ ,large ,large) (+ ,large ,large)))))
  675. \end{lstlisting}
  676. It produces an error:
  677. \begin{lstlisting}
  678. fx+: result is not a fixnum
  679. \end{lstlisting}
  680. We shall use the convention that if the interpreter for a language
  681. produces an error when run on a program, then the meaning of the
  682. program is unspecified. The compiler for the language is under no
  683. obligation for such a program; it can produce an executable that does
  684. anything.
  685. \noindent
  686. Moving on, the \key{read} operation prompts the user of the program
  687. for an integer. If we interpret the AST \eqref{eq:arith-prog} and give
  688. it the input \texttt{50}
  689. \begin{lstlisting}
  690. (interp-R0 ast1.1)
  691. \end{lstlisting}
  692. we get the answer to life, the universe, and everything:
  693. \begin{lstlisting}
  694. 42
  695. \end{lstlisting}
  696. We include the \key{read} operation in $R_0$ so a clever student
  697. cannot implement a compiler for $R_0$ simply by running the
  698. interpreter at compilation time to obtain the output and then
  699. generating the trivial code to return the output. (A clever student
  700. did this in a previous version of the course.)
  701. The job of a compiler is to translate a program in one language into a
  702. program in another language so that the output program behaves the
  703. same way as the input program. This idea is depicted in the following
  704. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  705. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  706. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  707. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  708. and $P_2$ on their respective interpreters with input $i$ should yield
  709. the same output $o$.
  710. \begin{equation} \label{eq:compile-correct}
  711. \begin{tikzpicture}[baseline=(current bounding box.center)]
  712. \node (p1) at (0, 0) {$P_1$};
  713. \node (p2) at (3, 0) {$P_2$};
  714. \node (o) at (3, -2.5) {$o$};
  715. \path[->] (p1) edge [above] node {compile} (p2);
  716. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  717. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  718. \end{tikzpicture}
  719. \end{equation}
  720. In the next section we see our first example of a compiler, which is
  721. another example of structural recursion.
  722. \section{Example Compiler: a Partial Evaluator}
  723. \label{sec:partial-evaluation}
  724. In this section we consider a compiler that translates $R_0$
  725. programs into $R_0$ programs that are more efficient, that is,
  726. this compiler is an optimizer. Our optimizer will accomplish this by
  727. trying to eagerly compute the parts of the program that do not depend
  728. on any inputs. For example, given the following program
  729. \begin{lstlisting}
  730. (+ (read) (- (+ 5 3)))
  731. \end{lstlisting}
  732. our compiler will translate it into the program
  733. \begin{lstlisting}
  734. (+ (read) -8)
  735. \end{lstlisting}
  736. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  737. evaluator for the $R_0$ language. The output of the partial evaluator
  738. is an $R_0$ program, which we build up using a combination of
  739. quasiquotes and commas. (Though no quasiquote is necessary for
  740. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  741. recursion is captured in the main \texttt{pe-arith} function whereas
  742. the code for partially evaluating negation and addition is factored
  743. into two separate helper functions: \texttt{pe-neg} and
  744. \texttt{pe-add}. The input to these helper functions is the output of
  745. partially evaluating the children nodes.
  746. \begin{figure}[tbp]
  747. \begin{lstlisting}
  748. (define (pe-neg r)
  749. (cond [(fixnum? r) (fx- 0 r)]
  750. [else `(- ,r)]))
  751. (define (pe-add r1 r2)
  752. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  753. [else `(+ ,r1 ,r2)]))
  754. (define (pe-arith e)
  755. (match e
  756. [(? fixnum?) e]
  757. [`(read) `(read)]
  758. [`(- ,e1)
  759. (pe-neg (pe-arith e1))]
  760. [`(+ ,e1 ,e2)
  761. (pe-add (pe-arith e1) (pe-arith e2))]))
  762. \end{lstlisting}
  763. \caption{A partial evaluator for $R_0$ expressions.}
  764. \label{fig:pe-arith}
  765. \end{figure}
  766. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  767. idea of checking whether their arguments are integers and if they are,
  768. to go ahead and perform the arithmetic. Otherwise, we use quasiquote
  769. to create an AST node for the appropriate operation (either negation
  770. or addition) and use comma to splice in the child nodes.
  771. To gain some confidence that the partial evaluator is correct, we can
  772. test whether it produces programs that get the same result as the
  773. input program. That is, we can test whether it satisfies Diagram
  774. \eqref{eq:compile-correct}. The following code runs the partial
  775. evaluator on several examples and tests the output program. The
  776. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  777. \begin{lstlisting}
  778. (define (test-pe p)
  779. (assert "testing pe-arith"
  780. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  781. (test-pe `(+ (read) (- (+ 5 3))))
  782. (test-pe `(+ 1 (+ (read) 1)))
  783. (test-pe `(- (+ (read) (- 5))))
  784. \end{lstlisting}
  785. \rn{Do we like the explicit whitespace? I've never been fond of it, in part
  786. because it breaks copy/pasting. But, then again, so do most of the quotes.}
  787. \begin{exercise}
  788. \normalfont % I don't like the italics for exercises. -Jeremy
  789. We challenge the reader to improve on the simple partial evaluator in
  790. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  791. \texttt{pe-add} helper functions with functions that know more about
  792. arithmetic. For example, your partial evaluator should translate
  793. \begin{lstlisting}
  794. (+ 1 (+ (read) 1))
  795. \end{lstlisting}
  796. into
  797. \begin{lstlisting}
  798. (+ 2 (read))
  799. \end{lstlisting}
  800. To accomplish this, we recommend that your partial evaluator produce
  801. output that takes the form of the $\itm{residual}$ non-terminal in the
  802. following grammar.
  803. \[
  804. \begin{array}{lcl}
  805. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  806. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  807. \end{array}
  808. \]
  809. \end{exercise}
  810. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  811. \chapter{Integers and Variables}
  812. \label{ch:int-exp}
  813. This chapter concerns the challenge of compiling a subset of Racket
  814. that includes integer arithmetic and local variable binding, which we
  815. name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}. Henceforth
  816. we shall refer to x86-64 simply as x86. The chapter begins with a
  817. description of the $R_1$ language (Section~\ref{sec:s0}) followed by a
  818. description of x86 (Section~\ref{sec:x86}). The x86 assembly language
  819. is quite large, so we only discuss what is needed for compiling
  820. $R_1$. We introduce more of x86 in later chapters. Once we have
  821. introduced $R_1$ and x86, we reflect on their differences and come up
  822. with a plan to break down the translation from $R_1$ to x86 into a
  823. handful of steps (Section~\ref{sec:plan-s0-x86}). The rest of the
  824. sections in this Chapter give detailed hints regarding each step
  825. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  826. to give enough hints that the well-prepared reader can implement a
  827. compiler from $R_1$ to x86 while at the same time leaving room for
  828. some fun and creativity.
  829. \section{The $R_1$ Language}
  830. \label{sec:s0}
  831. The $R_1$ language extends the $R_0$ language
  832. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  833. the $R_1$ language is defined by the grammar in
  834. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  835. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  836. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  837. the $R_1$ language includes the \key{program} construct to mark the
  838. top of the program, which is helpful in parts of the compiler. The
  839. $\itm{info}$ field of the \key{program} construct contain an
  840. association list that is used to communicating auxiliary data from one
  841. step of the compiler to the next.
  842. The $R_1$ language is rich enough to exhibit several compilation
  843. techniques but simple enough so that the reader, together with couple
  844. friends, can implement a compiler for it in a week or two of part-time
  845. work. To give the reader a feeling for the scale of this first
  846. compiler, the instructor solution for the $R_1$ compiler is less than
  847. 500 lines of code.
  848. \begin{figure}[btp]
  849. \centering
  850. \fbox{
  851. \begin{minipage}{0.96\textwidth}
  852. \[
  853. \begin{array}{rcl}
  854. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  855. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  856. R_1 &::=& (\key{program} \;\itm{info}\; \Exp)
  857. \end{array}
  858. \]
  859. \end{minipage}
  860. }
  861. \caption{The syntax of $R_1$, a language of integers and variables.}
  862. \label{fig:r1-syntax}
  863. \end{figure}
  864. Let us dive into the description of the $R_1$ language. The \key{let}
  865. construct defines a variable for use within its body and initializes
  866. the variable with the value of an expression. So the following
  867. program initializes \code{x} to \code{32} and then evaluates the body
  868. \code{(+ 10 x)}, producing \code{42}.
  869. \begin{lstlisting}
  870. (program ()
  871. (let ([x (+ 12 20)]) (+ 10 x)))
  872. \end{lstlisting}
  873. When there are multiple \key{let}'s for the same variable, the closest
  874. enclosing \key{let} is used. That is, variable definitions overshadow
  875. prior definitions. Consider the following program with two \key{let}'s
  876. that define variables named \code{x}. Can you figure out the result?
  877. \begin{lstlisting}
  878. (program ()
  879. (let ([x 32]) (+ (let ([x 10]) x) x)))
  880. \end{lstlisting}
  881. For the purposes of showing which variable uses correspond to which
  882. definitions, the following shows the \code{x}'s annotated with subscripts
  883. to distinguish them. Double check that your answer for the above is
  884. the same as your answer for this annotated version of the program.
  885. \begin{lstlisting}
  886. (program ()
  887. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  888. \end{lstlisting}
  889. The initializing expression is always evaluated before the body of the
  890. \key{let}, so in the following, the \key{read} for \code{x} is
  891. performed before the \key{read} for \code{y}. Given the input
  892. \code{52} then \code{10}, the following produces \code{42} (and not
  893. \code{-42}).
  894. \begin{lstlisting}
  895. (program ()
  896. (let ([x (read)]) (let ([y (read)]) (+ x (- y)))))
  897. \end{lstlisting}
  898. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  899. language. It extends the interpreter for $R_0$ with two new
  900. \key{match} clauses for variables and for \key{let}. For \key{let},
  901. we will need a way to communicate the initializing value of a variable
  902. to all the uses of a variable. To accomplish this, we maintain a
  903. mapping from variables to values, which is traditionally called an
  904. \emph{environment}. For simplicity, here we use an association list to
  905. represent the environment. The \code{interp-R1} function takes the
  906. current environment, \code{env}, as an extra parameter. When the
  907. interpreter encounters a variable, it finds the corresponding value
  908. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  909. When the interpreter encounters a \key{let}, it evaluates the
  910. initializing expression, extends the environment with the result bound
  911. to the variable, then evaluates the body of the \key{let}.
  912. \begin{figure}[tbp]
  913. \begin{lstlisting}
  914. (define (interp-exp env)
  915. (lambda (e)
  916. (match e
  917. [(? fixnum?) e]
  918. [`(read)
  919. (define r (read))
  920. (cond [(fixnum? r) r]
  921. [else (error 'interp-R1 "expected an integer" r)])]
  922. [`(- ,e)
  923. (define v ((interp-exp env) e))
  924. (fx- 0 v)]
  925. [`(+ ,e1 ,e2)
  926. (define v1 ((interp-exp env) e1))
  927. (define v2 ((interp-exp env) e2))
  928. (fx+ v1 v2)]
  929. [(? symbol?) (lookup e env)]
  930. [`(let ([,x ,e]) ,body)
  931. (define new-env (cons (cons x ((interp-exp env) e)) env))
  932. ((interp-exp new-env) body)]
  933. )))
  934. (define (interp-R1 env)
  935. (lambda (p)
  936. (match p
  937. [`(program ,info ,e) ((interp-exp '()) e)])))
  938. \end{lstlisting}
  939. \caption{Interpreter for the $R_1$ language.}
  940. \label{fig:interp-R1}
  941. \end{figure}
  942. The goal for this chapter is to implement a compiler that translates
  943. any program $P_1$ in the $R_1$ language into an x86 assembly
  944. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  945. computer as the $R_1$ program running in a Racket implementation.
  946. That is, they both output the same integer $n$.
  947. \[
  948. \begin{tikzpicture}[baseline=(current bounding box.center)]
  949. \node (p1) at (0, 0) {$P_1$};
  950. \node (p2) at (4, 0) {$P_2$};
  951. \node (o) at (4, -2) {$n$};
  952. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  953. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  954. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  955. \end{tikzpicture}
  956. \]
  957. In the next section we introduce enough of the x86 assembly
  958. language to compile $R_1$.
  959. \section{The x86 Assembly Language}
  960. \label{sec:x86}
  961. An x86 program is a sequence of instructions. The program is stored in the
  962. computer's memory and the \emph{program counter} points to the address of the
  963. next instruction to be executed. For most instructions, once the instruction is
  964. executed, the program counter is incremented to point to the immediately
  965. following instruction in memory. Each instruction may refer to integer
  966. constants (called \emph{immediate values}), variables called \emph{registers},
  967. and instructions may load and store values into memory. For our purposes, we
  968. can think of the computer's memory as a mapping of 64-bit addresses to 64-bit
  969. values%
  970. \footnote{This simple story suffices for describing how sequential
  971. programs access memory but is not sufficient for multi-threaded
  972. programs. However, multi-threaded execution is beyond the scope of
  973. this book.}.
  974. %
  975. Figure~\ref{fig:x86-a} defines the syntax for the
  976. subset of the x86 assembly language needed for this chapter.
  977. %
  978. We use the AT\&T syntax expected by the GNU assembler, which comes
  979. with the \key{gcc} compiler that we use for compiling assembly code to
  980. machine code.
  981. %
  982. Also, Appendix~\ref{sec:x86-quick-reference} includes a quick-reference of all
  983. the x86 instructions used in this book and a short explanation of what they do.
  984. % to do: finish treatment of imulq
  985. % it's needed for vector's in R6/R7
  986. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  987. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  988. && \key{r8} \mid \key{r9} \mid \key{r10}
  989. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  990. \mid \key{r14} \mid \key{r15}}
  991. \begin{figure}[tp]
  992. \fbox{
  993. \begin{minipage}{0.96\textwidth}
  994. \[
  995. \begin{array}{lcl}
  996. \Reg &::=& \allregisters{} \\
  997. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  998. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  999. \key{subq} \; \Arg, \Arg \mid
  1000. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  1001. && \key{callq} \; \mathit{label} \mid
  1002. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1003. \Prog &::= & \key{.globl main}\\
  1004. & & \key{main:} \; \Instr^{+}
  1005. \end{array}
  1006. \]
  1007. \end{minipage}
  1008. }
  1009. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1010. \label{fig:x86-a}
  1011. \end{figure}
  1012. An immediate value is written using the notation \key{\$}$n$ where $n$
  1013. is an integer.
  1014. %
  1015. A register is written with a \key{\%} followed by the register name,
  1016. such as \key{\%rax}.
  1017. %
  1018. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1019. which obtains the address stored in register $r$ and then
  1020. offsets the address by $n$ bytes
  1021. (8 bits). The address is then used to either load or store to memory
  1022. depending on whether it occurs as a source or destination argument of
  1023. an instruction.
  1024. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  1025. source $s$ and destination $d$, applies the arithmetic operation, then
  1026. writes the result in $d$.
  1027. %
  1028. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  1029. result in $d$.
  1030. %
  1031. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1032. specified by the label.
  1033. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1034. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1035. \key{main} procedure is externally visible, which is necessary so
  1036. that the operating system can call it. The label \key{main:}
  1037. indicates the beginning of the \key{main} procedure which is where
  1038. the operating system starts executing this program. The instruction
  1039. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1040. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1041. $10$ in \key{rax} and puts the result, $42$, back into
  1042. \key{rax}.
  1043. The last instruction, \key{retq}, finishes the \key{main} function by
  1044. returning the integer in \key{rax} to the operating system. The
  1045. operating system interprets this integer as the program's exit
  1046. code. By convention, an exit code of 0 indicates the program was
  1047. successful, and all other exit codes indicate various errors.
  1048. Nevertheless, we return the result of the program as the exit code.
  1049. %\begin{wrapfigure}{r}{2.25in}
  1050. \begin{figure}[tbp]
  1051. \begin{lstlisting}
  1052. .globl main
  1053. main:
  1054. movq $10, %rax
  1055. addq $32, %rax
  1056. retq
  1057. \end{lstlisting}
  1058. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1059. \label{fig:p0-x86}
  1060. %\end{wrapfigure}
  1061. \end{figure}
  1062. Unfortunately, x86 varies in a couple ways depending on what operating
  1063. system it is assembled in. The code examples shown here are correct on
  1064. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1065. labels like \key{main} must be prefixed with an underscore, as in
  1066. \key{\_main}.
  1067. We exhibit the use of memory for storing intermediate results in the
  1068. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1069. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1070. region of memory called the \emph{procedure call stack} (or
  1071. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1072. for each procedure call. The memory layout for an individual frame is
  1073. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1074. \emph{stack pointer} and points to the item at the top of the
  1075. stack. The stack grows downward in memory, so we increase the size of
  1076. the stack by subtracting from the stack pointer. The frame size is
  1077. required to be a multiple of 16 bytes. In the context of a procedure
  1078. call, the \emph{return address} is the next instruction on the caller
  1079. side that comes after the call instruction. During a function call,
  1080. the return address is pushed onto the stack. The register \key{rbp}
  1081. is the \emph{base pointer} which serves two purposes: 1) it saves the
  1082. location of the stack pointer for the calling procedure and 2) it is
  1083. used to access variables associated with the current procedure. The
  1084. base pointer of the calling procedure is pushed onto the stack after
  1085. the return address. We number the variables from $1$ to $n$. Variable
  1086. $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1087. $-16\key{(\%rbp)}$, etc.
  1088. \begin{figure}[tbp]
  1089. \begin{lstlisting}
  1090. start:
  1091. movq $10, -8(%rbp)
  1092. negq -8(%rbp)
  1093. movq -8(%rbp), %rax
  1094. addq $52, %rax
  1095. jmp conclusion
  1096. .globl main
  1097. main:
  1098. pushq %rbp
  1099. movq %rsp, %rbp
  1100. subq $16, %rsp
  1101. jmp start
  1102. conclusion:
  1103. addq $16, %rsp
  1104. popq %rbp
  1105. retq
  1106. \end{lstlisting}
  1107. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1108. \label{fig:p1-x86}
  1109. \end{figure}
  1110. \begin{figure}[tbp]
  1111. \centering
  1112. \begin{tabular}{|r|l|} \hline
  1113. Position & Contents \\ \hline
  1114. 8(\key{\%rbp}) & return address \\
  1115. 0(\key{\%rbp}) & old \key{rbp} \\
  1116. -8(\key{\%rbp}) & variable $1$ \\
  1117. -16(\key{\%rbp}) & variable $2$ \\
  1118. \ldots & \ldots \\
  1119. 0(\key{\%rsp}) & variable $n$\\ \hline
  1120. \end{tabular}
  1121. \caption{Memory layout of a frame.}
  1122. \label{fig:frame}
  1123. \end{figure}
  1124. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1125. three instructions are the typical \emph{prelude} for a procedure.
  1126. The instruction \key{pushq \%rbp} saves the base pointer for the
  1127. procedure that called the current one onto the stack and subtracts $8$
  1128. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  1129. changes the base pointer to the top of the stack. The instruction
  1130. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  1131. room for storing variables. This program just needs one variable ($8$
  1132. bytes) but because the frame size is required to be a multiple of 16
  1133. bytes, it rounds to 16 bytes.
  1134. The four instructions under the label \code{start} carry out the work
  1135. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1136. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1137. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1138. \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1139. \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1140. \key{rax}, at which point \key{rax} contains $42$.
  1141. The three instructions under the label \code{conclusion} are the
  1142. typical finale of a procedure. The first two are necessary to get the
  1143. state of the machine back to where it was at the beginning of the
  1144. procedure. The \key{addq \$16, \%rsp} instruction moves the stack
  1145. pointer back to point at the old base pointer. The amount added here
  1146. needs to match the amount that was subtracted in the prelude of the
  1147. procedure. Then \key{popq \%rbp} returns the old base pointer to
  1148. \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  1149. \key{retq}, jumps back to the procedure that called this one and adds
  1150. 8 to the stack pointer, which returns the stack pointer to where it
  1151. was prior to the procedure call.
  1152. The compiler will need a convenient representation for manipulating
  1153. x86 programs, so we define an abstract syntax for x86 in
  1154. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1155. a subscript $0$ because later we introduce extended versions of this
  1156. assembly language. The main difference compared to the concrete syntax
  1157. of x86 (Figure~\ref{fig:x86-a}) is that it does nto allow labelled
  1158. instructions to appear anywhere, but instead organizes instructions
  1159. into groups called \emph{blocks} and a label is associated with every
  1160. block, which is why the \key{program} form includes an association
  1161. list mapping labels to blocks. The reason for this organization
  1162. becomes apparent in Chapter~\ref{ch:bool-types}.
  1163. \begin{figure}[tp]
  1164. \fbox{
  1165. \begin{minipage}{0.96\textwidth}
  1166. \[
  1167. \begin{array}{lcl}
  1168. \itm{register} &::=& \allregisters{} \\
  1169. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1170. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1171. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1172. (\key{subq} \; \Arg\; \Arg) \mid
  1173. (\key{movq} \; \Arg\; \Arg) \mid
  1174. (\key{retq})\\
  1175. &\mid& (\key{negq} \; \Arg) \mid
  1176. (\key{callq} \; \mathit{label}) \mid
  1177. (\key{pushq}\;\Arg) \mid
  1178. (\key{popq}\;\Arg) \\
  1179. \Block &::= & (\key{block} \;\itm{info}\; \Instr^{+}) \\
  1180. x86_0 &::= & (\key{program} \;\itm{info} \; ((\itm{label} \,\key{.}\, \Block)^{+}))
  1181. \end{array}
  1182. \]
  1183. \end{minipage}
  1184. }
  1185. \caption{Abstract syntax for $x86_0$ assembly.}
  1186. \label{fig:x86-ast-a}
  1187. \end{figure}
  1188. \section{Planning the trip to x86 via the $C_0$ language}
  1189. \label{sec:plan-s0-x86}
  1190. To compile one language to another it helps to focus on the
  1191. differences between the two languages because the compiler will need
  1192. to bridge them. What are the differences between $R_1$ and x86
  1193. assembly? Here we list some of the most important ones.
  1194. \begin{enumerate}
  1195. \item[(a)] x86 arithmetic instructions typically have two arguments
  1196. and update the second argument in place. In contrast, $R_1$
  1197. arithmetic operations take two arguments and produce a new value.
  1198. An x86 instruction may have at most one memory-accessing argument.
  1199. Furthermore, some instructions place special restrictions on their
  1200. arguments.
  1201. \item[(b)] An argument to an $R_1$ operator can be any expression,
  1202. whereas x86 instructions restrict their arguments to be \emph{simple
  1203. expressions} like integers, registers, and memory locations. (All
  1204. the other kinds are called \emph{complex expressions}.)
  1205. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1206. sequence of instructions and jumps to labeled positions, whereas in
  1207. $R_1$ it is a left-to-right depth-first traversal of the abstract
  1208. syntax tree.
  1209. \item[(d)] An $R_1$ program can have any number of variables whereas
  1210. x86 has 16 registers and the procedure calls stack.
  1211. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1212. same name. The registers and memory locations of x86 all have unique
  1213. names or addresses.
  1214. \end{enumerate}
  1215. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1216. the problem into several steps, dealing with the above differences one
  1217. at a time. Each of these steps is called a \emph{pass} of the
  1218. compiler, because step traverses (passes over) the AST of the program.
  1219. %
  1220. We begin by giving a sketch about how we might implement each pass,
  1221. and give them names. We shall then figure out an ordering of the
  1222. passes and the input/output language for each pass. The very first
  1223. pass has $R_1$ as its input language and the last pass has x86 as its
  1224. output language. In between we can choose whichever language is most
  1225. convenient for expressing the output of each pass, whether that be
  1226. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1227. Finally, to implement the compiler, we shall write one function,
  1228. typically a structural recursive function, per pass.
  1229. \begin{description}
  1230. \item[Pass \key{select-instructions}] To handle the difference between
  1231. $R_1$ operations and x86 instructions we shall convert each $R_1$
  1232. operation to a short sequence of instructions that accomplishes the
  1233. same task.
  1234. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1235. subexpression (i.e. operator and operand, and hence \key{opera*}) is
  1236. a simple expression, we shall introduce temporary variables to hold
  1237. the results of subexpressions.
  1238. \item[Pass \key{explicate-control}] To make the execution order of the
  1239. program explicit, we shall convert from the abstract syntax tree
  1240. representation into a graph representation in which each node
  1241. contains a sequence of actions and the edges say where to go after
  1242. the sequence is complete.
  1243. \item[Pass \key{assign-homes}] To handle the difference between the
  1244. variables in $R_1$ versus the registers and stack location in x86,
  1245. we shall come up with an assignment of each variable to its
  1246. \emph{home}, that is, to a register or stack location.
  1247. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1248. by renaming every variable to a unique name, so that shadowing no
  1249. longer occurs.
  1250. \end{description}
  1251. The next question is: in what order should we apply these passes? This
  1252. question can be a challenging one to answer because it is difficult to
  1253. know ahead of time which orders will be better (easier to implement,
  1254. produce more efficient code, etc.) so often some trial-and-error is
  1255. involved. Nevertheless, we can try to plan ahead and make educated
  1256. choices regarding the orderings.
  1257. Let us consider the ordering of \key{uniquify} and
  1258. \key{remove-complex-opera*}. The assignment of subexpressions to
  1259. temporary variables involves introducing new variables and moving
  1260. subexpressions, which might change the shadowing of variables and
  1261. inadvertently change the behavior of the program. But if we apply
  1262. \key{uniquify} first, this will not be an issue. Of course, this means
  1263. that in \key{remove-complex-opera*}, we need to ensure that the
  1264. temporary variables that it creates are unique.
  1265. Next we shall consider the ordering of the \key{explicate-control}
  1266. pass and \key{select-instructions}. It is clear that
  1267. \key{explicate-control} must come first because the control-flow graph
  1268. that it generates is needed when determining where to place the x86
  1269. label and jump instructions.
  1270. %
  1271. Regarding the ordering of \key{explicate-control} with respect to
  1272. \key{uniquify}, it is important to apply \key{uniquify} first because
  1273. in \key{explicate-control} we change all the \key{let}-bound variables
  1274. to become local variables whose scope is the entire program.
  1275. %
  1276. With respect to \key{remove-complex-opera*}, it perhaps does not
  1277. matter very much, but it works well to place \key{explicate-control}
  1278. after removing complex subexpressions.
  1279. The \key{assign-homes} pass should come after
  1280. \key{remove-complex-opera*} and \key{explicate-control}. The
  1281. \key{remove-complex-opera*} pass generates temporary variables, which
  1282. also need to be assigned homes. The \key{explicate-control} pass
  1283. deletes branches that will never be executed, which can remove
  1284. variables. Thus it is good to place \key{explicate-control} prior to
  1285. \key{assign-homes} so that there are fewer variables that need to be
  1286. assigned homes. This is important because the \key{assign-homes} pass
  1287. has the highest time complexity.
  1288. Last, we need to decide on the ordering of \key{select-instructions}
  1289. and \key{assign-homes}. These two issues are intertwined, creating a
  1290. bit of a Gordian Knot. To do a good job of assigning homes, it is
  1291. helpful to have already determined which instructions will be used,
  1292. because x86 instructions have restrictions about which of their
  1293. arguments can be registers versus stack locations. For example, one
  1294. can give preferential treatment to variables that occur in
  1295. register-argument positions. On the other hand, it may turn out to be
  1296. impossible to make sure that all such variables are assigned to
  1297. registers, and then one must redo the selection of instructions. Some
  1298. compilers handle this problem by iteratively repeating these two
  1299. passes until a good solution is found. We shall use a simpler
  1300. approach in which \key{select-instructions} comes first, followed by
  1301. the \key{assign-homes}, followed by a third pass, named
  1302. \key{patch-instructions}, that uses a reserved register (\key{rax}) to
  1303. patch-up outstanding problems regarding instructions with too many
  1304. memory accesses.
  1305. \begin{figure}[tbp]
  1306. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1307. \node (R1) at (0,2) {\large $R_1$};
  1308. \node (R1-2) at (3,2) {\large $R_1$};
  1309. \node (R1-3) at (6,2) {\large $R_1$};
  1310. \node (C0-1) at (6,0) {\large $C_0$};
  1311. \node (C0-2) at (3,0) {\large $C_0$};
  1312. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1313. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1314. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1315. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1316. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1317. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1318. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  1319. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1320. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1321. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1322. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1323. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1324. \end{tikzpicture}
  1325. \caption{Overview of the passes for compiling $R_1$. }
  1326. \label{fig:R1-passes}
  1327. \end{figure}
  1328. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1329. passes in the form of a graph. Each pass is an edge and the
  1330. input/output language of each pass is a node in the graph. The output
  1331. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1332. are still in the $R_1$ language, but the output of the pass
  1333. \key{explicate-control} is in a different language that is designed to
  1334. make the order of evaluation explicit in its syntax, which we
  1335. introduce in the next section. Also, there are two passes of lesser
  1336. importance in Figure~\ref{fig:R1-passes} that we have not yet talked
  1337. about, \key{uncover-locals} and \key{print-x86}. We shall discuss them
  1338. later in this Chapter.
  1339. \subsection{The $C_0$ Intermediate Language}
  1340. It so happens that the output of \key{explicate-control} is vaguely
  1341. similar to the $C$ language~\citep{Kernighan:1988nx}, so we name it
  1342. $C_0$. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}.
  1343. %
  1344. The $C_0$ language supports the same operators as $R_1$ but the
  1345. arguments of operators are now restricted to just variables and
  1346. integers, thanks to the \key{remove-complex-opera*} pass. In the
  1347. literature this style of intermediate language is called
  1348. administrative normal form, or ANF for
  1349. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{let}
  1350. expressions, $C_0$ has assignment statements which can be executed in
  1351. sequence using the \key{seq} construct. A sequence of statements
  1352. always ends with \key{return}, a guarantee that is baked into the
  1353. grammar rules for the \itm{tail} non-terminal. The naming of this
  1354. non-terminal comes from the term \emph{tail position}, which refers to
  1355. an expression that is the last one to execute within a function. (A
  1356. expression in tail position may contain subexpressions, and those may
  1357. or may not be in tail position depending on the kind of expression.)
  1358. A $C_0$ program consists of an association list mapping labels to
  1359. tails. This is overkill for the present Chapter, as we do not yet need
  1360. to introduce \key{goto} for jumping to labels, but it saves us from
  1361. having to change the syntax of the program construct in
  1362. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1363. \key{start}, and the whole program will be it's tail.
  1364. %
  1365. The $\itm{info}$ field of the program construt, after the
  1366. \key{uncover-locals} pass, will contain a mapping from the symbol
  1367. \key{locals} to a list of variables, that is, a list of all the
  1368. variables used in the program. At the start of the program, these
  1369. variables are uninitialized (they contain garbage) and each variable
  1370. becomes initialized on its first assignment.
  1371. \begin{figure}[tbp]
  1372. \fbox{
  1373. \begin{minipage}{0.96\textwidth}
  1374. \[
  1375. \begin{array}{lcl}
  1376. \Arg &::=& \Int \mid \Var \\
  1377. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1378. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1379. \Tail &::= & \RETURN{\Exp} \mid (\key{seq}\; \Stmt\; \Tail) \\
  1380. C_0 & ::= & (\key{program}\;\itm{info}\;((\itm{label}\,\key{.}\,\Tail)^{+}))
  1381. \end{array}
  1382. \]
  1383. \end{minipage}
  1384. }
  1385. \caption{The $C_0$ intermediate language.}
  1386. \label{fig:c0-syntax}
  1387. \end{figure}
  1388. %% The \key{select-instructions} pass is optimistic in the sense that it
  1389. %% treats variables as if they were all mapped to registers. The
  1390. %% \key{select-instructions} pass generates a program that consists of
  1391. %% x86 instructions but that still uses variables, so it is an
  1392. %% intermediate language that is technically different than x86, which
  1393. %% explains the asterisks in the diagram above.
  1394. %% In this Chapter we shall take the easy road to implementing
  1395. %% \key{assign-homes} and simply map all variables to stack locations.
  1396. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1397. %% smarter approach in which we make a best-effort to map variables to
  1398. %% registers, resorting to the stack only when necessary.
  1399. %% Once variables have been assigned to their homes, we can finalize the
  1400. %% instruction selection by dealing with an idiosyncrasy of x86
  1401. %% assembly. Many x86 instructions have two arguments but only one of the
  1402. %% arguments may be a memory reference (and the stack is a part of
  1403. %% memory). Because some variables may get mapped to stack locations,
  1404. %% some of our generated instructions may violate this restriction. The
  1405. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1406. %% replacing every violating instruction with a short sequence of
  1407. %% instructions that use the \key{rax} register. Once we have implemented
  1408. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1409. %% need to patch instructions will be relatively rare.
  1410. \subsection{The dialects of x86}
  1411. The x86$^{*}_0$ language, pronounced ``pseudo-x86'', is the output of
  1412. the pass \key{select-instructions}. It extends $x86_0$ with variables
  1413. and looser rules regarding instruction arguments. The x86$^{\dagger}$
  1414. language, the output of \key{print-x86}, is the concrete syntax for
  1415. x86.
  1416. \section{Uniquify Variables}
  1417. \label{sec:uniquify-s0}
  1418. The purpose of this pass is to make sure that each \key{let} uses a
  1419. unique variable name. For example, the \code{uniquify} pass should
  1420. translate the program on the left into the program on the right. \\
  1421. \begin{tabular}{lll}
  1422. \begin{minipage}{0.4\textwidth}
  1423. \begin{lstlisting}
  1424. (program ()
  1425. (let ([x 32])
  1426. (+ (let ([x 10]) x) x)))
  1427. \end{lstlisting}
  1428. \end{minipage}
  1429. &
  1430. $\Rightarrow$
  1431. &
  1432. \begin{minipage}{0.4\textwidth}
  1433. \begin{lstlisting}
  1434. (program ()
  1435. (let ([x.1 32])
  1436. (+ (let ([x.2 10]) x.2) x.1)))
  1437. \end{lstlisting}
  1438. \end{minipage}
  1439. \end{tabular} \\
  1440. %
  1441. The following is another example translation, this time of a program
  1442. with a \key{let} nested inside the initializing expression of another
  1443. \key{let}.\\
  1444. \begin{tabular}{lll}
  1445. \begin{minipage}{0.4\textwidth}
  1446. \begin{lstlisting}
  1447. (program ()
  1448. (let ([x (let ([x 4])
  1449. (+ x 1))])
  1450. (+ x 2)))
  1451. \end{lstlisting}
  1452. \end{minipage}
  1453. &
  1454. $\Rightarrow$
  1455. &
  1456. \begin{minipage}{0.4\textwidth}
  1457. \begin{lstlisting}
  1458. (program ()
  1459. (let ([x.2 (let ([x.1 4])
  1460. (+ x.1 1))])
  1461. (+ x.2 2)))
  1462. \end{lstlisting}
  1463. \end{minipage}
  1464. \end{tabular}
  1465. We recommend implementing \code{uniquify} as a structurally recursive
  1466. function that mostly copies the input program. However, when
  1467. encountering a \key{let}, it should generate a unique name for the
  1468. variable (the Racket function \code{gensym} is handy for this) and
  1469. associate the old name with the new unique name in an association
  1470. list. The \code{uniquify} function will need to access this
  1471. association list when it gets to a variable reference, so we add
  1472. another parameter to \code{uniquify} for the association list. It is
  1473. quite common for a compiler pass to need a map to store extra
  1474. information about variables. Such maps are often called \emph{symbol
  1475. tables}.
  1476. The skeleton of the \code{uniquify} function is shown in
  1477. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1478. convenient to partially apply it to an association list and then apply
  1479. it to different expressions, as in the last clause for primitive
  1480. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1481. clause for the primitive operators, note the use of the comma-@
  1482. operator to splice a list of S-expressions into an enclosing
  1483. S-expression.
  1484. \begin{exercise}
  1485. \normalfont % I don't like the italics for exercises. -Jeremy
  1486. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1487. implement the clauses for variables and for the \key{let} construct.
  1488. \end{exercise}
  1489. \begin{figure}[tbp]
  1490. \begin{lstlisting}
  1491. (define (uniquify-exp alist)
  1492. (lambda (e)
  1493. (match e
  1494. [(? symbol?) ___]
  1495. [(? integer?) e]
  1496. [`(let ([,x ,e]) ,body) ___]
  1497. [`(,op ,es ...)
  1498. `(,op ,@(for/list ([e es]) ((uniquify-exp alist) e)))]
  1499. )))
  1500. (define (uniquify alist)
  1501. (lambda (e)
  1502. (match e
  1503. [`(program ,info ,e)
  1504. `(program ,info ,((uniquify-exp alist) e))]
  1505. )))
  1506. \end{lstlisting}
  1507. \caption{Skeleton for the \key{uniquify} pass.}
  1508. \label{fig:uniquify-s0}
  1509. \end{figure}
  1510. \begin{exercise}
  1511. \normalfont % I don't like the italics for exercises. -Jeremy
  1512. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1513. and checking whether the output programs produce the same result as
  1514. the input programs. The $R_1$ programs should be designed to test the
  1515. most interesting parts of the \key{uniquify} pass, that is, the
  1516. programs should include \key{let} constructs, variables, and variables
  1517. that overshadow each other. The five programs should be in a
  1518. subdirectory named \key{tests} and they should have the same file name
  1519. except for a different integer at the end of the name, followed by the
  1520. ending \key{.rkt}. Use the \key{interp-tests} function
  1521. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1522. your \key{uniquify} pass on the example programs.
  1523. \end{exercise}
  1524. \section{Remove Complex Operators and Operands}
  1525. \label{sec:remove-complex-opera-r1}
  1526. The \code{remove-complex-opera*} pass will transform $R_1$ programs so
  1527. that the arguments of operations are simple expressions. Put another
  1528. way, this pass removes complex subexpressions, such as the expression
  1529. \code{(- 10)} in the program below. This is accomplished by
  1530. introducing a new \key{let}-bound variable, binding the complex
  1531. subexpression to the new variable, and then using the new variable in
  1532. place of the complex expression, as shown in the output of
  1533. \code{remove-complex-opera*} on the right.\\
  1534. \begin{tabular}{lll}
  1535. \begin{minipage}{0.4\textwidth}
  1536. % s0_19.rkt
  1537. \begin{lstlisting}
  1538. (program ()
  1539. (+ 52 (- 10)))
  1540. \end{lstlisting}
  1541. \end{minipage}
  1542. &
  1543. $\Rightarrow$
  1544. &
  1545. \begin{minipage}{0.4\textwidth}
  1546. \begin{lstlisting}
  1547. (program ()
  1548. (let ([tmp.1 (- 10)])
  1549. (+ 52 tmp.1)))
  1550. \end{lstlisting}
  1551. \end{minipage}
  1552. \end{tabular}
  1553. We recommend implementing this pass with two mutually recursive
  1554. functions, \code{rco-arg} and \code{rco-exp}. The idea is to apply
  1555. \code{rco-arg} to subexpressions that need to become simple and to
  1556. apply \code{rco-exp} to subexpressions can stay complex.
  1557. Both functions take an expression in $R_1$ as input.
  1558. The \code{rco-exp} function returns an expression.
  1559. The \code{rco-arg} function returns two things:
  1560. a simple expression and association list mapping temporary variables
  1561. to complex subexpressions. You can return multiple things from a
  1562. function using Racket's \key{values} form and you can receive multiple
  1563. things from a function call using the \key{define-values} form. If you
  1564. are not familiar with these constructs, the Racket documentation will
  1565. be of help. Also, the \key{for/lists} construct is useful for
  1566. applying a function to each element of a list, in the case where the
  1567. function returns multiple values.
  1568. \begin{tabular}{lll}
  1569. \begin{minipage}{0.4\textwidth}
  1570. \begin{lstlisting}
  1571. (rco-arg `(- 10))
  1572. \end{lstlisting}
  1573. \end{minipage}
  1574. &
  1575. $\Rightarrow$
  1576. &
  1577. \begin{minipage}{0.4\textwidth}
  1578. \begin{lstlisting}
  1579. (values `tmp.1
  1580. `((tmp.1 . (- 10))))
  1581. \end{lstlisting}
  1582. \end{minipage}
  1583. \end{tabular}
  1584. Take special care of programs such as the following that
  1585. \key{let}-bind variables with integers or other variables. It should
  1586. leave them unchanged, as shown in to the program on the right \\
  1587. \begin{tabular}{lll}
  1588. \begin{minipage}{0.4\textwidth}
  1589. \begin{lstlisting}
  1590. (program ()
  1591. (let ([a 42])
  1592. (let ([b a])
  1593. b)))
  1594. \end{lstlisting}
  1595. \end{minipage}
  1596. &
  1597. $\Rightarrow$
  1598. &
  1599. \begin{minipage}{0.4\textwidth}
  1600. \begin{lstlisting}
  1601. (program ()
  1602. (let ([a 42])
  1603. (let ([b a])
  1604. b)))
  1605. \end{lstlisting}
  1606. \end{minipage}
  1607. \end{tabular} \\
  1608. and not translate them to the following, which might result from a
  1609. careless implementation of \key{rco-exp} and \key{rco-arg}.
  1610. \begin{minipage}{0.4\textwidth}
  1611. \begin{lstlisting}
  1612. (program ()
  1613. (let ([tmp.1 42])
  1614. (let ([a tmp.1])
  1615. (let ([tmp.2 a])
  1616. (let ([b tmp.2])
  1617. b)))))
  1618. \end{lstlisting}
  1619. \end{minipage}
  1620. \begin{exercise}
  1621. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1622. it on all of the example programs that you created to test the
  1623. \key{uniquify} pass and create three new example programs that are
  1624. designed to exercise all of the interesting code in the
  1625. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1626. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1627. your passes on the example programs.
  1628. \end{exercise}
  1629. \section{Explicate Control}
  1630. \label{sec:explicate-control-r1}
  1631. The \code{explicate-control} pass makes the order of execution
  1632. explicit in the syntax of the program. For $R_1$, this amounts to
  1633. flattening \key{let} constructs into a sequence of assignment
  1634. statements. For example, consider the following $R_1$ program.
  1635. % s0_11.rkt
  1636. \begin{lstlisting}
  1637. (program ()
  1638. (let ([y (let ([x 20])
  1639. (+ x (let ([x 22]) x)))])
  1640. y))
  1641. \end{lstlisting}
  1642. %
  1643. The output of \code{remove-complex-opera*} is shown below, on the
  1644. left. The right-hand-side of a \key{let} executes before its body, so
  1645. the order of evaluation for this program is to assign \code{20} to
  1646. \code{x.1}, assign \code{22} to \code{x.2}, assign \code{(+ x.1 x.2)}
  1647. to \code{y}, then return \code{y}. Indeed, the result of
  1648. \code{explicate-control} produces code in the $C_0$ language that
  1649. makes this explicit.\\
  1650. \begin{tabular}{lll}
  1651. \begin{minipage}{0.4\textwidth}
  1652. \begin{lstlisting}
  1653. (program ()
  1654. (let ([y (let ([x.1 20])
  1655. (let ([x.2 22])
  1656. (+ x.1 x.2)))])
  1657. y))
  1658. \end{lstlisting}
  1659. \end{minipage}
  1660. &
  1661. $\Rightarrow$
  1662. &
  1663. \begin{minipage}{0.4\textwidth}
  1664. \begin{lstlisting}
  1665. (program ()
  1666. ((start .
  1667. (seq (assign x.1 20)
  1668. (seq (assign x.2 22)
  1669. (seq (assign y (+ x.1 x.2))
  1670. (return y)))))))
  1671. \end{lstlisting}
  1672. \end{minipage}
  1673. \end{tabular}
  1674. We recommend implementing \code{explicate-control} using two mutually
  1675. recursive functions: \code{explicate-control-tail} and
  1676. \code{explicate-control-assign}. The \code{explicate-control-tail}
  1677. function should be applied to expressions in tail position, whereas
  1678. \code{explicate-control-assign} should be applied to expressions that
  1679. occur on the right-hand-side of a \code{let}. The function
  1680. \code{explicate-control-tail} takes an $R_1$ expression as input and
  1681. produces a $C_0$ $\Tail$ (see the grammar in
  1682. Figure~\ref{fig:c0-syntax}). The \code{explicate-control-assign}
  1683. function takes an $R_1$ expression, the variable that it is to be
  1684. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1685. assignment (e.g., the code generated for the body of the \key{let}).
  1686. \section{Uncover Locals}
  1687. \label{sec:uncover-locals-r1}
  1688. The pass \code{uncover-locals} simply collects all of the variables in
  1689. the program and places then in the $\itm{info}$ of the program
  1690. construct. Here is the output for the example program of the last
  1691. section.
  1692. \begin{minipage}{0.4\textwidth}
  1693. \begin{lstlisting}
  1694. (program ((locals . (x.1 x.2 y)))
  1695. ((start .
  1696. (seq (assign x.1 20)
  1697. (seq (assign x.2 22)
  1698. (seq (assign y (+ x.1 x.2))
  1699. (return y)))))))
  1700. \end{lstlisting}
  1701. \end{minipage}
  1702. \section{Select Instructions}
  1703. \label{sec:select-r1}
  1704. In the \code{select-instructions} pass we begin the work of
  1705. translating from $C_0$ to x86. The target language of this pass is a
  1706. pseudo-x86 language that still uses variables, so we add an AST node
  1707. of the form $\VAR{\itm{var}}$ to the x86 abstract syntax. We
  1708. recommend implementing the \code{select-instructions} in terms of
  1709. three auxilliary functions, one for each of the non-terminals of
  1710. $C_0$: $\Arg$, $\Stmt$, and $\Tail$.
  1711. The cases for $\itm{arg}$ are straightforward, simply putting
  1712. variables and integer literals into the s-expression format expected
  1713. of pseudo-x86, \code{(var $x$)} and \code{(int $n$)}, respectively.
  1714. Next we discuss some of the cases for $\itm{stmt}$, starting with
  1715. arithmetic operations. For example, in $C_0$ an addition operation can
  1716. take the form below. To translate to x86, we need to use the
  1717. \key{addq} instruction which does an in-place update. So we must first
  1718. move \code{10} to \code{x}. \\
  1719. \begin{tabular}{lll}
  1720. \begin{minipage}{0.4\textwidth}
  1721. \begin{lstlisting}
  1722. (assign x (+ 10 32))
  1723. \end{lstlisting}
  1724. \end{minipage}
  1725. &
  1726. $\Rightarrow$
  1727. &
  1728. \begin{minipage}{0.4\textwidth}
  1729. \begin{lstlisting}
  1730. (movq (int 10) (var x))
  1731. (addq (int 32) (var x))
  1732. \end{lstlisting}
  1733. \end{minipage}
  1734. \end{tabular} \\
  1735. %
  1736. There are some cases that require special care to avoid generating
  1737. needlessly complicated code. If one of the arguments is the same as
  1738. the left-hand side of the assignment, then there is no need for the
  1739. extra move instruction. For example, the following assignment
  1740. statement can be translated into a single \key{addq} instruction.\\
  1741. \begin{tabular}{lll}
  1742. \begin{minipage}{0.4\textwidth}
  1743. \begin{lstlisting}
  1744. (assign x (+ 10 x))
  1745. \end{lstlisting}
  1746. \end{minipage}
  1747. &
  1748. $\Rightarrow$
  1749. &
  1750. \begin{minipage}{0.4\textwidth}
  1751. \begin{lstlisting}
  1752. (addq (int 10) (var x))
  1753. \end{lstlisting}
  1754. \end{minipage}
  1755. \end{tabular} \\
  1756. The \key{read} operation does not have a direct counterpart in x86
  1757. assembly, so we have instead implemented this functionality in the C
  1758. language, with the function \code{read\_int} in the file
  1759. \code{runtime.c}. In general, we refer to all of the functionality in
  1760. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1761. for short. When compiling your generated x86 assembly code, you
  1762. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1763. file'', using \code{gcc} option \code{-c}) and link it into the final
  1764. executable. For our purposes of code generation, all you need to do is
  1765. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1766. (for left-hand side) into a call to the \code{read\_int} function
  1767. followed by a move from \code{rax} to the left-hand side. The move
  1768. from \code{rax} is needed because the return value from
  1769. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1770. \begin{tabular}{lll}
  1771. \begin{minipage}{0.4\textwidth}
  1772. \begin{lstlisting}
  1773. (assign |$\itm{lhs}$| (read))
  1774. \end{lstlisting}
  1775. \end{minipage}
  1776. &
  1777. $\Rightarrow$
  1778. &
  1779. \begin{minipage}{0.4\textwidth}
  1780. \begin{lstlisting}
  1781. (callq read_int)
  1782. (movq (reg rax) (var |$\itm{lhs}$|))
  1783. \end{lstlisting}
  1784. \end{minipage}
  1785. \end{tabular} \\
  1786. There are two cases for the $\Tail$ non-terminal: \key{return} and
  1787. \key{seq}. Regarding \RETURN{e}, we recommend treating it as an
  1788. assignment to the \key{rax} register followed by a jump to the
  1789. conclusion of the program (so the conclusion needs to be labeled).
  1790. For $(\key{seq}\,s\,t)$, we simply process the statement $s$ and tail
  1791. $t$ recursively and append the resulting instructions.
  1792. \begin{exercise}
  1793. \normalfont
  1794. Implement the \key{select-instructions} pass and test it on all of the
  1795. example programs that you created for the previous passes and create
  1796. three new example programs that are designed to exercise all of the
  1797. interesting code in this pass. Use the \key{interp-tests} function
  1798. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1799. your passes on the example programs.
  1800. \end{exercise}
  1801. \section{Assign Homes}
  1802. \label{sec:assign-r1}
  1803. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1804. \key{assign-homes} pass places all of the variables on the stack.
  1805. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1806. which after \key{select-instructions} looks like the following.
  1807. \begin{lstlisting}
  1808. (movq (int 10) (var tmp.1))
  1809. (negq (var tmp.1))
  1810. (movq (var tmp.1) (var tmp.2))
  1811. (addq (int 52) (var tmp.2))
  1812. (movq (var tmp.2) (reg rax)))
  1813. \end{lstlisting}
  1814. The variable \code{tmp.1} is assigned to stack location
  1815. \code{-8(\%rbp)}, and \code{tmp.2} is assign to \code{-16(\%rbp)}, so
  1816. the \code{assign-homes} pass translates the above to
  1817. \begin{lstlisting}
  1818. (movq (int 10) (deref rbp -8))
  1819. (negq (deref rbp -8))
  1820. (movq (deref rbp -8) (deref rbp -16))
  1821. (addq (int 52) (deref rbp -16))
  1822. (movq (deref rbp -16) (reg rax)))
  1823. \end{lstlisting}
  1824. In the process of assigning stack locations to variables, it is
  1825. convenient to compute and store the size of the frame (in bytes) in
  1826. the $\itm{info}$ field of the \key{program} node, with the key
  1827. \code{stack-space}, which will be needed later to generate the
  1828. procedure conclusion. Some operating systems place restrictions on
  1829. the frame size. For example, Mac OS X requires the frame size to be a
  1830. multiple of 16 bytes.
  1831. \begin{exercise}
  1832. \normalfont Implement the \key{assign-homes} pass and test it on all
  1833. of the example programs that you created for the previous passes pass.
  1834. We recommend that \key{assign-homes} take an extra parameter that is a
  1835. mapping of variable names to homes (stack locations for now). Use the
  1836. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1837. \key{utilities.rkt} to test your passes on the example programs.
  1838. \end{exercise}
  1839. \section{Patch Instructions}
  1840. \label{sec:patch-s0}
  1841. The purpose of this pass is to make sure that each instruction adheres
  1842. to the restrictions regarding which arguments can be memory
  1843. references. For most instructions, the rule is that at most one
  1844. argument may be a memory reference.
  1845. Consider again the following example.
  1846. \begin{lstlisting}
  1847. (let ([a 42])
  1848. (let ([b a])
  1849. b))
  1850. \end{lstlisting}
  1851. After \key{assign-homes} pass, the above has been translated to
  1852. \begin{lstlisting}
  1853. (movq (int 42) (deref rbp -8))
  1854. (movq (deref rbp -8) (deref rbp -16))
  1855. (movq (deref rbp -16) (reg rax))
  1856. (jmp conclusion)
  1857. \end{lstlisting}
  1858. The second \key{movq} instruction is problematic because both
  1859. arguments are stack locations. We suggest fixing this problem by
  1860. moving from the source to the register \key{rax} and then from
  1861. \key{rax} to the destination, as follows.
  1862. \begin{lstlisting}
  1863. (movq (int 42) (deref rbp -8))
  1864. (movq (deref rbp -8) (reg rax))
  1865. (movq (reg rax) (deref rbp -16))
  1866. (movq (deref rbp -16) (reg rax))
  1867. \end{lstlisting}
  1868. \begin{exercise}
  1869. \normalfont
  1870. Implement the \key{patch-instructions} pass and test it on all of the
  1871. example programs that you created for the previous passes and create
  1872. three new example programs that are designed to exercise all of the
  1873. interesting code in this pass. Use the \key{interp-tests} function
  1874. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1875. your passes on the example programs.
  1876. \end{exercise}
  1877. \section{Print x86}
  1878. \label{sec:print-x86}
  1879. The last step of the compiler from $R_1$ to x86 is to convert the x86
  1880. AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1881. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1882. \key{format} and \key{string-append} functions are useful in this
  1883. regard. The main work that this step needs to perform is to create the
  1884. \key{main} function and the standard instructions for its prelude and
  1885. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1886. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  1887. variables, so we suggest computing it in the \key{assign-homes} pass
  1888. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  1889. of the \key{program} node.
  1890. %% Your compiled code should print the result of the program's execution
  1891. %% by using the \code{print\_int} function provided in
  1892. %% \code{runtime.c}. If your compiler has been implemented correctly so
  1893. %% far, this final result should be stored in the \key{rax} register.
  1894. %% We'll talk more about how to perform function calls with arguments in
  1895. %% general later on, but for now, place the following after the compiled
  1896. %% code for the $R_1$ program but before the conclusion:
  1897. %% \begin{lstlisting}
  1898. %% movq %rax, %rdi
  1899. %% callq print_int
  1900. %% \end{lstlisting}
  1901. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  1902. %% stores the first argument to be passed into \key{print\_int}.
  1903. If you want your program to run on Mac OS X, your code needs to
  1904. determine whether or not it is running on a Mac, and prefix
  1905. underscores to labels like \key{main}. You can determine the platform
  1906. with the Racket call \code{(system-type 'os)}, which returns
  1907. \code{'macosx}, \code{'unix}, or \code{'windows}.
  1908. %% In addition to
  1909. %% placing underscores on \key{main}, you need to put them in front of
  1910. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1911. %% \_print\_int}).
  1912. \begin{exercise}
  1913. \normalfont Implement the \key{print-x86} pass and test it on all of
  1914. the example programs that you created for the previous passes. Use the
  1915. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1916. \key{utilities.rkt} to test your complete compiler on the example
  1917. programs.
  1918. % The following is specific to P423/P523. -Jeremy
  1919. %Mac support is optional, but your compiler has to output
  1920. %valid code for Unix machines.
  1921. \end{exercise}
  1922. \margincomment{\footnotesize To do: add a challenge section. Perhaps
  1923. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1924. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1925. \chapter{Register Allocation}
  1926. \label{ch:register-allocation-r1}
  1927. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1928. assembly by placing all variables on the stack. We can improve the
  1929. performance of the generated code considerably if we instead place as
  1930. many variables as possible into registers. The CPU can access a
  1931. register in a single cycle, whereas accessing the stack takes many
  1932. cycles to go to cache or many more to access main memory.
  1933. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1934. serves as a running example. We show the source program and also the
  1935. output of instruction selection. At that point the program is almost
  1936. x86 assembly but not quite; it still contains variables instead of
  1937. stack locations or registers.
  1938. \begin{figure}
  1939. \begin{minipage}{0.45\textwidth}
  1940. $R_1$ program:
  1941. % s0_22.rkt
  1942. \begin{lstlisting}
  1943. (program ()
  1944. (let ([v 1])
  1945. (let ([w 46])
  1946. (let ([x (+ v 7)])
  1947. (let ([y (+ 4 x)])
  1948. (let ([z (+ x w)])
  1949. (+ z (- y))))))))
  1950. \end{lstlisting}
  1951. \end{minipage}
  1952. \begin{minipage}{0.45\textwidth}
  1953. After instruction selection:
  1954. \begin{lstlisting}
  1955. (program
  1956. ((locals . (v w x y z t.1)))
  1957. ((start .
  1958. (block ()
  1959. (movq (int 1) (var v))
  1960. (movq (int 46) (var w))
  1961. (movq (var v) (var x))
  1962. (addq (int 7) (var x))
  1963. (movq (var x) (var y))
  1964. (addq (int 4) (var y))
  1965. (movq (var x) (var z))
  1966. (addq (var w) (var z))
  1967. (movq (var y) (var t.1))
  1968. (negq (var t.1))
  1969. (movq (var z) (reg rax))
  1970. (addq (var t.1) (reg rax))
  1971. (jmp conclusion)))))
  1972. \end{lstlisting}
  1973. \end{minipage}
  1974. \caption{An example program for register allocation.}
  1975. \label{fig:reg-eg}
  1976. \end{figure}
  1977. The goal of register allocation is to fit as many variables into
  1978. registers as possible. It is often the case that we have more
  1979. variables than registers, so we cannot map each variable to a
  1980. different register. Fortunately, it is common for different variables
  1981. to be needed during different periods of time, and in such cases
  1982. several variables can be mapped to the same register. Consider
  1983. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  1984. variable \code{x} is moved to \code{z} it is no longer needed.
  1985. Variable \code{y}, on the other hand, is used only after this point,
  1986. so \code{x} and \code{y} could share the same register. The topic of
  1987. Section~\ref{sec:liveness-analysis-r1} is how we compute where a variable
  1988. is needed. Once we have that information, we compute which variables
  1989. are needed at the same time, i.e., which ones \emph{interfere}, and
  1990. represent this relation as graph whose vertices are variables and
  1991. edges indicate when two variables interfere with eachother
  1992. (Section~\ref{sec:build-interference}). We then model register
  1993. allocation as a graph coloring problem, which we discuss in
  1994. Section~\ref{sec:graph-coloring}.
  1995. In the event that we run out of registers despite these efforts, we
  1996. place the remaining variables on the stack, similar to what we did in
  1997. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  1998. that is assigned to a stack location, it has been \emph{spilled}. The
  1999. process of spilling variables is handled as part of the graph coloring
  2000. process described in \ref{sec:graph-coloring}.
  2001. \section{Registers and Calling Conventions}
  2002. \label{sec:calling-conventions}
  2003. As we perform register allocation, we will need to be aware of the
  2004. conventions that govern the way in which registers interact with
  2005. function calls. The convention for x86 is that the caller is
  2006. responsible for freeing up some registers, the \emph{caller-saved
  2007. registers}, prior to the function call, and the callee is
  2008. responsible for saving and restoring some other registers, the
  2009. \emph{callee-saved registers}, before and after using them. The
  2010. caller-saved registers are
  2011. \begin{lstlisting}
  2012. rax rdx rcx rsi rdi r8 r9 r10 r11
  2013. \end{lstlisting}
  2014. while the callee-saved registers are
  2015. \begin{lstlisting}
  2016. rsp rbp rbx r12 r13 r14 r15
  2017. \end{lstlisting}
  2018. Another way to think about this caller/callee convention is the
  2019. following. The caller should assume that all the caller-saved registers
  2020. get overwritten with arbitrary values by the callee. On the other
  2021. hand, the caller can safely assume that all the callee-saved registers
  2022. contain the same values after the call that they did before the call.
  2023. The callee can freely use any of the caller-saved registers. However,
  2024. if the callee wants to use a callee-saved register, the callee must
  2025. arrange to put the original value back in the register prior to
  2026. returning to the caller, which is usually accomplished by saving and
  2027. restoring the value from the stack.
  2028. \section{Liveness Analysis}
  2029. \label{sec:liveness-analysis-r1}
  2030. A variable is \emph{live} if the variable is used at some later point
  2031. in the program and there is not an intervening assignment to the
  2032. variable.
  2033. %
  2034. To understand the latter condition, consider the following code
  2035. fragment in which there are two writes to \code{b}. Are \code{a} and
  2036. \code{b} both live at the same time?
  2037. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2038. (movq (int 5) (var a))
  2039. (movq (int 30) (var b))
  2040. (movq (var a) (var c))
  2041. (movq (int 10) (var b))
  2042. (addq (var b) (var c))
  2043. \end{lstlisting}
  2044. The answer is no because the value \code{30} written to \code{b} on
  2045. line 2 is never used. The variable \code{b} is read on line 5 and
  2046. there is an intervening write to \code{b} on line 4, so the read on
  2047. line 5 receives the value written on line 4, not line 2.
  2048. The live variables can be computed by traversing the instruction
  2049. sequence back to front (i.e., backwards in execution order). Let
  2050. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2051. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2052. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2053. variables before instruction $I_k$. The live variables after an
  2054. instruction are always the same as the live variables before the next
  2055. instruction.
  2056. \begin{equation*}
  2057. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2058. \end{equation*}
  2059. To start things off, there are no live variables after the last
  2060. instruction, so
  2061. \begin{equation*}
  2062. L_{\mathsf{after}}(n) = \emptyset
  2063. \end{equation*}
  2064. We then apply the following rule repeatedly, traversing the
  2065. instruction sequence back to front.
  2066. \begin{equation*}
  2067. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2068. \end{equation*}
  2069. where $W(k)$ are the variables written to by instruction $I_k$ and
  2070. $R(k)$ are the variables read by instruction $I_k$.
  2071. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2072. for the running example, with each instruction aligned with its
  2073. $L_{\mathtt{after}}$ set to make the figure easy to read.
  2074. \margincomment{JM: I think you should walk through the explanation of this formula,
  2075. connecting it back to the example from before. \\
  2076. JS: Agreed.}
  2077. \begin{figure}[tbp]
  2078. \hspace{20pt}
  2079. \begin{minipage}{0.45\textwidth}
  2080. \begin{lstlisting}[numbers=left]
  2081. (block ()
  2082. (movq (int 1) (var v))
  2083. (movq (int 46) (var w))
  2084. (movq (var v) (var x))
  2085. (addq (int 7) (var x))
  2086. (movq (var x) (var y))
  2087. (addq (int 4) (var y))
  2088. (movq (var x) (var z))
  2089. (addq (var w) (var z))
  2090. (movq (var y) (var t.1))
  2091. (negq (var t.1))
  2092. (movq (var z) (reg rax))
  2093. (addq (var t.1) (reg rax))
  2094. (jmp conclusion))
  2095. \end{lstlisting}
  2096. \end{minipage}
  2097. \vrule\hspace{10pt}
  2098. \begin{minipage}{0.45\textwidth}
  2099. \begin{lstlisting}
  2100. |$\{\}$|
  2101. |$\{v \}$|
  2102. |$\{v,w\}$|
  2103. |$\{w,x\}$|
  2104. |$\{w,x\}$|
  2105. |$\{w,x,y\}$|
  2106. |$\{w,x,y\}$|
  2107. |$\{w,y,z\}$|
  2108. |$\{y,z\}$|
  2109. |$\{z,t.1\}$|
  2110. |$\{z,t.1\}$|
  2111. |$\{t.1\}$|
  2112. |$\{\}$|
  2113. |$\{\}$|
  2114. \end{lstlisting}
  2115. \end{minipage}
  2116. \caption{An example block annotated with live-after sets.}
  2117. \label{fig:live-eg}
  2118. \end{figure}
  2119. \begin{exercise}\normalfont
  2120. Implement the compiler pass named \code{uncover-live} that computes
  2121. the live-after sets. We recommend storing the live-after sets (a list
  2122. of lists of variables) in the $\itm{info}$ field of the \key{block}
  2123. construct.
  2124. %
  2125. We recommend organizing your code to use a helper function that takes
  2126. a list of instructions and an initial live-after set (typically empty)
  2127. and returns the list of live-after sets.
  2128. %
  2129. We recommend creating helper functions to 1) compute the set of
  2130. variables that appear in an argument (of an instruction), 2) compute
  2131. the variables read by an instruction which corresponds to the $R$
  2132. function discussed above, and 3) the variables written by an
  2133. instruction which corresponds to $W$.
  2134. \end{exercise}
  2135. \section{Building the Interference Graph}
  2136. \label{sec:build-interference}
  2137. Based on the liveness analysis, we know where each variable is needed.
  2138. However, during register allocation, we need to answer questions of
  2139. the specific form: are variables $u$ and $v$ live at the same time?
  2140. (And therefore cannot be assigned to the same register.) To make this
  2141. question easier to answer, we create an explicit data structure, an
  2142. \emph{interference graph}. An interference graph is an undirected
  2143. graph that has an edge between two variables if they are live at the
  2144. same time, that is, if they interfere with each other.
  2145. The most obvious way to compute the interference graph is to look at
  2146. the set of live variables between each statement in the program, and
  2147. add an edge to the graph for every pair of variables in the same set.
  2148. This approach is less than ideal for two reasons. First, it can be
  2149. rather expensive because it takes $O(n^2)$ time to look at every pair
  2150. in a set of $n$ live variables. Second, there is a special case in
  2151. which two variables that are live at the same time do not actually
  2152. interfere with each other: when they both contain the same value
  2153. because we have assigned one to the other.
  2154. A better way to compute the interference graph is to focus on the
  2155. writes. That is, for each instruction, create an edge between the
  2156. variable being written to and all the \emph{other} live variables.
  2157. (One should not create self edges.) For a \key{callq} instruction,
  2158. think of all caller-saved registers as being written to, so and edge
  2159. must be added between every live variable and every caller-saved
  2160. register. For \key{movq}, we deal with the above-mentioned special
  2161. case by not adding an edge between a live variable $v$ and destination
  2162. $d$ if $v$ matches the source of the move. So we have the following
  2163. three rules.
  2164. \begin{enumerate}
  2165. \item If instruction $I_k$ is an arithmetic instruction such as
  2166. (\key{addq} $s$\, $d$), then add the edge $(d,v)$ for every $v \in
  2167. L_{\mathsf{after}}(k)$ unless $v = d$.
  2168. \item If instruction $I_k$ is of the form (\key{callq}
  2169. $\mathit{label}$), then add an edge $(r,v)$ for every caller-saved
  2170. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2171. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  2172. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2173. d$ or $v = s$.
  2174. \end{enumerate}
  2175. \margincomment{JM: I think you could give examples of each one of these
  2176. using the example program and use those to help explain why these
  2177. rules are correct.\\
  2178. JS: Agreed.}
  2179. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2180. the following interference for the instruction at the specified line
  2181. number.
  2182. \begin{quote}
  2183. Line 2: no interference,\\
  2184. Line 3: $w$ interferes with $v$,\\
  2185. Line 4: $x$ interferes with $w$,\\
  2186. Line 5: $x$ interferes with $w$,\\
  2187. Line 6: $y$ interferes with $w$,\\
  2188. Line 7: $y$ interferes with $w$ and $x$,\\
  2189. Line 8: $z$ interferes with $w$ and $y$,\\
  2190. Line 9: $z$ interferes with $y$, \\
  2191. Line 10: $t.1$ interferes with $z$, \\
  2192. Line 11: $t.1$ interferes with $z$, \\
  2193. Line 12: no interference, \\
  2194. Line 13: no interference. \\
  2195. Line 14: no interference.
  2196. \end{quote}
  2197. The resulting interference graph is shown in
  2198. Figure~\ref{fig:interfere}.
  2199. \begin{figure}[tbp]
  2200. \large
  2201. \[
  2202. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2203. \node (v) at (0,0) {$v$};
  2204. \node (w) at (2,0) {$w$};
  2205. \node (x) at (4,0) {$x$};
  2206. \node (t1) at (6,-2) {$t.1$};
  2207. \node (y) at (2,-2) {$y$};
  2208. \node (z) at (4,-2) {$z$};
  2209. \draw (v) to (w);
  2210. \foreach \i in {w,x,y}
  2211. {
  2212. \foreach \j in {w,x,y}
  2213. {
  2214. \draw (\i) to (\j);
  2215. }
  2216. }
  2217. \draw (z) to (w);
  2218. \draw (z) to (y);
  2219. \draw (t1) to (z);
  2220. \end{tikzpicture}
  2221. \]
  2222. \caption{The interference graph of the example program.}
  2223. \label{fig:interfere}
  2224. \end{figure}
  2225. %% Our next concern is to choose a data structure for representing the
  2226. %% interference graph. There are many choices for how to represent a
  2227. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2228. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2229. %% data structure is to study the algorithm that uses the data structure,
  2230. %% determine what operations need to be performed, and then choose the
  2231. %% data structure that provide the most efficient implementations of
  2232. %% those operations. Often times the choice of data structure can have an
  2233. %% effect on the time complexity of the algorithm, as it does here. If
  2234. %% you skim the next section, you will see that the register allocation
  2235. %% algorithm needs to ask the graph for all of its vertices and, given a
  2236. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2237. %% correct choice of graph representation is that of an adjacency
  2238. %% list. There are helper functions in \code{utilities.rkt} for
  2239. %% representing graphs using the adjacency list representation:
  2240. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2241. %% (Appendix~\ref{appendix:utilities}).
  2242. %% %
  2243. %% \margincomment{\footnotesize To do: change to use the
  2244. %% Racket graph library. \\ --Jeremy}
  2245. %% %
  2246. %% In particular, those functions use a hash table to map each vertex to
  2247. %% the set of adjacent vertices, and the sets are represented using
  2248. %% Racket's \key{set}, which is also a hash table.
  2249. \begin{exercise}\normalfont
  2250. Implement the compiler pass named \code{build-interference} according
  2251. to the algorithm suggested above. We recommend using the Racket
  2252. \code{graph} package to create and inspect the interference graph.
  2253. The output graph of this pass should be stored in the $\itm{info}$
  2254. field of the program, under the key \code{conflicts}.
  2255. \end{exercise}
  2256. \section{Graph Coloring via Sudoku}
  2257. \label{sec:graph-coloring}
  2258. We now come to the main event, mapping variables to registers (or to
  2259. stack locations in the event that we run out of registers). We need
  2260. to make sure not to map two variables to the same register if the two
  2261. variables interfere with each other. In terms of the interference
  2262. graph, this means that adjacent vertices must be mapped to different
  2263. registers. If we think of registers as colors, the register
  2264. allocation problem becomes the widely-studied graph coloring
  2265. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2266. The reader may be more familiar with the graph coloring problem than he
  2267. or she realizes; the popular game of Sudoku is an instance of the
  2268. graph coloring problem. The following describes how to build a graph
  2269. out of an initial Sudoku board.
  2270. \begin{itemize}
  2271. \item There is one vertex in the graph for each Sudoku square.
  2272. \item There is an edge between two vertices if the corresponding squares
  2273. are in the same row, in the same column, or if the squares are in
  2274. the same $3\times 3$ region.
  2275. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2276. \item Based on the initial assignment of numbers to squares in the
  2277. Sudoku board, assign the corresponding colors to the corresponding
  2278. vertices in the graph.
  2279. \end{itemize}
  2280. If you can color the remaining vertices in the graph with the nine
  2281. colors, then you have also solved the corresponding game of Sudoku.
  2282. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2283. the corresponding graph with colored vertices. We map the Sudoku
  2284. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2285. sampling of the vertices (those that are colored) because showing
  2286. edges for all of the vertices would make the graph unreadable.
  2287. \begin{figure}[tbp]
  2288. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2289. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2290. \caption{A Sudoku game board and the corresponding colored graph.}
  2291. \label{fig:sudoku-graph}
  2292. \end{figure}
  2293. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2294. strategies to come up with an algorithm for allocating registers. For
  2295. example, one of the basic techniques for Sudoku is called Pencil
  2296. Marks. The idea is that you use a process of elimination to determine
  2297. what numbers no longer make sense for a square, and write down those
  2298. numbers in the square (writing very small). For example, if the number
  2299. $1$ is assigned to a square, then by process of elimination, you can
  2300. write the pencil mark $1$ in all the squares in the same row, column,
  2301. and region. Many Sudoku computer games provide automatic support for
  2302. Pencil Marks.
  2303. %
  2304. The Pencil Marks technique corresponds to the notion of color
  2305. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2306. vertex, in Sudoku terms, is the set of colors that are no longer
  2307. available. In graph terminology, we have the following definition:
  2308. \begin{equation*}
  2309. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2310. \text{ and } \mathrm{color}(v) = c \}
  2311. \end{equation*}
  2312. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2313. edge with $u$.
  2314. Using the Pencil Marks technique leads to a simple strategy for
  2315. filling in numbers: if there is a square with only one possible number
  2316. left, then write down that number! But what if there are no squares
  2317. with only one possibility left? One brute-force approach is to just
  2318. make a guess. If that guess ultimately leads to a solution, great. If
  2319. not, backtrack to the guess and make a different guess. One good
  2320. thing about Pencil Marks is that it reduces the degree of branching in
  2321. the search tree. Nevertheless, backtracking can be horribly time
  2322. consuming. One way to reduce the amount of backtracking is to use the
  2323. most-constrained-first heuristic. That is, when making a guess, always
  2324. choose a square with the fewest possibilities left (the vertex with
  2325. the highest saturation). The idea is that choosing highly constrained
  2326. squares earlier rather than later is better because later there may
  2327. not be any possibilities.
  2328. In some sense, register allocation is easier than Sudoku because we
  2329. can always cheat and add more numbers by mapping variables to the
  2330. stack. We say that a variable is \emph{spilled} when we decide to map
  2331. it to a stack location. We would like to minimize the time needed to
  2332. color the graph, and backtracking is expensive. Thus, it makes sense
  2333. to keep the most-constrained-first heuristic but drop the backtracking
  2334. in favor of greedy search (guess and just keep going).
  2335. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2336. greedy algorithm for register allocation based on saturation and the
  2337. most-constrained-first heuristic, which is roughly equivalent to the
  2338. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2339. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2340. as in Sudoku, the algorithm represents colors with integers, with the
  2341. first $k$ colors corresponding to the $k$ registers in a given machine
  2342. and the rest of the integers corresponding to stack locations.
  2343. \begin{figure}[btp]
  2344. \centering
  2345. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2346. Algorithm: DSATUR
  2347. Input: a graph |$G$|
  2348. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2349. |$W \gets \mathit{vertices}(G)$|
  2350. while |$W \neq \emptyset$| do
  2351. pick a vertex |$u$| from |$W$| with the highest saturation,
  2352. breaking ties randomly
  2353. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2354. |$\mathrm{color}[u] \gets c$|
  2355. |$W \gets W - \{u\}$|
  2356. \end{lstlisting}
  2357. \caption{The saturation-based greedy graph coloring algorithm.}
  2358. \label{fig:satur-algo}
  2359. \end{figure}
  2360. With this algorithm in hand, let us return to the running example and
  2361. consider how to color the interference graph in
  2362. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2363. register allocation because we use it to patch instructions, so we
  2364. remove that vertex from the graph. Initially, all of the vertices are
  2365. not yet colored and they are unsaturated, so we annotate each of them
  2366. with a dash for their color and an empty set for the saturation.
  2367. \[
  2368. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2369. \node (v) at (0,0) {$v:-,\{\}$};
  2370. \node (w) at (3,0) {$w:-,\{\}$};
  2371. \node (x) at (6,0) {$x:-,\{\}$};
  2372. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2373. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2374. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2375. \draw (v) to (w);
  2376. \foreach \i in {w,x,y}
  2377. {
  2378. \foreach \j in {w,x,y}
  2379. {
  2380. \draw (\i) to (\j);
  2381. }
  2382. }
  2383. \draw (z) to (w);
  2384. \draw (z) to (y);
  2385. \draw (t1) to (z);
  2386. \end{tikzpicture}
  2387. \]
  2388. We select a maximally saturated vertex and color it $0$. In this case we
  2389. have a 7-way tie, so we arbitrarily pick $t.1$. The then mark color $0$
  2390. as no longer available for $z$ because it interferes
  2391. with $t.1$.
  2392. \[
  2393. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2394. \node (v) at (0,0) {$v:-,\{\}$};
  2395. \node (w) at (3,0) {$w:-,\{\}$};
  2396. \node (x) at (6,0) {$x:-,\{\}$};
  2397. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2398. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2399. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2400. \draw (v) to (w);
  2401. \foreach \i in {w,x,y}
  2402. {
  2403. \foreach \j in {w,x,y}
  2404. {
  2405. \draw (\i) to (\j);
  2406. }
  2407. }
  2408. \draw (z) to (w);
  2409. \draw (z) to (y);
  2410. \draw (t1) to (z);
  2411. \end{tikzpicture}
  2412. \]
  2413. Now we repeat the process, selecting another maximally saturated
  2414. vertex, which in this case is $z$. We color $z$ with $1$.
  2415. \[
  2416. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2417. \node (v) at (0,0) {$v:-,\{\}$};
  2418. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2419. \node (x) at (6,0) {$x:-,\{\}$};
  2420. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2421. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2422. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2423. \draw (t1) to (z);
  2424. \draw (v) to (w);
  2425. \foreach \i in {w,x,y}
  2426. {
  2427. \foreach \j in {w,x,y}
  2428. {
  2429. \draw (\i) to (\j);
  2430. }
  2431. }
  2432. \draw (z) to (w);
  2433. \draw (z) to (y);
  2434. \end{tikzpicture}
  2435. \]
  2436. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2437. first available color, which is $0$.
  2438. \[
  2439. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2440. \node (v) at (0,0) {$v:-,\{\}$};
  2441. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2442. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2443. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2444. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2445. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2446. \draw (t1) to (z);
  2447. \draw (v) to (w);
  2448. \foreach \i in {w,x,y}
  2449. {
  2450. \foreach \j in {w,x,y}
  2451. {
  2452. \draw (\i) to (\j);
  2453. }
  2454. }
  2455. \draw (z) to (w);
  2456. \draw (z) to (y);
  2457. \end{tikzpicture}
  2458. \]
  2459. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2460. \[
  2461. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2462. \node (v) at (0,0) {$v:-,\{2\}$};
  2463. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2464. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2465. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2466. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2467. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2468. \draw (t1) to (z);
  2469. \draw (v) to (w);
  2470. \foreach \i in {w,x,y}
  2471. {
  2472. \foreach \j in {w,x,y}
  2473. {
  2474. \draw (\i) to (\j);
  2475. }
  2476. }
  2477. \draw (z) to (w);
  2478. \draw (z) to (y);
  2479. \end{tikzpicture}
  2480. \]
  2481. Now $x$ has the highest saturation, so we color it $1$.
  2482. \[
  2483. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2484. \node (v) at (0,0) {$v:-,\{2\}$};
  2485. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2486. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2487. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2488. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2489. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2490. \draw (t1) to (z);
  2491. \draw (v) to (w);
  2492. \foreach \i in {w,x,y}
  2493. {
  2494. \foreach \j in {w,x,y}
  2495. {
  2496. \draw (\i) to (\j);
  2497. }
  2498. }
  2499. \draw (z) to (w);
  2500. \draw (z) to (y);
  2501. \end{tikzpicture}
  2502. \]
  2503. In the last step of the algorithm, we color $v$ with $0$.
  2504. \[
  2505. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2506. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2507. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2508. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2509. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2510. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2511. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2512. \draw (t1) to (z);
  2513. \draw (v) to (w);
  2514. \foreach \i in {w,x,y}
  2515. {
  2516. \foreach \j in {w,x,y}
  2517. {
  2518. \draw (\i) to (\j);
  2519. }
  2520. }
  2521. \draw (z) to (w);
  2522. \draw (z) to (y);
  2523. \end{tikzpicture}
  2524. \]
  2525. With the coloring complete, we can finalize the assignment of
  2526. variables to registers and stack locations. Recall that if we have $k$
  2527. registers, we map the first $k$ colors to registers and the rest to
  2528. stack locations. Suppose for the moment that we have just one
  2529. register to use for register allocation, \key{rcx}. Then the following
  2530. is the mapping of colors to registers and stack allocations.
  2531. \[
  2532. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2533. \]
  2534. Putting this mapping together with the above coloring of the variables, we
  2535. arrive at the assignment:
  2536. \begin{gather*}
  2537. \{ v \mapsto \key{\%rcx}, \,
  2538. w \mapsto \key{-16(\%rbp)}, \,
  2539. x \mapsto \key{-8(\%rbp)}, \\
  2540. y \mapsto \key{\%rcx}, \,
  2541. z\mapsto \key{-8(\%rbp)},
  2542. t.1\mapsto \key{\%rcx} \}
  2543. \end{gather*}
  2544. Applying this assignment to our running example, on the left, yields
  2545. the program on the right.\\
  2546. % why frame size of 32? -JGS
  2547. \begin{minipage}{0.4\textwidth}
  2548. \begin{lstlisting}
  2549. (block ()
  2550. (movq (int 1) (var v))
  2551. (movq (int 46) (var w))
  2552. (movq (var v) (var x))
  2553. (addq (int 7) (var x))
  2554. (movq (var x) (var y))
  2555. (addq (int 4) (var y))
  2556. (movq (var x) (var z))
  2557. (addq (var w) (var z))
  2558. (movq (var y) (var t.1))
  2559. (negq (var t.1))
  2560. (movq (var z) (reg rax))
  2561. (addq (var t.1) (reg rax))
  2562. (jmp conclusion))
  2563. \end{lstlisting}
  2564. \end{minipage}
  2565. $\Rightarrow$
  2566. \begin{minipage}{0.45\textwidth}
  2567. \begin{lstlisting}
  2568. (block ()
  2569. (movq (int 1) (reg rcx))
  2570. (movq (int 46) (deref rbp -16))
  2571. (movq (reg rcx) (deref rbp -8))
  2572. (addq (int 7) (deref rbp -8))
  2573. (movq (deref rbp -8) (reg rcx))
  2574. (addq (int 4) (reg rcx))
  2575. (movq (deref rbp -8) (deref rbp -8))
  2576. (addq (deref rbp -16) (deref rbp -8))
  2577. (movq (reg rcx) (reg rcx))
  2578. (negq (reg rcx))
  2579. (movq (deref rbp -8) (reg rax))
  2580. (addq (reg rcx) (reg rax))
  2581. (jmp conclusion))
  2582. \end{lstlisting}
  2583. \end{minipage}
  2584. The resulting program is almost an x86 program. The remaining step
  2585. is to apply the patch instructions pass. In this example, the trivial
  2586. move of \code{-8(\%rbp)} to itself is deleted and the addition of
  2587. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2588. \code{rax} as follows.
  2589. \begin{lstlisting}
  2590. (movq (deref rbp -16) (reg rax)
  2591. (addq (reg rax) (deref rbp -8))
  2592. \end{lstlisting}
  2593. An overview of all of the passes involved in register allocation is
  2594. shown in Figure~\ref{fig:reg-alloc-passes}.
  2595. \begin{figure}[tbp]
  2596. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2597. \node (R1) at (0,2) {\large $R_1$};
  2598. \node (R1-2) at (3,2) {\large $R_1$};
  2599. \node (R1-3) at (6,2) {\large $R_1$};
  2600. \node (C0-1) at (6,0) {\large $C_0$};
  2601. \node (C0-2) at (3,0) {\large $C_0$};
  2602. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2603. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2604. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2605. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2606. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2607. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2608. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2609. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2610. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2611. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2612. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2613. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2614. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2615. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2616. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2617. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2618. \end{tikzpicture}
  2619. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2620. \label{fig:reg-alloc-passes}
  2621. \end{figure}
  2622. \begin{exercise}\normalfont
  2623. Implement the pass \code{allocate-registers}, which should come
  2624. after the \code{build-interference} pass. The three new passes,
  2625. \code{uncover-live}, \code{build-interference}, and
  2626. \code{allocate-registers} replace the \code{assign-homes} pass of
  2627. Section~\ref{sec:assign-r1}.
  2628. We recommend that you create a helper function named
  2629. \code{color-graph} that takes an interference graph and a list of
  2630. all the variables in the program. This function should return a
  2631. mapping of variables to their colors (represented as natural
  2632. numbers). By creating this helper function, you will be able to
  2633. reuse it in Chapter~\ref{ch:functions} when you add support for
  2634. functions.
  2635. Once you have obtained the coloring from \code{color-graph}, you can
  2636. assign the variables to registers or stack locations and then reuse
  2637. code from the \code{assign-homes} pass from
  2638. Section~\ref{sec:assign-r1} to replace the variables with their
  2639. assigned location.
  2640. Test your updated compiler by creating new example programs that
  2641. exercise all of the register allocation algorithm, such as forcing
  2642. variables to be spilled to the stack.
  2643. \end{exercise}
  2644. \section{Print x86 and Conventions for Registers}
  2645. \label{sec:print-x86-reg-alloc}
  2646. Recall the \code{print-x86} pass generates the prelude and
  2647. conclusion instructions for the \code{main} function.
  2648. %
  2649. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2650. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2651. reason for this is that our \code{main} function must adhere to the
  2652. x86 calling conventions that we described in
  2653. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2654. function needs to restore (in the conclusion) any callee-saved
  2655. registers that get used during register allocation. The simplest
  2656. approach is to save and restore all of the callee-saved registers. The
  2657. more efficient approach is to keep track of which callee-saved
  2658. registers were used and only save and restore them. Either way, make
  2659. sure to take this use of stack space into account when you are
  2660. calculating the size of the frame. Also, don't forget that the size of
  2661. the frame needs to be a multiple of 16 bytes.
  2662. \section{Challenge: Move Biasing$^{*}$}
  2663. \label{sec:move-biasing}
  2664. This section describes an optional enhancement to register allocation
  2665. for those students who are looking for an extra challenge or who have
  2666. a deeper interest in register allocation.
  2667. We return to the running example, but we remove the supposition that
  2668. we only have one register to use. So we have the following mapping of
  2669. color numbers to registers.
  2670. \[
  2671. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2672. \]
  2673. Using the same assignment that was produced by register allocator
  2674. described in the last section, we get the following program.
  2675. \begin{minipage}{0.45\textwidth}
  2676. \begin{lstlisting}
  2677. (block ()
  2678. (movq (int 1) (var v))
  2679. (movq (int 46) (var w))
  2680. (movq (var v) (var x))
  2681. (addq (int 7) (var x))
  2682. (movq (var x) (var y))
  2683. (addq (int 4) (var y))
  2684. (movq (var x) (var z))
  2685. (addq (var w) (var z))
  2686. (movq (var y) (var t.1))
  2687. (negq (var t.1))
  2688. (movq (var z) (reg rax))
  2689. (addq (var t.1) (reg rax))
  2690. (jmp conclusion))
  2691. \end{lstlisting}
  2692. \end{minipage}
  2693. $\Rightarrow$
  2694. \begin{minipage}{0.45\textwidth}
  2695. \begin{lstlisting}
  2696. (block ()
  2697. (movq (int 1) (reg rbx))
  2698. (movq (int 46) (reg rdx))
  2699. (movq (reg rbx) (reg rcx))
  2700. (addq (int 7) (reg rcx))
  2701. (movq (reg rcx) (reg rbx))
  2702. (addq (int 4) (reg rbx))
  2703. (movq (reg rcx) (reg rcx))
  2704. (addq (reg rdx) (reg rcx))
  2705. (movq (reg rbx) (reg rbx))
  2706. (negq (reg rbx))
  2707. (movq (reg rcx) (reg rax))
  2708. (addq (reg rbx) (reg rax))
  2709. (jmp conclusion))
  2710. \end{lstlisting}
  2711. \end{minipage}
  2712. While this allocation is quite good, we could do better. For example,
  2713. the variables \key{v} and \key{x} ended up in different registers, but
  2714. if they had been placed in the same register, then the move from
  2715. \key{v} to \key{x} could be removed.
  2716. We say that two variables $p$ and $q$ are \emph{move related} if they
  2717. participate together in a \key{movq} instruction, that is, \key{movq}
  2718. $p$, $q$ or \key{movq} $q$, $p$. When the register allocator chooses a
  2719. color for a variable, it should prefer a color that has already been
  2720. used for a move-related variable (assuming that they do not
  2721. interfere). Of course, this preference should not override the
  2722. preference for registers over stack locations, but should only be used
  2723. as a tie breaker when choosing between registers or when choosing
  2724. between stack locations.
  2725. We recommend that you represent the move relationships in a graph,
  2726. similar to how we represented interference. The following is the
  2727. \emph{move graph} for our running example.
  2728. \[
  2729. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2730. \node (v) at (0,0) {$v$};
  2731. \node (w) at (3,0) {$w$};
  2732. \node (x) at (6,0) {$x$};
  2733. \node (y) at (3,-1.5) {$y$};
  2734. \node (z) at (6,-1.5) {$z$};
  2735. \node (t1) at (9,-1.5) {$t.1$};
  2736. \draw[bend left=15] (t1) to (y);
  2737. \draw[bend left=15] (v) to (x);
  2738. \draw (x) to (y);
  2739. \draw (x) to (z);
  2740. \end{tikzpicture}
  2741. \]
  2742. Now we replay the graph coloring, pausing to see the coloring of $x$
  2743. and $v$. So we have the following coloring and the most saturated
  2744. vertex is $x$.
  2745. \[
  2746. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2747. \node (v) at (0,0) {$v:-,\{2\}$};
  2748. \node (w) at (3,0) {$w:2,\{0,1\}$};
  2749. \node (x) at (6,0) {$x:-,\{0,2\}$};
  2750. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2751. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2752. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2753. \draw (t1) to (z);
  2754. \draw (v) to (w);
  2755. \foreach \i in {w,x,y}
  2756. {
  2757. \foreach \j in {w,x,y}
  2758. {
  2759. \draw (\i) to (\j);
  2760. }
  2761. }
  2762. \draw (z) to (w);
  2763. \draw (z) to (y);
  2764. \end{tikzpicture}
  2765. \]
  2766. Last time we chose to color $x$ with $1$,
  2767. %
  2768. which so happens to be the color of $z$, and $x$ is move related to
  2769. $z$. This was rather lucky, and if the program had been a little
  2770. different, and say $z$ had been already assigned to $2$, then $x$
  2771. would still get $1$ and our luck would have run out. With move
  2772. biasing, we use the fact that $x$ and $z$ are move related to
  2773. influence the choice of color for $x$, in this case choosing $1$
  2774. because that's the color of $z$.
  2775. \[
  2776. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2777. \node (v) at (0,0) {$v:-,\{2\}$};
  2778. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2779. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2780. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2781. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2782. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2783. \draw (t1) to (z);
  2784. \draw (v) to (w);
  2785. \foreach \i in {w,x,y}
  2786. {
  2787. \foreach \j in {w,x,y}
  2788. {
  2789. \draw (\i) to (\j);
  2790. }
  2791. }
  2792. \draw (z) to (w);
  2793. \draw (z) to (y);
  2794. \end{tikzpicture}
  2795. \]
  2796. Next we consider coloring the variable $v$, and we just need to avoid
  2797. choosing $2$ because of the interference with $w$. Last time we choose
  2798. the color $0$, simply because it was the lowest, but this time we know
  2799. that $v$ is move related to $x$, so we choose the color $1$.
  2800. \[
  2801. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2802. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  2803. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2804. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2805. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2806. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2807. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2808. \draw (t1) to (z);
  2809. \draw (v) to (w);
  2810. \foreach \i in {w,x,y}
  2811. {
  2812. \foreach \j in {w,x,y}
  2813. {
  2814. \draw (\i) to (\j);
  2815. }
  2816. }
  2817. \draw (z) to (w);
  2818. \draw (z) to (y);
  2819. \end{tikzpicture}
  2820. \]
  2821. We apply this register assignment to the running example, on the left,
  2822. to obtain the code on right.
  2823. \begin{minipage}{0.45\textwidth}
  2824. \begin{lstlisting}
  2825. (block ()
  2826. (movq (int 1) (var v))
  2827. (movq (int 46) (var w))
  2828. (movq (var v) (var x))
  2829. (addq (int 7) (var x))
  2830. (movq (var x) (var y))
  2831. (addq (int 4) (var y))
  2832. (movq (var x) (var z))
  2833. (addq (var w) (var z))
  2834. (movq (var y) (var t.1))
  2835. (negq (var t.1))
  2836. (movq (var z) (reg rax))
  2837. (addq (var t.1) (reg rax))
  2838. (jmp conclusion))
  2839. \end{lstlisting}
  2840. \end{minipage}
  2841. $\Rightarrow$
  2842. \begin{minipage}{0.45\textwidth}
  2843. \begin{lstlisting}
  2844. (block ()
  2845. (movq (int 1) (reg rcx))
  2846. (movq (int 46) (reg rbx))
  2847. (movq (reg rcx) (reg rcx))
  2848. (addq (int 7) (reg rcx))
  2849. (movq (reg rcx) (reg rdx))
  2850. (addq (int 4) (reg rdx))
  2851. (movq (reg rcx) (reg rcx))
  2852. (addq (reg rbx) (reg rcx))
  2853. (movq (reg rdx) (reg rbx))
  2854. (negq (reg rbx))
  2855. (movq (reg rcx) (reg rax))
  2856. (addq (reg rbx) (reg rax))
  2857. (jmp conclusion))
  2858. \end{lstlisting}
  2859. \end{minipage}
  2860. The \code{patch-instructions} then removes the trivial moves from
  2861. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  2862. result.
  2863. \begin{minipage}{0.45\textwidth}
  2864. \begin{lstlisting}
  2865. (block ()
  2866. (movq (int 1) (reg rcx))
  2867. (movq (int 46) (reg rbx))
  2868. (addq (int 7) (reg rcx))
  2869. (movq (reg rcx) (reg rdx))
  2870. (addq (int 4) (reg rdx))
  2871. (addq (reg rbx) (reg rcx))
  2872. (movq (reg rdx) (reg rbx))
  2873. (negq (reg rbx))
  2874. (movq (reg rcx) (reg rax))
  2875. (addq (reg rbx) (reg rax))
  2876. (jmp conclusion))
  2877. \end{lstlisting}
  2878. \end{minipage}
  2879. \begin{exercise}\normalfont
  2880. Change your implementation of \code{allocate-registers} to take move
  2881. biasing into account. Make sure that your compiler still passes all of
  2882. the previous tests. Create two new tests that include at least one
  2883. opportunity for move biasing and visually inspect the output x86
  2884. programs to make sure that your move biasing is working properly.
  2885. \end{exercise}
  2886. \margincomment{\footnotesize To do: another neat challenge would be to do
  2887. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2888. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2889. \chapter{Booleans and Control Flow}
  2890. \label{ch:bool-types}
  2891. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2892. integers. In this Chapter we add a second kind of value, the Booleans,
  2893. to create the $R_2$ language. The Boolean values \emph{true} and
  2894. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2895. Racket. We also introduce several operations that involve Booleans
  2896. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2897. \key{if} expression. With the addition of \key{if} expressions,
  2898. programs can have non-trivial control flow which has an impact on
  2899. several parts of the compiler. Also, because we now have two kinds of
  2900. values, we need to worry about programs that apply an operation to the
  2901. wrong kind of value, such as \code{(not 1)}.
  2902. There are two language design options for such situations. One option
  2903. is to signal an error and the other is to provide a wider
  2904. interpretation of the operation. The Racket language uses a mixture of
  2905. these two options, depending on the operation and the kind of
  2906. value. For example, the result of \code{(not 1)} in Racket is
  2907. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2908. the other hand, \code{(car 1)} results in a run-time error in Racket
  2909. stating that \code{car} expects a pair.
  2910. The Typed Racket language makes similar design choices as Racket,
  2911. except much of the error detection happens at compile time instead of
  2912. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2913. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2914. reports a compile-time error because Typed Racket expects the type of
  2915. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2916. For the $R_2$ language we choose to be more like Typed Racket in that
  2917. we shall perform type checking during compilation. In
  2918. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2919. is, how to compile a dynamically typed language like Racket. The
  2920. $R_2$ language is a subset of Typed Racket but by no means includes
  2921. all of Typed Racket. Furthermore, for many of the operations we shall
  2922. take a narrower interpretation than Typed Racket, for example,
  2923. rejecting \code{(not 1)}.
  2924. This chapter is organized as follows. We begin by defining the syntax
  2925. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2926. then introduce the idea of type checking and build a type checker for
  2927. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2928. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2929. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2930. how our compiler passes need to change to accommodate Booleans and
  2931. conditional control flow.
  2932. \section{The $R_2$ Language}
  2933. \label{sec:r2-lang}
  2934. The syntax of the $R_2$ language is defined in
  2935. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray),
  2936. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2937. \code{if} expression. Also, we expand the operators to include
  2938. subtraction, \key{and}, \key{or} and \key{not}, the \key{eq?}
  2939. operations for comparing two integers or two Booleans, and the
  2940. \key{<}, \key{<=}, \key{>}, and \key{>=} operations for comparing
  2941. integers.
  2942. \begin{figure}[tp]
  2943. \centering
  2944. \fbox{
  2945. \begin{minipage}{0.96\textwidth}
  2946. \[
  2947. \begin{array}{lcl}
  2948. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2949. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \mid (\key{-}\;\Exp\;\Exp) \\
  2950. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2951. &\mid& \key{\#t} \mid \key{\#f}
  2952. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  2953. \mid (\key{not}\;\Exp) \\
  2954. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2955. R_2 &::=& (\key{program} \; \itm{info}\; \Exp)
  2956. \end{array}
  2957. \]
  2958. \end{minipage}
  2959. }
  2960. \caption{The syntax of $R_2$, extending $R_1$
  2961. (Figure~\ref{fig:r1-syntax}) with Booleans and conditionals.}
  2962. \label{fig:r2-syntax}
  2963. \end{figure}
  2964. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2965. the parts that are the same as the interpreter for $R_1$
  2966. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2967. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2968. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2969. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2970. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2971. operations \code{not} and \code{and} behave as you might expect, but
  2972. note that the \code{and} operation is short-circuiting. That is, given
  2973. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2974. evaluated if $e_1$ evaluates to \code{\#f}.
  2975. With the addition of the comparison operations, there are quite a few
  2976. primitive operations and the interpreter code for them is somewhat
  2977. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2978. parts into the \code{interp-op} function and the similar parts into
  2979. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  2980. use \code{interp-op} for the \code{and} operation because of the
  2981. short-circuiting behavior in the order of evaluation of its arguments.
  2982. \begin{figure}[tbp]
  2983. \begin{lstlisting}
  2984. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2985. (define (interp-op op)
  2986. (match op
  2987. ...
  2988. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2989. ['eq? (lambda (v1 v2)
  2990. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2991. (and (boolean? v1) (boolean? v2)))
  2992. (eq? v1 v2)]))]
  2993. ['< (lambda (v1 v2)
  2994. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  2995. ['<= (lambda (v1 v2)
  2996. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  2997. ['> (lambda (v1 v2)
  2998. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  2999. ['>= (lambda (v1 v2)
  3000. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3001. [else (error 'interp-op "unknown operator")]))
  3002. (define (interp-exp env)
  3003. (lambda (e)
  3004. (define recur (interp-exp env))
  3005. (match e
  3006. ...
  3007. [(? boolean?) e]
  3008. [`(if ,cnd ,thn ,els)
  3009. (define b (recur cnd))
  3010. (match b
  3011. [#t (recur thn)]
  3012. [#f (recur els)])]
  3013. [`(and ,e1 ,e2)
  3014. (define v1 (recur e1))
  3015. (match v1
  3016. [#t (match (recur e2) [#t #t] [#f #f])]
  3017. [#f #f])]
  3018. [`(,op ,args ...)
  3019. #:when (set-member? primitives op)
  3020. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3021. )))
  3022. (define (interp-R2 env)
  3023. (lambda (p)
  3024. (match p
  3025. [`(program ,info ,e)
  3026. ((interp-exp '()) e)])))
  3027. \end{lstlisting}
  3028. \caption{Interpreter for the $R_2$ language.}
  3029. \label{fig:interp-R2}
  3030. \end{figure}
  3031. \section{Type Checking $R_2$ Programs}
  3032. \label{sec:type-check-r2}
  3033. It is helpful to think about type checking in two complementary
  3034. ways. A type checker predicts the \emph{type} of value that will be
  3035. produced by each expression in the program. For $R_2$, we have just
  3036. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3037. predict that
  3038. \begin{lstlisting}
  3039. (+ 10 (- (+ 12 20)))
  3040. \end{lstlisting}
  3041. produces an \key{Integer} while
  3042. \begin{lstlisting}
  3043. (and (not #f) #t)
  3044. \end{lstlisting}
  3045. produces a \key{Boolean}.
  3046. As mentioned at the beginning of this chapter, a type checker also
  3047. rejects programs that apply operators to the wrong type of value. Our
  3048. type checker for $R_2$ will signal an error for the following
  3049. expression because, as we have seen above, the expression \code{(+ 10
  3050. ...)} has type \key{Integer}, and we require the argument of a
  3051. \code{not} to have type \key{Boolean}.
  3052. \begin{lstlisting}
  3053. (not (+ 10 (- (+ 12 20))))
  3054. \end{lstlisting}
  3055. The type checker for $R_2$ is best implemented as a structurally
  3056. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3057. many of the clauses for the \code{type-check-exp} function. Given an
  3058. input expression \code{e}, the type checker either returns the type
  3059. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3060. the type of an integer literal is \code{Integer} and the type of a
  3061. Boolean literal is \code{Boolean}. To handle variables, the type
  3062. checker, like the interpreter, uses an association list. However, in
  3063. this case the association list maps variables to types instead of
  3064. values. Consider the clause for \key{let}. We type check the
  3065. initializing expression to obtain its type \key{T} and then associate
  3066. type \code{T} with the variable \code{x}. When the type checker
  3067. encounters the use of a variable, it can find its type in the
  3068. association list.
  3069. \begin{figure}[tbp]
  3070. \begin{lstlisting}
  3071. (define (type-check-exp env)
  3072. (lambda (e)
  3073. (define recur (type-check-exp env))
  3074. (match e
  3075. [(? fixnum?) 'Integer]
  3076. [(? boolean?) 'Boolean]
  3077. [(? symbol? x) (dict-ref env x)]
  3078. [`(read) 'Integer]
  3079. [`(let ([,x ,e]) ,body)
  3080. (define T (recur e))
  3081. (define new-env (cons (cons x T) env))
  3082. (type-check-exp new-env body)]
  3083. ...
  3084. [`(not ,e)
  3085. (match (recur e)
  3086. ['Boolean 'Boolean]
  3087. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  3088. ...
  3089. )))
  3090. (define (type-check-R2 env)
  3091. (lambda (e)
  3092. (match e
  3093. [`(program ,info ,body)
  3094. (define ty ((type-check-exp '()) body))
  3095. `(program ,info ,body)]
  3096. )))
  3097. \end{lstlisting}
  3098. \caption{Skeleton of a type checker for the $R_2$ language.}
  3099. \label{fig:type-check-R2}
  3100. \end{figure}
  3101. %% To print the resulting value correctly, the overall type of the
  3102. %% program must be threaded through the remainder of the passes. We can
  3103. %% store the type within the \key{program} form as shown in Figure
  3104. %% \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3105. %% intermediate language produced by the type checker, which we define as
  3106. %% follows: \\[1ex]
  3107. %% \fbox{
  3108. %% \begin{minipage}{0.87\textwidth}
  3109. %% \[
  3110. %% \begin{array}{lcl}
  3111. %% R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3112. %% \end{array}
  3113. %% \]
  3114. %% \end{minipage}
  3115. %% }
  3116. \begin{exercise}\normalfont
  3117. Complete the implementation of \code{type-check-R2} and test it on 10
  3118. new example programs in $R_2$ that you choose based on how thoroughly
  3119. they test the type checking algorithm. Half of the example programs
  3120. should have a type error, to make sure that your type checker properly
  3121. rejects them. The other half of the example programs should not have
  3122. type errors. Your testing should check that the result of the type
  3123. checker agrees with the value returned by the interpreter, that is, if
  3124. the type checker returns \key{Integer}, then the interpreter should
  3125. return an integer. Likewise, if the type checker returns
  3126. \key{Boolean}, then the interpreter should return \code{\#t} or
  3127. \code{\#f}. Note that if your type checker does not signal an error
  3128. for a program, then interpreting that program should not encounter an
  3129. error. If it does, there is something wrong with your type checker.
  3130. \end{exercise}
  3131. \section{Shrink the $R_2$ Language}
  3132. \label{sec:shrink-r2}
  3133. The $R_2$ language includes several operators that are easily
  3134. expressible in terms of other operators. For example, subtraction is
  3135. expressible in terms of addition and negation.
  3136. \[
  3137. (\key{-}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3138. \]
  3139. Several of the comparison operations are expressible in terms of
  3140. less-than and logical negation.
  3141. \[
  3142. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{not}\;(\key{<}\;e_2\;e_1))
  3143. \]
  3144. By performing these translations near the front-end of the compiler,
  3145. the later passes of the compiler will not need to deal with these
  3146. constructs, making those passes shorter. On the other hand, sometimes
  3147. these translations make it more difficult to generate the most
  3148. efficient code with respect to the number of instructions. However,
  3149. these differences typically do not affect the number of accesses to
  3150. memory, which is the primary factor that determines execution time on
  3151. modern computer architectures.
  3152. \begin{exercise}\normalfont
  3153. Implement the pass \code{shrink} that removes subtraction,
  3154. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3155. by translating them to other constructs in $R_2$. Create tests to
  3156. make sure that the behavior of all of these constructs stays the
  3157. same after translation.
  3158. \end{exercise}
  3159. \section{XOR, Comparisons, and Control Flow in x86}
  3160. \label{sec:x86-1}
  3161. To implement the new logical operations, the comparison operations,
  3162. and the \key{if} expression, we need to delve further into the x86
  3163. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3164. larger subset of x86 that includes instructions for logical
  3165. operations, comparisons, and jumps.
  3166. One small challenge is that x86 does not provide an instruction that
  3167. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3168. However, the \code{xorq} instruction can be used to encode \code{not}.
  3169. The \key{xorq} instruction takes two arguments, performs a pairwise
  3170. exclusive-or operation on each bit of its arguments, and writes the
  3171. results into its second argument. Recall the truth table for
  3172. exclusive-or:
  3173. \begin{center}
  3174. \begin{tabular}{l|cc}
  3175. & 0 & 1 \\ \hline
  3176. 0 & 0 & 1 \\
  3177. 1 & 1 & 0
  3178. \end{tabular}
  3179. \end{center}
  3180. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3181. in row of the table for the bit $1$, the result is the opposite of the
  3182. second bit. Thus, the \code{not} operation can be implemented by
  3183. \code{xorq} with $1$ as the first argument: $0001
  3184. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3185. 0001 = 0000$.
  3186. \begin{figure}[tp]
  3187. \fbox{
  3188. \begin{minipage}{0.96\textwidth}
  3189. \[
  3190. \begin{array}{lcl}
  3191. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3192. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3193. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3194. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3195. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3196. (\key{subq} \; \Arg\; \Arg) \mid
  3197. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3198. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3199. (\key{pushq}\;\Arg) \mid
  3200. (\key{popq}\;\Arg) \mid
  3201. (\key{retq})} \\
  3202. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3203. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3204. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3205. \mid (\key{jmp} \; \itm{label})
  3206. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3207. &\mid& (\key{label} \; \itm{label}) \\
  3208. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3209. \end{array}
  3210. \]
  3211. \end{minipage}
  3212. }
  3213. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3214. \label{fig:x86-1}
  3215. \end{figure}
  3216. Next we consider the x86 instructions that are relevant for
  3217. compiling the comparison operations. The \key{cmpq} instruction
  3218. compares its two arguments to determine whether one argument is less
  3219. than, equal, or greater than the other argument. The \key{cmpq}
  3220. instruction is unusual regarding the order of its arguments and where
  3221. the result is placed. The argument order is backwards: if you want to
  3222. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3223. \key{cmpq} is placed in the special EFLAGS register. This register
  3224. cannot be accessed directly but it can be queried by a number of
  3225. instructions, including the \key{set} instruction. The \key{set}
  3226. instruction puts a \key{1} or \key{0} into its destination depending
  3227. on whether the comparison came out according to the condition code
  3228. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3229. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3230. The set instruction has an annoying quirk in that its destination
  3231. argument must be single byte register, such as \code{al}, which is
  3232. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3233. instruction can then be used to move from a single byte register to a
  3234. normal 64-bit register.
  3235. For compiling the \key{if} expression, the x86 instructions for
  3236. jumping are relevant. The \key{jmp} instruction updates the program
  3237. counter to point to the instruction after the indicated label. The
  3238. \key{jmp-if} instruction updates the program counter to point to the
  3239. instruction after the indicated label depending on whether the result
  3240. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3241. the \key{jmp-if} instruction falls through to the next
  3242. instruction. Because the \key{jmp-if} instruction relies on the EFLAGS
  3243. register, it is quite common for the \key{jmp-if} to be immediately
  3244. preceeded by a \key{cmpq} instruction, to set the EFLAGS regsiter.
  3245. Our abstract syntax for \key{jmp-if} differs from the concrete syntax
  3246. for x86 to separate the instruction name from the condition code. For
  3247. example, \code{(jmp-if le foo)} corresponds to \code{jle foo}.
  3248. \section{The $C_1$ Intermediate Language}
  3249. \label{sec:c1}
  3250. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3251. language, but we need to grow that intermediate language to handle the
  3252. new features in $R_2$: Booleans and conditional expressions.
  3253. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3254. logic and comparison operators to the $\Exp$ non-terminal, the
  3255. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3256. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3257. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3258. goto's in the grammar for $\Tail$. This means that a sequence of
  3259. statements may now end with a \code{goto} or a conditional
  3260. \code{goto}, which jumps to one of two labeled pieces of code
  3261. depending on the outcome of the comparison. In
  3262. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3263. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3264. and \key{goto}'s.
  3265. \begin{figure}[tp]
  3266. \fbox{
  3267. \begin{minipage}{0.96\textwidth}
  3268. \[
  3269. \begin{array}{lcl}
  3270. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3271. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3272. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3273. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3274. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3275. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  3276. &\mid& (\key{goto}\,\itm{label}) \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})} \\
  3277. C_1 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  3278. \end{array}
  3279. \]
  3280. \end{minipage}
  3281. }
  3282. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3283. \label{fig:c1-syntax}
  3284. \end{figure}
  3285. \section{Explicate Control}
  3286. \label{sec:explicate-control-r2}
  3287. Recall that the purpose of \code{explicate-control} is to make the
  3288. order of evaluation explicit in the syntax of the program. With the
  3289. addition of \key{if} in $R_2$, things get more interesting.
  3290. As a motivating example, consider the following program that has an
  3291. \key{if} expression nested in the predicate of another \key{if}.
  3292. % s1_38.rkt
  3293. \begin{lstlisting}
  3294. (program ()
  3295. (if (if (eq? (read) 1)
  3296. (eq? (read) 0)
  3297. (eq? (read) 2))
  3298. (+ 10 32)
  3299. (+ 700 77)))
  3300. \end{lstlisting}
  3301. %
  3302. The naive way to compile \key{if} and \key{eq?} would be to handle
  3303. each of them in isolation, regardless of their context. Each
  3304. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3305. by a couple instructions to move the result from the EFLAGS register
  3306. into a general purpose register or stack location. Each \key{if} would
  3307. be translated into the combination of a \key{cmpq} and \key{jmp-if}.
  3308. However, if we take context into account we can do better and reduce
  3309. the use of \key{cmpq} and EFLAG-accessing instructions.
  3310. One idea is to try and reorganize the code at the level of $R_2$,
  3311. pushing the outer \key{if} inside the inner one. This would yield the
  3312. following code.
  3313. \begin{lstlisting}
  3314. (if (eq? (read) 1)
  3315. (if (eq? (read) 0)
  3316. (+ 10 32)
  3317. (+ 700 77))
  3318. (if (eq? (read) 2))
  3319. (+ 10 32)
  3320. (+ 700 77))
  3321. \end{lstlisting}
  3322. Unfortunately, this approach duplicates the two branches, and a
  3323. compiler must never duplicate code!
  3324. We need a way to perform the above transformation, but without
  3325. duplicating code. The solution is straightforward if we think at the
  3326. level of x86 assembly: we can label the code for each of the branches
  3327. and insert \key{goto}'s in all the places that need to execute the
  3328. branches. Put another way, we need to move away from abstract syntax
  3329. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3330. use a standard program representation called a \emph{control flow
  3331. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3332. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3333. each edge represents a jump to another block. The \key{program}
  3334. construct of $C_0$ and $C_1$ represents a control flow graph as an
  3335. association list mapping labels to basic blocks. Each block is
  3336. represented by the $\Tail$ non-terminal.
  3337. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3338. \code{remove-complex-opera*} pass and then the
  3339. \code{explicate-control} pass on the example program. We shall walk
  3340. through the output program and then discuss the algorithm.
  3341. %
  3342. Following the order of evaluation in the output of
  3343. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3344. comparison to \code{1} from the predicate of the inner \key{if}. In
  3345. the output of \code{explicate-control}, in the \code{start} block,
  3346. this becomes a \code{(read)} followed by a conditional goto to either
  3347. \code{block61} or \code{block62}. Each of these contains the
  3348. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3349. 1)}, respectively. Regarding \code{block61}, we start with the
  3350. \code{(read)} and comparison to \code{0} and then have a conditional
  3351. goto, either to \code{block59} or \code{block60}, which indirectly
  3352. take us to \code{block55} and \code{block56}, the two branches of the
  3353. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3354. story for \code{block62} is similar.
  3355. \begin{figure}[tbp]
  3356. \begin{tabular}{lll}
  3357. \begin{minipage}{0.4\textwidth}
  3358. \begin{lstlisting}
  3359. (program ()
  3360. (if (if (eq? (read) 1)
  3361. (eq? (read) 0)
  3362. (eq? (read) 2))
  3363. (+ 10 32)
  3364. (+ 700 77)))
  3365. \end{lstlisting}
  3366. \hspace{40pt}$\Downarrow$
  3367. \begin{lstlisting}
  3368. (program ()
  3369. (if (if (let ([tmp52 (read)])
  3370. (eq? tmp52 1))
  3371. (let ([tmp53 (read)])
  3372. (eq? tmp53 0))
  3373. (let ([tmp54 (read)])
  3374. (eq? tmp54 2)))
  3375. (+ 10 32)
  3376. (+ 700 77)))
  3377. \end{lstlisting}
  3378. \end{minipage}
  3379. &
  3380. $\Rightarrow$
  3381. &
  3382. \begin{minipage}{0.55\textwidth}
  3383. \begin{lstlisting}
  3384. (program ()
  3385. ((block62 .
  3386. (seq (assign tmp54 (read))
  3387. (if (eq? tmp54 2)
  3388. (goto block59)
  3389. (goto block60))))
  3390. (block61 .
  3391. (seq (assign tmp53 (read))
  3392. (if (eq? tmp53 0)
  3393. (goto block57)
  3394. (goto block58))))
  3395. (block60 . (goto block56))
  3396. (block59 . (goto block55))
  3397. (block58 . (goto block56))
  3398. (block57 . (goto block55))
  3399. (block56 . (return (+ 700 77)))
  3400. (block55 . (return (+ 10 32)))
  3401. (start .
  3402. (seq (assign tmp52 (read))
  3403. (if (eq? tmp52 1)
  3404. (goto block61)
  3405. (goto block62))))))
  3406. \end{lstlisting}
  3407. \end{minipage}
  3408. \end{tabular}
  3409. \caption{Example translation from $R_2$ to $C_1$
  3410. via the \code{explicate-control}.}
  3411. \label{fig:explicate-control-s1-38}
  3412. \end{figure}
  3413. The nice thing about the output of \code{explicate-control} is that
  3414. there are no unnecessary uses of \code{eq?} and every use of
  3415. \code{eq?} is part of a conditional jump. The down-side of this output
  3416. is that it includes trivial blocks, such as \code{block57} through
  3417. \code{block60}, that only jump to another block. We discuss a solution
  3418. to this problem in Section~\ref{sec:opt-jumps}.
  3419. Recall that in Section~\ref{sec:explicate-control-r1} we implement the
  3420. \code{explicate-control} pass for $R_1$ using two mutually recursive
  3421. functions, \code{explicate-control-tail} and
  3422. \code{explicate-control-assign}. The former function translated
  3423. expressions in tail position whereas the later function translated
  3424. expressions on the right-hand-side of a \key{let}. With the addition
  3425. of \key{if} expression in $R_2$ we have a new kind of context to deal
  3426. with: the predicate position of the \key{if}. So we shall need another
  3427. function, \code{explicate-control-pred}, that takes an $R_2$
  3428. expression and two pieces of $C_1$ code (two $\Tail$'s) for the
  3429. then-branch and else-branch. The output of
  3430. \code{explicate-control-pred} is a $C_1$ $\Tail$. However, these
  3431. three functions also need to contruct the control-flow graph, which we
  3432. recommend they do via updates to a global variable. Next we consider
  3433. the specific additions to the tail and assign functions, and some of
  3434. cases for the pred function.
  3435. The \code{explicate-control-tail} function needs an additional case
  3436. for \key{if}. The branches of the \key{if} inherit the current
  3437. context, so they are in tail position. Let $B_1$ be the result of
  3438. \code{explicate-control-tail} on the $\itm{thn}$ branch and $B_2$ be
  3439. the result of apply \code{explicate-control-tail} to the $\itm{else}$
  3440. branch. Then the \key{if} translates to the block $B_3$ which is the
  3441. result of applying \code{explicate-control-pred} to the predicate
  3442. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3443. \[
  3444. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3445. \]
  3446. Next we consider the case for \key{if} in the
  3447. \code{explicate-control-assign} function. So the context of the
  3448. \key{if} is an assignment to some variable $x$ and then the control
  3449. continues to some block $B_1$. The code that we generate for both the
  3450. $\itm{thn}$ and $\itm{els}$ branches shall both need to continue to
  3451. $B_1$, so we add $B_1$ to the control flow graph with a fresh label
  3452. $\ell_1$. Again, the branches of the \key{if} inherit the current
  3453. context, so that are in assignment positions. Let $B_2$ be the result
  3454. of applying \code{explicate-control-assign} to the $\itm{thn}$ branch,
  3455. variable $x$, and the block \code{(goto $\ell_1$)}. Let $B_3$ be the
  3456. result of applying \code{explicate-control-assign} to the $\itm{else}$
  3457. branch, variable $x$, and the block \code{(goto $\ell_1$)}. The
  3458. \key{if} translates to the block $B_4$ which is the result of applying
  3459. \code{explicate-control-pred} to the predicate $\itm{cnd}$ and the
  3460. blocks $B_2$ and $B_3$.
  3461. \[
  3462. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3463. \]
  3464. The function \code{explicate-control-pred} will need a case for every
  3465. expression that can have type \code{Boolean}. We detail a few cases
  3466. here and leave the rest for the reader. The input to this function is
  3467. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3468. enclosing \key{if}. One of the base cases of this function is when the
  3469. expression is a less-than comparision. We translate it to a
  3470. conditional \code{goto}. We need labels for the two branches $B_1$ and
  3471. $B_2$, so we add them to the control flow graph and obtain some labels
  3472. $\ell_1$ and $\ell_2$. The translation of the less-than comparison is
  3473. as follows.
  3474. \[
  3475. (\key{<}\;e_1\;e_2) \quad\Rightarrow\quad
  3476. (\key{if}\;(\key{<}\;e_1\;e_2)\;(\key{goto}\;\ell_1)\;(\key{goto}\;\ell_2))
  3477. \]
  3478. The case for \key{if} in \code{explicate-control-pred} is particularly
  3479. illuminating, as it deals with the challenges that we discussed above
  3480. regarding the example of the nested \key{if} expressions. Again, we
  3481. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3482. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3483. and $\itm{els}$ of the current \key{if} inherit their context from the
  3484. current one, i.e., predicate context. So we apply
  3485. \code{explicate-control-pred} to $\itm{thn}$ with the two blocks
  3486. \code{(goto $\ell_1$)} and \code{(goto $\ell_2$)}, to obtain $B_3$.
  3487. Similarly for the $\itm{els}$ branch, to obtain $B_4$.
  3488. Finally, we apply \code{explicate-control-pred} to
  3489. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3490. to obtain the result $B_5$.
  3491. \[
  3492. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3493. \quad\Rightarrow\quad
  3494. B_5
  3495. \]
  3496. \begin{exercise}\normalfont
  3497. Implement the pass \code{explicate-code} by adding the cases for
  3498. \key{if} to the functions for tail and assignment contexts, and
  3499. implement the function for predicate contexts. Create test cases
  3500. that exercise all of the new cases in the code for this pass.
  3501. \end{exercise}
  3502. \section{Select Instructions}
  3503. \label{sec:select-r2}
  3504. Recall that the \code{select-instructions} pass lowers from our
  3505. $C$-like intermediate representation to the pseudo-x86 language, which
  3506. is suitable for conducting register allocation. The pass is
  3507. implemented using three auxilliary functions, one for each of the
  3508. non-terminals $\Arg$, $\Stmt$, and $\Tail$.
  3509. For $\Arg$, we have new cases for the Booleans. We take the usual
  3510. approach of encoding them as integers, with true as 1 and false as 0.
  3511. \[
  3512. \key{\#t} \Rightarrow \key{1}
  3513. \qquad
  3514. \key{\#f} \Rightarrow \key{0}
  3515. \]
  3516. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3517. be implemented in terms of \code{xorq} as we discussed at the
  3518. beginning of this section. Given an assignment \code{(assign
  3519. $\itm{lhs}$ (not $\Arg$))}, if the left-hand side $\itm{lhs}$ is
  3520. the same as $\Arg$, then just the \code{xorq} suffices:
  3521. \[
  3522. (\key{assign}\; x\; (\key{not}\; x))
  3523. \quad\Rightarrow\quad
  3524. ((\key{xorq}\;(\key{int}\;1)\;x'))
  3525. \]
  3526. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3527. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3528. $\Arg$. Then we have
  3529. \[
  3530. (\key{assign}\; \itm{lhs}\; (\key{not}\; \Arg))
  3531. \quad\Rightarrow\quad
  3532. ((\key{movq}\; \Arg'\; \itm{lhs}') \; (\key{xorq}\;(\key{int}\;1)\;\itm{lhs}'))
  3533. \]
  3534. Next consider the cases for \code{eq?} and less-than comparison.
  3535. Translating these operations to x86 is slightly involved due to the
  3536. unusual nature of the \key{cmpq} instruction discussed above. We
  3537. recommend translating an assignment from \code{eq?} into the following
  3538. sequence of three instructions. \\
  3539. \begin{tabular}{lll}
  3540. \begin{minipage}{0.4\textwidth}
  3541. \begin{lstlisting}
  3542. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3543. \end{lstlisting}
  3544. \end{minipage}
  3545. &
  3546. $\Rightarrow$
  3547. &
  3548. \begin{minipage}{0.4\textwidth}
  3549. \begin{lstlisting}
  3550. (cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3551. (set e (byte-reg al))
  3552. (movzbq (byte-reg al) |$\itm{lhs}'$|)
  3553. \end{lstlisting}
  3554. \end{minipage}
  3555. \end{tabular} \\
  3556. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3557. \key{goto} and conditional \key{goto}. Both are straightforward
  3558. to handle. A \key{goto} becomes a jump instruction.
  3559. \[
  3560. (\key{goto}\; \ell) \quad \Rightarrow \quad ((\key{jmp} \;\ell))
  3561. \]
  3562. A conditional \key{goto} becomes a compare instruction followed
  3563. by a conditional jump (for ``then'') and the fall-through is
  3564. to a regular jump (for ``else'').\\
  3565. \begin{tabular}{lll}
  3566. \begin{minipage}{0.4\textwidth}
  3567. \begin{lstlisting}
  3568. (if (eq? |$\Arg_1$| |$\Arg_2$|)
  3569. (goto |$\ell_1$|)
  3570. (goto |$\ell_2$|))
  3571. \end{lstlisting}
  3572. \end{minipage}
  3573. &
  3574. $\Rightarrow$
  3575. &
  3576. \begin{minipage}{0.4\textwidth}
  3577. \begin{lstlisting}
  3578. ((cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3579. (jmp-if e |$\ell_1$|)
  3580. (jmp |$\ell_2$|))
  3581. \end{lstlisting}
  3582. \end{minipage}
  3583. \end{tabular} \\
  3584. \begin{exercise}\normalfont
  3585. Expand your \code{select-instructions} pass to handle the new features
  3586. of the $R_2$ language. Test the pass on all the examples you have
  3587. created and make sure that you have some test programs that use the
  3588. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3589. the output using the \code{interp-x86} interpreter
  3590. (Appendix~\ref{appendix:interp}).
  3591. \end{exercise}
  3592. \section{Register Allocation}
  3593. \label{sec:register-allocation-r2}
  3594. The changes required for $R_2$ affect the liveness analysis, building
  3595. the interference graph, and assigning homes, but the graph coloring
  3596. algorithm itself does not need to change.
  3597. \subsection{Liveness Analysis}
  3598. \label{sec:liveness-analysis-r2}
  3599. Recall that for $R_1$ we implemented liveness analysis for a single
  3600. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3601. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3602. now produces many basic blocks arranged in a control-flow graph. The
  3603. first question we need to consider is in what order should we process
  3604. the basic blocks? Recall that to perform liveness analysis, we need to
  3605. know the live-after set. If a basic block has no successor blocks,
  3606. then it has an empty live-after set and we can immediately apply
  3607. liveness analysis to it. If a basic block has some successors, then we
  3608. need to complete liveness analysis on those blocks first.
  3609. Furthermore, we know that the control flow graph does not contain any
  3610. cycles (it is a DAG, that is, a directed acyclic graph)\footnote{If we
  3611. were to add loops to the language, then the CFG could contain cycles
  3612. and we would instead need to use the classic worklist algorithm for
  3613. computing the fixed point of the liveness
  3614. analysis~\citep{Aho:1986qf}.}. What all this amounts to is that we
  3615. need to process the basic blocks in reverse topological order. We
  3616. recommend using the \code{tsort} and \code{transpose} functions of the
  3617. Racket \code{graph} package to obtain this ordering.
  3618. The next question is how to compute the live-after set of a block
  3619. given the live-before sets of all its successor blocks. During
  3620. compilation we do not know which way the branch will go, so we do not
  3621. know which of the successor's live-before set to use. The solution
  3622. comes from the observation that there is no harm in identifying more
  3623. variables as live than absolutely necessary. Thus, we can take the
  3624. union of the live-before sets from all the successors to be the
  3625. live-after set for the block. Once we have computed the live-after
  3626. set, we can proceed to perform liveness analysis on the block just as
  3627. we did in Section~\ref{sec:liveness-analysis-r1}.
  3628. The helper functions for computing the variables in an instruction's
  3629. argument and for computing the variables read-from ($R$) or written-to
  3630. ($W$) by an instruction need to be updated to handle the new kinds of
  3631. arguments and instructions in x86$_1$.
  3632. \subsection{Build Interference}
  3633. \label{sec:build-interference-r2}
  3634. Many of the new instructions in x86$_1$ can be handled in the same way
  3635. as the instructions in x86$_0$. Thus, if your code was already quite
  3636. general, it will not need to be changed to handle the new
  3637. instructions. If not, I recommend that you change your code to be more
  3638. general. The \key{movzbq} instruction should be handled like the
  3639. \key{movq} instruction.
  3640. %% \subsection{Assign Homes}
  3641. %% \label{sec:assign-homes-r2}
  3642. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3643. %% to be updated to handle the \key{if} statement, simply by recursively
  3644. %% processing the child nodes. Hopefully your code already handles the
  3645. %% other new instructions, but if not, you can generalize your code.
  3646. \begin{exercise}\normalfont
  3647. Update the \code{register-allocation} pass so that it works for $R_2$
  3648. and test your compiler using your previously created programs on the
  3649. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3650. \end{exercise}
  3651. %% \section{Lower Conditionals (New Pass)}
  3652. %% \label{sec:lower-conditionals}
  3653. %% In the \code{select-instructions} pass we decided to procrastinate in
  3654. %% the lowering of the \key{if} statement, thereby making liveness
  3655. %% analysis easier. Now we need to make up for that and turn the \key{if}
  3656. %% statement into the appropriate instruction sequence. The following
  3657. %% translation gives the general idea. If the condition is true, we need
  3658. %% to execute the $\itm{thns}$ branch and otherwise we need to execute
  3659. %% the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3660. %% jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3661. %% is appropriate for the comparison operator \itm{cmp}. If the
  3662. %% condition is false, we fall through to the $\itm{elss}$ branch. At the
  3663. %% end of the $\itm{elss}$ branch we need to take care to not fall
  3664. %% through to the $\itm{thns}$ branch. So we jump to the
  3665. %% $\itm{endlabel}$. All of the labels in the generated code should be
  3666. %% created with \code{gensym}.
  3667. %% \begin{tabular}{lll}
  3668. %% \begin{minipage}{0.4\textwidth}
  3669. %% \begin{lstlisting}
  3670. %% (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3671. %% \end{lstlisting}
  3672. %% \end{minipage}
  3673. %% &
  3674. %% $\Rightarrow$
  3675. %% &
  3676. %% \begin{minipage}{0.4\textwidth}
  3677. %% \begin{lstlisting}
  3678. %% (cmpq |$\Arg_2$| |$\Arg_1$|)
  3679. %% (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3680. %% |$\itm{elss}$|
  3681. %% (jmp |$\itm{endlabel}$|)
  3682. %% (label |$\itm{thenlabel}$|)
  3683. %% |$\itm{thns}$|
  3684. %% (label |$\itm{endlabel}$|)
  3685. %% \end{lstlisting}
  3686. %% \end{minipage}
  3687. %% \end{tabular}
  3688. %% \begin{exercise}\normalfont
  3689. %% Implement the \code{lower-conditionals} pass. Test your compiler using
  3690. %% your previously created programs on the \code{interp-x86} interpreter
  3691. %% (Appendix~\ref{appendix:interp}).
  3692. %% \end{exercise}
  3693. \section{Patch Instructions}
  3694. The second argument of the \key{cmpq} instruction must not be an
  3695. immediate value (such as a literal integer). So if you are comparing
  3696. two immediates, we recommend inserting a \key{movq} instruction to put
  3697. the second argument in \key{rax}.
  3698. %
  3699. The second argument of the \key{movzbq} must be a register.
  3700. %
  3701. There are no special restrictions on the x86 instructions
  3702. \key{jmp-if}, \key{jmp}, and \key{label}.
  3703. \begin{exercise}\normalfont
  3704. Update \code{patch-instructions} to handle the new x86 instructions.
  3705. Test your compiler using your previously created programs on the
  3706. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3707. \end{exercise}
  3708. \section{An Example Translation}
  3709. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3710. $R_2$ translated to x86, showing the results of
  3711. \code{explicate-control}, \code{select-instructions}, and the final
  3712. x86 assembly code.
  3713. \begin{figure}[tbp]
  3714. \begin{tabular}{lll}
  3715. \begin{minipage}{0.5\textwidth}
  3716. % s1_20.rkt
  3717. \begin{lstlisting}
  3718. (program ()
  3719. (if (eq? (read) 1) 42 0))
  3720. \end{lstlisting}
  3721. $\Downarrow$
  3722. \begin{lstlisting}
  3723. (program ()
  3724. ((block32 . (return 0))
  3725. (block31 . (return 42))
  3726. (start .
  3727. (seq (assign tmp30 (read))
  3728. (if (eq? tmp30 1)
  3729. (goto block31)
  3730. (goto block32))))))
  3731. \end{lstlisting}
  3732. $\Downarrow$
  3733. \begin{lstlisting}
  3734. (program ((locals . (tmp30)))
  3735. ((block32 .
  3736. (block ()
  3737. (movq (int 0) (reg rax))
  3738. (jmp conclusion)))
  3739. (block31 .
  3740. (block ()
  3741. (movq (int 42) (reg rax))
  3742. (jmp conclusion)))
  3743. (start .
  3744. (block ()
  3745. (callq read_int)
  3746. (movq (reg rax) (var tmp30))
  3747. (cmpq (int 1) (var tmp30))
  3748. (jmp-if e block31)
  3749. (jmp block32)))))
  3750. \end{lstlisting}
  3751. \end{minipage}
  3752. &
  3753. $\Rightarrow$
  3754. \begin{minipage}{0.4\textwidth}
  3755. \begin{lstlisting}
  3756. _block31:
  3757. movq $42, %rax
  3758. jmp _conclusion
  3759. _block32:
  3760. movq $0, %rax
  3761. jmp _conclusion
  3762. _start:
  3763. callq _read_int
  3764. movq %rax, %rcx
  3765. cmpq $1, %rcx
  3766. je _block31
  3767. jmp _block32
  3768. .globl _main
  3769. _main:
  3770. pushq %rbp
  3771. movq %rsp, %rbp
  3772. pushq %r12
  3773. pushq %rbx
  3774. pushq %r13
  3775. pushq %r14
  3776. subq $0, %rsp
  3777. jmp _start
  3778. _conclusion:
  3779. addq $0, %rsp
  3780. popq %r14
  3781. popq %r13
  3782. popq %rbx
  3783. popq %r12
  3784. popq %rbp
  3785. retq
  3786. \end{lstlisting}
  3787. \end{minipage}
  3788. \end{tabular}
  3789. \caption{Example compilation of an \key{if} expression to x86.}
  3790. \label{fig:if-example-x86}
  3791. \end{figure}
  3792. \begin{figure}[p]
  3793. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3794. \node (R2) at (0,2) {\large $R_2$};
  3795. \node (R2-2) at (3,2) {\large $R_2$};
  3796. \node (R2-3) at (6,2) {\large $R_2$};
  3797. \node (R2-4) at (9,2) {\large $R_2$};
  3798. \node (R2-5) at (12,2) {\large $R_2$};
  3799. \node (C1-1) at (6,0) {\large $C_1$};
  3800. \node (C1-2) at (3,0) {\large $C_1$};
  3801. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3802. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3803. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3804. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  3805. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3806. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3807. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  3808. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  3809. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  3810. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  3811. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  3812. \path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  3813. \path[->,bend right=15] (C1-2) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3814. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3815. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3816. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3817. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  3818. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  3819. \end{tikzpicture}
  3820. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3821. \label{fig:R2-passes}
  3822. \end{figure}
  3823. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  3824. compilation of $R_2$.
  3825. \section{Challenge: Optimize Jumps$^{*}$}
  3826. \label{sec:opt-jumps}
  3827. UNDER CONSTRUCTION
  3828. %% \section{Challenge: Optimizing Conditions$^{*}$}
  3829. %% \label{sec:opt-if}
  3830. %% A close inspection of the x86 code generated in
  3831. %% Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3832. %% regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3833. %% twice using \key{cmpq} as follows.
  3834. %% % Wierd LaTeX bug if I remove the following. -Jeremy
  3835. %% % Does it have to do with page breaks?
  3836. %% \begin{lstlisting}
  3837. %% \end{lstlisting}
  3838. %% \begin{lstlisting}
  3839. %% cmpq $1, %rcx
  3840. %% sete %al
  3841. %% movzbq %al, %rcx
  3842. %% cmpq $1, %rcx
  3843. %% je then21288
  3844. %% \end{lstlisting}
  3845. %% The reason for this non-optimal code has to do with the \code{flatten}
  3846. %% pass earlier in this Chapter. We recommended flattening the condition
  3847. %% to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3848. %% is already an \code{eq?} test, then we would like to use that
  3849. %% directly. In fact, for many of the expressions of Boolean type, we can
  3850. %% generate more optimized code. For example, if the condition is
  3851. %% \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3852. %% all. If the condition is a \code{let}, we can optimize based on the
  3853. %% form of its body. If the condition is a \code{not}, then we can flip
  3854. %% the two branches.
  3855. %% %
  3856. %% \margincomment{\tiny We could do even better by converting to basic
  3857. %% blocks.\\ --Jeremy}
  3858. %% %
  3859. %% On the other hand, if the condition is a \code{and}
  3860. %% or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3861. %% code duplication.
  3862. %% Figure~\ref{fig:opt-if} shows an example program and the result of
  3863. %% applying the above suggested optimizations.
  3864. %% \begin{exercise}\normalfont
  3865. %% Change the \code{flatten} pass to improve the code that gets
  3866. %% generated for \code{if} expressions. We recommend writing a helper
  3867. %% function that recursively traverses the condition of the \code{if}.
  3868. %% \end{exercise}
  3869. %% \begin{figure}[tbp]
  3870. %% \begin{tabular}{lll}
  3871. %% \begin{minipage}{0.5\textwidth}
  3872. %% \begin{lstlisting}
  3873. %% (program
  3874. %% (if (let ([x 1])
  3875. %% (not (eq? x (read))))
  3876. %% 777
  3877. %% 42))
  3878. %% \end{lstlisting}
  3879. %% $\Downarrow$
  3880. %% \begin{lstlisting}
  3881. %% (program (x.1 if.2 tmp.3)
  3882. %% (type Integer)
  3883. %% (assign x.1 1)
  3884. %% (assign tmp.3 (read))
  3885. %% (if (eq? x.1 tmp.3)
  3886. %% ((assign if.2 42))
  3887. %% ((assign if.2 777)))
  3888. %% (return if.2))
  3889. %% \end{lstlisting}
  3890. %% $\Downarrow$
  3891. %% \begin{lstlisting}
  3892. %% (program (x.1 if.2 tmp.3)
  3893. %% (type Integer)
  3894. %% (movq (int 1) (var x.1))
  3895. %% (callq read_int)
  3896. %% (movq (reg rax) (var tmp.3))
  3897. %% (if (eq? (var x.1) (var tmp.3))
  3898. %% ((movq (int 42) (var if.2)))
  3899. %% ((movq (int 777) (var if.2))))
  3900. %% (movq (var if.2) (reg rax)))
  3901. %% \end{lstlisting}
  3902. %% \end{minipage}
  3903. %% &
  3904. %% $\Rightarrow$
  3905. %% \begin{minipage}{0.4\textwidth}
  3906. %% \begin{lstlisting}
  3907. %% .globl _main
  3908. %% _main:
  3909. %% pushq %rbp
  3910. %% movq %rsp, %rbp
  3911. %% pushq %r13
  3912. %% pushq %r14
  3913. %% pushq %r12
  3914. %% pushq %rbx
  3915. %% subq $0, %rsp
  3916. %% movq $1, %rbx
  3917. %% callq _read_int
  3918. %% movq %rax, %rcx
  3919. %% cmpq %rcx, %rbx
  3920. %% je then35989
  3921. %% movq $777, %rbx
  3922. %% jmp if_end35990
  3923. %% then35989:
  3924. %% movq $42, %rbx
  3925. %% if_end35990:
  3926. %% movq %rbx, %rax
  3927. %% movq %rax, %rdi
  3928. %% callq _print_int
  3929. %% movq $0, %rax
  3930. %% addq $0, %rsp
  3931. %% popq %rbx
  3932. %% popq %r12
  3933. %% popq %r14
  3934. %% popq %r13
  3935. %% popq %rbp
  3936. %% retq
  3937. %% \end{lstlisting}
  3938. %% \end{minipage}
  3939. %% \end{tabular}
  3940. %% \caption{Example program with optimized conditionals.}
  3941. %% \label{fig:opt-if}
  3942. %% \end{figure}
  3943. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3944. \chapter{Tuples and Garbage Collection}
  3945. \label{ch:tuples}
  3946. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  3947. things to discuss in this chapter. \\ --Jeremy}
  3948. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3949. all the IR grammars are spelled out! \\ --Jeremy}
  3950. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  3951. but keep type annotations on vector creation and local variables, function
  3952. parameters, etc. \\ --Jeremy}
  3953. \margincomment{\scriptsize Be more explicit about how to deal with
  3954. the root stack. \\ --Jeremy}
  3955. In this chapter we study the implementation of mutable tuples (called
  3956. ``vectors'' in Racket). This language feature is the first to use the
  3957. computer's \emph{heap} because the lifetime of a Racket tuple is
  3958. indefinite, that is, a tuple lives forever from the programmer's
  3959. viewpoint. Of course, from an implementor's viewpoint, it is important
  3960. to reclaim the space associated with a tuple when it is no longer
  3961. needed, which is why we also study \emph{garbage collection}
  3962. techniques in this chapter.
  3963. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3964. interpreter and type checker. The $R_3$ language extends the $R_2$
  3965. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  3966. ``void'' value. The reason for including the later is that the
  3967. \code{vector-set!} operation returns a value of type
  3968. \code{Void}\footnote{This may sound contradictory, but Racket's
  3969. \code{Void} type corresponds to what is more commonly called the
  3970. \code{Unit} type. This type is inhabited by a single value that is
  3971. usually written \code{unit} or \code{()}\citep{Pierce:2002hj}.}.
  3972. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  3973. copying live objects back and forth between two halves of the
  3974. heap. The garbage collector requires coordination with the compiler so
  3975. that it can see all of the \emph{root} pointers, that is, pointers in
  3976. registers or on the procedure call stack.
  3977. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  3978. discuss all the necessary changes and additions to the compiler
  3979. passes, including a new compiler pass named \code{expose-allocation}.
  3980. \section{The $R_3$ Language}
  3981. \label{sec:r3}
  3982. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3983. includes three new forms for creating a tuple, reading an element of a
  3984. tuple, and writing to an element of a tuple. The program in
  3985. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3986. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3987. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3988. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3989. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3990. $40$, to which we add the $2$, the element at index $0$ of the
  3991. 1-tuple.
  3992. \begin{figure}[tbp]
  3993. \begin{lstlisting}
  3994. (let ([t (vector 40 #t (vector 2))])
  3995. (if (vector-ref t 1)
  3996. (+ (vector-ref t 0)
  3997. (vector-ref (vector-ref t 2) 0))
  3998. 44))
  3999. \end{lstlisting}
  4000. \caption{Example program that creates tuples and reads from them.}
  4001. \label{fig:vector-eg}
  4002. \end{figure}
  4003. \begin{figure}[tbp]
  4004. \centering
  4005. \fbox{
  4006. \begin{minipage}{0.96\textwidth}
  4007. \[
  4008. \begin{array}{lcl}
  4009. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4010. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4011. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4012. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4013. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4014. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4015. \mid (\key{and}\;\Exp\;\Exp)
  4016. \mid (\key{or}\;\Exp\;\Exp)
  4017. \mid (\key{not}\;\Exp) } \\
  4018. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4019. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4020. &\mid& (\key{vector}\;\Exp^{+})
  4021. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4022. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4023. &\mid& (\key{void}) \\
  4024. R_3 &::=& (\key{program} \; \Exp)
  4025. \end{array}
  4026. \]
  4027. \end{minipage}
  4028. }
  4029. \caption{The syntax of $R_3$, extending $R_2$
  4030. (Figure~\ref{fig:r2-syntax}) with tuples.}
  4031. \label{fig:r3-syntax}
  4032. \end{figure}
  4033. Tuples are our first encounter with heap-allocated data, which raises
  4034. several interesting issues. First, variable binding performs a
  4035. shallow-copy when dealing with tuples, which means that different
  4036. variables can refer to the same tuple, i.e., different variables can
  4037. be \emph{aliases} for the same thing. Consider the following example
  4038. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4039. the mutation through \code{t2} is visible when referencing the tuple
  4040. from \code{t1}, so the result of this program is \code{42}.
  4041. \begin{lstlisting}
  4042. (let ([t1 (vector 3 7)])
  4043. (let ([t2 t1])
  4044. (let ([_ (vector-set! t2 0 42)])
  4045. (vector-ref t1 0))))
  4046. \end{lstlisting}
  4047. The next issue concerns the lifetime of tuples. Of course, they are
  4048. created by the \code{vector} form, but when does their lifetime end?
  4049. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4050. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4051. is not tied to any notion of static scoping. For example, the
  4052. following program returns \code{3} even though the variable \code{t}
  4053. goes out of scope prior to accessing the vector.
  4054. \begin{lstlisting}
  4055. (vector-ref
  4056. (let ([t (vector 3 7)])
  4057. t)
  4058. 0)
  4059. \end{lstlisting}
  4060. From the perspective of programmer-observable behavior, tuples live
  4061. forever. Of course, if they really lived forever, then many programs
  4062. would run out of memory.\footnote{The $R_3$ language does not have
  4063. looping or recursive function, so it is nigh impossible to write a
  4064. program in $R_3$ that will run out of memory. However, we add
  4065. recursive functions in the next Chapter!} A Racket implementation
  4066. must therefore perform automatic garbage collection.
  4067. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4068. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  4069. checker. The additions to the interpreter are straightforward but the
  4070. updates to the type checker deserve some explanation. As we shall see
  4071. in Section~\ref{sec:GC}, we need to know which variables are pointers
  4072. into the heap, that is, which variables are vectors. Also, when
  4073. allocating a vector, we shall need to know which elements of the
  4074. vector are pointers. We can obtain this information during type
  4075. checking and when we uncover local variables. The type checker in
  4076. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4077. expression, it also wraps every sub-expression $e$ with the form
  4078. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  4079. the \code{uncover-locals} pass (Section~\ref{sec:uncover-locals-r3})
  4080. this type information is propagated to all variables (including the
  4081. temporaries generated by \code{remove-complex-opera*}).
  4082. \begin{figure}[tbp]
  4083. \begin{lstlisting}
  4084. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4085. (define (interp-op op)
  4086. (match op
  4087. ...
  4088. ['vector vector]
  4089. ['vector-ref vector-ref]
  4090. ['vector-set! vector-set!]
  4091. [else (error 'interp-op "unknown operator")]))
  4092. (define (interp-R3 env)
  4093. (lambda (e)
  4094. (match e
  4095. ...
  4096. [else (error 'interp-R3 "unrecognized expression")]
  4097. )))
  4098. \end{lstlisting}
  4099. \caption{Interpreter for the $R_3$ language.}
  4100. \label{fig:interp-R3}
  4101. \end{figure}
  4102. \begin{figure}[tbp]
  4103. \begin{lstlisting}
  4104. (define (type-check-exp env)
  4105. (lambda (e)
  4106. (define recur (type-check-exp env))
  4107. (match e
  4108. ...
  4109. ['(void) (values '(has-type (void) Void) 'Void)]
  4110. [`(vector ,es ...)
  4111. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4112. (recur e)))
  4113. (let ([t `(Vector ,@t*)])
  4114. (debug "vector/type-check-exp finished vector" t)
  4115. (values `(has-type (vector ,@e*) ,t) t))]
  4116. [`(vector-ref ,e ,i)
  4117. (define-values (e^ t) (recur e))
  4118. (match t
  4119. [`(Vector ,ts ...)
  4120. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4121. (error 'type-check-exp "invalid index ~a" i))
  4122. (let ([t (list-ref ts i)])
  4123. (values `(has-type (vector-ref ,e^ (has-type ,i Integer)) ,t)
  4124. t))]
  4125. [else (error "expected a vector in vector-ref, not" t)])]
  4126. [`(eq? ,arg1 ,arg2)
  4127. (define-values (e1 t1) (recur arg1))
  4128. (define-values (e2 t2) (recur arg2))
  4129. (match* (t1 t2)
  4130. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  4131. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  4132. [(other wise) ((super type-check-exp env) e)])]
  4133. ...
  4134. )))
  4135. \end{lstlisting}
  4136. \caption{Type checker for the $R_3$ language.}
  4137. \label{fig:typecheck-R3}
  4138. \end{figure}
  4139. \section{Garbage Collection}
  4140. \label{sec:GC}
  4141. Here we study a relatively simple algorithm for garbage collection
  4142. that is the basis of state-of-the-art garbage
  4143. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4144. particular, we describe a two-space copying
  4145. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4146. perform the
  4147. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4148. coarse-grained depiction of what happens in a two-space collector,
  4149. showing two time steps, prior to garbage collection on the top and
  4150. after garbage collection on the bottom. In a two-space collector, the
  4151. heap is divided into two parts, the FromSpace and the
  4152. ToSpace. Initially, all allocations go to the FromSpace until there is
  4153. not enough room for the next allocation request. At that point, the
  4154. garbage collector goes to work to make more room.
  4155. The garbage collector must be careful not to reclaim tuples that will
  4156. be used by the program in the future. Of course, it is impossible in
  4157. general to predict what a program will do, but we can overapproximate
  4158. the will-be-used tuples by preserving all tuples that could be
  4159. accessed by \emph{any} program given the current computer state. A
  4160. program could access any tuple whose address is in a register or on
  4161. the procedure call stack. These addresses are called the \emph{root
  4162. set}. In addition, a program could access any tuple that is
  4163. transitively reachable from the root set. Thus, it is safe for the
  4164. garbage collector to reclaim the tuples that are not reachable in this
  4165. way.
  4166. So the goal of the garbage collector is twofold:
  4167. \begin{enumerate}
  4168. \item preserve all tuple that are reachable from the root set via a
  4169. path of pointers, that is, the \emph{live} tuples, and
  4170. \item reclaim the memory of everything else, that is, the
  4171. \emph{garbage}.
  4172. \end{enumerate}
  4173. A copying collector accomplishes this by copying all of the live
  4174. objects from the FromSpace into the ToSpace and then performs a slight
  4175. of hand, treating the ToSpace as the new FromSpace and the old
  4176. FromSpace as the new ToSpace. In the example of
  4177. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4178. root set, one in a register and two on the stack. All of the live
  4179. objects have been copied to the ToSpace (the right-hand side of
  4180. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4181. pointer relationships. For example, the pointer in the register still
  4182. points to a 2-tuple whose first element is a 3-tuple and second
  4183. element is a 2-tuple. There are four tuples that are not reachable
  4184. from the root set and therefore do not get copied into the ToSpace.
  4185. (The sitation in Figure~\ref{fig:copying-collector}, with a
  4186. cycle, cannot be created by a well-typed program in $R_3$. However,
  4187. creating cycles will be possible once we get to $R_6$. We design
  4188. the garbage collector to deal with cycles to begin with, so we will
  4189. not need to revisit this issue.)
  4190. \begin{figure}[tbp]
  4191. \centering
  4192. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4193. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4194. \caption{A copying collector in action.}
  4195. \label{fig:copying-collector}
  4196. \end{figure}
  4197. There are many alternatives to copying collectors (and their older
  4198. siblings, the generational collectors) when its comes to garbage
  4199. collection, such as mark-and-sweep and reference counting. The
  4200. strengths of copying collectors are that allocation is fast (just a
  4201. test and pointer increment), there is no fragmentation, cyclic garbage
  4202. is collected, and the time complexity of collection only depends on
  4203. the amount of live data, and not on the amount of
  4204. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4205. copying collectors is that they use a lot of space, though that
  4206. problem is ameliorated in generational collectors. Racket and Scheme
  4207. programs tend to allocate many small objects and generate a lot of
  4208. garbage, so copying and generational collectors are a good fit. Of
  4209. course, garbage collection is an active research topic, especially
  4210. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4211. continuously developing new techniques and revisiting old
  4212. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4213. \subsection{Graph Copying via Cheney's Algorithm}
  4214. \label{sec:cheney}
  4215. Let us take a closer look at how the copy works. The allocated objects
  4216. and pointers can be viewed as a graph and we need to copy the part of
  4217. the graph that is reachable from the root set. To make sure we copy
  4218. all of the reachable vertices in the graph, we need an exhaustive
  4219. graph traversal algorithm, such as depth-first search or breadth-first
  4220. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4221. take into account the possibility of cycles by marking which vertices
  4222. have already been visited, so as to ensure termination of the
  4223. algorithm. These search algorithms also use a data structure such as a
  4224. stack or queue as a to-do list to keep track of the vertices that need
  4225. to be visited. We shall use breadth-first search and a trick due to
  4226. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4227. copying tuples into the ToSpace.
  4228. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4229. copy progresses. The queue is represented by a chunk of contiguous
  4230. memory at the beginning of the ToSpace, using two pointers to track
  4231. the front and the back of the queue. The algorithm starts by copying
  4232. all tuples that are immediately reachable from the root set into the
  4233. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4234. old tuple to indicate that it has been visited. (We discuss the
  4235. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4236. inside the copied tuples in the queue still point back to the
  4237. FromSpace. Once the initial queue has been created, the algorithm
  4238. enters a loop in which it repeatedly processes the tuple at the front
  4239. of the queue and pops it off the queue. To process a tuple, the
  4240. algorithm copies all the tuple that are directly reachable from it to
  4241. the ToSpace, placing them at the back of the queue. The algorithm then
  4242. updates the pointers in the popped tuple so they point to the newly
  4243. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4244. step we copy the tuple whose second element is $42$ to the back of the
  4245. queue. The other pointer goes to a tuple that has already been copied,
  4246. so we do not need to copy it again, but we do need to update the
  4247. pointer to the new location. This can be accomplished by storing a
  4248. \emph{forwarding} pointer to the new location in the old tuple, back
  4249. when we initially copied the tuple into the ToSpace. This completes
  4250. one step of the algorithm. The algorithm continues in this way until
  4251. the front of the queue is empty, that is, until the front catches up
  4252. with the back.
  4253. \begin{figure}[tbp]
  4254. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4255. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4256. \label{fig:cheney}
  4257. \end{figure}
  4258. \subsection{Data Representation}
  4259. \label{sec:data-rep-gc}
  4260. The garbage collector places some requirements on the data
  4261. representations used by our compiler. First, the garbage collector
  4262. needs to distinguish between pointers and other kinds of data. There
  4263. are several ways to accomplish this.
  4264. \begin{enumerate}
  4265. \item Attached a tag to each object that identifies what type of
  4266. object it is~\citep{McCarthy:1960dz}.
  4267. \item Store different types of objects in different
  4268. regions~\citep{Steele:1977ab}.
  4269. \item Use type information from the program to either generate
  4270. type-specific code for collecting or to generate tables that can
  4271. guide the
  4272. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4273. \end{enumerate}
  4274. Dynamically typed languages, such as Lisp, need to tag objects
  4275. anyways, so option 1 is a natural choice for those languages.
  4276. However, $R_3$ is a statically typed language, so it would be
  4277. unfortunate to require tags on every object, especially small and
  4278. pervasive objects like integers and Booleans. Option 3 is the
  4279. best-performing choice for statically typed languages, but comes with
  4280. a relatively high implementation complexity. To keep this chapter to a
  4281. 2-week time budget, we recommend a combination of options 1 and 2,
  4282. with separate strategies used for the stack and the heap.
  4283. Regarding the stack, we recommend using a separate stack for
  4284. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4285. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4286. local variable needs to be spilled and is of type \code{(Vector
  4287. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4288. of the normal procedure call stack. Furthermore, we always spill
  4289. vector-typed variables if they are live during a call to the
  4290. collector, thereby ensuring that no pointers are in registers during a
  4291. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4292. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4293. layout using a root stack. The root stack contains the two pointers
  4294. from the regular stack and also the pointer in the second
  4295. register.
  4296. \begin{figure}[tbp]
  4297. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4298. \caption{Maintaining a root stack to facilitate garbage collection.}
  4299. \label{fig:shadow-stack}
  4300. \end{figure}
  4301. The problem of distinguishing between pointers and other kinds of data
  4302. also arises inside of each tuple. We solve this problem by attaching a
  4303. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4304. in on the tags for two of the tuples in the example from
  4305. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4306. in a big-endian way, from right-to-left, with bit location 0 (the
  4307. least significant bit) on the far right, which corresponds to the
  4308. directionality of the x86 shifting instructions \key{salq} (shift
  4309. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4310. specifying which elements of the tuple are pointers, the part labeled
  4311. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4312. a pointer and a 0 bit indicates some other kind of data. The pointer
  4313. mask starts at bit location 7. We have limited tuples to a maximum
  4314. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4315. tag also contains two other pieces of information. The length of the
  4316. tuple (number of elements) is stored in bits location 1 through
  4317. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4318. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4319. has not yet been copied. If the bit has value 0 then the entire tag
  4320. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4321. always zero anyways because our tuples are 8-byte aligned.)
  4322. \begin{figure}[tbp]
  4323. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4324. \caption{Representation for tuples in the heap.}
  4325. \label{fig:tuple-rep}
  4326. \end{figure}
  4327. \subsection{Implementation of the Garbage Collector}
  4328. \label{sec:organize-gz}
  4329. The implementation of the garbage collector needs to do a lot of
  4330. bit-level data manipulation and we need to link it with our
  4331. compiler-generated x86 code. Thus, we recommend implementing the
  4332. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4333. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4334. interface to the garbage collector. The \code{initialize} function
  4335. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4336. function is meant to be called near the beginning of \code{main},
  4337. before the rest of the program executes. The \code{initialize}
  4338. function puts the address of the beginning of the FromSpace into the
  4339. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4340. points to the address that is 1-past the last element of the
  4341. FromSpace. (We use half-open intervals to represent chunks of
  4342. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4343. points to the first element of the root stack.
  4344. As long as there is room left in the FromSpace, your generated code
  4345. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4346. %
  4347. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4348. --Jeremy}
  4349. %
  4350. The amount of room left in FromSpace is the difference between the
  4351. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4352. function should be called when there is not enough room left in the
  4353. FromSpace for the next allocation. The \code{collect} function takes
  4354. a pointer to the current top of the root stack (one past the last item
  4355. that was pushed) and the number of bytes that need to be
  4356. allocated. The \code{collect} function performs the copying collection
  4357. and leaves the heap in a state such that the next allocation will
  4358. succeed.
  4359. \begin{figure}[tbp]
  4360. \begin{lstlisting}
  4361. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4362. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4363. int64_t* free_ptr;
  4364. int64_t* fromspace_begin;
  4365. int64_t* fromspace_end;
  4366. int64_t** rootstack_begin;
  4367. \end{lstlisting}
  4368. \caption{The compiler's interface to the garbage collector.}
  4369. \label{fig:gc-header}
  4370. \end{figure}
  4371. \begin{exercise}
  4372. In the file \code{runtime.c} you will find the implementation of
  4373. \code{initialize} and a partial implementation of \code{collect}.
  4374. The \code{collect} function calls another function, \code{cheney},
  4375. to perform the actual copy, and that function is left to the reader
  4376. to implement. The following is the prototype for \code{cheney}.
  4377. \begin{lstlisting}
  4378. static void cheney(int64_t** rootstack_ptr);
  4379. \end{lstlisting}
  4380. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4381. rootstack (which is an array of pointers). The \code{cheney} function
  4382. also communicates with \code{collect} through the global
  4383. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4384. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4385. the ToSpace:
  4386. \begin{lstlisting}
  4387. static int64_t* tospace_begin;
  4388. static int64_t* tospace_end;
  4389. \end{lstlisting}
  4390. The job of the \code{cheney} function is to copy all the live
  4391. objects (reachable from the root stack) into the ToSpace, update
  4392. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4393. update the root stack so that it points to the objects in the
  4394. ToSpace, and finally to swap the global pointers for the FromSpace
  4395. and ToSpace.
  4396. \end{exercise}
  4397. %% \section{Compiler Passes}
  4398. %% \label{sec:code-generation-gc}
  4399. The introduction of garbage collection has a non-trivial impact on our
  4400. compiler passes. We introduce one new compiler pass called
  4401. \code{expose-allocation} and make non-trivial changes to
  4402. \code{type-check}, \code{flatten}, \code{select-instructions},
  4403. \code{allocate-registers}, and \code{print-x86}. The following
  4404. program will serve as our running example. It creates two tuples, one
  4405. nested inside the other. Both tuples have length one. The example then
  4406. accesses the element in the inner tuple tuple via two vector
  4407. references.
  4408. % tests/s2_17.rkt
  4409. \begin{lstlisting}
  4410. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4411. \end{lstlisting}
  4412. Next we proceed to discuss the new \code{expose-allocation} pass.
  4413. \section{Expose Allocation}
  4414. \label{sec:expose-allocation}
  4415. The pass \code{expose-allocation} lowers the \code{vector} creation
  4416. form into a conditional call to the collector followed by the
  4417. allocation. We choose to place the \code{expose-allocation} pass
  4418. before \code{flatten} because \code{expose-allocation} introduces new
  4419. variables, which can be done locally with \code{let}, but \code{let}
  4420. is gone after \code{flatten}. In the following, we show the
  4421. transformation for the \code{vector} form into let-bindings for the
  4422. intializing expressions, by a conditional \code{collect}, an
  4423. \code{allocate}, and the initialization of the vector.
  4424. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4425. total bytes need to be allocated for the vector, which is 8 for the
  4426. tag plus \itm{len} times 8.)
  4427. \begin{lstlisting}
  4428. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4429. |$\Longrightarrow$|
  4430. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4431. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4432. (global-value fromspace_end))
  4433. (void)
  4434. (collect |\itm{bytes}|))])
  4435. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4436. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4437. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4438. |$v$|) ... )))) ...)
  4439. \end{lstlisting}
  4440. (In the above, we suppressed all of the \code{has-type} forms in the
  4441. output for the sake of readability.) The placement of the initializing
  4442. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4443. the sequence of \code{vector-set!}'s is important, as those expressions
  4444. may trigger garbage collection and we do not want an allocated but
  4445. uninitialized tuple to be present during a garbage collection.
  4446. The output of \code{expose-allocation} is a language that extends
  4447. $R_3$ with the three new forms that we use above in the translation of
  4448. \code{vector}.
  4449. \[
  4450. \begin{array}{lcl}
  4451. \Exp &::=& \cdots
  4452. \mid (\key{collect} \,\itm{int})
  4453. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4454. \mid (\key{global-value} \,\itm{name})
  4455. \end{array}
  4456. \]
  4457. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4458. %% the beginning of the program which will instruct the garbage collector
  4459. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4460. %% two arguments of \code{initialize} specify the initial allocated space
  4461. %% for the root stack and for the heap.
  4462. %
  4463. %% The \code{expose-allocation} pass annotates all of the local variables
  4464. %% in the \code{program} form with their type.
  4465. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4466. \code{expose-allocation} pass on our running example.
  4467. \begin{figure}[tbp]
  4468. \begin{lstlisting}
  4469. (program ()
  4470. (vector-ref
  4471. (vector-ref
  4472. (let ((vecinit48
  4473. (let ((vecinit44 42))
  4474. (let ((collectret46
  4475. (if (<
  4476. (+ (global-value free_ptr) 16)
  4477. (global-value fromspace_end))
  4478. (void)
  4479. (collect 16))))
  4480. (let ((alloc43 (allocate 1 (Vector Integer))))
  4481. (let ((initret45 (vector-set! alloc43 0 vecinit44)))
  4482. alloc43))))))
  4483. (let ((collectret50
  4484. (if (< (+ (global-value free_ptr) 16)
  4485. (global-value fromspace_end))
  4486. (void)
  4487. (collect 16))))
  4488. (let ((alloc47 (allocate 1 (Vector (Vector Integer)))))
  4489. (let ((initret49 (vector-set! alloc47 0 vecinit48)))
  4490. alloc47))))
  4491. 0)
  4492. 0))
  4493. \end{lstlisting}
  4494. \caption{Output of the \code{expose-allocation} pass, minus
  4495. all of the \code{has-type} forms.}
  4496. \label{fig:expose-alloc-output}
  4497. \end{figure}
  4498. %\clearpage
  4499. \section{Explicate Control and the $C_2$ language}
  4500. \label{sec:explicate-control-r3}
  4501. \begin{figure}[tp]
  4502. \fbox{
  4503. \begin{minipage}{0.96\textwidth}
  4504. \[
  4505. \begin{array}{lcl}
  4506. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4507. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4508. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4509. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4510. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4511. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4512. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4513. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4514. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4515. \mid (\key{collect} \,\itm{int}) \\
  4516. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4517. &\mid& \gray{(\key{goto}\,\itm{label})
  4518. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4519. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4520. \end{array}
  4521. \]
  4522. \end{minipage}
  4523. }
  4524. \caption{The $C_2$ language, extending $C_1$
  4525. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4526. \label{fig:c2-syntax}
  4527. \end{figure}
  4528. The output of \code{explicate-control} is a program in the
  4529. intermediate language $C_2$, whose syntax is defined in
  4530. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4531. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4532. \key{global-value} expressions and the \code{collect} statement. The
  4533. \code{explicate-control} pass can treat these new forms much like the
  4534. other forms.
  4535. \section{Uncover Locals}
  4536. \label{sec:uncover-locals-r3}
  4537. Recall that the \code{uncover-locals} function collects all of the
  4538. local variables so that it can store them in the $\itm{info}$ field of
  4539. the \code{program} form. Also recall that we need to know the types of
  4540. all the local variables for purposes of identifying the root set for
  4541. the garbage collector. Thus, we change \code{uncover-locals} to
  4542. collect not just the variables, but the variables and their types in
  4543. the form of an association list. Thanks to the \code{has-type} forms,
  4544. the types are readily available. Figure~\ref{fig:uncover-locals-r3}
  4545. lists the output of the \code{uncover-locals} pass on the running
  4546. example.
  4547. \begin{figure}[tbp]
  4548. \begin{lstlisting}
  4549. (program
  4550. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4551. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4552. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4553. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4554. (tmp52 . Integer) (tmp57 . (Vector Integer))
  4555. (vecinit44 . Integer) (tmp56 . Integer) (initret49 . Void)
  4556. (collectret50 . Void))))
  4557. ((block63 . (seq (collect 16) (goto block61)))
  4558. (block62 . (seq (assign collectret46 (void)) (goto block61)))
  4559. (block61 . (seq (assign alloc43 (allocate 1 (Vector Integer)))
  4560. (seq (assign initret45 (vector-set! alloc43 0 vecinit44))
  4561. (seq (assign vecinit48 alloc43)
  4562. (seq (assign tmp54 (global-value free_ptr))
  4563. (seq (assign tmp55 (+ tmp54 16))
  4564. (seq (assign tmp56 (global-value fromspace_end))
  4565. (if (< tmp55 tmp56) (goto block59) (goto block60)))))))))
  4566. (block60 . (seq (collect 16) (goto block58)))
  4567. (block59 . (seq (assign collectret50 (void)) (goto block58)))
  4568. (block58 . (seq (assign alloc47 (allocate 1 (Vector (Vector Integer))))
  4569. (seq (assign initret49 (vector-set! alloc47 0 vecinit48))
  4570. (seq (assign tmp57 (vector-ref alloc47 0))
  4571. (return (vector-ref tmp57 0))))))
  4572. (start . (seq (assign vecinit44 42)
  4573. (seq (assign tmp51 (global-value free_ptr))
  4574. (seq (assign tmp52 (+ tmp51 16))
  4575. (seq (assign tmp53 (global-value fromspace_end))
  4576. (if (< tmp52 tmp53) (goto block62) (goto block63)))))))))
  4577. \end{lstlisting}
  4578. \caption{Output of \code{uncover-locals} for the running example.}
  4579. \label{fig:uncover-locals-r3}
  4580. \end{figure}
  4581. \clearpage
  4582. \section{Select Instructions}
  4583. \label{sec:select-instructions-gc}
  4584. %% void (rep as zero)
  4585. %% allocate
  4586. %% collect (callq collect)
  4587. %% vector-ref
  4588. %% vector-set!
  4589. %% global-value (postpone)
  4590. In this pass we generate x86 code for most of the new operations that
  4591. were needed to compile tuples, including \code{allocate},
  4592. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4593. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4594. The \code{vector-ref} and \code{vector-set!} forms translate into
  4595. \code{movq} instructions with the appropriate \key{deref}. (The
  4596. plus one is to get past the tag at the beginning of the tuple
  4597. representation.)
  4598. \begin{lstlisting}
  4599. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4600. |$\Longrightarrow$|
  4601. (movq |$\itm{vec}'$| (reg r11))
  4602. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4603. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4604. |$\Longrightarrow$|
  4605. (movq |$\itm{vec}'$| (reg r11))
  4606. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4607. (movq (int 0) |$\itm{lhs}$|)
  4608. \end{lstlisting}
  4609. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4610. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4611. register \code{r11} ensures that offsets are only performed with
  4612. register operands. This requires removing \code{r11} from
  4613. consideration by the register allocating.
  4614. We compile the \code{allocate} form to operations on the
  4615. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4616. is the next free address in the FromSpace, so we move it into the
  4617. \itm{lhs} and then move it forward by enough space for the tuple being
  4618. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4619. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4620. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4621. how the tag is organized. We recommend using the Racket operations
  4622. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4623. The type annoation in the \code{vector} form is used to determine the
  4624. pointer mask region of the tag.
  4625. \begin{lstlisting}
  4626. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4627. |$\Longrightarrow$|
  4628. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4629. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4630. (movq |$\itm{lhs}'$| (reg r11))
  4631. (movq (int |$\itm{tag}$|) (deref r11 0))
  4632. \end{lstlisting}
  4633. The \code{collect} form is compiled to a call to the \code{collect}
  4634. function in the runtime. The arguments to \code{collect} are the top
  4635. of the root stack and the number of bytes that need to be allocated.
  4636. We shall use a dedicated register, \code{r15}, to store the pointer to
  4637. the top of the root stack. So \code{r15} is not available for use by
  4638. the register allocator.
  4639. \begin{lstlisting}
  4640. (collect |$\itm{bytes}$|)
  4641. |$\Longrightarrow$|
  4642. (movq (reg r15) (reg rdi))
  4643. (movq |\itm{bytes}| (reg rsi))
  4644. (callq collect)
  4645. \end{lstlisting}
  4646. \begin{figure}[tp]
  4647. \fbox{
  4648. \begin{minipage}{0.96\textwidth}
  4649. \[
  4650. \begin{array}{lcl}
  4651. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4652. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4653. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4654. \mid (\key{global-value}\; \itm{name}) \\
  4655. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4656. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4657. (\key{subq} \; \Arg\; \Arg) \mid
  4658. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4659. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4660. (\key{pushq}\;\Arg) \mid
  4661. (\key{popq}\;\Arg) \mid
  4662. (\key{retq})} \\
  4663. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4664. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4665. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4666. \mid (\key{jmp} \; \itm{label})
  4667. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  4668. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  4669. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4670. \end{array}
  4671. \]
  4672. \end{minipage}
  4673. }
  4674. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4675. \label{fig:x86-2}
  4676. \end{figure}
  4677. The syntax of the $x86_2$ language is defined in
  4678. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4679. of the form for global variables.
  4680. %
  4681. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4682. \code{select-instructions} pass on the running example.
  4683. \begin{figure}[tbp]
  4684. \centering
  4685. \begin{minipage}{0.75\textwidth}
  4686. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4687. (program
  4688. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4689. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4690. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4691. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4692. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  4693. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  4694. ((block63 . (block ()
  4695. (movq (reg r15) (reg rdi))
  4696. (movq (int 16) (reg rsi))
  4697. (callq collect)
  4698. (jmp block61)))
  4699. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  4700. (block61 . (block ()
  4701. (movq (global-value free_ptr) (var alloc43))
  4702. (addq (int 16) (global-value free_ptr))
  4703. (movq (var alloc43) (reg r11))
  4704. (movq (int 3) (deref r11 0))
  4705. (movq (var alloc43) (reg r11))
  4706. (movq (var vecinit44) (deref r11 8))
  4707. (movq (int 0) (var initret45))
  4708. (movq (var alloc43) (var vecinit48))
  4709. (movq (global-value free_ptr) (var tmp54))
  4710. (movq (var tmp54) (var tmp55))
  4711. (addq (int 16) (var tmp55))
  4712. (movq (global-value fromspace_end) (var tmp56))
  4713. (cmpq (var tmp56) (var tmp55))
  4714. (jmp-if l block59)
  4715. (jmp block60)))
  4716. (block60 . (block ()
  4717. (movq (reg r15) (reg rdi))
  4718. (movq (int 16) (reg rsi))
  4719. (callq collect)
  4720. (jmp block58))
  4721. (block59 . (block ()
  4722. (movq (int 0) (var collectret50))
  4723. (jmp block58)))
  4724. (block58 . (block ()
  4725. (movq (global-value free_ptr) (var alloc47))
  4726. (addq (int 16) (global-value free_ptr))
  4727. (movq (var alloc47) (reg r11))
  4728. (movq (int 131) (deref r11 0))
  4729. (movq (var alloc47) (reg r11))
  4730. (movq (var vecinit48) (deref r11 8))
  4731. (movq (int 0) (var initret49))
  4732. (movq (var alloc47) (reg r11))
  4733. (movq (deref r11 8) (var tmp57))
  4734. (movq (var tmp57) (reg r11))
  4735. (movq (deref r11 8) (reg rax))
  4736. (jmp conclusion)))
  4737. (start . (block ()
  4738. (movq (int 42) (var vecinit44))
  4739. (movq (global-value free_ptr) (var tmp51))
  4740. (movq (var tmp51) (var tmp52))
  4741. (addq (int 16) (var tmp52))
  4742. (movq (global-value fromspace_end) (var tmp53))
  4743. (cmpq (var tmp53) (var tmp52))
  4744. (jmp-if l block62)
  4745. (jmp block63))))))
  4746. \end{lstlisting}
  4747. \end{minipage}
  4748. \caption{Output of the \code{select-instructions} pass.}
  4749. \label{fig:select-instr-output-gc}
  4750. \end{figure}
  4751. \clearpage
  4752. \section{Register Allocation}
  4753. \label{sec:reg-alloc-gc}
  4754. As discussed earlier in this chapter, the garbage collector needs to
  4755. access all the pointers in the root set, that is, all variables that
  4756. are vectors. It will be the responsibility of the register allocator
  4757. to make sure that:
  4758. \begin{enumerate}
  4759. \item the root stack is used for spilling vector-typed variables, and
  4760. \item if a vector-typed variable is live during a call to the
  4761. collector, it must be spilled to ensure it is visible to the
  4762. collector.
  4763. \end{enumerate}
  4764. The later responsibility can be handled during construction of the
  4765. inference graph, by adding interference edges between the call-live
  4766. vector-typed variables and all the callee-saved registers. (They
  4767. already interfere with the caller-saved registers.) The type
  4768. information for variables is in the \code{program} form, so we
  4769. recommend adding another parameter to the \code{build-interference}
  4770. function to communicate this association list.
  4771. The spilling of vector-typed variables to the root stack can be
  4772. handled after graph coloring, when choosing how to assign the colors
  4773. (integers) to registers and stack locations. The \code{program} output
  4774. of this pass changes to also record the number of spills to the root
  4775. stack.
  4776. % build-interference
  4777. %
  4778. % callq
  4779. % extra parameter for var->type assoc. list
  4780. % update 'program' and 'if'
  4781. % allocate-registers
  4782. % allocate spilled vectors to the rootstack
  4783. % don't change color-graph
  4784. \section{Print x86}
  4785. \label{sec:print-x86-gc}
  4786. \margincomment{\scriptsize We need to show the translation to x86 and what
  4787. to do about global-value. \\ --Jeremy}
  4788. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4789. \code{print-x86} pass on the running example. In the prelude and
  4790. conclusion of the \code{main} function, we treat the root stack very
  4791. much like the regular stack in that we move the root stack pointer
  4792. (\code{r15}) to make room for all of the spills to the root stack,
  4793. except that the root stack grows up instead of down. For the running
  4794. example, there was just one spill so we increment \code{r15} by 8
  4795. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  4796. One issue that deserves special care is that there may be a call to
  4797. \code{collect} prior to the initializing assignments for all the
  4798. variables in the root stack. We do not want the garbage collector to
  4799. accidentaly think that some uninitialized variable is a pointer that
  4800. needs to be followed. Thus, we zero-out all locations on the root
  4801. stack in the prelude of \code{main}. In
  4802. Figure~\ref{fig:print-x86-output-gc}, the instruction
  4803. %
  4804. \lstinline{movq $0, (%r15)}
  4805. %
  4806. accomplishes this task. The garbage collector tests each root to see
  4807. if it is null prior to dereferencing it.
  4808. \begin{figure}[htbp]
  4809. \begin{minipage}[t]{0.5\textwidth}
  4810. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4811. _block58:
  4812. movq _free_ptr(%rip), %rcx
  4813. addq $16, _free_ptr(%rip)
  4814. movq %rcx, %r11
  4815. movq $131, 0(%r11)
  4816. movq %rcx, %r11
  4817. movq -8(%r15), %rax
  4818. movq %rax, 8(%r11)
  4819. movq $0, %rdx
  4820. movq %rcx, %r11
  4821. movq 8(%r11), %rcx
  4822. movq %rcx, %r11
  4823. movq 8(%r11), %rax
  4824. jmp _conclusion
  4825. _block59:
  4826. movq $0, %rcx
  4827. jmp _block58
  4828. _block62:
  4829. movq $0, %rcx
  4830. jmp _block61
  4831. _block60:
  4832. movq %r15, %rdi
  4833. movq $16, %rsi
  4834. callq _collect
  4835. jmp _block58
  4836. _block63:
  4837. movq %r15, %rdi
  4838. movq $16, %rsi
  4839. callq _collect
  4840. jmp _block61
  4841. _start:
  4842. movq $42, %rbx
  4843. movq _free_ptr(%rip), %rdx
  4844. addq $16, %rdx
  4845. movq _fromspace_end(%rip), %rcx
  4846. cmpq %rcx, %rdx
  4847. jl _block62
  4848. jmp _block63
  4849. \end{lstlisting}
  4850. \end{minipage}
  4851. \begin{minipage}[t]{0.45\textwidth}
  4852. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4853. _block61:
  4854. movq _free_ptr(%rip), %rcx
  4855. addq $16, _free_ptr(%rip)
  4856. movq %rcx, %r11
  4857. movq $3, 0(%r11)
  4858. movq %rcx, %r11
  4859. movq %rbx, 8(%r11)
  4860. movq $0, %rdx
  4861. movq %rcx, -8(%r15)
  4862. movq _free_ptr(%rip), %rcx
  4863. addq $16, %rcx
  4864. movq _fromspace_end(%rip), %rdx
  4865. cmpq %rdx, %rcx
  4866. jl _block59
  4867. jmp _block60
  4868. .globl _main
  4869. _main:
  4870. pushq %rbp
  4871. movq %rsp, %rbp
  4872. pushq %r12
  4873. pushq %rbx
  4874. pushq %r13
  4875. pushq %r14
  4876. subq $0, %rsp
  4877. movq $16384, %rdi
  4878. movq $16, %rsi
  4879. callq _initialize
  4880. movq _rootstack_begin(%rip), %r15
  4881. movq $0, (%r15)
  4882. addq $8, %r15
  4883. jmp _start
  4884. _conclusion:
  4885. subq $8, %r15
  4886. addq $0, %rsp
  4887. popq %r14
  4888. popq %r13
  4889. popq %rbx
  4890. popq %r12
  4891. popq %rbp
  4892. retq
  4893. \end{lstlisting}
  4894. \end{minipage}
  4895. \caption{Output of the \code{print-x86} pass.}
  4896. \label{fig:print-x86-output-gc}
  4897. \end{figure}
  4898. \margincomment{\scriptsize Suggest an implementation strategy
  4899. in which the students first do the code gen and test that
  4900. without GC (just use a big heap), then after that is debugged,
  4901. implement the GC. \\ --Jeremy}
  4902. \begin{figure}[p]
  4903. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4904. \node (R3) at (0,2) {\large $R_3$};
  4905. \node (R3-2) at (3,2) {\large $R_3$};
  4906. \node (R3-3) at (6,2) {\large $R_3$};
  4907. \node (R3-4) at (9,2) {\large $R_3$};
  4908. \node (R3-5) at (12,2) {\large $R_3$};
  4909. \node (C2-4) at (3,0) {\large $C_2$};
  4910. \node (C2-3) at (6,0) {\large $C_2$};
  4911. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  4912. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  4913. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  4914. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  4915. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  4916. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  4917. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  4918. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  4919. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  4920. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  4921. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  4922. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  4923. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4924. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4925. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  4926. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4927. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4928. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  4929. \end{tikzpicture}
  4930. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4931. \label{fig:R3-passes}
  4932. \end{figure}
  4933. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4934. for the compilation of $R_3$.
  4935. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4936. \chapter{Functions}
  4937. \label{ch:functions}
  4938. This chapter studies the compilation of functions at the level of
  4939. abstraction of the C language. This corresponds to a subset of Typed
  4940. Racket in which only top-level function definitions are allowed. These
  4941. kind of functions are an important stepping stone to implementing
  4942. lexically-scoped functions in the form of \key{lambda} abstractions,
  4943. which is the topic of Chapter~\ref{ch:lambdas}.
  4944. \section{The $R_4$ Language}
  4945. The syntax for function definitions and function application is shown
  4946. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  4947. Programs in $R_4$ start with zero or more function definitions. The
  4948. function names from these definitions are in-scope for the entire
  4949. program, including all other function definitions (so the ordering of
  4950. function definitions does not matter). The syntax for function
  4951. application does not include an explicit keyword, which is error prone
  4952. when using \code{match}. To alleviate this problem, we change the
  4953. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  4954. during type checking.
  4955. Functions are first-class in the sense that a function pointer is data
  4956. and can be stored in memory or passed as a parameter to another
  4957. function. Thus, we introduce a function type, written
  4958. \begin{lstlisting}
  4959. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4960. \end{lstlisting}
  4961. for a function whose $n$ parameters have the types $\Type_1$ through
  4962. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4963. these functions (with respect to Racket functions) is that they are
  4964. not lexically scoped. That is, the only external entities that can be
  4965. referenced from inside a function body are other globally-defined
  4966. functions. The syntax of $R_4$ prevents functions from being nested
  4967. inside each other.
  4968. \begin{figure}[tp]
  4969. \centering
  4970. \fbox{
  4971. \begin{minipage}{0.96\textwidth}
  4972. \[
  4973. \begin{array}{lcl}
  4974. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4975. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4976. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4977. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  4978. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4979. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4980. \mid (\key{and}\;\Exp\;\Exp)
  4981. \mid (\key{or}\;\Exp\;\Exp)
  4982. \mid (\key{not}\;\Exp)} \\
  4983. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4984. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4985. (\key{vector-ref}\;\Exp\;\Int)} \\
  4986. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4987. &\mid& (\Exp \; \Exp^{*}) \\
  4988. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4989. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  4990. \end{array}
  4991. \]
  4992. \end{minipage}
  4993. }
  4994. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  4995. with functions.}
  4996. \label{fig:r4-syntax}
  4997. \end{figure}
  4998. The program in Figure~\ref{fig:r4-function-example} is a
  4999. representative example of defining and using functions in $R_4$. We
  5000. define a function \code{map-vec} that applies some other function
  5001. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5002. vector containing the results. We also define a function \code{add1}
  5003. that does what its name suggests. The program then applies
  5004. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5005. \code{(vector 1 42)}, from which we return the \code{42}.
  5006. \begin{figure}[tbp]
  5007. \begin{lstlisting}
  5008. (program ()
  5009. (define (map-vec [f : (Integer -> Integer)]
  5010. [v : (Vector Integer Integer)])
  5011. : (Vector Integer Integer)
  5012. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5013. (define (add1 [x : Integer]) : Integer
  5014. (+ x 1))
  5015. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5016. )
  5017. \end{lstlisting}
  5018. \caption{Example of using functions in $R_4$.}
  5019. \label{fig:r4-function-example}
  5020. \end{figure}
  5021. The definitional interpreter for $R_4$ is in
  5022. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5023. responsible for setting up the mutual recursion between the top-level
  5024. function definitions. We use the classic backpatching approach that
  5025. uses mutable variables and makes two passes over the function
  5026. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5027. top-level environment using a mutable cons cell for each function
  5028. definition. Note that the \code{lambda} value for each function is
  5029. incomplete; it does not yet include the environment. Once the
  5030. top-level environment is constructed, we then iterate over it and
  5031. update the \code{lambda} value's to use the top-level environment.
  5032. \begin{figure}[tp]
  5033. \begin{lstlisting}
  5034. (define (interp-exp env)
  5035. (lambda (e)
  5036. (define recur (interp-exp env))
  5037. (match e
  5038. ...
  5039. [`(,fun ,args ...)
  5040. (define arg-vals (for/list ([e args]) (recur e)))
  5041. (define fun-val (recur fun))
  5042. (match fun-val
  5043. [`(lambda (,xs ...) ,body ,fun-env)
  5044. (define new-env (append (map cons xs arg-vals) fun-env))
  5045. ((interp-exp new-env) body)]
  5046. [else (error "interp-exp, expected function, not" fun-val)])]
  5047. [else (error 'interp-exp "unrecognized expression")]
  5048. )))
  5049. (define (interp-def d)
  5050. (match d
  5051. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5052. (mcons f `(lambda ,xs ,body ()))]
  5053. ))
  5054. (define (interp-R4 p)
  5055. (match p
  5056. [`(program ,ds ... ,body)
  5057. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5058. (for/list ([b top-level])
  5059. (set-mcdr! b (match (mcdr b)
  5060. [`(lambda ,xs ,body ())
  5061. `(lambda ,xs ,body ,top-level)])))
  5062. ((interp-exp top-level) body))]
  5063. ))
  5064. \end{lstlisting}
  5065. \caption{Interpreter for the $R_4$ language.}
  5066. \label{fig:interp-R4}
  5067. \end{figure}
  5068. \section{Functions in x86}
  5069. \label{sec:fun-x86}
  5070. \margincomment{\tiny Make sure callee-saved registers are discussed
  5071. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5072. \margincomment{\tiny Talk about the return address on the
  5073. stack and what callq and retq does.\\ --Jeremy }
  5074. The x86 architecture provides a few features to support the
  5075. implementation of functions. We have already seen that x86 provides
  5076. labels so that one can refer to the location of an instruction, as is
  5077. needed for jump instructions. Labels can also be used to mark the
  5078. beginning of the instructions for a function. Going further, we can
  5079. obtain the address of a label by using the \key{leaq} instruction and
  5080. \key{rip}-relative addressing. For example, the following puts the
  5081. address of the \code{add1} label into the \code{rbx} register.
  5082. \begin{lstlisting}
  5083. leaq add1(%rip), %rbx
  5084. \end{lstlisting}
  5085. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5086. instruction for jumping to a function whose location is given by a
  5087. label. Here we instead will be jumping to a function whose location is
  5088. given by an address, that is, we need to make an \emph{indirect
  5089. function call}. The x86 syntax is to give the register name prefixed
  5090. with an asterisk.
  5091. \begin{lstlisting}
  5092. callq *%rbx
  5093. \end{lstlisting}
  5094. \subsection{Calling Conventions}
  5095. The \code{callq} instruction provides partial support for implementing
  5096. functions, but it does not handle (1) parameter passing, (2) saving
  5097. and restoring frames on the procedure call stack, or (3) determining
  5098. how registers are shared by different functions. These issues require
  5099. coordination between the caller and the callee, which is often
  5100. assembly code written by different programmers or generated by
  5101. different compilers. As a result, people have developed
  5102. \emph{conventions} that govern how functions calls are performed.
  5103. Here we shall use the same conventions used by the \code{gcc}
  5104. compiler~\citep{Matz:2013aa}.
  5105. Regarding (1) parameter passing, the convention is to use the
  5106. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5107. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5108. than six arguments, then the convention is to use space on the frame
  5109. of the caller for the rest of the arguments. However, to ease the
  5110. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5111. we shall arrange to never have more than six arguments.
  5112. %
  5113. The register \code{rax} is for the return value of the function.
  5114. Regarding (2) frames and the procedure call stack, the convention is
  5115. that the stack grows down, with each function call using a chunk of
  5116. space called a frame. The caller sets the stack pointer, register
  5117. \code{rsp}, to the last data item in its frame. The callee must not
  5118. change anything in the caller's frame, that is, anything that is at or
  5119. above the stack pointer. The callee is free to use locations that are
  5120. below the stack pointer.
  5121. Regarding (3) the sharing of registers between different functions,
  5122. recall from Section~\ref{sec:calling-conventions} that the registers
  5123. are divided into two groups, the caller-saved registers and the
  5124. callee-saved registers. The caller should assume that all the
  5125. caller-saved registers get overwritten with arbitrary values by the
  5126. callee. Thus, the caller should either 1) not put values that are live
  5127. across a call in caller-saved registers, or 2) save and restore values
  5128. that are live across calls. We shall recommend option 1). On the flip
  5129. side, if the callee wants to use a callee-saved register, the callee
  5130. must save the contents of those registers on their stack frame and
  5131. then put them back prior to returning to the caller. The base
  5132. pointer, register \code{rbp}, is used as a point-of-reference within a
  5133. frame, so that each local variable can be accessed at a fixed offset
  5134. from the base pointer.
  5135. %
  5136. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5137. frames.
  5138. %% If we were to use stack arguments, they would be between the
  5139. %% caller locals and the callee return address.
  5140. \begin{figure}[tbp]
  5141. \centering
  5142. \begin{tabular}{r|r|l|l} \hline
  5143. Caller View & Callee View & Contents & Frame \\ \hline
  5144. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5145. 0(\key{\%rbp}) & & old \key{rbp} \\
  5146. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5147. \ldots & & \ldots \\
  5148. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5149. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5150. \ldots & & \ldots \\
  5151. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5152. %% & & \\
  5153. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5154. %% & \ldots & \ldots \\
  5155. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5156. \hline
  5157. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5158. & 0(\key{\%rbp}) & old \key{rbp} \\
  5159. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5160. & \ldots & \ldots \\
  5161. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5162. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5163. & \ldots & \ldots \\
  5164. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5165. \end{tabular}
  5166. \caption{Memory layout of caller and callee frames.}
  5167. \label{fig:call-frames}
  5168. \end{figure}
  5169. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5170. %% local variables and for storing the values of callee-saved registers
  5171. %% (we shall refer to all of these collectively as ``locals''), and that
  5172. %% at the beginning of a function we move the stack pointer \code{rsp}
  5173. %% down to make room for them.
  5174. %% We recommend storing the local variables
  5175. %% first and then the callee-saved registers, so that the local variables
  5176. %% can be accessed using \code{rbp} the same as before the addition of
  5177. %% functions.
  5178. %% To make additional room for passing arguments, we shall
  5179. %% move the stack pointer even further down. We count how many stack
  5180. %% arguments are needed for each function call that occurs inside the
  5181. %% body of the function and find their maximum. Adding this number to the
  5182. %% number of locals gives us how much the \code{rsp} should be moved at
  5183. %% the beginning of the function. In preparation for a function call, we
  5184. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5185. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5186. %% so on.
  5187. %% Upon calling the function, the stack arguments are retrieved by the
  5188. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5189. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5190. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5191. %% the layout of the caller and callee frames. Notice how important it is
  5192. %% that we correctly compute the maximum number of arguments needed for
  5193. %% function calls; if that number is too small then the arguments and
  5194. %% local variables will smash into each other!
  5195. \subsection{Efficient Tail Calls}
  5196. \label{sec:tail-call}
  5197. In general, the amount of stack space used by a program is determined
  5198. by the longest chain of nested function calls. That is, if function
  5199. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5200. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5201. $n$ can grow quite large in the case of recursive or mutually
  5202. recursive functions. However, in some cases we can arrange to use only
  5203. constant space, i.e. $O(1)$, instead of $O(n)$.
  5204. If a function call is the last action in a function body, then that
  5205. call is said to be a \emph{tail call}. In such situations, the frame
  5206. of the caller is no longer needed, so we can pop the caller's frame
  5207. before making the tail call. With this approach, a recursive function
  5208. that only makes tail calls will only use $O(1)$ stack space.
  5209. Functional languages like Racket typically rely heavily on recursive
  5210. functions, so they typically guarantee that all tail calls will be
  5211. optimized in this way.
  5212. However, some care is needed with regards to argument passing in tail
  5213. calls. As mentioned above, for arguments beyond the sixth, the
  5214. convention is to use space in the caller's frame for passing
  5215. arguments. But here we've popped the caller's frame and can no longer
  5216. use it. Another alternative is to use space in the callee's frame for
  5217. passing arguments. However, this option is also problematic because
  5218. the caller and callee's frame overlap in memory. As we begin to copy
  5219. the arguments from their sources in the caller's frame, the target
  5220. locations in the callee's frame might overlap with the sources for
  5221. later arguments! We solve this problem by not using the stack for
  5222. paramter passing but instead use the heap, as we describe in the next
  5223. section.
  5224. As briefly mentioned above, for a tail call we pop the caller's frame
  5225. prior to making the tail call. The instructions for popping a frame
  5226. are the instructions that we usually place in the conclusion of a
  5227. function. Thus, we also need to place such code immediately before
  5228. each tail call. These instructions include restoring the callee-saved
  5229. registers, so it is good that the argument passing registers are all
  5230. caller-saved registers.
  5231. One last note regarding which instruction to use to make the tail
  5232. call. When the callee is finished, it should not return to the current
  5233. function, but it should return to the function that called the current
  5234. one. Thus, the return address that is already on the stack is the
  5235. right one, and we should not use \key{callq} to make the tail call, as
  5236. that would unnecessarily overwrite the return address. Instead we can
  5237. simply use the \key{jmp} instruction. Like the indirect function call,
  5238. we write an indirect jump with a register prefixed with an asterisk.
  5239. We recommend using \code{rax} to hold the jump target because the
  5240. preceeding ``conclusion'' overwrites just about everything else.
  5241. \begin{lstlisting}
  5242. jmp *%rax
  5243. \end{lstlisting}
  5244. %% Now that we have a good understanding of functions as they appear in
  5245. %% $R_4$ and the support for functions in x86, we need to plan the
  5246. %% changes to our compiler, that is, do we need any new passes and/or do
  5247. %% we need to change any existing passes? Also, do we need to add new
  5248. %% kinds of AST nodes to any of the intermediate languages?
  5249. \section{Shrink $R_4$}
  5250. \label{sec:shrink-r4}
  5251. The \code{shrink} pass performs a couple minor modifications to the
  5252. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5253. field to each function definition:
  5254. \begin{lstlisting}
  5255. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5256. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5257. \end{lstlisting}
  5258. and introduces an explicit \code{main} function.\\
  5259. \begin{tabular}{lll}
  5260. \begin{minipage}{0.45\textwidth}
  5261. \begin{lstlisting}
  5262. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5263. \end{lstlisting}
  5264. \end{minipage}
  5265. &
  5266. $\Rightarrow$
  5267. &
  5268. \begin{minipage}{0.45\textwidth}
  5269. \begin{lstlisting}
  5270. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5271. \end{lstlisting}
  5272. \end{minipage}
  5273. \end{tabular} \\
  5274. where $\itm{mainDef}$ is
  5275. \begin{lstlisting}
  5276. (define (main) : Integer () |$\Exp'$|)
  5277. \end{lstlisting}
  5278. \section{Reveal Functions}
  5279. \label{sec:reveal-functions-r4}
  5280. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5281. compilation because it conflates the use of function names and local
  5282. variables. This is a problem because we need to compile the use of a
  5283. function name differently than the use of a local variable; we need to
  5284. use \code{leaq} to convert the function name (a label in x86) to an
  5285. address in a register. Thus, it is a good idea to create a new pass
  5286. that changes function references from just a symbol $f$ to
  5287. \code{(fun-ref $f$)}. A good name for this pass is
  5288. \code{reveal-functions} and the output language, $F_1$, is defined in
  5289. Figure~\ref{fig:f1-syntax}.
  5290. \begin{figure}[tp]
  5291. \centering
  5292. \fbox{
  5293. \begin{minipage}{0.96\textwidth}
  5294. \[
  5295. \begin{array}{lcl}
  5296. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5297. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5298. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5299. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5300. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5301. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5302. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5303. (\key{vector-ref}\;\Exp\;\Int)} \\
  5304. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5305. (\key{app}\; \Exp \; \Exp^{*})} \\
  5306. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5307. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5308. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5309. \end{array}
  5310. \]
  5311. \end{minipage}
  5312. }
  5313. \caption{The $F_1$ language, an extension of $R_4$
  5314. (Figure~\ref{fig:r4-syntax}).}
  5315. \label{fig:f1-syntax}
  5316. \end{figure}
  5317. %% Distinguishing between calls in tail position and non-tail position
  5318. %% requires the pass to have some notion of context. We recommend using
  5319. %% two mutually recursive functions, one for processing expressions in
  5320. %% tail position and another for the rest.
  5321. Placing this pass after \code{uniquify} is a good idea, because it
  5322. will make sure that there are no local variables and functions that
  5323. share the same name. On the other hand, \code{reveal-functions} needs
  5324. to come before the \code{explicate-control} pass because that pass
  5325. will help us compile \code{fun-ref} into assignment statements.
  5326. \section{Limit Functions}
  5327. \label{sec:limit-functions-r4}
  5328. This pass transforms functions so that they have at most six
  5329. parameters and transforms all function calls so that they pass at most
  5330. six arguments. A simple strategy for imposing an argument limit of
  5331. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5332. into a vector, making that subsequent vector the $n$th argument.
  5333. \begin{tabular}{lll}
  5334. \begin{minipage}{0.2\textwidth}
  5335. \begin{lstlisting}
  5336. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5337. \end{lstlisting}
  5338. \end{minipage}
  5339. &
  5340. $\Rightarrow$
  5341. &
  5342. \begin{minipage}{0.4\textwidth}
  5343. \begin{lstlisting}
  5344. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5345. \end{lstlisting}
  5346. \end{minipage}
  5347. \end{tabular}
  5348. In the body of the function, all occurrances of the $i$th argument in
  5349. which $i>5$ must be replaced with a \code{vector-ref}.
  5350. \section{Remove Complex Operators and Operands}
  5351. \label{sec:rco-r4}
  5352. The primary decisions to make for this pass is whether to classify
  5353. \code{fun-ref} and \code{app} as either simple or complex
  5354. expressions. Recall that a simple expression will eventually end up as
  5355. just an ``immediate'' argument of an x86 instruction. Function
  5356. application will be translated to a sequence of instructions, so
  5357. \code{app} must be classified as complex expression. Regarding
  5358. \code{fun-ref}, as discussed above, the function label needs to
  5359. be converted to an address using the \code{leaq} instruction. Thus,
  5360. even though \code{fun-ref} seems rather simple, it needs to be
  5361. classified as a complex expression so that we generate an assignment
  5362. statement with a left-hand side that can serve as the target of the
  5363. \code{leaq}.
  5364. \section{Explicate Control and the $C_3$ language}
  5365. \label{sec:explicate-control-r4}
  5366. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5367. \key{explicate-control}. The three mutually recursive functions for
  5368. this pass, for assignment, tail, and predicate contexts, must all be
  5369. updated with cases for \code{fun-ref} and \code{app}. In
  5370. assignment and predicate contexts, \code{app} becomes \code{call},
  5371. whereas in tail position \code{app} becomes \code{tailcall}. We
  5372. recommend defining a new function for processing function definitions.
  5373. This code is similar to the case for \code{program} in $R_3$. The
  5374. top-level \code{explicate-control} function that handles the
  5375. \code{program} form of $R_4$ can then apply this new function to all
  5376. the function definitions.
  5377. \begin{figure}[tp]
  5378. \fbox{
  5379. \begin{minipage}{0.96\textwidth}
  5380. \[
  5381. \begin{array}{lcl}
  5382. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5383. \\
  5384. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5385. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5386. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5387. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5388. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5389. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5390. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5391. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5392. \mid (\key{collect} \,\itm{int}) }\\
  5393. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5394. &\mid& \gray{(\key{goto}\,\itm{label})
  5395. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5396. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5397. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5398. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5399. \end{array}
  5400. \]
  5401. \end{minipage}
  5402. }
  5403. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5404. \label{fig:c3-syntax}
  5405. \end{figure}
  5406. \section{Uncover Locals}
  5407. \label{sec:uncover-locals-r4}
  5408. The function for processing $\Tail$ should be updated with a case for
  5409. \code{tailcall}. We also recommend creating a new function for
  5410. processing function definitions. Each function definition in $C_3$ has
  5411. its own set of local variables, so the code for function definitions
  5412. should be similar to the case for the \code{program} form in $C_2$.
  5413. \section{Select Instructions}
  5414. \label{sec:select-r4}
  5415. The output of select instructions is a program in the x86$_3$
  5416. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5417. \begin{figure}[tp]
  5418. \fbox{
  5419. \begin{minipage}{0.96\textwidth}
  5420. \[
  5421. \begin{array}{lcl}
  5422. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  5423. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  5424. &\mid& \gray{ (\key{byte-reg}\; \itm{register})
  5425. \mid (\key{global-value}\; \itm{name}) } \\
  5426. &\mid& (\key{fun-ref}\; \itm{label})\\
  5427. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5428. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5429. (\key{subq} \; \Arg\; \Arg) \mid
  5430. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5431. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5432. (\key{pushq}\;\Arg) \mid
  5433. (\key{popq}\;\Arg) \mid
  5434. (\key{retq}) } \\
  5435. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5436. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5437. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5438. \mid (\key{jmp} \; \itm{label})
  5439. \mid (\key{j}\itm{cc} \; \itm{label})
  5440. \mid (\key{label} \; \itm{label}) } \\
  5441. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5442. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5443. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5444. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5445. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5446. \end{array}
  5447. \]
  5448. \end{minipage}
  5449. }
  5450. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5451. \label{fig:x86-3}
  5452. \end{figure}
  5453. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5454. as follows: \\
  5455. \begin{tabular}{lll}
  5456. \begin{minipage}{0.45\textwidth}
  5457. \begin{lstlisting}
  5458. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5459. \end{lstlisting}
  5460. \end{minipage}
  5461. &
  5462. $\Rightarrow$
  5463. &
  5464. \begin{minipage}{0.4\textwidth}
  5465. \begin{lstlisting}
  5466. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5467. \end{lstlisting}
  5468. \end{minipage}
  5469. \end{tabular} \\
  5470. Regarding function definitions, we need to remove their parameters and
  5471. instead perform parameter passing in terms of the conventions
  5472. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5473. in the argument passing registers, and inside the function we should
  5474. generate a \code{movq} instruction for each parameter, to move the
  5475. argument value from the appropriate register to a new local variable
  5476. with the same name as the old parameter.
  5477. Next, consider the compilation of function calls, which have the
  5478. following form upon input to \code{select-instructions}.
  5479. \begin{lstlisting}
  5480. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5481. \end{lstlisting}
  5482. In the mirror image of handling the parameters of function
  5483. definitions, the arguments \itm{args} need to be moved to the argument
  5484. passing registers.
  5485. %
  5486. Once the instructions for parameter passing have been generated, the
  5487. function call itself can be performed with an indirect function call,
  5488. for which I recommend creating the new instruction
  5489. \code{indirect-callq}. Of course, the return value from the function
  5490. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5491. \begin{lstlisting}
  5492. (indirect-callq |\itm{fun}|)
  5493. (movq (reg rax) |\itm{lhs}|)
  5494. \end{lstlisting}
  5495. Regarding tail calls, the parameter passing is the same as non-tail
  5496. calls: generate instructions to move the arguments into to the
  5497. argument passing registers. After that we need to pop the frame from
  5498. the procedure call stack. However, we do not yet know how big the
  5499. frame is; that gets determined during register allocation. So instead
  5500. of generating those instructions here, we invent a new instruction
  5501. that means ``pop the frame and then do an indirect jump'', which we
  5502. name \code{tail-jmp}.
  5503. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5504. using the label \code{start} for the initial block of a program, and
  5505. in Section~\ref{sec:select-r1} we recommended labelling the conclusion
  5506. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5507. can be compiled to an assignment to \code{rax} followed by a jump to
  5508. \code{conclusion}. With the addition of function definitions, we will
  5509. have a starting block and conclusion for each function, but their
  5510. labels need to be unique. We recommend prepending the function's name
  5511. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5512. labels. (Alternatively, one could \code{gensym} labels for the start
  5513. and conclusion and store them in the $\itm{info}$ field of the
  5514. function definition.)
  5515. \section{Uncover Live}
  5516. %% The rest of the passes need only minor modifications to handle the new
  5517. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5518. %% \code{leaq}.
  5519. Inside \code{uncover-live}, when computing the $W$ set (written
  5520. variables) for an \code{indirect-callq} instruction, we recommend
  5521. including all the caller-saved registers, which will have the affect
  5522. of making sure that no caller-saved register actually needs to be
  5523. saved.
  5524. \section{Build Interference Graph}
  5525. With the addition of function definitions, we compute an interference
  5526. graph for each function (not just one for the whole program).
  5527. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5528. spill vector-typed variables that are live during a call to the
  5529. \code{collect}. With the addition of functions to our language, we
  5530. need to revisit this issue. Many functions will perform allocation and
  5531. therefore have calls to the collector inside of them. Thus, we should
  5532. not only spill a vector-typed variable when it is live during a call
  5533. to \code{collect}, but we should spill the variable if it is live
  5534. during any function call. Thus, in the \code{build-interference} pass,
  5535. we recommend adding interference edges between call-live vector-typed
  5536. variables and the callee-saved registers (in addition to the usual
  5537. addition of edges between call-live variables and the caller-saved
  5538. registers).
  5539. \section{Patch Instructions}
  5540. In \code{patch-instructions}, you should deal with the x86
  5541. idiosyncrasy that the destination argument of \code{leaq} must be a
  5542. register. Additionally, you should ensure that the argument of
  5543. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5544. code generation more convenient, because we will be trampling many
  5545. registers before the tail call (as explained below).
  5546. \section{Print x86}
  5547. For the \code{print-x86} pass, we recommend the following translations:
  5548. \begin{lstlisting}
  5549. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5550. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5551. \end{lstlisting}
  5552. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5553. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5554. is what we will want to do, but before the jump we need to pop the
  5555. current frame. So we need to restore the state of the registers to the
  5556. point they were at when the current function was called. This
  5557. sequence of instructions is the same as the code for the conclusion of
  5558. a function.
  5559. Note that your \code{print-x86} pass needs to add the code for saving
  5560. and restoring callee-saved registers, if you have not already
  5561. implemented that. This is necessary when generating code for function
  5562. definitions.
  5563. \section{An Example Translation}
  5564. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5565. function in $R_4$ to x86. The figure also includes the results of the
  5566. \code{explicate-control} and \code{select-instructions} passes. We
  5567. have ommited the \code{has-type} AST nodes for readability. Can you
  5568. see any ways to improve the translation?
  5569. \begin{figure}[tbp]
  5570. \begin{tabular}{ll}
  5571. \begin{minipage}{0.45\textwidth}
  5572. % s3_2.rkt
  5573. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5574. (program
  5575. (define (add [x : Integer]
  5576. [y : Integer])
  5577. : Integer (+ x y))
  5578. (add 40 2))
  5579. \end{lstlisting}
  5580. $\Downarrow$
  5581. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5582. (program ()
  5583. (define (add86 [x87 : Integer]
  5584. [y88 : Integer]) : Integer ()
  5585. ((add86start . (return (+ x87 y88)))))
  5586. (define (main) : Integer ()
  5587. ((mainstart .
  5588. (seq (assign tmp89 (fun-ref add86))
  5589. (tailcall tmp89 40 2))))))
  5590. \end{lstlisting}
  5591. \end{minipage}
  5592. &
  5593. $\Rightarrow$
  5594. \begin{minipage}{0.5\textwidth}
  5595. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5596. (program ()
  5597. (define (add86)
  5598. ((locals (x87 . Integer) (y88 . Integer))
  5599. (num-params . 2))
  5600. ((add86start .
  5601. (block ()
  5602. (movq (reg rcx) (var x87))
  5603. (movq (reg rdx) (var y88))
  5604. (movq (var x87) (reg rax))
  5605. (addq (var y88) (reg rax))
  5606. (jmp add86conclusion)))))
  5607. (define (main)
  5608. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5609. (num-params . 0))
  5610. ((mainstart .
  5611. (block ()
  5612. (leaq (fun-ref add86) (var tmp89))
  5613. (movq (int 40) (reg rcx))
  5614. (movq (int 2) (reg rdx))
  5615. (tail-jmp (var tmp89))))))
  5616. \end{lstlisting}
  5617. $\Downarrow$
  5618. \end{minipage}
  5619. \end{tabular}
  5620. \begin{tabular}{lll}
  5621. \begin{minipage}{0.3\textwidth}
  5622. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5623. _add90start:
  5624. movq %rcx, %rsi
  5625. movq %rdx, %rcx
  5626. movq %rsi, %rax
  5627. addq %rcx, %rax
  5628. jmp _add90conclusion
  5629. .globl _add90
  5630. .align 16
  5631. _add90:
  5632. pushq %rbp
  5633. movq %rsp, %rbp
  5634. pushq %r12
  5635. pushq %rbx
  5636. pushq %r13
  5637. pushq %r14
  5638. subq $0, %rsp
  5639. jmp _add90start
  5640. _add90conclusion:
  5641. addq $0, %rsp
  5642. popq %r14
  5643. popq %r13
  5644. popq %rbx
  5645. popq %r12
  5646. subq $0, %r15
  5647. popq %rbp
  5648. retq
  5649. \end{lstlisting}
  5650. \end{minipage}
  5651. &
  5652. \begin{minipage}{0.3\textwidth}
  5653. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5654. _mainstart:
  5655. leaq _add90(%rip), %rsi
  5656. movq $40, %rcx
  5657. movq $2, %rdx
  5658. movq %rsi, %rax
  5659. addq $0, %rsp
  5660. popq %r14
  5661. popq %r13
  5662. popq %rbx
  5663. popq %r12
  5664. subq $0, %r15
  5665. popq %rbp
  5666. jmp *%rax
  5667. .globl _main
  5668. .align 16
  5669. _main:
  5670. pushq %rbp
  5671. movq %rsp, %rbp
  5672. pushq %r12
  5673. pushq %rbx
  5674. pushq %r13
  5675. pushq %r14
  5676. subq $0, %rsp
  5677. movq $16384, %rdi
  5678. movq $16, %rsi
  5679. callq _initialize
  5680. movq _rootstack_begin(%rip), %r15
  5681. jmp _mainstart
  5682. \end{lstlisting}
  5683. \end{minipage}
  5684. &
  5685. \begin{minipage}{0.3\textwidth}
  5686. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5687. _mainconclusion:
  5688. addq $0, %rsp
  5689. popq %r14
  5690. popq %r13
  5691. popq %rbx
  5692. popq %r12
  5693. subq $0, %r15
  5694. popq %rbp
  5695. retq
  5696. \end{lstlisting}
  5697. \end{minipage}
  5698. \end{tabular}
  5699. \caption{Example compilation of a simple function to x86.}
  5700. \label{fig:add-fun}
  5701. \end{figure}
  5702. \begin{exercise}\normalfont
  5703. Expand your compiler to handle $R_4$ as outlined in this section.
  5704. Create 5 new programs that use functions, including examples that pass
  5705. functions and return functions from other functions and including
  5706. recursive functions. Test your compiler on these new programs and all
  5707. of your previously created test programs.
  5708. \end{exercise}
  5709. \begin{figure}[p]
  5710. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5711. \node (R4) at (0,2) {\large $R_4$};
  5712. \node (R4-2) at (3,2) {\large $R_4$};
  5713. \node (R4-3) at (6,2) {\large $R_4$};
  5714. \node (F1-1) at (12,0) {\large $F_1$};
  5715. \node (F1-2) at (9,0) {\large $F_1$};
  5716. \node (F1-3) at (6,0) {\large $F_1$};
  5717. \node (F1-4) at (3,0) {\large $F_1$};
  5718. \node (C3-1) at (6,-2) {\large $C_3$};
  5719. \node (C3-2) at (3,-2) {\large $C_3$};
  5720. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5721. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5722. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5723. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  5724. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5725. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5726. \path[->,bend left=15] (R4) edge [above] node
  5727. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  5728. \path[->,bend left=15] (R4-2) edge [above] node
  5729. {\ttfamily\footnotesize uniquify} (R4-3);
  5730. \path[->,bend left=15] (R4-3) edge [right] node
  5731. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  5732. \path[->,bend left=15] (F1-1) edge [below] node
  5733. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  5734. \path[->,bend right=15] (F1-2) edge [above] node
  5735. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  5736. \path[->,bend right=15] (F1-3) edge [above] node
  5737. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  5738. \path[->,bend left=15] (F1-4) edge [right] node
  5739. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  5740. \path[->,bend left=15] (C3-1) edge [below] node
  5741. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  5742. \path[->,bend right=15] (C3-2) edge [left] node
  5743. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5744. \path[->,bend left=15] (x86-2) edge [left] node
  5745. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5746. \path[->,bend right=15] (x86-2-1) edge [below] node
  5747. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5748. \path[->,bend right=15] (x86-2-2) edge [left] node
  5749. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5750. \path[->,bend left=15] (x86-3) edge [above] node
  5751. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  5752. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5753. \end{tikzpicture}
  5754. \caption{Diagram of the passes for $R_4$, a language with functions.}
  5755. \label{fig:R4-passes}
  5756. \end{figure}
  5757. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  5758. the compilation of $R_4$.
  5759. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5760. \chapter{Lexically Scoped Functions}
  5761. \label{ch:lambdas}
  5762. This chapter studies lexically scoped functions as they appear in
  5763. functional languages such as Racket. By lexical scoping we mean that a
  5764. function's body may refer to variables whose binding site is outside
  5765. of the function, in an enclosing scope.
  5766. %
  5767. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5768. anonymous function defined using the \key{lambda} form. The body of
  5769. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5770. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5771. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5772. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5773. returned from the function \code{f}. Below the definition of \code{f},
  5774. we have two calls to \code{f} with different arguments for \code{x},
  5775. first \code{5} then \code{3}. The functions returned from \code{f} are
  5776. bound to variables \code{g} and \code{h}. Even though these two
  5777. functions were created by the same \code{lambda}, they are really
  5778. different functions because they use different values for
  5779. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5780. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5781. the result of this program is \code{42}.
  5782. \begin{figure}[btp]
  5783. % s4_6.rkt
  5784. \begin{lstlisting}
  5785. (define (f [x : Integer]) : (Integer -> Integer)
  5786. (let ([y 4])
  5787. (lambda: ([z : Integer]) : Integer
  5788. (+ x (+ y z)))))
  5789. (let ([g (f 5)])
  5790. (let ([h (f 3)])
  5791. (+ (g 11) (h 15))))
  5792. \end{lstlisting}
  5793. \caption{Example of a lexically scoped function.}
  5794. \label{fig:lexical-scoping}
  5795. \end{figure}
  5796. \section{The $R_5$ Language}
  5797. The syntax for this language with anonymous functions and lexical
  5798. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5799. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5800. for function application. In this chapter we shall descibe how to
  5801. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5802. into a combination of functions (as in $R_4$) and tuples (as in
  5803. $R_3$).
  5804. \begin{figure}[tp]
  5805. \centering
  5806. \fbox{
  5807. \begin{minipage}{0.96\textwidth}
  5808. \[
  5809. \begin{array}{lcl}
  5810. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5811. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5812. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5813. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5814. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  5815. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  5816. &\mid& \gray{\key{\#t} \mid \key{\#f}
  5817. \mid (\key{and}\;\Exp\;\Exp)
  5818. \mid (\key{or}\;\Exp\;\Exp)
  5819. \mid (\key{not}\;\Exp) } \\
  5820. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5821. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5822. (\key{vector-ref}\;\Exp\;\Int)} \\
  5823. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5824. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5825. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5826. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5827. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5828. \end{array}
  5829. \]
  5830. \end{minipage}
  5831. }
  5832. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  5833. with \key{lambda}.}
  5834. \label{fig:r5-syntax}
  5835. \end{figure}
  5836. To compile lexically-scoped functions to top-level function
  5837. definitions, the compiler will need to provide special treatment to
  5838. variable occurences such as \code{x} and \code{y} in the body of the
  5839. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  5840. of $R_4$ may not refer to variables defined outside the function. To
  5841. identify such variable occurences, we review the standard notion of
  5842. free variable.
  5843. \begin{definition}
  5844. A variable is \emph{free with respect to an expression} $e$ if the
  5845. variable occurs inside $e$ but does not have an enclosing binding in
  5846. $e$.
  5847. \end{definition}
  5848. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5849. free with respect to the expression \code{(+ x (+ y z))}. On the
  5850. other hand, only \code{x} and \code{y} are free with respect to the
  5851. following expression becuase \code{z} is bound by the \code{lambda}.
  5852. \begin{lstlisting}
  5853. (lambda: ([z : Integer]) : Integer
  5854. (+ x (+ y z)))
  5855. \end{lstlisting}
  5856. Once we have identified the free variables of a \code{lambda}, we need
  5857. to arrange for some way to transport, at runtime, the values of those
  5858. variables from the point where the \code{lambda} was created to the
  5859. point where the \code{lambda} is applied. Referring again to
  5860. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5861. needs to be used in the application of \code{g} to \code{11}, but the
  5862. binding of \code{x} to \code{3} needs to be used in the application of
  5863. \code{h} to \code{15}. The solution is to bundle the values of the
  5864. free variables together with the function pointer for the lambda's
  5865. code into a data structure called a \emph{closure}. Fortunately, we
  5866. already have the appropriate ingredients to make closures,
  5867. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  5868. gave us function pointers. The function pointer shall reside at index
  5869. $0$ and the values for free variables will fill in the rest of the
  5870. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  5871. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  5872. Because the two closures came from the same \key{lambda}, they share
  5873. the same code but differ in the values for free variable \code{x}.
  5874. \begin{figure}[tbp]
  5875. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  5876. \caption{Example closure representation for the \key{lambda}'s
  5877. in Figure~\ref{fig:lexical-scoping}.}
  5878. \label{fig:closures}
  5879. \end{figure}
  5880. \section{Interpreting $R_5$}
  5881. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5882. $R_5$. The clause for \key{lambda} saves the current environment
  5883. inside the returned \key{lambda}. Then the clause for \key{app} uses
  5884. the environment from the \key{lambda}, the \code{lam-env}, when
  5885. interpreting the body of the \key{lambda}. The \code{lam-env}
  5886. environment is extended with the mapping of parameters to argument
  5887. values.
  5888. \begin{figure}[tbp]
  5889. \begin{lstlisting}
  5890. (define (interp-exp env)
  5891. (lambda (e)
  5892. (define recur (interp-exp env))
  5893. (match e
  5894. ...
  5895. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5896. `(lambda ,xs ,body ,env)]
  5897. [`(app ,fun ,args ...)
  5898. (define fun-val ((interp-exp env) fun))
  5899. (define arg-vals (map (interp-exp env) args))
  5900. (match fun-val
  5901. [`(lambda (,xs ...) ,body ,lam-env)
  5902. (define new-env (append (map cons xs arg-vals) lam-env))
  5903. ((interp-exp new-env) body)]
  5904. [else (error "interp-exp, expected function, not" fun-val)])]
  5905. [else (error 'interp-exp "unrecognized expression")]
  5906. )))
  5907. \end{lstlisting}
  5908. \caption{Interpreter for $R_5$.}
  5909. \label{fig:interp-R5}
  5910. \end{figure}
  5911. \section{Type Checking $R_5$}
  5912. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5913. \key{lambda} form. The body of the \key{lambda} is checked in an
  5914. environment that includes the current environment (because it is
  5915. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5916. require the body's type to match the declared return type.
  5917. \begin{figure}[tbp]
  5918. \begin{lstlisting}
  5919. (define (typecheck-R5 env)
  5920. (lambda (e)
  5921. (match e
  5922. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5923. (define new-env (append (map cons xs Ts) env))
  5924. (define bodyT ((typecheck-R5 new-env) body))
  5925. (cond [(equal? rT bodyT)
  5926. `(,@Ts -> ,rT)]
  5927. [else
  5928. (error "mismatch in return type" bodyT rT)])]
  5929. ...
  5930. )))
  5931. \end{lstlisting}
  5932. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5933. \label{fig:typecheck-R5}
  5934. \end{figure}
  5935. \section{Closure Conversion}
  5936. The compiling of lexically-scoped functions into top-level function
  5937. definitions is accomplished in the pass \code{convert-to-closures}
  5938. that comes after \code{reveal-functions} and before
  5939. \code{limit-functions}.
  5940. As usual, we shall implement the pass as a recursive function over the
  5941. AST. All of the action is in the clauses for \key{lambda} and
  5942. \key{app}. We transform a \key{lambda} expression into an expression
  5943. that creates a closure, that is, creates a vector whose first element
  5944. is a function pointer and the rest of the elements are the free
  5945. variables of the \key{lambda}. The \itm{name} is a unique symbol
  5946. generated to identify the function.
  5947. \begin{tabular}{lll}
  5948. \begin{minipage}{0.4\textwidth}
  5949. \begin{lstlisting}
  5950. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5951. \end{lstlisting}
  5952. \end{minipage}
  5953. &
  5954. $\Rightarrow$
  5955. &
  5956. \begin{minipage}{0.4\textwidth}
  5957. \begin{lstlisting}
  5958. (vector |\itm{name}| |\itm{fvs}| ...)
  5959. \end{lstlisting}
  5960. \end{minipage}
  5961. \end{tabular} \\
  5962. %
  5963. In addition to transforming each \key{lambda} into a \key{vector}, we
  5964. must create a top-level function definition for each \key{lambda}, as
  5965. shown below.\\
  5966. \begin{minipage}{0.8\textwidth}
  5967. \begin{lstlisting}
  5968. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  5969. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5970. ...
  5971. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5972. |\itm{body'}|)...))
  5973. \end{lstlisting}
  5974. \end{minipage}\\
  5975. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  5976. parameters are the normal parameters of the \key{lambda}. The types
  5977. $\itm{fvts}$ are the types of the free variables in the lambda and the
  5978. underscore is a dummy type because it is rather difficult to give a
  5979. type to the function in the closure's type, and it does not matter.
  5980. The sequence of \key{let} forms bind the free variables to their
  5981. values obtained from the closure.
  5982. We transform function application into code that retreives the
  5983. function pointer from the closure and then calls the function, passing
  5984. in the closure as the first argument. We bind $e'$ to a temporary
  5985. variable to avoid code duplication.
  5986. \begin{tabular}{lll}
  5987. \begin{minipage}{0.3\textwidth}
  5988. \begin{lstlisting}
  5989. (app |$e$| |\itm{es}| ...)
  5990. \end{lstlisting}
  5991. \end{minipage}
  5992. &
  5993. $\Rightarrow$
  5994. &
  5995. \begin{minipage}{0.5\textwidth}
  5996. \begin{lstlisting}
  5997. (let ([|\itm{tmp}| |$e'$|])
  5998. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5999. \end{lstlisting}
  6000. \end{minipage}
  6001. \end{tabular} \\
  6002. There is also the question of what to do with top-level function
  6003. definitions. To maintain a uniform translation of function
  6004. application, we turn function references into closures.
  6005. \begin{tabular}{lll}
  6006. \begin{minipage}{0.3\textwidth}
  6007. \begin{lstlisting}
  6008. (fun-ref |$f$|)
  6009. \end{lstlisting}
  6010. \end{minipage}
  6011. &
  6012. $\Rightarrow$
  6013. &
  6014. \begin{minipage}{0.5\textwidth}
  6015. \begin{lstlisting}
  6016. (vector (fun-ref |$f$|))
  6017. \end{lstlisting}
  6018. \end{minipage}
  6019. \end{tabular} \\
  6020. %
  6021. The top-level function definitions need to be updated as well to take
  6022. an extra closure parameter.
  6023. \section{An Example Translation}
  6024. \label{sec:example-lambda}
  6025. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6026. conversion for the example program demonstrating lexical scoping that
  6027. we discussed at the beginning of this chapter.
  6028. \begin{figure}[h]
  6029. \begin{minipage}{0.8\textwidth}
  6030. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6031. (program
  6032. (define (f [x : Integer]) : (Integer -> Integer)
  6033. (let ([y 4])
  6034. (lambda: ([z : Integer]) : Integer
  6035. (+ x (+ y z)))))
  6036. (let ([g (f 5)])
  6037. (let ([h (f 3)])
  6038. (+ (g 11) (h 15)))))
  6039. \end{lstlisting}
  6040. $\Downarrow$
  6041. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6042. (program (type Integer)
  6043. (define (f (x : Integer)) : (Integer -> Integer)
  6044. (let ((y 4))
  6045. (lambda: ((z : Integer)) : Integer
  6046. (+ x (+ y z)))))
  6047. (let ((g (app (fun-ref f) 5)))
  6048. (let ((h (app (fun-ref f) 3)))
  6049. (+ (app g 11) (app h 15)))))
  6050. \end{lstlisting}
  6051. $\Downarrow$
  6052. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6053. (program (type Integer)
  6054. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6055. (let ((y 4))
  6056. (vector (fun-ref lam.1) x y)))
  6057. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6058. (let ((x (vector-ref clos.2 1)))
  6059. (let ((y (vector-ref clos.2 2)))
  6060. (+ x (+ y z)))))
  6061. (let ((g (let ((t.1 (vector (fun-ref f))))
  6062. (app (vector-ref t.1 0) t.1 5))))
  6063. (let ((h (let ((t.2 (vector (fun-ref f))))
  6064. (app (vector-ref t.2 0) t.2 3))))
  6065. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6066. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6067. \end{lstlisting}
  6068. \end{minipage}
  6069. \caption{Example of closure conversion.}
  6070. \label{fig:lexical-functions-example}
  6071. \end{figure}
  6072. \begin{figure}[p]
  6073. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6074. \node (R4) at (0,2) {\large $R_4$};
  6075. \node (R4-2) at (3,2) {\large $R_4$};
  6076. \node (R4-3) at (6,2) {\large $R_4$};
  6077. \node (F1-1) at (12,0) {\large $F_1$};
  6078. \node (F1-2) at (9,0) {\large $F_1$};
  6079. \node (F1-3) at (6,0) {\large $F_1$};
  6080. \node (F1-4) at (3,0) {\large $F_1$};
  6081. \node (F1-5) at (0,0) {\large $F_1$};
  6082. \node (C3-1) at (6,-2) {\large $C_3$};
  6083. \node (C3-2) at (3,-2) {\large $C_3$};
  6084. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6085. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6086. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6087. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6088. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6089. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6090. \path[->,bend left=15] (R4) edge [above] node
  6091. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6092. \path[->,bend left=15] (R4-2) edge [above] node
  6093. {\ttfamily\footnotesize uniquify} (R4-3);
  6094. \path[->] (R4-3) edge [right] node
  6095. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6096. \path[->,bend left=15] (F1-1) edge [below] node
  6097. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6098. \path[->,bend right=15] (F1-2) edge [above] node
  6099. {\ttfamily\footnotesize limit-functions} (F1-3);
  6100. \path[->,bend right=15] (F1-3) edge [above] node
  6101. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6102. \path[->,bend right=15] (F1-4) edge [above] node
  6103. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6104. \path[->] (F1-5) edge [left] node
  6105. {\ttfamily\footnotesize explicate-control} (C3-1);
  6106. \path[->,bend left=15] (C3-1) edge [below] node
  6107. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6108. \path[->,bend right=15] (C3-2) edge [left] node
  6109. {\ttfamily\footnotesize select-instr.} (x86-2);
  6110. \path[->,bend left=15] (x86-2) edge [left] node
  6111. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6112. \path[->,bend right=15] (x86-2-1) edge [below] node
  6113. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6114. \path[->,bend right=15] (x86-2-2) edge [left] node
  6115. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6116. \path[->,bend left=15] (x86-3) edge [above] node
  6117. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6118. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6119. \end{tikzpicture}
  6120. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6121. functions.}
  6122. \label{fig:R5-passes}
  6123. \end{figure}
  6124. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6125. for the compilation of $R_5$.
  6126. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6127. \chapter{Dynamic Typing}
  6128. \label{ch:type-dynamic}
  6129. In this chapter we discuss the compilation of a dynamically typed
  6130. language, named $R_7$, that is a subset of the Racket
  6131. language. (Recall that in the previous chapters we have studied
  6132. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6133. languages, an expression may produce values of differing
  6134. type. Consider the following example with a conditional expression
  6135. that may return a Boolean or an integer depending on the input to the
  6136. program.
  6137. \begin{lstlisting}
  6138. (not (if (eq? (read) 1) #f 0))
  6139. \end{lstlisting}
  6140. Languages that allow expressions to produce different kinds of values
  6141. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6142. such as subtype polymorphism and parametric
  6143. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6144. talking about here does not have a special name, but it is the usual
  6145. kind that arrises in dynamically typed languages.
  6146. Another characteristic of dynamically typed languages is that
  6147. primitive operations, such as \code{not}, are often defined to operate
  6148. on many different types of values. In fact, in Racket, the \code{not}
  6149. operator produces a result for any kind of value: given \code{\#f} it
  6150. returns \code{\#t} and given anything else it returns \code{\#f}.
  6151. Furthermore, even when primitive operations restrict their inputs to
  6152. values of a certain type, this restriction is enforced at runtime
  6153. instead of during compilation. For example, the following vector
  6154. reference results in a run-time contract violation.
  6155. \begin{lstlisting}
  6156. (vector-ref (vector 42) #t)
  6157. \end{lstlisting}
  6158. \begin{figure}[tp]
  6159. \centering
  6160. \fbox{
  6161. \begin{minipage}{0.97\textwidth}
  6162. \[
  6163. \begin{array}{rcl}
  6164. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6165. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6166. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6167. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6168. &\mid& \key{\#t} \mid \key{\#f}
  6169. \mid (\key{and}\;\Exp\;\Exp)
  6170. \mid (\key{or}\;\Exp\;\Exp)
  6171. \mid (\key{not}\;\Exp) \\
  6172. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6173. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6174. (\key{vector-ref}\;\Exp\;\Exp) \\
  6175. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6176. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6177. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6178. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6179. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6180. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6181. \end{array}
  6182. \]
  6183. \end{minipage}
  6184. }
  6185. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6186. \label{fig:r7-syntax}
  6187. \end{figure}
  6188. The syntax of $R_7$, our subset of Racket, is defined in
  6189. Figure~\ref{fig:r7-syntax}.
  6190. %
  6191. The definitional interpreter for $R_7$ is given in
  6192. Figure~\ref{fig:interp-R7}.
  6193. \begin{figure}[tbp]
  6194. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6195. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6196. (define (valid-op? op) (member op '(+ - and or not)))
  6197. (define (interp-r7 env)
  6198. (lambda (ast)
  6199. (define recur (interp-r7 env))
  6200. (match ast
  6201. [(? symbol?) (lookup ast env)]
  6202. [(? integer?) `(inject ,ast Integer)]
  6203. [#t `(inject #t Boolean)]
  6204. [#f `(inject #f Boolean)]
  6205. [`(read) `(inject ,(read-fixnum) Integer)]
  6206. [`(lambda (,xs ...) ,body)
  6207. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6208. [`(define (,f ,xs ...) ,body)
  6209. (mcons f `(lambda ,xs ,body))]
  6210. [`(program ,ds ... ,body)
  6211. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6212. (for/list ([b top-level])
  6213. (set-mcdr! b (match (mcdr b)
  6214. [`(lambda ,xs ,body)
  6215. `(inject (lambda ,xs ,body ,top-level)
  6216. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6217. ((interp-r7 top-level) body))]
  6218. [`(vector ,(app recur elts) ...)
  6219. (define tys (map get-tagged-type elts))
  6220. `(inject ,(apply vector elts) (Vector ,@tys))]
  6221. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6222. (match v1
  6223. [`(inject ,vec ,ty)
  6224. (vector-set! vec n v2)
  6225. `(inject (void) Void)])]
  6226. [`(vector-ref ,(app recur v) ,n)
  6227. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6228. [`(let ([,x ,(app recur v)]) ,body)
  6229. ((interp-r7 (cons (cons x v) env)) body)]
  6230. [`(,op ,es ...) #:when (valid-op? op)
  6231. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6232. [`(eq? ,(app recur l) ,(app recur r))
  6233. `(inject ,(equal? l r) Boolean)]
  6234. [`(if ,(app recur q) ,t ,f)
  6235. (match q
  6236. [`(inject #f Boolean) (recur f)]
  6237. [else (recur t)])]
  6238. [`(,(app recur f-val) ,(app recur vs) ...)
  6239. (match f-val
  6240. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6241. (define new-env (append (map cons xs vs) lam-env))
  6242. ((interp-r7 new-env) body)]
  6243. [else (error "interp-r7, expected function, not" f-val)])])))
  6244. \end{lstlisting}
  6245. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6246. \label{fig:interp-R7}
  6247. \end{figure}
  6248. Let us consider how we might compile $R_7$ to x86, thinking about the
  6249. first example above. Our bit-level representation of the Boolean
  6250. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6251. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6252. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6253. general, cannot be determined at compile time, but depends on the
  6254. runtime type of its input, as in the example above that depends on the
  6255. result of \code{(read)}.
  6256. The way around this problem is to include information about a value's
  6257. runtime type in the value itself, so that this information can be
  6258. inspected by operators such as \code{not}. In particular, we shall
  6259. steal the 3 right-most bits from our 64-bit values to encode the
  6260. runtime type. We shall use $001$ to identify integers, $100$ for
  6261. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6262. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6263. define the following auxilliary function.
  6264. \begin{align*}
  6265. \itm{tagof}(\key{Integer}) &= 001 \\
  6266. \itm{tagof}(\key{Boolean}) &= 100 \\
  6267. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6268. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6269. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6270. \itm{tagof}(\key{Void}) &= 101
  6271. \end{align*}
  6272. (We shall say more about the new \key{Vectorof} type shortly.)
  6273. This stealing of 3 bits comes at some
  6274. price: our integers are reduced to ranging from $-2^{60}$ to
  6275. $2^{60}$. The stealing does not adversely affect vectors and
  6276. procedures because those values are addresses, and our addresses are
  6277. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6278. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6279. bits with the tag and we can simply zero-out the tag to recover the
  6280. original address.
  6281. In some sense, these tagged values are a new kind of value. Indeed,
  6282. we can extend our \emph{typed} language with tagged values by adding a
  6283. new type to classify them, called \key{Any}, and with operations for
  6284. creating and using tagged values, yielding the $R_6$ language that we
  6285. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6286. fundamental support for polymorphism and runtime types that we need to
  6287. support dynamic typing.
  6288. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6289. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6290. extend our compiler to handle the new features of $R_6$
  6291. (Sections~\ref{sec:shrink-r6} and \ref{sec:select-r6}).
  6292. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6293. \label{sec:r6-lang}
  6294. \begin{figure}[tp]
  6295. \centering
  6296. \fbox{
  6297. \begin{minipage}{0.97\textwidth}
  6298. \[
  6299. \begin{array}{lcl}
  6300. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6301. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6302. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6303. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  6304. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6305. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6306. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6307. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6308. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6309. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6310. \mid (\key{and}\;\Exp\;\Exp)
  6311. \mid (\key{or}\;\Exp\;\Exp)
  6312. \mid (\key{not}\;\Exp)} \\
  6313. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6314. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6315. (\key{vector-ref}\;\Exp\;\Int)} \\
  6316. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6317. &\mid& \gray{(\Exp \; \Exp^{*})
  6318. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6319. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6320. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6321. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6322. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6323. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6324. \end{array}
  6325. \]
  6326. \end{minipage}
  6327. }
  6328. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6329. with \key{Any}.}
  6330. \label{fig:r6-syntax}
  6331. \end{figure}
  6332. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6333. $(\key{inject}\; e\; T)$ form converts the value produced by
  6334. expression $e$ of type $T$ into a tagged value. The
  6335. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6336. expression $e$ into a value of type $T$ or else halts the program if
  6337. the type tag does not match $T$. Note that in both \key{inject} and
  6338. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6339. which simplifies the implementation and corresponds with what is
  6340. needed for compiling untyped Racket. The type predicates,
  6341. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6342. if the tag corresponds to the predicate, and return \key{\#t}
  6343. otherwise.
  6344. %
  6345. Selections from the type checker for $R_6$ are shown in
  6346. Figure~\ref{fig:typecheck-R6} and the definitional interpreter for
  6347. $R_6$ is in Figure~\ref{fig:interp-R6}.
  6348. \begin{figure}[btp]
  6349. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6350. (define (typecheck-R6 env)
  6351. (lambda (e)
  6352. (define recur (typecheck-R6 env))
  6353. (match e
  6354. [`(inject ,e ,ty)
  6355. (define-values (new-e e-ty) (recur e))
  6356. (cond
  6357. [(equal? e-ty ty)
  6358. (values `(inject ,new-e ,ty) 'Any)]
  6359. [else
  6360. (error "inject expected ~a to have type ~a" e ty)])]
  6361. [`(project ,e ,ty)
  6362. (define-values (new-e e-ty) (recur e))
  6363. (cond
  6364. [(equal? e-ty 'Any)
  6365. (values `(project ,new-e ,ty) ty)]
  6366. [else
  6367. (error "project expected ~a to have type Any" e)])]
  6368. [`(vector-ref ,e ,i)
  6369. (define-values (new-e e-ty) (recur e))
  6370. (match e-ty
  6371. [`(Vector ,ts ...) ...]
  6372. [`(Vectorof ,ty)
  6373. (unless (exact-nonnegative-integer? i)
  6374. (error 'type-check "invalid index ~a" i))
  6375. (values `(vector-ref ,new-e ,i) ty)]
  6376. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6377. ...
  6378. )))
  6379. \end{lstlisting}
  6380. \caption{Type checker for parts of the $R_6$ language.}
  6381. \label{fig:typecheck-R6}
  6382. \end{figure}
  6383. % to do: add rules for vector-ref, etc. for Vectorof
  6384. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6385. \begin{figure}[tbp]
  6386. \begin{lstlisting}
  6387. (define primitives (set 'boolean? ...))
  6388. (define (interp-op op)
  6389. (match op
  6390. ['boolean? (lambda (v)
  6391. (match v
  6392. [`(tagged ,v1 Boolean) #t]
  6393. [else #f]))]
  6394. ...))
  6395. (define (interp-R6 env)
  6396. (lambda (ast)
  6397. (match ast
  6398. [`(inject ,e ,t)
  6399. `(tagged ,((interp-R6 env) e) ,t)]
  6400. [`(project ,e ,t2)
  6401. (define v ((interp-R6 env) e))
  6402. (match v
  6403. [`(tagged ,v1 ,t1)
  6404. (cond [(equal? t1 t2)
  6405. v1]
  6406. [else
  6407. (error "in project, type mismatch" t1 t2)])]
  6408. [else
  6409. (error "in project, expected tagged value" v)])]
  6410. ...)))
  6411. \end{lstlisting}
  6412. \caption{Interpreter for $R_6$.}
  6413. \label{fig:interp-R6}
  6414. \end{figure}
  6415. \clearpage
  6416. \section{Shrinking $R_6$}
  6417. \label{sec:shrink-r6}
  6418. In the \code{shrink} pass we recommend compiling \code{project} into
  6419. an explicit \code{if} expression that uses three new operations:
  6420. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6421. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6422. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6423. value from a tagged value. Finally, the \code{exit} operation ends the
  6424. execution of the program by invoking the operating system's
  6425. \code{exit} function. So the translation for \code{project} is as
  6426. follows. (We have ommitted the \code{has-type} AST nodes to make this
  6427. output more readable.)
  6428. \begin{tabular}{lll}
  6429. \begin{minipage}{0.3\textwidth}
  6430. \begin{lstlisting}
  6431. (project |$e$| |$\Type$|)
  6432. \end{lstlisting}
  6433. \end{minipage}
  6434. &
  6435. $\Rightarrow$
  6436. &
  6437. \begin{minipage}{0.5\textwidth}
  6438. \begin{lstlisting}
  6439. (let ([|$\itm{tmp}$| |$e'$|])
  6440. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6441. (value-of-any |$\itm{tmp}$|)
  6442. (exit)))
  6443. \end{lstlisting}
  6444. \end{minipage}
  6445. \end{tabular} \\
  6446. Similarly, we recommend translating the type predicates
  6447. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6448. \section{Instruction Selection for $R_6$}
  6449. \label{sec:select-r6}
  6450. \paragraph{Inject}
  6451. We recommend compiling an \key{inject} as follows if the type is
  6452. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6453. destination to the left by the number of bits specified its source
  6454. argument (in this case $3$, the length of the tag) and it preserves
  6455. the sign of the integer. We use the \key{orq} instruction to combine
  6456. the tag and the value to form the tagged value. \\
  6457. \begin{tabular}{lll}
  6458. \begin{minipage}{0.4\textwidth}
  6459. \begin{lstlisting}
  6460. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6461. \end{lstlisting}
  6462. \end{minipage}
  6463. &
  6464. $\Rightarrow$
  6465. &
  6466. \begin{minipage}{0.5\textwidth}
  6467. \begin{lstlisting}
  6468. (movq |$e'$| |\itm{lhs}'|)
  6469. (salq (int 3) |\itm{lhs}'|)
  6470. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6471. \end{lstlisting}
  6472. \end{minipage}
  6473. \end{tabular} \\
  6474. The instruction selection for vectors and procedures is different
  6475. because their is no need to shift them to the left. The rightmost 3
  6476. bits are already zeros as described above. So we just combine the
  6477. value and the tag using \key{orq}. \\
  6478. \begin{tabular}{lll}
  6479. \begin{minipage}{0.4\textwidth}
  6480. \begin{lstlisting}
  6481. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6482. \end{lstlisting}
  6483. \end{minipage}
  6484. &
  6485. $\Rightarrow$
  6486. &
  6487. \begin{minipage}{0.5\textwidth}
  6488. \begin{lstlisting}
  6489. (movq |$e'$| |\itm{lhs}'|)
  6490. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6491. \end{lstlisting}
  6492. \end{minipage}
  6493. \end{tabular}
  6494. \paragraph{Tag of Any}
  6495. Recall that the \code{tag-of-any} operation extracts the type tag from
  6496. a value of type \code{Any}. The type tag is the bottom three bits, so
  6497. we obtain the tag by taking the bitwise-and of the value with $111$
  6498. ($7$ in decimal).
  6499. \begin{tabular}{lll}
  6500. \begin{minipage}{0.4\textwidth}
  6501. \begin{lstlisting}
  6502. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6503. \end{lstlisting}
  6504. \end{minipage}
  6505. &
  6506. $\Rightarrow$
  6507. &
  6508. \begin{minipage}{0.5\textwidth}
  6509. \begin{lstlisting}
  6510. (movq |$e'$| |\itm{lhs}'|)
  6511. (andq (int 7) |\itm{lhs}'|)
  6512. \end{lstlisting}
  6513. \end{minipage}
  6514. \end{tabular}
  6515. \paragraph{Value of Any}
  6516. Like \key{inject}, the instructions for \key{value-of-any} are
  6517. different depending on whether the type $T$ is a pointer (vector or
  6518. procedure) or not (Integer or Boolean). The following shows the
  6519. instruction selection for Integer and Boolean. We produce an untagged
  6520. value by shifting it to the right by 3 bits.
  6521. %
  6522. \\
  6523. \begin{tabular}{lll}
  6524. \begin{minipage}{0.4\textwidth}
  6525. \begin{lstlisting}
  6526. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6527. \end{lstlisting}
  6528. \end{minipage}
  6529. &
  6530. $\Rightarrow$
  6531. &
  6532. \begin{minipage}{0.5\textwidth}
  6533. \begin{lstlisting}
  6534. (movq |$e'$| |\itm{lhs}'|)
  6535. (sarq (int 3) |\itm{lhs}'|)
  6536. \end{lstlisting}
  6537. \end{minipage}
  6538. \end{tabular} \\
  6539. %
  6540. In the case for vectors and procedures, there is no need to
  6541. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6542. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6543. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6544. \code{movq} into the destination $\itm{lhs}$. We then generate
  6545. \code{andq} with the tagged value to get the desired result. \\
  6546. %
  6547. \begin{tabular}{lll}
  6548. \begin{minipage}{0.4\textwidth}
  6549. \begin{lstlisting}
  6550. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6551. \end{lstlisting}
  6552. \end{minipage}
  6553. &
  6554. $\Rightarrow$
  6555. &
  6556. \begin{minipage}{0.5\textwidth}
  6557. \begin{lstlisting}
  6558. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6559. (andq |$e'$| |\itm{lhs}'|)
  6560. \end{lstlisting}
  6561. \end{minipage}
  6562. \end{tabular}
  6563. %% \paragraph{Type Predicates} We leave it to the reader to
  6564. %% devise a sequence of instructions to implement the type predicates
  6565. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6566. \section{Compiling $R_7$ to $R_6$}
  6567. \label{sec:compile-r7}
  6568. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6569. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6570. given a subexpression $e$ of $R_7$, the pass will produce an
  6571. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6572. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6573. the Boolean \code{\#t}, which must be injected to produce an
  6574. expression of type \key{Any}.
  6575. %
  6576. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6577. addition, is representative of compilation for many operations: the
  6578. arguments have type \key{Any} and must be projected to \key{Integer}
  6579. before the addition can be performed.
  6580. The compilation of \key{lambda} (third row of
  6581. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6582. produce type annotations: we simply use \key{Any}.
  6583. %
  6584. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  6585. has to account for some differences in behavior between $R_7$ and
  6586. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  6587. kind of values can be used in various places. For example, the
  6588. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  6589. the arguments need not be of the same type (but in that case, the
  6590. result will be \code{\#f}).
  6591. \begin{figure}[btp]
  6592. \centering
  6593. \begin{tabular}{|lll|} \hline
  6594. \begin{minipage}{0.25\textwidth}
  6595. \begin{lstlisting}
  6596. #t
  6597. \end{lstlisting}
  6598. \end{minipage}
  6599. &
  6600. $\Rightarrow$
  6601. &
  6602. \begin{minipage}{0.6\textwidth}
  6603. \begin{lstlisting}
  6604. (inject #t Boolean)
  6605. \end{lstlisting}
  6606. \end{minipage}
  6607. \\[2ex]\hline
  6608. \begin{minipage}{0.25\textwidth}
  6609. \begin{lstlisting}
  6610. (+ |$e_1$| |$e_2$|)
  6611. \end{lstlisting}
  6612. \end{minipage}
  6613. &
  6614. $\Rightarrow$
  6615. &
  6616. \begin{minipage}{0.6\textwidth}
  6617. \begin{lstlisting}
  6618. (inject
  6619. (+ (project |$e'_1$| Integer)
  6620. (project |$e'_2$| Integer))
  6621. Integer)
  6622. \end{lstlisting}
  6623. \end{minipage}
  6624. \\[2ex]\hline
  6625. \begin{minipage}{0.25\textwidth}
  6626. \begin{lstlisting}
  6627. (lambda (|$x_1 \ldots$|) |$e$|)
  6628. \end{lstlisting}
  6629. \end{minipage}
  6630. &
  6631. $\Rightarrow$
  6632. &
  6633. \begin{minipage}{0.6\textwidth}
  6634. \begin{lstlisting}
  6635. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  6636. (Any|$\ldots$|Any -> Any))
  6637. \end{lstlisting}
  6638. \end{minipage}
  6639. \\[2ex]\hline
  6640. \begin{minipage}{0.25\textwidth}
  6641. \begin{lstlisting}
  6642. (app |$e_0$| |$e_1 \ldots e_n$|)
  6643. \end{lstlisting}
  6644. \end{minipage}
  6645. &
  6646. $\Rightarrow$
  6647. &
  6648. \begin{minipage}{0.6\textwidth}
  6649. \begin{lstlisting}
  6650. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6651. |$e'_1 \ldots e'_n$|)
  6652. \end{lstlisting}
  6653. \end{minipage}
  6654. \\[2ex]\hline
  6655. \begin{minipage}{0.25\textwidth}
  6656. \begin{lstlisting}
  6657. (vector-ref |$e_1$| |$e_2$|)
  6658. \end{lstlisting}
  6659. \end{minipage}
  6660. &
  6661. $\Rightarrow$
  6662. &
  6663. \begin{minipage}{0.6\textwidth}
  6664. \begin{lstlisting}
  6665. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6666. (let ([tmp2 (project |$e'_2$| Integer)])
  6667. (vector-ref tmp1 tmp2)))
  6668. \end{lstlisting}
  6669. \end{minipage}
  6670. \\[2ex]\hline
  6671. \begin{minipage}{0.25\textwidth}
  6672. \begin{lstlisting}
  6673. (if |$e_1$| |$e_2$| |$e_3$|)
  6674. \end{lstlisting}
  6675. \end{minipage}
  6676. &
  6677. $\Rightarrow$
  6678. &
  6679. \begin{minipage}{0.6\textwidth}
  6680. \begin{lstlisting}
  6681. (if (eq? |$e'_1$| (inject #f Boolean))
  6682. |$e'_3$|
  6683. |$e'_2$|)
  6684. \end{lstlisting}
  6685. \end{minipage}
  6686. \\[2ex]\hline
  6687. \begin{minipage}{0.25\textwidth}
  6688. \begin{lstlisting}
  6689. (eq? |$e_1$| |$e_2$|)
  6690. \end{lstlisting}
  6691. \end{minipage}
  6692. &
  6693. $\Rightarrow$
  6694. &
  6695. \begin{minipage}{0.6\textwidth}
  6696. \begin{lstlisting}
  6697. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6698. \end{lstlisting}
  6699. \end{minipage}
  6700. \\[2ex]\hline
  6701. \end{tabular}
  6702. \caption{Compiling $R_7$ to $R_6$.}
  6703. \label{fig:compile-r7-r6}
  6704. \end{figure}
  6705. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6706. \chapter{Gradual Typing}
  6707. \label{ch:gradual-typing}
  6708. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  6709. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6710. \chapter{Parametric Polymorphism}
  6711. \label{ch:parametric-polymorphism}
  6712. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  6713. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  6714. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6715. \chapter{High-level Optimization}
  6716. \label{ch:high-level-optimization}
  6717. This chapter will present a procedure inlining pass based on the
  6718. algorithm of \citet{Waddell:1997fk}.
  6719. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6720. \chapter{Appendix}
  6721. \section{Interpreters}
  6722. \label{appendix:interp}
  6723. We provide several interpreters in the \key{interp.rkt} file. The
  6724. \key{interp-scheme} function takes an AST in one of the Racket-like
  6725. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  6726. the program, returning the result value. The \key{interp-C} function
  6727. interprets an AST for a program in one of the C-like languages ($C_0,
  6728. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  6729. for an x86 program.
  6730. \section{Utility Functions}
  6731. \label{appendix:utilities}
  6732. The utility function described in this section can be found in the
  6733. \key{utilities.rkt} file.
  6734. The \key{read-program} function takes a file path and parses that file
  6735. (it must be a Racket program) into an abstract syntax tree (as an
  6736. S-expression) with a \key{program} AST at the top.
  6737. The \key{assert} function displays the error message \key{msg} if the
  6738. Boolean \key{bool} is false.
  6739. \begin{lstlisting}
  6740. (define (assert msg bool) ...)
  6741. \end{lstlisting}
  6742. The \key{lookup} function takes a key and an association list (a list
  6743. of key-value pairs), and returns the first value that is associated
  6744. with the given key, if there is one. If not, an error is triggered.
  6745. The association list may contain both immutable pairs (built with
  6746. \key{cons}) and mutable mapirs (built with \key{mcons}).
  6747. The \key{map2} function ...
  6748. %% \subsection{Graphs}
  6749. %% \begin{itemize}
  6750. %% \item The \code{make-graph} function takes a list of vertices
  6751. %% (symbols) and returns a graph.
  6752. %% \item The \code{add-edge} function takes a graph and two vertices and
  6753. %% adds an edge to the graph that connects the two vertices. The graph
  6754. %% is updated in-place. There is no return value for this function.
  6755. %% \item The \code{adjacent} function takes a graph and a vertex and
  6756. %% returns the set of vertices that are adjacent to the given
  6757. %% vertex. The return value is a Racket \code{hash-set} so it can be
  6758. %% used with functions from the \code{racket/set} module.
  6759. %% \item The \code{vertices} function takes a graph and returns the list
  6760. %% of vertices in the graph.
  6761. %% \end{itemize}
  6762. \subsection{Testing}
  6763. The \key{interp-tests} function takes a compiler name (a string), a
  6764. description of the passes, an interpreter for the source language, a
  6765. test family name (a string), and a list of test numbers, and runs the
  6766. compiler passes and the interpreters to check whether the passes
  6767. correct. The description of the passes is a list with one entry per
  6768. pass. An entry is a list with three things: a string giving the name
  6769. of the pass, the function that implements the pass (a translator from
  6770. AST to AST), and a function that implements the interpreter (a
  6771. function from AST to result value) for the language of the output of
  6772. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  6773. good choice. The \key{interp-tests} function assumes that the
  6774. subdirectory \key{tests} has a bunch of Scheme programs whose names
  6775. all start with the family name, followed by an underscore and then the
  6776. test number, ending in \key{.scm}. Also, for each Scheme program there
  6777. is a file with the same number except that it ends with \key{.in} that
  6778. provides the input for the Scheme program.
  6779. \begin{lstlisting}
  6780. (define (interp-tests name passes test-family test-nums) ...
  6781. \end{lstlisting}
  6782. The compiler-tests function takes a compiler name (a string) a
  6783. description of the passes (see the comment for \key{interp-tests}) a
  6784. test family name (a string), and a list of test numbers (see the
  6785. comment for interp-tests), and runs the compiler to generate x86 (a
  6786. \key{.s} file) and then runs gcc to generate machine code. It runs
  6787. the machine code and checks that the output is 42.
  6788. \begin{lstlisting}
  6789. (define (compiler-tests name passes test-family test-nums) ...)
  6790. \end{lstlisting}
  6791. The compile-file function takes a description of the compiler passes
  6792. (see the comment for \key{interp-tests}) and returns a function that,
  6793. given a program file name (a string ending in \key{.scm}), applies all
  6794. of the passes and writes the output to a file whose name is the same
  6795. as the program file name but with \key{.scm} replaced with \key{.s}.
  6796. \begin{lstlisting}
  6797. (define (compile-file passes)
  6798. (lambda (prog-file-name) ...))
  6799. \end{lstlisting}
  6800. \section{x86 Instruction Set Quick-Reference}
  6801. \label{sec:x86-quick-reference}
  6802. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  6803. do. We write $A \to B$ to mean that the value of $A$ is written into
  6804. location $B$. Address offsets are given in bytes. The instruction
  6805. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  6806. registers (such as $\%rax$), or memory references (such as
  6807. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  6808. reference per instruction. Other operands must be immediates or
  6809. registers.
  6810. \begin{table}[tbp]
  6811. \centering
  6812. \begin{tabular}{l|l}
  6813. \textbf{Instruction} & \textbf{Operation} \\ \hline
  6814. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  6815. \texttt{negq} $A$ & $- A \to A$ \\
  6816. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  6817. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  6818. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  6819. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  6820. \texttt{retq} & Pops the return address and jumps to it \\
  6821. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  6822. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  6823. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  6824. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  6825. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  6826. matches the condition code of the instruction, otherwise go to the
  6827. next instructions. The condition codes are \key{e} for ``equal'',
  6828. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6829. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6830. \texttt{jl} $L$ & \\
  6831. \texttt{jle} $L$ & \\
  6832. \texttt{jg} $L$ & \\
  6833. \texttt{jge} $L$ & \\
  6834. \texttt{jmp} $L$ & Jump to label $L$ \\
  6835. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6836. \texttt{movzbq} $A$, $B$ &
  6837. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6838. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6839. and the extra bytes of $B$ are set to zero.} \\
  6840. & \\
  6841. & \\
  6842. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6843. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6844. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6845. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6846. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6847. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6848. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6849. description of the condition codes. $A$ must be a single byte register
  6850. (e.g., \texttt{al} or \texttt{cl}).} \\
  6851. \texttt{setl} $A$ & \\
  6852. \texttt{setle} $A$ & \\
  6853. \texttt{setg} $A$ & \\
  6854. \texttt{setge} $A$ &
  6855. \end{tabular}
  6856. \vspace{5pt}
  6857. \caption{Quick-reference for the x86 instructions used in this book.}
  6858. \label{tab:x86-instr}
  6859. \end{table}
  6860. \bibliographystyle{plainnat}
  6861. \bibliography{all}
  6862. \end{document}
  6863. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6864. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6865. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6866. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6867. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6868. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6869. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6870. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6871. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6872. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6873. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6874. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6875. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6876. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6877. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6878. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6879. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6880. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6881. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6882. %% LocalWords: len prev rootlen heaplen setl lt