book.tex 337 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  76. deletekeywords={read},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~}
  80. }
  81. \newtheorem{theorem}{Theorem}
  82. \newtheorem{lemma}[theorem]{Lemma}
  83. \newtheorem{corollary}[theorem]{Corollary}
  84. \newtheorem{proposition}[theorem]{Proposition}
  85. \newtheorem{constraint}[theorem]{Constraint}
  86. \newtheorem{definition}[theorem]{Definition}
  87. \newtheorem{exercise}[theorem]{Exercise}
  88. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  89. % 'dedication' environment: To add a dedication paragraph at the start of book %
  90. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  91. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  92. \newenvironment{dedication}
  93. {
  94. \cleardoublepage
  95. \thispagestyle{empty}
  96. \vspace*{\stretch{1}}
  97. \hfill\begin{minipage}[t]{0.66\textwidth}
  98. \raggedright
  99. }
  100. {
  101. \end{minipage}
  102. \vspace*{\stretch{3}}
  103. \clearpage
  104. }
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. % Chapter quote at the start of chapter %
  107. % Source: http://tex.stackexchange.com/a/53380 %
  108. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  109. \makeatletter
  110. \renewcommand{\@chapapp}{}% Not necessary...
  111. \newenvironment{chapquote}[2][2em]
  112. {\setlength{\@tempdima}{#1}%
  113. \def\chapquote@author{#2}%
  114. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  115. \itshape}
  116. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  117. \makeatother
  118. \input{defs}
  119. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  120. \title{\Huge \textbf{Essentials of Compilation} \\
  121. \huge An Incremental Approach}
  122. \author{\textsc{Jeremy G. Siek} \\
  123. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  124. Indiana University \\
  125. \\
  126. with contributions from: \\
  127. Carl Factora \\
  128. Andre Kuhlenschmidt \\
  129. Ryan R. Newton \\
  130. Ryan Scott \\
  131. Cameron Swords \\
  132. Michael M. Vitousek \\
  133. Michael Vollmer
  134. }
  135. \begin{document}
  136. \frontmatter
  137. \maketitle
  138. \begin{dedication}
  139. This book is dedicated to the programming language wonks at Indiana
  140. University.
  141. \end{dedication}
  142. \tableofcontents
  143. \listoffigures
  144. %\listoftables
  145. \mainmatter
  146. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  147. \chapter*{Preface}
  148. The tradition of compiler writing at Indiana University goes back to
  149. research and courses about programming languages by Daniel Friedman in
  150. the 1970's and 1980's. Dan conducted research on lazy
  151. evaluation~\citep{Friedman:1976aa} in the context of
  152. Lisp~\citep{McCarthy:1960dz} and then studied
  153. continuations~\citep{Felleisen:kx} and
  154. macros~\citep{Kohlbecker:1986dk} in the context of the
  155. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  156. of those courses, Kent Dybvig, went on to build Chez
  157. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  158. compiler for Scheme. After completing his Ph.D. at the University of
  159. North Carolina, Kent returned to teach at Indiana University.
  160. Throughout the 1990's and 2000's, Kent continued development of Chez
  161. Scheme and taught the compiler course.
  162. The compiler course evolved to incorporate novel pedagogical ideas
  163. while also including elements of effective real-world compilers. One
  164. of Dan's ideas was to split the compiler into many small ``passes'' so
  165. that the code for each pass would be easy to understood in isolation.
  166. (In contrast, most compilers of the time were organized into only a
  167. few monolithic passes for reasons of compile-time efficiency.) Kent,
  168. with later help from his students Dipanwita Sarkar and Andrew Keep,
  169. developed infrastructure to support this approach and evolved the
  170. course, first to use micro-sized passes and then into even smaller
  171. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  172. student in this compiler course in the early 2000's, as part of his
  173. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  174. the course immensely!
  175. During that time, another student named Abdulaziz Ghuloum observed
  176. that the front-to-back organization of the course made it difficult
  177. for students to understand the rationale for the compiler
  178. design. Abdulaziz proposed an incremental approach in which the
  179. students build the compiler in stages; they start by implementing a
  180. complete compiler for a very small subset of the input language and in
  181. each subsequent stage they add a language feature and add or modify
  182. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  183. the students see how the language features motivate aspects of the
  184. compiler design.
  185. After graduating from Indiana University in 2005, Jeremy went on to
  186. teach at the University of Colorado. He adapted the nano pass and
  187. incremental approaches to compiling a subset of the Python
  188. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  189. on the surface but there is a large overlap in the compiler techniques
  190. required for the two languages. Thus, Jeremy was able to teach much of
  191. the same content from the Indiana compiler course. He very much
  192. enjoyed teaching the course organized in this way, and even better,
  193. many of the students learned a lot and got excited about compilers.
  194. Jeremy returned to teach at Indiana University in 2013. In his
  195. absence the compiler course had switched from the front-to-back
  196. organization to a back-to-front organization. Seeing how well the
  197. incremental approach worked at Colorado, he started porting and
  198. adapting the structure of the Colorado course back into the land of
  199. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  200. the course is now about compiling a subset of Racket (and Typed
  201. Racket) to the x86 assembly language. The compiler is implemented in
  202. Racket 7.1~\citep{plt-tr}.
  203. This is the textbook for the incremental version of the compiler
  204. course at Indiana University (Spring 2016 - present) and it is the
  205. first open textbook for an Indiana compiler course. With this book we
  206. hope to make the Indiana compiler course available to people that have
  207. not had the chance to study in Bloomington in person. Many of the
  208. compiler design decisions in this book are drawn from the assignment
  209. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  210. are the most important topics from \cite{Dybvig:2010aa} but we have
  211. omitted topics that we think are less interesting conceptually and we
  212. have made simplifications to reduce complexity. In this way, this
  213. book leans more towards pedagogy than towards the efficiency of the
  214. generated code. Also, the book differs in places where we saw the
  215. opportunity to make the topics more fun, such as in relating register
  216. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  217. \section*{Prerequisites}
  218. The material in this book is challenging but rewarding. It is meant to
  219. prepare students for a lifelong career in programming languages.
  220. The book uses the Racket language both for the implementation of the
  221. compiler and for the language that is compiled, so a student should be
  222. proficient with Racket (or Scheme) prior to reading this book. There
  223. are many excellent resources for learning Scheme and
  224. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  225. is helpful but not necessary for the student to have prior exposure to
  226. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  227. obtain from a computer systems
  228. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  229. parts of x86-64 assembly language that are needed.
  230. %\section*{Structure of book}
  231. % You might want to add short description about each chapter in this book.
  232. %\section*{About the companion website}
  233. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  234. %\begin{itemize}
  235. % \item A link to (freely downlodable) latest version of this document.
  236. % \item Link to download LaTeX source for this document.
  237. % \item Miscellaneous material (e.g. suggested readings etc).
  238. %\end{itemize}
  239. \section*{Acknowledgments}
  240. Many people have contributed to the ideas, techniques, organization,
  241. and teaching of the materials in this book. We especially thank the
  242. following people.
  243. \begin{itemize}
  244. \item Bor-Yuh Evan Chang
  245. \item Kent Dybvig
  246. \item Daniel P. Friedman
  247. \item Ronald Garcia
  248. \item Abdulaziz Ghuloum
  249. \item Jay McCarthy
  250. \item Dipanwita Sarkar
  251. \item Andrew Keep
  252. \item Oscar Waddell
  253. \item Michael Wollowski
  254. \end{itemize}
  255. \mbox{}\\
  256. \noindent Jeremy G. Siek \\
  257. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  258. %\noindent Spring 2016
  259. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  260. \chapter{Preliminaries}
  261. \label{ch:trees-recur}
  262. In this chapter we review the basic tools that are needed to implement
  263. a compiler. Programs are typically input by a programmer as text,
  264. i.e., a sequence of characters. The program-as-text representation is
  265. called \emph{concrete syntax}. We use concrete syntax to concisely
  266. write down and talk about programs. Inside the compiler, we use
  267. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  268. that efficiently supports the operations that the compiler needs to
  269. perform.
  270. \index{concrete syntax}
  271. \index{abstract syntax}
  272. \index{abstract syntax tree}
  273. \index{AST}
  274. \index{program}
  275. \index{parse}
  276. %
  277. The translation from concrete syntax to abstract syntax is a process
  278. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  279. and implementation of parsing in this book. A parser is provided in
  280. the supporting materials for translating from concrete syntax to
  281. abstract syntax for the languages used in this book.
  282. ASTs can be represented in many different ways inside the compiler,
  283. depending on the programming language used to write the compiler.
  284. %
  285. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  286. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  287. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  288. and pattern matching to inspect individual nodes in an AST
  289. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  290. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  291. chapter provides an brief introduction to these ideas.
  292. \index{struct}
  293. \section{Abstract Syntax Trees and Racket Structures}
  294. \label{sec:ast}
  295. Compilers use abstract syntax trees to represent programs because
  296. compilers often need to ask questions like: for a given part of a
  297. program, what kind of language feature is it? What are the sub-parts
  298. of this part of the program? Consider the program on the left and its
  299. AST on the right. This program is an addition and it has two
  300. sub-parts, a read operation and a negation. The negation has another
  301. sub-part, the integer constant \code{8}. By using a tree to represent
  302. the program, we can easily follow the links to go from one part of a
  303. program to its sub-parts.
  304. \begin{center}
  305. \begin{minipage}{0.4\textwidth}
  306. \begin{lstlisting}
  307. (+ (read) (- 8))
  308. \end{lstlisting}
  309. \end{minipage}
  310. \begin{minipage}{0.4\textwidth}
  311. \begin{equation}
  312. \begin{tikzpicture}
  313. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  314. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  315. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  316. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  317. \draw[->] (plus) to (read);
  318. \draw[->] (plus) to (minus);
  319. \draw[->] (minus) to (8);
  320. \end{tikzpicture}
  321. \label{eq:arith-prog}
  322. \end{equation}
  323. \end{minipage}
  324. \end{center}
  325. We use the standard terminology for trees to describe ASTs: each
  326. circle above is called a \emph{node}. The arrows connect a node to its
  327. \emph{children} (which are also nodes). The top-most node is the
  328. \emph{root}. Every node except for the root has a \emph{parent} (the
  329. node it is the child of). If a node has no children, it is a
  330. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  331. \index{node}
  332. \index{children}
  333. \index{root}
  334. \index{parent}
  335. \index{leaf}
  336. \index{internal node}
  337. %% Recall that an \emph{symbolic expression} (S-expression) is either
  338. %% \begin{enumerate}
  339. %% \item an atom, or
  340. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  341. %% where $e_1$ and $e_2$ are each an S-expression.
  342. %% \end{enumerate}
  343. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  344. %% null value \code{'()}, etc. We can create an S-expression in Racket
  345. %% simply by writing a backquote (called a quasi-quote in Racket)
  346. %% followed by the textual representation of the S-expression. It is
  347. %% quite common to use S-expressions to represent a list, such as $a, b
  348. %% ,c$ in the following way:
  349. %% \begin{lstlisting}
  350. %% `(a . (b . (c . ())))
  351. %% \end{lstlisting}
  352. %% Each element of the list is in the first slot of a pair, and the
  353. %% second slot is either the rest of the list or the null value, to mark
  354. %% the end of the list. Such lists are so common that Racket provides
  355. %% special notation for them that removes the need for the periods
  356. %% and so many parenthesis:
  357. %% \begin{lstlisting}
  358. %% `(a b c)
  359. %% \end{lstlisting}
  360. %% The following expression creates an S-expression that represents AST
  361. %% \eqref{eq:arith-prog}.
  362. %% \begin{lstlisting}
  363. %% `(+ (read) (- 8))
  364. %% \end{lstlisting}
  365. %% When using S-expressions to represent ASTs, the convention is to
  366. %% represent each AST node as a list and to put the operation symbol at
  367. %% the front of the list. The rest of the list contains the children. So
  368. %% in the above case, the root AST node has operation \code{`+} and its
  369. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  370. %% diagram \eqref{eq:arith-prog}.
  371. %% To build larger S-expressions one often needs to splice together
  372. %% several smaller S-expressions. Racket provides the comma operator to
  373. %% splice an S-expression into a larger one. For example, instead of
  374. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  375. %% we could have first created an S-expression for AST
  376. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  377. %% S-expression.
  378. %% \begin{lstlisting}
  379. %% (define ast1.4 `(- 8))
  380. %% (define ast1.1 `(+ (read) ,ast1.4))
  381. %% \end{lstlisting}
  382. %% In general, the Racket expression that follows the comma (splice)
  383. %% can be any expression that produces an S-expression.
  384. We define a Racket \code{struct} for each kind of node. For this
  385. chapter we require just two kinds of nodes: one for integer constants
  386. and one for primitive operations. The following is the \code{struct}
  387. definition for integer constants.
  388. \begin{lstlisting}
  389. (struct Int (value))
  390. \end{lstlisting}
  391. An integer node includes just one thing: the integer value.
  392. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  393. \begin{lstlisting}
  394. (define eight (Int 8))
  395. \end{lstlisting}
  396. We say that the value created by \code{(Int 8)} is an
  397. \emph{instance} of the \code{Int} structure.
  398. The following is the \code{struct} definition for primitives operations.
  399. \begin{lstlisting}
  400. (struct Prim (op arg*))
  401. \end{lstlisting}
  402. A primitive operation node includes an operator symbol \code{op}
  403. and a list of children \code{arg*}. For example, to create
  404. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  405. \begin{lstlisting}
  406. (define neg-eight (Prim '- (list eight)))
  407. \end{lstlisting}
  408. Primitive operations may have zero or more children. The \code{read}
  409. operator has zero children:
  410. \begin{lstlisting}
  411. (define rd (Prim 'read '()))
  412. \end{lstlisting}
  413. whereas the addition operator has two children:
  414. \begin{lstlisting}
  415. (define ast1.1 (Prim '+ (list rd neg-eight)))
  416. \end{lstlisting}
  417. We have made a design choice regarding the \code{Prim} structure.
  418. Instead of using one structure for many different operations
  419. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  420. structure for each operation, as follows.
  421. \begin{lstlisting}
  422. (struct Read ())
  423. (struct Add (left right))
  424. (struct Neg (value))
  425. \end{lstlisting}
  426. The reason we choose to use just one structure is that in many parts
  427. of the compiler the code for the different primitive operators is the
  428. same, so we might as well just write that code once, which is enabled
  429. by using a single structure.
  430. When compiling a program such as \eqref{eq:arith-prog}, we need to
  431. know that the operation associated with the root node is addition and
  432. we need to be able to access its two children. Racket provides pattern
  433. matching over structures to support these kinds of queries, as we
  434. shall see in Section~\ref{sec:pattern-matching}.
  435. In this book, we often write down the concrete syntax of a program
  436. even when we really have in mind the AST because the concrete syntax
  437. is more concise. We recommend that, in your mind, you always think of
  438. programs as abstract syntax trees.
  439. \section{Grammars}
  440. \label{sec:grammar}
  441. A programming language can be thought of as a \emph{set} of programs.
  442. The set is typically infinite (one can always create larger and larger
  443. programs), so one cannot simply describe a language by listing all of
  444. the programs in the language. Instead we write down a set of rules, a
  445. \emph{grammar}, for building programs. Grammars are often used to
  446. define the concrete syntax of a language, but they can also be used to
  447. describe the abstract syntax. We shall write our rules in a variant of
  448. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  449. \index{Backus-Naur Form}\index{BNF}
  450. As an example, we describe a small language, named $R_0$, that consists of
  451. integers and arithmetic operations.
  452. \index{grammar}
  453. The first grammar rule for the abstract syntax of $R_0$ says that an
  454. instance of the \code{Int} structure is an expression:
  455. \begin{equation}
  456. \Exp ::= \INT{\Int} \label{eq:arith-int}
  457. \end{equation}
  458. %
  459. Each rule has a left-hand-side and a right-hand-side. The way to read
  460. a rule is that if you have all the program parts on the
  461. right-hand-side, then you can create an AST node and categorize it
  462. according to the left-hand-side.
  463. %
  464. A name such as $\Exp$ that is
  465. defined by the grammar rules is a \emph{non-terminal}.
  466. \index{non-terminal}
  467. %
  468. The name $\Int$ is a also a non-terminal, but instead of defining it
  469. with a grammar rule, we define it with the following explanation. We
  470. make the simplifying design decision that all of the languages in this
  471. book only handle machine-representable integers. On most modern
  472. machines this corresponds to integers represented with 64-bits, i.e.,
  473. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  474. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  475. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  476. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  477. that the sequence of decimals represent an integer in range $-2^{62}$
  478. to $2^{62}-1$.
  479. The second grammar rule is the \texttt{read} operation that receives
  480. an input integer from the user of the program.
  481. \begin{equation}
  482. \Exp ::= \READ{} \label{eq:arith-read}
  483. \end{equation}
  484. The third rule says that, given an $\Exp$ node, you can build another
  485. $\Exp$ node by negating it.
  486. \begin{equation}
  487. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  488. \end{equation}
  489. Symbols in typewriter font such as \key{-} and \key{read} are
  490. \emph{terminal} symbols and must literally appear in the program for
  491. the rule to be applicable.
  492. \index{terminal}
  493. We can apply the rules to build ASTs in the $R_0$
  494. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  495. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  496. an $\Exp$.
  497. \begin{center}
  498. \begin{minipage}{0.4\textwidth}
  499. \begin{lstlisting}
  500. (Prim '- (list (Int 8)))
  501. \end{lstlisting}
  502. \end{minipage}
  503. \begin{minipage}{0.25\textwidth}
  504. \begin{equation}
  505. \begin{tikzpicture}
  506. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  507. \node[draw, circle] (8) at (0, -1.2) {$8$};
  508. \draw[->] (minus) to (8);
  509. \end{tikzpicture}
  510. \label{eq:arith-neg8}
  511. \end{equation}
  512. \end{minipage}
  513. \end{center}
  514. The next grammar rule defines addition expressions:
  515. \begin{equation}
  516. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  517. \end{equation}
  518. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  519. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  520. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  521. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  522. to show that
  523. \begin{lstlisting}
  524. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  525. \end{lstlisting}
  526. is an $\Exp$ in the $R_0$ language.
  527. If you have an AST for which the above rules do not apply, then the
  528. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  529. is not in $R_0$ because there are no rules for \code{+} with only one
  530. argument, nor for \key{-} with two arguments. Whenever we define a
  531. language with a grammar, the language only includes those programs
  532. that are justified by the rules.
  533. The last grammar rule for $R_0$ states that there is a \code{Program}
  534. node to mark the top of the whole program:
  535. \[
  536. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  537. \]
  538. The \code{Program} structure is defined as follows
  539. \begin{lstlisting}
  540. (struct Program (info body))
  541. \end{lstlisting}
  542. where \code{body} is an expression. In later chapters, the \code{info}
  543. part will be used to store auxiliary information but for now it is
  544. just the empty list.
  545. It is common to have many grammar rules with the same left-hand side
  546. but different right-hand sides, such as the rules for $\Exp$ in the
  547. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  548. combine several right-hand-sides into a single rule.
  549. We collect all of the grammar rules for the abstract syntax of $R_0$
  550. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  551. defined in Figure~\ref{fig:r0-concrete-syntax}.
  552. The \code{read-program} function provided in \code{utilities.rkt} of
  553. the support materials reads a program in from a file (the sequence of
  554. characters in the concrete syntax of Racket) and parses it into an
  555. abstract syntax tree. See the description of \code{read-program} in
  556. Appendix~\ref{appendix:utilities} for more details.
  557. \begin{figure}[tp]
  558. \fbox{
  559. \begin{minipage}{0.96\textwidth}
  560. \[
  561. \begin{array}{rcl}
  562. \begin{array}{rcl}
  563. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  564. R_0 &::=& \Exp
  565. \end{array}
  566. \end{array}
  567. \]
  568. \end{minipage}
  569. }
  570. \caption{The concrete syntax of $R_0$.}
  571. \label{fig:r0-concrete-syntax}
  572. \end{figure}
  573. \begin{figure}[tp]
  574. \fbox{
  575. \begin{minipage}{0.96\textwidth}
  576. \[
  577. \begin{array}{rcl}
  578. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  579. &\mid& \ADD{\Exp}{\Exp} \\
  580. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  581. \end{array}
  582. \]
  583. \end{minipage}
  584. }
  585. \caption{The abstract syntax of $R_0$.}
  586. \label{fig:r0-syntax}
  587. \end{figure}
  588. \section{Pattern Matching}
  589. \label{sec:pattern-matching}
  590. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  591. the parts of an AST node. Racket provides the \texttt{match} form to
  592. access the parts of a structure. Consider the following example and
  593. the output on the right. \index{match} \index{pattern matching}
  594. \begin{center}
  595. \begin{minipage}{0.5\textwidth}
  596. \begin{lstlisting}
  597. (match ast1.1
  598. [(Prim op (list child1 child2))
  599. (print op)])
  600. \end{lstlisting}
  601. \end{minipage}
  602. \vrule
  603. \begin{minipage}{0.25\textwidth}
  604. \begin{lstlisting}
  605. '+
  606. \end{lstlisting}
  607. \end{minipage}
  608. \end{center}
  609. In the above example, the \texttt{match} form takes the AST
  610. \eqref{eq:arith-prog} and binds its parts to the three pattern
  611. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  612. general, a match clause consists of a \emph{pattern} and a
  613. \emph{body}.
  614. \index{pattern}
  615. Patterns are recursively defined to be either a pattern
  616. variable, a structure name followed by a pattern for each of the
  617. structure's arguments, or an S-expression (symbols, lists, etc.).
  618. (See Chapter 12 of The Racket
  619. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  620. and Chapter 9 of The Racket
  621. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  622. for a complete description of \code{match}.)
  623. %
  624. The body of a match clause may contain arbitrary Racket code. The
  625. pattern variables can be used in the scope of the body.
  626. A \code{match} form may contain several clauses, as in the following
  627. function \code{leaf?} that recognizes when an $R_0$ node is
  628. a leaf. The \code{match} proceeds through the clauses in order,
  629. checking whether the pattern can match the input AST. The
  630. body of the first clause that matches is executed. The output of
  631. \code{leaf?} for several ASTs is shown on the right.
  632. \begin{center}
  633. \begin{minipage}{0.6\textwidth}
  634. \begin{lstlisting}
  635. (define (leaf? arith)
  636. (match arith
  637. [(Int n) #t]
  638. [(Prim 'read '()) #t]
  639. [(Prim '- (list c1)) #f]
  640. [(Prim '+ (list c1 c2)) #f]))
  641. (leaf? (Prim 'read '()))
  642. (leaf? (Prim '- (list (Int 8))))
  643. (leaf? (Int 8))
  644. \end{lstlisting}
  645. \end{minipage}
  646. \vrule
  647. \begin{minipage}{0.25\textwidth}
  648. \begin{lstlisting}
  649. #t
  650. #f
  651. #t
  652. \end{lstlisting}
  653. \end{minipage}
  654. \end{center}
  655. When writing a \code{match}, we refer to the grammar definition to
  656. identify which non-terminal we are expecting to match against, then we
  657. make sure that 1) we have one clause for each alternative of that
  658. non-terminal and 2) that the pattern in each clause corresponds to the
  659. corresponding right-hand side of a grammar rule. For the \code{match}
  660. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  661. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  662. alternatives, so the \code{match} has 4 clauses. The pattern in each
  663. clause corresponds to the right-hand side of a grammar rule. For
  664. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  665. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  666. patterns, replace non-terminals such as $\Exp$ with pattern variables
  667. of your choice (e.g. \code{c1} and \code{c2}).
  668. \section{Recursion}
  669. \label{sec:recursion}
  670. \index{recursive function}
  671. Programs are inherently recursive. For example, an $R_0$ expression is
  672. often made of smaller expressions. Thus, the natural way to process an
  673. entire program is with a recursive function. As a first example of
  674. such a recursive function, we define \texttt{exp?} below, which takes
  675. an arbitrary value and determines whether or not it is an $R_0$
  676. expression.
  677. %
  678. When a recursive function is defined using a sequence of match clauses
  679. that correspond to a grammar, and the body of each clause makes a
  680. recursive call on each child node, then we say the function is defined
  681. by \emph{structural recursion}\footnote{This principle of structuring
  682. code according to the data definition is advocated in the book
  683. \emph{How to Design Programs}
  684. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  685. define a second function, named \code{R0?}, that determines whether a
  686. value is an $R_0$ program. In general we can expect to write one
  687. recursive function to handle each non-terminal in a grammar.
  688. \index{structural recursion}
  689. %
  690. \begin{center}
  691. \begin{minipage}{0.7\textwidth}
  692. \begin{lstlisting}
  693. (define (exp? ast)
  694. (match ast
  695. [(Int n) #t]
  696. [(Prim 'read '()) #t]
  697. [(Prim '- (list e)) (exp? e)]
  698. [(Prim '+ (list e1 e2))
  699. (and (exp? e1) (exp? e2))]
  700. [else #f]))
  701. (define (R0? ast)
  702. (match ast
  703. [(Program '() e) (exp? e)]
  704. [else #f]))
  705. (R0? (Program '() ast1.1)
  706. (R0? (Program '()
  707. (Prim '- (list (Prim 'read '())
  708. (Prim '+ (list (Num 8)))))))
  709. \end{lstlisting}
  710. \end{minipage}
  711. \vrule
  712. \begin{minipage}{0.25\textwidth}
  713. \begin{lstlisting}
  714. #t
  715. #f
  716. \end{lstlisting}
  717. \end{minipage}
  718. \end{center}
  719. You may be tempted to merge the two functions into one, like this:
  720. \begin{center}
  721. \begin{minipage}{0.5\textwidth}
  722. \begin{lstlisting}
  723. (define (R0? ast)
  724. (match ast
  725. [(Int n) #t]
  726. [(Prim 'read '()) #t]
  727. [(Prim '- (list e)) (R0? e)]
  728. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  729. [(Program '() e) (R0? e)]
  730. [else #f]))
  731. \end{lstlisting}
  732. \end{minipage}
  733. \end{center}
  734. %
  735. Sometimes such a trick will save a few lines of code, especially when
  736. it comes to the \code{Program} wrapper. Yet this style is generally
  737. \emph{not} recommended because it can get you into trouble.
  738. %
  739. For example, the above function is subtly wrong:
  740. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  741. will return true, when it should return false.
  742. %% NOTE FIXME - must check for consistency on this issue throughout.
  743. \section{Interpreters}
  744. \label{sec:interp-R0}
  745. \index{interpreter}
  746. The meaning, or semantics, of a program is typically defined in the
  747. specification of the language. For example, the Scheme language is
  748. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  749. defined in its reference manual~\citep{plt-tr}. In this book we use an
  750. interpreter to define the meaning of each language that we consider,
  751. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  752. interpreter that is designated (by some people) as the definition of a
  753. language is called a \emph{definitional interpreter}.
  754. \index{definitional interpreter}
  755. We warm up by creating a definitional interpreter for the $R_0$ language, which
  756. serves as a second example of structural recursion. The
  757. \texttt{interp-R0} function is defined in
  758. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  759. input program followed by a call to the \lstinline{interp-exp} helper
  760. function, which in turn has one match clause per grammar rule for
  761. $R_0$ expressions.
  762. \begin{figure}[tp]
  763. \begin{lstlisting}
  764. (define (interp-exp e)
  765. (match e
  766. [(Int n) n]
  767. [(Prim 'read '())
  768. (define r (read))
  769. (cond [(fixnum? r) r]
  770. [else (error 'interp-R0 "expected an integer" r)])]
  771. [(Prim '- (list e))
  772. (define v (interp-exp e))
  773. (fx- 0 v)]
  774. [(Prim '+ (list e1 e2))
  775. (define v1 (interp-exp e1))
  776. (define v2 (interp-exp e2))
  777. (fx+ v1 v2)]
  778. ))
  779. (define (interp-R0 p)
  780. (match p
  781. [(Program '() e) (interp-exp e)]
  782. ))
  783. \end{lstlisting}
  784. \caption{Interpreter for the $R_0$ language.}
  785. \label{fig:interp-R0}
  786. \end{figure}
  787. Let us consider the result of interpreting a few $R_0$ programs. The
  788. following program adds two integers.
  789. \begin{lstlisting}
  790. (+ 10 32)
  791. \end{lstlisting}
  792. The result is \key{42}. We wrote the above program in concrete syntax,
  793. whereas the parsed abstract syntax is:
  794. \begin{lstlisting}
  795. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  796. \end{lstlisting}
  797. The next example demonstrates that expressions may be nested within
  798. each other, in this case nesting several additions and negations.
  799. \begin{lstlisting}
  800. (+ 10 (- (+ 12 20)))
  801. \end{lstlisting}
  802. What is the result of the above program?
  803. As mentioned previously, the $R_0$ language does not support
  804. arbitrarily-large integers, but only $63$-bit integers, so we
  805. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  806. in Racket.
  807. Suppose
  808. \[
  809. n = 999999999999999999
  810. \]
  811. which indeed fits in $63$-bits. What happens when we run the
  812. following program in our interpreter?
  813. \begin{lstlisting}
  814. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  815. \end{lstlisting}
  816. It produces an error:
  817. \begin{lstlisting}
  818. fx+: result is not a fixnum
  819. \end{lstlisting}
  820. We establish the convention that if running the definitional
  821. interpreter on a program produces an error, then the meaning of that
  822. program is \emph{unspecified}. That means a compiler for the language
  823. is under no obligations regarding that program; it may or may not
  824. produce an executable, and if it does, that executable can do
  825. anything. This convention applies to the languages defined in this
  826. book, as a way to simplify the student's task of implementing them,
  827. but this convention is not applicable to all programming languages.
  828. \index{unspecified behavior}
  829. Moving on to the last feature of the $R_0$ language, the \key{read}
  830. operation prompts the user of the program for an integer. Recall that
  831. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  832. \code{8}. So if we run
  833. \begin{lstlisting}
  834. (interp-R0 (Program '() ast1.1))
  835. \end{lstlisting}
  836. and if the input is \code{50}, then we get the answer to life, the
  837. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  838. Guide to the Galaxy} by Douglas Adams.}
  839. We include the \key{read} operation in $R_0$ so a clever student
  840. cannot implement a compiler for $R_0$ that simply runs the interpreter
  841. during compilation to obtain the output and then generates the trivial
  842. code to produce the output. (Yes, a clever student did this in the
  843. first instance of this course.)
  844. The job of a compiler is to translate a program in one language into a
  845. program in another language so that the output program behaves the
  846. same way as the input program does according to its definitional
  847. interpreter. This idea is depicted in the following diagram. Suppose
  848. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  849. interpreter for each language. Suppose that the compiler translates
  850. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  851. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  852. respective interpreters with input $i$ should yield the same output
  853. $o$.
  854. \begin{equation} \label{eq:compile-correct}
  855. \begin{tikzpicture}[baseline=(current bounding box.center)]
  856. \node (p1) at (0, 0) {$P_1$};
  857. \node (p2) at (3, 0) {$P_2$};
  858. \node (o) at (3, -2.5) {$o$};
  859. \path[->] (p1) edge [above] node {compile} (p2);
  860. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  861. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  862. \end{tikzpicture}
  863. \end{equation}
  864. In the next section we see our first example of a compiler.
  865. \section{Example Compiler: a Partial Evaluator}
  866. \label{sec:partial-evaluation}
  867. In this section we consider a compiler that translates $R_0$ programs
  868. into $R_0$ programs that may be more efficient, that is, this compiler
  869. is an optimizer. This optimizer eagerly computes the parts of the
  870. program that do not depend on any inputs, a process known as
  871. \emph{partial evaluation}~\cite{Jones:1993uq}.
  872. \index{partial evaluation}
  873. For example, given the following program
  874. \begin{lstlisting}
  875. (+ (read) (- (+ 5 3)))
  876. \end{lstlisting}
  877. our compiler will translate it into the program
  878. \begin{lstlisting}
  879. (+ (read) -8)
  880. \end{lstlisting}
  881. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  882. evaluator for the $R_0$ language. The output of the partial evaluator
  883. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  884. recursion over $\Exp$ is captured in the \code{pe-exp} function
  885. whereas the code for partially evaluating the negation and addition
  886. operations is factored into two separate helper functions:
  887. \code{pe-neg} and \code{pe-add}. The input to these helper
  888. functions is the output of partially evaluating the children.
  889. \begin{figure}[tp]
  890. \begin{lstlisting}
  891. (define (pe-neg r)
  892. (match r
  893. [(Int n) (Int (fx- 0 n))]
  894. [else (Prim '- (list r))]))
  895. (define (pe-add r1 r2)
  896. (match* (r1 r2)
  897. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  898. [(_ _) (Prim '+ (list r1 r2))]))
  899. (define (pe-exp e)
  900. (match e
  901. [(Int n) (Int n)]
  902. [(Prim 'read '()) (Prim 'read '())]
  903. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  904. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  905. ))
  906. (define (pe-R0 p)
  907. (match p
  908. [(Program '() e) (Program '() (pe-exp e))]
  909. ))
  910. \end{lstlisting}
  911. \caption{A partial evaluator for $R_0$ expressions.}
  912. \label{fig:pe-arith}
  913. \end{figure}
  914. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  915. arguments are integers and if they are, perform the appropriate
  916. arithmetic. Otherwise, they create an AST node for the operation
  917. (either negation or addition).
  918. To gain some confidence that the partial evaluator is correct, we can
  919. test whether it produces programs that get the same result as the
  920. input programs. That is, we can test whether it satisfies Diagram
  921. \eqref{eq:compile-correct}. The following code runs the partial
  922. evaluator on several examples and tests the output program. The
  923. \texttt{parse-program} and \texttt{assert} functions are defined in
  924. Appendix~\ref{appendix:utilities}.\\
  925. \begin{minipage}{1.0\textwidth}
  926. \begin{lstlisting}
  927. (define (test-pe p)
  928. (assert "testing pe-R0"
  929. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  930. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  931. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  932. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  933. \end{lstlisting}
  934. \end{minipage}
  935. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  936. \chapter{Integers and Variables}
  937. \label{ch:int-exp}
  938. \index{variable}
  939. \index{integer}
  940. \index{literal}
  941. \index{constant}
  942. This chapter is about compiling the subset of Racket that includes
  943. integer arithmetic and local variable binding, which we name $R_1$, to
  944. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  945. to x86-64 simply as x86. The chapter begins with a description of the
  946. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  947. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  948. discuss only what is needed for compiling $R_1$. We introduce more of
  949. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  950. reflect on their differences and come up with a plan to break down the
  951. translation from $R_1$ to x86 into a handful of steps
  952. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  953. chapter give detailed hints regarding each step
  954. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  955. to give enough hints that the well-prepared reader, together with a
  956. few friends, can implement a compiler from $R_1$ to x86 in a couple
  957. weeks while at the same time leaving room for some fun and creativity.
  958. To give the reader a feeling for the scale of this first compiler, the
  959. instructor solution for the $R_1$ compiler is less than 500 lines of
  960. code.
  961. \section{The $R_1$ Language}
  962. \label{sec:s0}
  963. The $R_1$ language extends the $R_0$ language with variable
  964. definitions. The concrete syntax of the $R_1$ language is defined by
  965. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  966. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  967. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  968. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  969. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  970. \key{Program} struct to mark the top of the program.
  971. %% The $\itm{info}$
  972. %% field of the \key{Program} structure contains an \emph{association
  973. %% list} (a list of key-value pairs) that is used to communicate
  974. %% auxiliary data from one compiler pass the next.
  975. Despite the simplicity of the $R_1$ language, it is rich enough to
  976. exhibit several compilation techniques.
  977. \begin{figure}[tp]
  978. \centering
  979. \fbox{
  980. \begin{minipage}{0.96\textwidth}
  981. \[
  982. \begin{array}{rcl}
  983. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  984. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  985. R_1 &::=& \Exp
  986. \end{array}
  987. \]
  988. \end{minipage}
  989. }
  990. \caption{The concrete syntax of $R_1$.}
  991. \label{fig:r1-concrete-syntax}
  992. \end{figure}
  993. \begin{figure}[tp]
  994. \centering
  995. \fbox{
  996. \begin{minipage}{0.96\textwidth}
  997. \[
  998. \begin{array}{rcl}
  999. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1000. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1001. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1002. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1003. \end{array}
  1004. \]
  1005. \end{minipage}
  1006. }
  1007. \caption{The abstract syntax of $R_1$.}
  1008. \label{fig:r1-syntax}
  1009. \end{figure}
  1010. Let us dive further into the syntax and semantics of the $R_1$
  1011. language. The \key{Let} feature defines a variable for use within its
  1012. body and initializes the variable with the value of an expression.
  1013. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1014. The concrete syntax for \key{Let} is
  1015. \begin{lstlisting}
  1016. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1017. \end{lstlisting}
  1018. For example, the following program initializes \code{x} to $32$ and then
  1019. evaluates the body \code{(+ 10 x)}, producing $42$.
  1020. \begin{lstlisting}
  1021. (let ([x (+ 12 20)]) (+ 10 x))
  1022. \end{lstlisting}
  1023. When there are multiple \key{let}'s for the same variable, the closest
  1024. enclosing \key{let} is used. That is, variable definitions overshadow
  1025. prior definitions. Consider the following program with two \key{let}'s
  1026. that define variables named \code{x}. Can you figure out the result?
  1027. \begin{lstlisting}
  1028. (let ([x 32]) (+ (let ([x 10]) x) x))
  1029. \end{lstlisting}
  1030. For the purposes of depicting which variable uses correspond to which
  1031. definitions, the following shows the \code{x}'s annotated with
  1032. subscripts to distinguish them. Double check that your answer for the
  1033. above is the same as your answer for this annotated version of the
  1034. program.
  1035. \begin{lstlisting}
  1036. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1037. \end{lstlisting}
  1038. The initializing expression is always evaluated before the body of the
  1039. \key{let}, so in the following, the \key{read} for \code{x} is
  1040. performed before the \key{read} for \code{y}. Given the input
  1041. $52$ then $10$, the following produces $42$ (not $-42$).
  1042. \begin{lstlisting}
  1043. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1044. \end{lstlisting}
  1045. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1046. \small
  1047. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1048. An \emph{association list} (alist) is a list of key-value pairs.
  1049. For example, we can map people to their ages with an alist.
  1050. \index{alist}\index{association list}
  1051. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1052. (define ages
  1053. '((jane . 25) (sam . 24) (kate . 45)))
  1054. \end{lstlisting}
  1055. The \emph{dictionary} interface is for mapping keys to values.
  1056. Every alist implements this interface. \index{dictionary} The package
  1057. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1058. provides many functions for working with dictionaries. Here
  1059. are a few of them:
  1060. \begin{description}
  1061. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1062. returns the value associated with the given $\itm{key}$.
  1063. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1064. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1065. but otherwise is the same as $\itm{dict}$.
  1066. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1067. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1068. of keys and values in $\itm{dict}$. For example, the following
  1069. creates a new alist in which the ages are incremented.
  1070. \end{description}
  1071. \vspace{-10pt}
  1072. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1073. (for/list ([(k v) (in-dict ages)])
  1074. (cons k (add1 v)))
  1075. \end{lstlisting}
  1076. \end{tcolorbox}
  1077. \end{wrapfigure}
  1078. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1079. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1080. \key{match} clauses for variables and for \key{let}. For \key{let},
  1081. we need a way to communicate the value of a variable to all the uses
  1082. of a variable. To accomplish this, we maintain a mapping from
  1083. variables to values. Throughout the compiler we often need to map
  1084. variables to information about them. We refer to these mappings as
  1085. \emph{environments}\index{environment}
  1086. \footnote{Another common term for environment in the compiler
  1087. literature is \emph{symbol table}\index{symbol table}.}.
  1088. For simplicity, we use an
  1089. association list (alist) to represent the environment. The sidebar to
  1090. the right gives a brief introduction to alists and the
  1091. \code{racket/dict} package. The \code{interp-R1} function takes the
  1092. current environment, \code{env}, as an extra parameter. When the
  1093. interpreter encounters a variable, it finds the corresponding value
  1094. using the \code{dict-ref} function. When the interpreter encounters a
  1095. \key{Let}, it evaluates the initializing expression, extends the
  1096. environment with the result value bound to the variable, using
  1097. \code{dict-set}, then evaluates the body of the \key{Let}.
  1098. \begin{figure}[tp]
  1099. \begin{lstlisting}
  1100. (define (interp-exp env)
  1101. (lambda (e)
  1102. (match e
  1103. [(Int n) n]
  1104. [(Prim 'read '())
  1105. (define r (read))
  1106. (cond [(fixnum? r) r]
  1107. [else (error 'interp-R1 "expected an integer" r)])]
  1108. [(Prim '- (list e))
  1109. (define v ((interp-exp env) e))
  1110. (fx- 0 v)]
  1111. [(Prim '+ (list e1 e2))
  1112. (define v1 ((interp-exp env) e1))
  1113. (define v2 ((interp-exp env) e2))
  1114. (fx+ v1 v2)]
  1115. [(Var x) (dict-ref env x)]
  1116. [(Let x e body)
  1117. (define new-env (dict-set env x ((interp-exp env) e)))
  1118. ((interp-exp new-env) body)]
  1119. )))
  1120. (define (interp-R1 p)
  1121. (match p
  1122. [(Program '() e) ((interp-exp '()) e)]
  1123. ))
  1124. \end{lstlisting}
  1125. \caption{Interpreter for the $R_1$ language.}
  1126. \label{fig:interp-R1}
  1127. \end{figure}
  1128. The goal for this chapter is to implement a compiler that translates
  1129. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1130. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1131. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1132. is, they both output the same integer $n$. We depict this correctness
  1133. criteria in the following diagram.
  1134. \[
  1135. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1136. \node (p1) at (0, 0) {$P_1$};
  1137. \node (p2) at (4, 0) {$P_2$};
  1138. \node (o) at (4, -2) {$n$};
  1139. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1140. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1141. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1142. \end{tikzpicture}
  1143. \]
  1144. In the next section we introduce enough of the x86 assembly
  1145. language to compile $R_1$.
  1146. \section{The x86$_0$ Assembly Language}
  1147. \label{sec:x86}
  1148. \index{x86}
  1149. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1150. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1151. %
  1152. An x86 program begins with a \code{main} label followed by a sequence
  1153. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1154. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1155. instructions.\index{instruction}
  1156. %
  1157. An x86 program is stored in the computer's memory and the computer has
  1158. a \emph{program counter}\index{program counter} that points to the address of the next
  1159. instruction to be executed. For most instructions, once the
  1160. instruction is executed, the program counter is incremented to point
  1161. to the immediately following instruction in memory. Most x86
  1162. instructions take two operands, where each operand is either an
  1163. integer constant (called \emph{immediate value}\index{immediate value}),
  1164. a \emph{register}\index{register}, or a memory location.
  1165. A register is a special kind of variable. Each
  1166. one holds a 64-bit value; there are 16 registers in the computer and
  1167. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1168. as a mapping of 64-bit addresses to 64-bit values%
  1169. \footnote{This simple story suffices for describing how sequential
  1170. programs access memory but is not sufficient for multi-threaded
  1171. programs. However, multi-threaded execution is beyond the scope of
  1172. this book.}.
  1173. %
  1174. We use the AT\&T syntax expected by the GNU assembler, which comes
  1175. with the \key{gcc} compiler that we use for compiling assembly code to
  1176. machine code.
  1177. %
  1178. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1179. the x86 instructions used in this book.
  1180. % to do: finish treatment of imulq
  1181. % it's needed for vector's in R6/R7
  1182. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1183. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1184. && \key{r8} \mid \key{r9} \mid \key{r10}
  1185. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1186. \mid \key{r14} \mid \key{r15}}
  1187. \begin{figure}[tp]
  1188. \fbox{
  1189. \begin{minipage}{0.96\textwidth}
  1190. \[
  1191. \begin{array}{lcl}
  1192. \Reg &::=& \allregisters{} \\
  1193. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1194. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1195. \key{subq} \; \Arg\key{,} \Arg \mid
  1196. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1197. && \key{callq} \; \mathit{label} \mid
  1198. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1199. && \itm{label}\key{:}\; \Instr \\
  1200. x86_0 &::= & \key{.globl main}\\
  1201. & & \key{main:} \; \Instr\ldots
  1202. \end{array}
  1203. \]
  1204. \end{minipage}
  1205. }
  1206. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1207. \label{fig:x86-0-concrete}
  1208. \end{figure}
  1209. An immediate value is written using the notation \key{\$}$n$ where $n$
  1210. is an integer.
  1211. %
  1212. A register is written with a \key{\%} followed by the register name,
  1213. such as \key{\%rax}.
  1214. %
  1215. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1216. which obtains the address stored in register $r$ and then adds $n$
  1217. bytes to the address. The resulting address is used to either load or
  1218. store to memory depending on whether it occurs as a source or
  1219. destination argument of an instruction.
  1220. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1221. source $s$ and destination $d$, applies the arithmetic operation, then
  1222. writes the result back to the destination $d$.
  1223. %
  1224. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1225. stores the result in $d$.
  1226. %
  1227. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1228. specified by the label and $\key{retq}$ returns from a procedure to
  1229. its caller. We discuss procedure calls in more detail later in this
  1230. chapter and in Chapter~\ref{ch:functions}. The
  1231. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1232. the address of the instruction after the specified label.
  1233. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1234. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1235. \key{main} procedure is externally visible, which is necessary so
  1236. that the operating system can call it. The label \key{main:}
  1237. indicates the beginning of the \key{main} procedure which is where
  1238. the operating system starts executing this program. The instruction
  1239. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1240. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1241. $10$ in \key{rax} and puts the result, $42$, back into
  1242. \key{rax}.
  1243. %
  1244. The last instruction, \key{retq}, finishes the \key{main} function by
  1245. returning the integer in \key{rax} to the operating system. The
  1246. operating system interprets this integer as the program's exit
  1247. code. By convention, an exit code of 0 indicates that a program
  1248. completed successfully, and all other exit codes indicate various
  1249. errors. Nevertheless, we return the result of the program as the exit
  1250. code.
  1251. %\begin{wrapfigure}{r}{2.25in}
  1252. \begin{figure}[tbp]
  1253. \begin{lstlisting}
  1254. .globl main
  1255. main:
  1256. movq $10, %rax
  1257. addq $32, %rax
  1258. retq
  1259. \end{lstlisting}
  1260. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1261. \label{fig:p0-x86}
  1262. %\end{wrapfigure}
  1263. \end{figure}
  1264. Unfortunately, x86 varies in a couple ways depending on what operating
  1265. system it is assembled in. The code examples shown here are correct on
  1266. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1267. labels like \key{main} must be prefixed with an underscore, as in
  1268. \key{\_main}.
  1269. We exhibit the use of memory for storing intermediate results in the
  1270. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1271. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1272. memory called the \emph{procedure call stack} (or \emph{stack} for
  1273. short). \index{stack}\index{procedure call stack} The stack consists
  1274. of a separate \emph{frame} for each procedure call.\index{frame} The
  1275. memory layout for an individual frame is shown in
  1276. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1277. \emph{stack pointer}\index{stack pointer} and points to the item at
  1278. the top of the stack. The stack grows downward in memory, so we
  1279. increase the size of the stack by subtracting from the stack pointer.
  1280. In the context of a procedure call, the \emph{return
  1281. address}\index{return address} is the next instruction after the
  1282. call instruction on the caller side. During a function call, the
  1283. return address is pushed onto the stack. The register \key{rbp} is
  1284. the \emph{base pointer}\index{base pointer} and is used to access
  1285. variables associated with the current procedure call. The base
  1286. pointer of the caller is pushed onto the stack after the return
  1287. address. We number the variables from $1$ to $n$. Variable $1$ is
  1288. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1289. $-16\key{(\%rbp)}$, etc.
  1290. \begin{figure}[tbp]
  1291. \begin{lstlisting}
  1292. start:
  1293. movq $10, -8(%rbp)
  1294. negq -8(%rbp)
  1295. movq -8(%rbp), %rax
  1296. addq $52, %rax
  1297. jmp conclusion
  1298. .globl main
  1299. main:
  1300. pushq %rbp
  1301. movq %rsp, %rbp
  1302. subq $16, %rsp
  1303. jmp start
  1304. conclusion:
  1305. addq $16, %rsp
  1306. popq %rbp
  1307. retq
  1308. \end{lstlisting}
  1309. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1310. \label{fig:p1-x86}
  1311. \end{figure}
  1312. \begin{figure}[tbp]
  1313. \centering
  1314. \begin{tabular}{|r|l|} \hline
  1315. Position & Contents \\ \hline
  1316. 8(\key{\%rbp}) & return address \\
  1317. 0(\key{\%rbp}) & old \key{rbp} \\
  1318. -8(\key{\%rbp}) & variable $1$ \\
  1319. -16(\key{\%rbp}) & variable $2$ \\
  1320. \ldots & \ldots \\
  1321. 0(\key{\%rsp}) & variable $n$\\ \hline
  1322. \end{tabular}
  1323. \caption{Memory layout of a frame.}
  1324. \label{fig:frame}
  1325. \end{figure}
  1326. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1327. control is transfered from the operating system to the \code{main}
  1328. function. The operating system issues a \code{callq main} instruction
  1329. which pushes its return address on the stack and then jumps to
  1330. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1331. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1332. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1333. alignment (because the \code{callq} pushed the return address). The
  1334. first three instructions are the typical \emph{prelude}\index{prelude}
  1335. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1336. pointer for the caller onto the stack and subtracts $8$ from the stack
  1337. pointer. At this point the stack pointer is back to being 16-byte
  1338. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1339. base pointer so that it points the location of the old base
  1340. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1341. pointer down to make enough room for storing variables. This program
  1342. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1343. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1344. we are ready to make calls to other functions. The last instruction of
  1345. the prelude is \code{jmp start}, which transfers control to the
  1346. instructions that were generated from the Racket expression \code{(+
  1347. 10 32)}.
  1348. The four instructions under the label \code{start} carry out the work
  1349. of computing \code{(+ 52 (- 10)))}. The first instruction
  1350. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1351. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1352. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1353. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1354. \code{rax}, at which point \code{rax} contains $42$.
  1355. The three instructions under the label \code{conclusion} are the
  1356. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1357. two instructions are necessary to get the state of the machine back to
  1358. where it was at the beginning of the procedure. The instruction
  1359. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1360. old base pointer. The amount added here needs to match the amount that
  1361. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1362. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1363. pointer. The last instruction, \key{retq}, jumps back to the
  1364. procedure that called this one and adds 8 to the stack pointer, which
  1365. returns the stack pointer to where it was prior to the procedure call.
  1366. The compiler needs a convenient representation for manipulating x86
  1367. programs, so we define an abstract syntax for x86 in
  1368. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1369. a subscript $0$ because later we introduce extended versions of this
  1370. assembly language. The main difference compared to the concrete syntax
  1371. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1372. labeled instructions to appear anywhere, but instead organizes
  1373. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1374. and associates a label with every block, which is why the \key{CFG} struct
  1375. (for control-flow graph) includes an alist mapping labels to
  1376. blocks. The reason for this organization becomes apparent in
  1377. Chapter~\ref{ch:bool-types} when we introduce conditional
  1378. branching. The \code{Block} structure includes an $\itm{info}$ field
  1379. that is not needed for this chapter, but will become useful in
  1380. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1381. field should just contain an empty list.
  1382. \begin{figure}[tp]
  1383. \fbox{
  1384. \begin{minipage}{0.96\textwidth}
  1385. \small
  1386. \[
  1387. \begin{array}{lcl}
  1388. \Reg &::=& \allregisters{} \\
  1389. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1390. \mid \DEREF{\Reg}{\Int} \\
  1391. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1392. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1393. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1394. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1395. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1396. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1397. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1398. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1399. \end{array}
  1400. \]
  1401. \end{minipage}
  1402. }
  1403. \caption{The abstract syntax of x86$_0$ assembly.}
  1404. \label{fig:x86-0-ast}
  1405. \end{figure}
  1406. \section{Planning the trip to x86 via the $C_0$ language}
  1407. \label{sec:plan-s0-x86}
  1408. To compile one language to another it helps to focus on the
  1409. differences between the two languages because the compiler will need
  1410. to bridge those differences. What are the differences between $R_1$
  1411. and x86 assembly? Here are some of the most important ones:
  1412. \begin{enumerate}
  1413. \item[(a)] x86 arithmetic instructions typically have two arguments
  1414. and update the second argument in place. In contrast, $R_1$
  1415. arithmetic operations take two arguments and produce a new value.
  1416. An x86 instruction may have at most one memory-accessing argument.
  1417. Furthermore, some instructions place special restrictions on their
  1418. arguments.
  1419. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1420. whereas x86 instructions restrict their arguments to be integers
  1421. constants, registers, and memory locations.
  1422. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1423. sequence of instructions and jumps to labeled positions, whereas in
  1424. $R_1$ the order of evaluation is a left-to-right depth-first
  1425. traversal of the abstract syntax tree.
  1426. \item[(d)] An $R_1$ program can have any number of variables whereas
  1427. x86 has 16 registers and the procedure calls stack.
  1428. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1429. same name. The registers and memory locations of x86 all have unique
  1430. names or addresses.
  1431. \end{enumerate}
  1432. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1433. the problem into several steps, dealing with the above differences one
  1434. at a time. Each of these steps is called a \emph{pass} of the
  1435. compiler.\index{pass}\index{compiler pass}
  1436. %
  1437. This terminology comes from each step traverses (i.e. passes over) the
  1438. AST of the program.
  1439. %
  1440. We begin by sketching how we might implement each pass, and give them
  1441. names. We then figure out an ordering of the passes and the
  1442. input/output language for each pass. The very first pass has $R_1$ as
  1443. its input language and the last pass has x86 as its output
  1444. language. In between we can choose whichever language is most
  1445. convenient for expressing the output of each pass, whether that be
  1446. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1447. Finally, to implement each pass we write one recursive function per
  1448. non-terminal in the grammar of the input language of the pass.
  1449. \index{intermediate language}
  1450. \begin{description}
  1451. \item[Pass \key{select-instructions}] To handle the difference between
  1452. $R_1$ operations and x86 instructions we convert each $R_1$
  1453. operation to a short sequence of instructions that accomplishes the
  1454. same task.
  1455. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1456. subexpression (i.e. operator and operand, and hence the name
  1457. \key{opera*}) is an \emph{atomic} expression (a variable or
  1458. integer), we introduce temporary variables to hold the results
  1459. of subexpressions.\index{atomic expression}
  1460. \item[Pass \key{explicate-control}] To make the execution order of the
  1461. program explicit, we convert from the abstract syntax tree
  1462. representation into a control-flow graph in which each node
  1463. contains a sequence of statements and the edges between nodes say
  1464. where to go at the end of the sequence.
  1465. \item[Pass \key{assign-homes}] To handle the difference between the
  1466. variables in $R_1$ versus the registers and stack locations in x86,
  1467. we map each variable to a register or stack location.
  1468. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1469. by renaming every variable to a unique name, so that shadowing no
  1470. longer occurs.
  1471. \end{description}
  1472. The next question is: in what order should we apply these passes? This
  1473. question can be challenging because it is difficult to know ahead of
  1474. time which orders will be better (easier to implement, produce more
  1475. efficient code, etc.) so oftentimes trial-and-error is
  1476. involved. Nevertheless, we can try to plan ahead and make educated
  1477. choices regarding the ordering.
  1478. Let us consider the ordering of \key{uniquify} and
  1479. \key{remove-complex-opera*}. The assignment of subexpressions to
  1480. temporary variables involves introducing new variables and moving
  1481. subexpressions, which might change the shadowing of variables and
  1482. inadvertently change the behavior of the program. But if we apply
  1483. \key{uniquify} first, this will not be an issue. Of course, this means
  1484. that in \key{remove-complex-opera*}, we need to ensure that the
  1485. temporary variables that it creates are unique.
  1486. What should be the ordering of \key{explicate-control} with respect to
  1487. \key{uniquify}? The \key{uniquify} pass should come first because
  1488. \key{explicate-control} changes all the \key{let}-bound variables to
  1489. become local variables whose scope is the entire program, which would
  1490. confuse variables with the same name.
  1491. %
  1492. Likewise, we place \key{explicate-control} after
  1493. \key{remove-complex-opera*} because \key{explicate-control} removes
  1494. the \key{let} form, but it is convenient to use \key{let} in the
  1495. output of \key{remove-complex-opera*}.
  1496. %
  1497. Regarding \key{assign-homes}, it is helpful to place
  1498. \key{explicate-control} first because \key{explicate-control} changes
  1499. \key{let}-bound variables into program-scope variables. This means
  1500. that the \key{assign-homes} pass can read off the variables from the
  1501. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1502. entire program in search of \key{let}-bound variables.
  1503. Last, we need to decide on the ordering of \key{select-instructions}
  1504. and \key{assign-homes}. These two passes are intertwined, creating a
  1505. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1506. have already determined which instructions will be used, because x86
  1507. instructions have restrictions about which of their arguments can be
  1508. registers versus stack locations. One might want to give preferential
  1509. treatment to variables that occur in register-argument positions. On
  1510. the other hand, it may turn out to be impossible to make sure that all
  1511. such variables are assigned to registers, and then one must redo the
  1512. selection of instructions. Some compilers handle this problem by
  1513. iteratively repeating these two passes until a good solution is found.
  1514. We shall use a simpler approach in which \key{select-instructions}
  1515. comes first, followed by the \key{assign-homes}, then a third
  1516. pass named \key{patch-instructions} that uses a reserved register to
  1517. patch-up outstanding problems regarding instructions with too many
  1518. memory accesses. The disadvantage of this approach is some programs
  1519. may not execute as efficiently as they would if we used the iterative
  1520. approach and used all of the registers for variables.
  1521. \begin{figure}[tbp]
  1522. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1523. \node (R1) at (0,2) {\large $R_1$};
  1524. \node (R1-2) at (3,2) {\large $R_1$};
  1525. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1526. %\node (C0-1) at (6,0) {\large $C_0$};
  1527. \node (C0-2) at (3,0) {\large $C_0$};
  1528. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1529. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1530. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1531. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1532. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1533. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1534. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1535. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1536. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1537. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1538. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1539. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1540. \end{tikzpicture}
  1541. \caption{Overview of the passes for compiling $R_1$. }
  1542. \label{fig:R1-passes}
  1543. \end{figure}
  1544. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1545. passes in the form of a graph. Each pass is an edge and the
  1546. input/output language of each pass is a node in the graph. The output
  1547. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1548. are still in the $R_1$ language, but the output of the pass
  1549. \key{explicate-control} is in a different language $C_0$ that is
  1550. designed to make the order of evaluation explicit in its syntax, which
  1551. we introduce in the next section. The \key{select-instruction} pass
  1552. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1553. \key{patch-instructions} passes input and output variants of x86
  1554. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1555. \key{print-x86}, which converts from the abstract syntax of
  1556. $\text{x86}_0$ to the concrete syntax of x86.
  1557. In the next sections we discuss the $C_0$ language and the
  1558. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1559. remainder of this chapter gives hints regarding the implementation of
  1560. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1561. \subsection{The $C_0$ Intermediate Language}
  1562. The output of \key{explicate-control} is similar to the $C$
  1563. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1564. categories for expressions and statements, so we name it $C_0$. The
  1565. concrete syntax for $C_0$ is defined in
  1566. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1567. is defined in Figure~\ref{fig:c0-syntax}.
  1568. %
  1569. The $C_0$ language supports the same operators as $R_1$ but the
  1570. arguments of operators are restricted to atomic expressions (variables
  1571. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1572. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1573. executed in sequence using the \key{Seq} form. A sequence of
  1574. statements always ends with \key{Return}, a guarantee that is baked
  1575. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1576. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1577. which refers to an expression that is the last one to execute within a
  1578. function. (A expression in tail position may contain subexpressions,
  1579. and those may or may not be in tail position depending on the kind of
  1580. expression.)
  1581. A $C_0$ program consists of a control-flow graph (represented as an
  1582. alist mapping labels to tails). This is more general than
  1583. necessary for the present chapter, as we do not yet need to introduce
  1584. \key{goto} for jumping to labels, but it saves us from having to
  1585. change the syntax of the program construct in
  1586. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1587. \key{start}, and the whole program is its tail.
  1588. %
  1589. The $\itm{info}$ field of the \key{Program} form, after the
  1590. \key{explicate-control} pass, contains a mapping from the symbol
  1591. \key{locals} to a list of variables, that is, a list of all the
  1592. variables used in the program. At the start of the program, these
  1593. variables are uninitialized; they become initialized on their first
  1594. assignment.
  1595. \begin{figure}[tbp]
  1596. \fbox{
  1597. \begin{minipage}{0.96\textwidth}
  1598. \[
  1599. \begin{array}{lcl}
  1600. \Atm &::=& \Int \mid \Var \\
  1601. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1602. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1603. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1604. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1605. \end{array}
  1606. \]
  1607. \end{minipage}
  1608. }
  1609. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1610. \label{fig:c0-concrete-syntax}
  1611. \end{figure}
  1612. \begin{figure}[tbp]
  1613. \fbox{
  1614. \begin{minipage}{0.96\textwidth}
  1615. \[
  1616. \begin{array}{lcl}
  1617. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1618. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1619. &\mid& \ADD{\Atm}{\Atm}\\
  1620. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1621. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1622. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1623. \end{array}
  1624. \]
  1625. \end{minipage}
  1626. }
  1627. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1628. \label{fig:c0-syntax}
  1629. \end{figure}
  1630. %% The \key{select-instructions} pass is optimistic in the sense that it
  1631. %% treats variables as if they were all mapped to registers. The
  1632. %% \key{select-instructions} pass generates a program that consists of
  1633. %% x86 instructions but that still uses variables, so it is an
  1634. %% intermediate language that is technically different than x86, which
  1635. %% explains the asterisks in the diagram above.
  1636. %% In this Chapter we shall take the easy road to implementing
  1637. %% \key{assign-homes} and simply map all variables to stack locations.
  1638. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1639. %% smarter approach in which we make a best-effort to map variables to
  1640. %% registers, resorting to the stack only when necessary.
  1641. %% Once variables have been assigned to their homes, we can finalize the
  1642. %% instruction selection by dealing with an idiosyncrasy of x86
  1643. %% assembly. Many x86 instructions have two arguments but only one of the
  1644. %% arguments may be a memory reference (and the stack is a part of
  1645. %% memory). Because some variables may get mapped to stack locations,
  1646. %% some of our generated instructions may violate this restriction. The
  1647. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1648. %% replacing every violating instruction with a short sequence of
  1649. %% instructions that use the \key{rax} register. Once we have implemented
  1650. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1651. %% need to patch instructions will be relatively rare.
  1652. \subsection{The dialects of x86}
  1653. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1654. the pass \key{select-instructions}. It extends x86$_0$ with an
  1655. unbounded number of program-scope variables and has looser rules
  1656. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1657. output of \key{print-x86}, is the concrete syntax for x86.
  1658. \section{Uniquify Variables}
  1659. \label{sec:uniquify-s0}
  1660. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1661. programs in which every \key{let} uses a unique variable name. For
  1662. example, the \code{uniquify} pass should translate the program on the
  1663. left into the program on the right. \\
  1664. \begin{tabular}{lll}
  1665. \begin{minipage}{0.4\textwidth}
  1666. \begin{lstlisting}
  1667. (let ([x 32])
  1668. (+ (let ([x 10]) x) x))
  1669. \end{lstlisting}
  1670. \end{minipage}
  1671. &
  1672. $\Rightarrow$
  1673. &
  1674. \begin{minipage}{0.4\textwidth}
  1675. \begin{lstlisting}
  1676. (let ([x.1 32])
  1677. (+ (let ([x.2 10]) x.2) x.1))
  1678. \end{lstlisting}
  1679. \end{minipage}
  1680. \end{tabular} \\
  1681. %
  1682. The following is another example translation, this time of a program
  1683. with a \key{let} nested inside the initializing expression of another
  1684. \key{let}.\\
  1685. \begin{tabular}{lll}
  1686. \begin{minipage}{0.4\textwidth}
  1687. \begin{lstlisting}
  1688. (let ([x (let ([x 4])
  1689. (+ x 1))])
  1690. (+ x 2))
  1691. \end{lstlisting}
  1692. \end{minipage}
  1693. &
  1694. $\Rightarrow$
  1695. &
  1696. \begin{minipage}{0.4\textwidth}
  1697. \begin{lstlisting}
  1698. (let ([x.2 (let ([x.1 4])
  1699. (+ x.1 1))])
  1700. (+ x.2 2))
  1701. \end{lstlisting}
  1702. \end{minipage}
  1703. \end{tabular}
  1704. We recommend implementing \code{uniquify} by creating a function named
  1705. \code{uniquify-exp} that is structurally recursive function and mostly
  1706. just copies the input program. However, when encountering a \key{let},
  1707. it should generate a unique name for the variable (the Racket function
  1708. \code{gensym} is handy for this) and associate the old name with the
  1709. new unique name in an alist. The \code{uniquify-exp}
  1710. function will need to access this alist when it gets to a
  1711. variable reference, so we add another parameter to \code{uniquify-exp}
  1712. for the alist.
  1713. The skeleton of the \code{uniquify-exp} function is shown in
  1714. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1715. convenient to partially apply it to a symbol table and then apply it
  1716. to different expressions, as in the last clause for primitive
  1717. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1718. form is useful for applying a function to each element of a list to produce
  1719. a new list.
  1720. \index{for/list}
  1721. \begin{exercise}
  1722. \normalfont % I don't like the italics for exercises. -Jeremy
  1723. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1724. implement the clauses for variables and for the \key{let} form.
  1725. \end{exercise}
  1726. \begin{figure}[tbp]
  1727. \begin{lstlisting}
  1728. (define (uniquify-exp symtab)
  1729. (lambda (e)
  1730. (match e
  1731. [(Var x) ___]
  1732. [(Int n) (Int n)]
  1733. [(Let x e body) ___]
  1734. [(Prim op es)
  1735. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1736. )))
  1737. (define (uniquify p)
  1738. (match p
  1739. [(Program '() e)
  1740. (Program '() ((uniquify-exp '()) e))]
  1741. )))
  1742. \end{lstlisting}
  1743. \caption{Skeleton for the \key{uniquify} pass.}
  1744. \label{fig:uniquify-s0}
  1745. \end{figure}
  1746. \begin{exercise}
  1747. \normalfont % I don't like the italics for exercises. -Jeremy
  1748. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1749. and checking whether the output programs produce the same result as
  1750. the input programs. The $R_1$ programs should be designed to test the
  1751. most interesting parts of the \key{uniquify} pass, that is, the
  1752. programs should include \key{let} forms, variables, and variables
  1753. that overshadow each other. The five programs should be in a
  1754. subdirectory named \key{tests} and they should have the same file name
  1755. except for a different integer at the end of the name, followed by the
  1756. ending \key{.rkt}. Use the \key{interp-tests} function
  1757. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1758. your \key{uniquify} pass on the example programs. See the
  1759. \key{run-tests.rkt} script in the student support code for an example
  1760. of how to use \key{interp-tests}.
  1761. \end{exercise}
  1762. \section{Remove Complex Operands}
  1763. \label{sec:remove-complex-opera-R1}
  1764. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1765. $R_1$ programs in which the arguments of operations are atomic
  1766. expressions. Put another way, this pass removes complex
  1767. operands\index{complex operand}, such as the expression \code{(- 10)}
  1768. in the program below. This is accomplished by introducing a new
  1769. \key{let}-bound variable, binding the complex operand to the new
  1770. variable, and then using the new variable in place of the complex
  1771. operand, as shown in the output of \code{remove-complex-opera*} on the
  1772. right.\\
  1773. \begin{tabular}{lll}
  1774. \begin{minipage}{0.4\textwidth}
  1775. % s0_19.rkt
  1776. \begin{lstlisting}
  1777. (+ 52 (- 10))
  1778. \end{lstlisting}
  1779. \end{minipage}
  1780. &
  1781. $\Rightarrow$
  1782. &
  1783. \begin{minipage}{0.4\textwidth}
  1784. \begin{lstlisting}
  1785. (let ([tmp.1 (- 10)])
  1786. (+ 52 tmp.1))
  1787. \end{lstlisting}
  1788. \end{minipage}
  1789. \end{tabular}
  1790. \begin{figure}[tp]
  1791. \centering
  1792. \fbox{
  1793. \begin{minipage}{0.96\textwidth}
  1794. \[
  1795. \begin{array}{rcl}
  1796. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1797. \Exp &::=& \Atm \mid \READ{} \\
  1798. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1799. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1800. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1801. \end{array}
  1802. \]
  1803. \end{minipage}
  1804. }
  1805. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1806. \label{fig:r1-anf-syntax}
  1807. \end{figure}
  1808. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1809. this pass, language $R_1^{\dagger}$. The main difference is that
  1810. operator arguments are required to be atomic expressions. In the
  1811. literature this is called \emph{administrative normal form}, or ANF
  1812. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1813. \index{administrative normal form}
  1814. \index{ANF}
  1815. We recommend implementing this pass with two mutually recursive
  1816. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1817. \code{rco-atom} to subexpressions that are required to be atomic and
  1818. to apply \code{rco-exp} to subexpressions that can be atomic or
  1819. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1820. $R_1$ expression as input. The \code{rco-exp} function returns an
  1821. expression. The \code{rco-atom} function returns two things: an
  1822. atomic expression and alist mapping temporary variables to complex
  1823. subexpressions. You can return multiple things from a function using
  1824. Racket's \key{values} form and you can receive multiple things from a
  1825. function call using the \key{define-values} form. If you are not
  1826. familiar with these features, review the Racket documentation. Also,
  1827. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1828. form is useful for applying a function to each
  1829. element of a list, in the case where the function returns multiple
  1830. values.
  1831. \index{for/lists}
  1832. The following shows the output of \code{rco-atom} on the expression
  1833. \code{(- 10)} (using concrete syntax to be concise).
  1834. \begin{tabular}{lll}
  1835. \begin{minipage}{0.4\textwidth}
  1836. \begin{lstlisting}
  1837. (- 10)
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. &
  1841. $\Rightarrow$
  1842. &
  1843. \begin{minipage}{0.4\textwidth}
  1844. \begin{lstlisting}
  1845. tmp.1
  1846. ((tmp.1 . (- 10)))
  1847. \end{lstlisting}
  1848. \end{minipage}
  1849. \end{tabular}
  1850. Take special care of programs such as the next one that \key{let}-bind
  1851. variables with integers or other variables. You should leave them
  1852. unchanged, as shown in to the program on the right \\
  1853. \begin{tabular}{lll}
  1854. \begin{minipage}{0.4\textwidth}
  1855. % s0_20.rkt
  1856. \begin{lstlisting}
  1857. (let ([a 42])
  1858. (let ([b a])
  1859. b))
  1860. \end{lstlisting}
  1861. \end{minipage}
  1862. &
  1863. $\Rightarrow$
  1864. &
  1865. \begin{minipage}{0.4\textwidth}
  1866. \begin{lstlisting}
  1867. (let ([a 42])
  1868. (let ([b a])
  1869. b))
  1870. \end{lstlisting}
  1871. \end{minipage}
  1872. \end{tabular} \\
  1873. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1874. produce the following output.\\
  1875. \begin{minipage}{0.4\textwidth}
  1876. \begin{lstlisting}
  1877. (let ([tmp.1 42])
  1878. (let ([a tmp.1])
  1879. (let ([tmp.2 a])
  1880. (let ([b tmp.2])
  1881. b))))
  1882. \end{lstlisting}
  1883. \end{minipage}
  1884. \begin{exercise}
  1885. \normalfont Implement the \code{remove-complex-opera*} pass.
  1886. Test the new pass on all of the example programs that you created to test the
  1887. \key{uniquify} pass and create three new example programs that are
  1888. designed to exercise the interesting code in the
  1889. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1890. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1891. your passes on the example programs.
  1892. \end{exercise}
  1893. \section{Explicate Control}
  1894. \label{sec:explicate-control-r1}
  1895. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1896. programs that make the order of execution explicit in their
  1897. syntax. For now this amounts to flattening \key{let} constructs into a
  1898. sequence of assignment statements. For example, consider the following
  1899. $R_1$ program.\\
  1900. % s0_11.rkt
  1901. \begin{minipage}{0.96\textwidth}
  1902. \begin{lstlisting}
  1903. (let ([y (let ([x 20])
  1904. (+ x (let ([x 22]) x)))])
  1905. y)
  1906. \end{lstlisting}
  1907. \end{minipage}\\
  1908. %
  1909. The output of the previous pass and of \code{explicate-control} is
  1910. shown below. Recall that the right-hand-side of a \key{let} executes
  1911. before its body, so the order of evaluation for this program is to
  1912. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1913. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1914. output of \code{explicate-control} makes this ordering explicit.\\
  1915. \begin{tabular}{lll}
  1916. \begin{minipage}{0.4\textwidth}
  1917. \begin{lstlisting}
  1918. (let ([y (let ([x.1 20])
  1919. (let ([x.2 22])
  1920. (+ x.1 x.2)))])
  1921. y)
  1922. \end{lstlisting}
  1923. \end{minipage}
  1924. &
  1925. $\Rightarrow$
  1926. &
  1927. \begin{minipage}{0.4\textwidth}
  1928. \begin{lstlisting}
  1929. locals: y x.1 x.2
  1930. start:
  1931. x.1 = 20;
  1932. x.2 = 22;
  1933. y = (+ x.1 x.2);
  1934. return y;
  1935. \end{lstlisting}
  1936. \end{minipage}
  1937. \end{tabular}
  1938. We recommend implementing \code{explicate-control} using two mutually
  1939. recursive functions: \code{explicate-tail} and
  1940. \code{explicate-assign}. The first function should be applied to
  1941. expressions in tail position whereas the second should be applied to
  1942. expressions that occur on the right-hand-side of a \key{let}.
  1943. %
  1944. The \code{explicate-tail} function takes an $R_1$ expression as input
  1945. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1946. list of formerly \key{let}-bound variables.
  1947. %
  1948. The \code{explicate-assign} function takes an $R_1$ expression, the
  1949. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1950. should come after the assignment (e.g., the code generated for the
  1951. body of the \key{let}). It returns a $\Tail$ and a list of
  1952. variables. The \code{explicate-assign} function is in
  1953. accumulator-passing style in that its third parameter is some $C_0$
  1954. code which it then adds to and returns. The reader might be tempted to
  1955. instead organize \code{explicate-assign} in a more direct fashion,
  1956. without the third parameter and perhaps using \code{append} to combine
  1957. statements. We warn against that alternative because the
  1958. accumulator-passing style is key to how we generate high-quality code
  1959. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1960. The top-level \code{explicate-control} function should invoke
  1961. \code{explicate-tail} on the body of the \key{program} and then
  1962. associate the \code{locals} symbol with the resulting list of
  1963. variables in the $\itm{info}$ field, as in the above example.
  1964. \section{Select Instructions}
  1965. \label{sec:select-r1}
  1966. \index{instruction selection}
  1967. In the \code{select-instructions} pass we begin the work of
  1968. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1969. this pass is a variant of x86 that still uses variables, so we add an
  1970. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1971. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1972. \code{select-instructions} in terms of three auxiliary functions, one
  1973. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1974. The cases for $\Atm$ are straightforward, variables stay
  1975. the same and integer constants are changed to immediates:
  1976. $\INT{n}$ changes to $\IMM{n}$.
  1977. Next we consider the cases for $\Stmt$, starting with arithmetic
  1978. operations. For example, in $C_0$ an addition operation can take the
  1979. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1980. need to use the \key{addq} instruction which does an in-place
  1981. update. So we must first move \code{10} to \code{x}. \\
  1982. \begin{tabular}{lll}
  1983. \begin{minipage}{0.4\textwidth}
  1984. \begin{lstlisting}
  1985. x = (+ 10 32);
  1986. \end{lstlisting}
  1987. \end{minipage}
  1988. &
  1989. $\Rightarrow$
  1990. &
  1991. \begin{minipage}{0.4\textwidth}
  1992. \begin{lstlisting}
  1993. movq $10, x
  1994. addq $32, x
  1995. \end{lstlisting}
  1996. \end{minipage}
  1997. \end{tabular} \\
  1998. %
  1999. There are cases that require special care to avoid generating
  2000. needlessly complicated code. If one of the arguments of the addition
  2001. is the same as the left-hand side of the assignment, then there is no
  2002. need for the extra move instruction. For example, the following
  2003. assignment statement can be translated into a single \key{addq}
  2004. instruction.\\
  2005. \begin{tabular}{lll}
  2006. \begin{minipage}{0.4\textwidth}
  2007. \begin{lstlisting}
  2008. x = (+ 10 x);
  2009. \end{lstlisting}
  2010. \end{minipage}
  2011. &
  2012. $\Rightarrow$
  2013. &
  2014. \begin{minipage}{0.4\textwidth}
  2015. \begin{lstlisting}
  2016. addq $10, x
  2017. \end{lstlisting}
  2018. \end{minipage}
  2019. \end{tabular} \\
  2020. The \key{read} operation does not have a direct counterpart in x86
  2021. assembly, so we have instead implemented this functionality in the C
  2022. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2023. in the file \code{runtime.c}. In general, we refer to all of the
  2024. functionality in this file as the \emph{runtime system}\index{runtime system},
  2025. or simply the \emph{runtime} for short. When compiling your generated x86
  2026. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2027. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2028. the executable. For our purposes of code generation, all you need to
  2029. do is translate an assignment of \key{read} into some variable
  2030. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2031. function followed by a move from \code{rax} to the left-hand side.
  2032. The move from \code{rax} is needed because the return value from
  2033. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2034. \begin{tabular}{lll}
  2035. \begin{minipage}{0.3\textwidth}
  2036. \begin{lstlisting}
  2037. |$\itm{var}$| = (read);
  2038. \end{lstlisting}
  2039. \end{minipage}
  2040. &
  2041. $\Rightarrow$
  2042. &
  2043. \begin{minipage}{0.3\textwidth}
  2044. \begin{lstlisting}
  2045. callq read_int
  2046. movq %rax, |$\itm{var}$|
  2047. \end{lstlisting}
  2048. \end{minipage}
  2049. \end{tabular} \\
  2050. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2051. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2052. assignment to the \key{rax} register followed by a jump to the
  2053. conclusion of the program (so the conclusion needs to be labeled).
  2054. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2055. recursively and append the resulting instructions.
  2056. \begin{exercise}
  2057. \normalfont
  2058. Implement the \key{select-instructions} pass and test it on all of the
  2059. example programs that you created for the previous passes and create
  2060. three new example programs that are designed to exercise all of the
  2061. interesting code in this pass. Use the \key{interp-tests} function
  2062. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2063. your passes on the example programs.
  2064. \end{exercise}
  2065. \section{Assign Homes}
  2066. \label{sec:assign-r1}
  2067. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2068. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2069. Thus, the \key{assign-homes} pass is responsible for placing all of
  2070. the program variables in registers or on the stack. For runtime
  2071. efficiency, it is better to place variables in registers, but as there
  2072. are only 16 registers, some programs must necessarily resort to
  2073. placing some variables on the stack. In this chapter we focus on the
  2074. mechanics of placing variables on the stack. We study an algorithm for
  2075. placing variables in registers in
  2076. Chapter~\ref{ch:register-allocation-r1}.
  2077. Consider again the following $R_1$ program.
  2078. % s0_20.rkt
  2079. \begin{lstlisting}
  2080. (let ([a 42])
  2081. (let ([b a])
  2082. b))
  2083. \end{lstlisting}
  2084. For reference, we repeat the output of \code{select-instructions} on
  2085. the left and show the output of \code{assign-homes} on the right.
  2086. Recall that \key{explicate-control} associated the list of
  2087. variables with the \code{locals} symbol in the program's $\itm{info}$
  2088. field, so \code{assign-homes} has convenient access to the them. In
  2089. this example, we assign variable \code{a} to stack location
  2090. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2091. \begin{tabular}{l}
  2092. \begin{minipage}{0.4\textwidth}
  2093. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2094. locals: a b
  2095. start:
  2096. movq $42, a
  2097. movq a, b
  2098. movq b, %rax
  2099. jmp conclusion
  2100. \end{lstlisting}
  2101. \end{minipage}
  2102. {$\Rightarrow$}
  2103. \begin{minipage}{0.4\textwidth}
  2104. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2105. stack-space: 16
  2106. start:
  2107. movq $42, -8(%rbp)
  2108. movq -8(%rbp), -16(%rbp)
  2109. movq -16(%rbp), %rax
  2110. jmp conclusion
  2111. \end{lstlisting}
  2112. \end{minipage}
  2113. \end{tabular} \\
  2114. In the process of assigning variables to stack locations, it is
  2115. convenient to compute and store the size of the frame (in bytes) in
  2116. the $\itm{info}$ field of the \key{Program} node, with the key
  2117. \code{stack-space}, which will be needed later to generate the
  2118. procedure conclusion. Some operating systems place restrictions on
  2119. the frame size. For example, Mac OS X requires the frame size to be a
  2120. multiple of 16 bytes.
  2121. \begin{exercise}
  2122. \normalfont Implement the \key{assign-homes} pass and test it on all
  2123. of the example programs that you created for the previous passes pass.
  2124. We recommend that \key{assign-homes} take an extra parameter that is a
  2125. mapping of variable names to homes (stack locations for now). Use the
  2126. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2127. \key{utilities.rkt} to test your passes on the example programs.
  2128. \end{exercise}
  2129. \section{Patch Instructions}
  2130. \label{sec:patch-s0}
  2131. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2132. programs to $\text{x86}_0$ programs by making sure that each
  2133. instruction adheres to the restrictions of the x86 assembly language.
  2134. In particular, at most one argument of an instruction may be a memory
  2135. reference.
  2136. We return to the following running example.
  2137. % s0_20.rkt
  2138. \begin{lstlisting}
  2139. (let ([a 42])
  2140. (let ([b a])
  2141. b))
  2142. \end{lstlisting}
  2143. After the \key{assign-homes} pass, the above program has been translated to
  2144. the following. \\
  2145. \begin{minipage}{0.5\textwidth}
  2146. \begin{lstlisting}
  2147. stack-space: 16
  2148. start:
  2149. movq $42, -8(%rbp)
  2150. movq -8(%rbp), -16(%rbp)
  2151. movq -16(%rbp), %rax
  2152. jmp conclusion
  2153. \end{lstlisting}
  2154. \end{minipage}\\
  2155. The second \key{movq} instruction is problematic because both
  2156. arguments are stack locations. We suggest fixing this problem by
  2157. moving from the source location to the register \key{rax} and then
  2158. from \key{rax} to the destination location, as follows.
  2159. \begin{lstlisting}
  2160. movq -8(%rbp), %rax
  2161. movq %rax, -16(%rbp)
  2162. \end{lstlisting}
  2163. \begin{exercise}
  2164. \normalfont
  2165. Implement the \key{patch-instructions} pass and test it on all of the
  2166. example programs that you created for the previous passes and create
  2167. three new example programs that are designed to exercise all of the
  2168. interesting code in this pass. Use the \key{interp-tests} function
  2169. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2170. your passes on the example programs.
  2171. \end{exercise}
  2172. \section{Print x86}
  2173. \label{sec:print-x86}
  2174. The last step of the compiler from $R_1$ to x86 is to convert the
  2175. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2176. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2177. \key{format} and \key{string-append} functions are useful in this
  2178. regard. The main work that this step needs to perform is to create the
  2179. \key{main} function and the standard instructions for its prelude and
  2180. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2181. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2182. variables, so we suggest computing it in the \key{assign-homes} pass
  2183. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2184. of the \key{program} node.
  2185. %% Your compiled code should print the result of the program's execution
  2186. %% by using the \code{print\_int} function provided in
  2187. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2188. %% far, this final result should be stored in the \key{rax} register.
  2189. %% We'll talk more about how to perform function calls with arguments in
  2190. %% general later on, but for now, place the following after the compiled
  2191. %% code for the $R_1$ program but before the conclusion:
  2192. %% \begin{lstlisting}
  2193. %% movq %rax, %rdi
  2194. %% callq print_int
  2195. %% \end{lstlisting}
  2196. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2197. %% stores the first argument to be passed into \key{print\_int}.
  2198. If you want your program to run on Mac OS X, your code needs to
  2199. determine whether or not it is running on a Mac, and prefix
  2200. underscores to labels like \key{main}. You can determine the platform
  2201. with the Racket call \code{(system-type 'os)}, which returns
  2202. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2203. %% In addition to
  2204. %% placing underscores on \key{main}, you need to put them in front of
  2205. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2206. %% \_print\_int}).
  2207. \begin{exercise}
  2208. \normalfont Implement the \key{print-x86} pass and test it on all of
  2209. the example programs that you created for the previous passes. Use the
  2210. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2211. \key{utilities.rkt} to test your complete compiler on the example
  2212. programs. See the \key{run-tests.rkt} script in the student support
  2213. code for an example of how to use \key{compiler-tests}. Also, remember
  2214. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2215. \key{gcc}.
  2216. \end{exercise}
  2217. \section{Challenge: Partial Evaluator for $R_1$}
  2218. \label{sec:pe-R1}
  2219. This section describes optional challenge exercises that involve
  2220. adapting and improving the partial evaluator for $R_0$ that was
  2221. introduced in Section~\ref{sec:partial-evaluation}.
  2222. \begin{exercise}\label{ex:pe-R1}
  2223. \normalfont
  2224. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2225. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2226. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2227. and variables to the $R_0$ language, so you will need to add cases for
  2228. them in the \code{pe-exp} function. Also, note that the \key{program}
  2229. form changes slightly to include an $\itm{info}$ field. Once
  2230. complete, add the partial evaluation pass to the front of your
  2231. compiler and make sure that your compiler still passes all of the
  2232. tests.
  2233. \end{exercise}
  2234. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2235. \begin{exercise}
  2236. \normalfont
  2237. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2238. \code{pe-add} auxiliary functions with functions that know more about
  2239. arithmetic. For example, your partial evaluator should translate
  2240. \begin{lstlisting}
  2241. (+ 1 (+ (read) 1))
  2242. \end{lstlisting}
  2243. into
  2244. \begin{lstlisting}
  2245. (+ 2 (read))
  2246. \end{lstlisting}
  2247. To accomplish this, the \code{pe-exp} function should produce output
  2248. in the form of the $\itm{residual}$ non-terminal of the following
  2249. grammar.
  2250. \[
  2251. \begin{array}{lcl}
  2252. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2253. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2254. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2255. \end{array}
  2256. \]
  2257. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2258. that their inputs are $\itm{residual}$ expressions and they should
  2259. return $\itm{residual}$ expressions. Once the improvements are
  2260. complete, make sure that your compiler still passes all of the tests.
  2261. After all, fast code is useless if it produces incorrect results!
  2262. \end{exercise}
  2263. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2264. \chapter{Register Allocation}
  2265. \label{ch:register-allocation-r1}
  2266. \index{register allocation}
  2267. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2268. make our life easier. However, we can improve the performance of the
  2269. generated code if we instead place some variables into registers. The
  2270. CPU can access a register in a single cycle, whereas accessing the
  2271. stack takes many cycles if the relevant data is in cache or many more
  2272. to access main memory if the data is not in cache.
  2273. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2274. serves as a running example. We show the source program and also the
  2275. output of instruction selection. At that point the program is almost
  2276. x86 assembly but not quite; it still contains variables instead of
  2277. stack locations or registers.
  2278. \begin{figure}
  2279. \begin{minipage}{0.45\textwidth}
  2280. Example $R_1$ program:
  2281. % s0_28.rkt
  2282. \begin{lstlisting}
  2283. (let ([v 1])
  2284. (let ([w 42])
  2285. (let ([x (+ v 7)])
  2286. (let ([y x])
  2287. (let ([z (+ x w)])
  2288. (+ z (- y)))))))
  2289. \end{lstlisting}
  2290. \end{minipage}
  2291. \begin{minipage}{0.45\textwidth}
  2292. After instruction selection:
  2293. \begin{lstlisting}
  2294. locals: (v w x y z t)
  2295. start:
  2296. movq $1, v
  2297. movq $42, w
  2298. movq v, x
  2299. addq $7, x
  2300. movq x, y
  2301. movq x, z
  2302. addq w, z
  2303. movq y, t
  2304. negq t
  2305. movq z, %rax
  2306. addq t, %rax
  2307. jmp conclusion
  2308. \end{lstlisting}
  2309. \end{minipage}
  2310. \caption{An example program for register allocation.}
  2311. \label{fig:reg-eg}
  2312. \end{figure}
  2313. The goal of register allocation is to fit as many variables into
  2314. registers as possible. A program sometimes has more variables than
  2315. registers, so we cannot map each variable to a different
  2316. register. Fortunately, it is common for different variables to be
  2317. needed during different periods of time during program execution, and
  2318. in such cases several variables can be mapped to the same register.
  2319. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2320. After the variable \code{x} is moved to \code{z} it is no longer
  2321. needed. Variable \code{y}, on the other hand, is used only after this
  2322. point, so \code{x} and \code{y} could share the same register. The
  2323. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2324. where a variable is needed. Once we have that information, we compute
  2325. which variables are needed at the same time, i.e., which ones
  2326. \emph{interfere} with each other, and represent this relation as an
  2327. undirected graph whose vertices are variables and edges indicate when
  2328. two variables interfere (Section~\ref{sec:build-interference}). We
  2329. then model register allocation as a graph coloring problem, which we
  2330. discuss in Section~\ref{sec:graph-coloring}.
  2331. In the event that we run out of registers despite these efforts, we
  2332. place the remaining variables on the stack, similar to what we did in
  2333. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2334. for assigning a variable to a stack location. The process of spilling
  2335. variables is handled as part of the graph coloring process described
  2336. in \ref{sec:graph-coloring}.
  2337. We make the simplifying assumption that each variable is assigned to
  2338. one location (a register or stack address). A more sophisticated
  2339. approach is to assign a variable to one or more locations in different
  2340. regions of the program. For example, if a variable is used many times
  2341. in short sequence and then only used again after many other
  2342. instructions, it could be more efficient to assign the variable to a
  2343. register during the intial sequence and then move it to the stack for
  2344. the rest of its lifetime. We refer the interested reader to
  2345. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2346. about this approach.
  2347. % discuss prioritizing variables based on how much they are used.
  2348. \section{Registers and Calling Conventions}
  2349. \label{sec:calling-conventions}
  2350. \index{calling conventions}
  2351. As we perform register allocation, we need to be aware of the
  2352. conventions that govern the way in which registers interact with
  2353. function calls, such as calls to the \code{read\_int} function in our
  2354. generated code and even the call that the operating system makes to
  2355. execute our \code{main} function. The convention for x86 is that the
  2356. caller is responsible for freeing up some registers, the
  2357. \emph{caller-saved registers}, prior to the function call, and the
  2358. callee is responsible for preserving the values in some other
  2359. registers, the \emph{callee-saved registers}.
  2360. \index{caller-saved registers}
  2361. \index{callee-saved registers}
  2362. The caller-saved registers are
  2363. \begin{lstlisting}
  2364. rax rcx rdx rsi rdi r8 r9 r10 r11
  2365. \end{lstlisting}
  2366. while the callee-saved registers are
  2367. \begin{lstlisting}
  2368. rsp rbp rbx r12 r13 r14 r15
  2369. \end{lstlisting}
  2370. We can think about this caller/callee convention from two points of
  2371. view, the caller view and the callee view:
  2372. \begin{itemize}
  2373. \item The caller should assume that all the caller-saved registers get
  2374. overwritten with arbitrary values by the callee. On the other hand,
  2375. the caller can safely assume that all the callee-saved registers
  2376. contain the same values after the call that they did before the
  2377. call.
  2378. \item The callee can freely use any of the caller-saved registers.
  2379. However, if the callee wants to use a callee-saved register, the
  2380. callee must arrange to put the original value back in the register
  2381. prior to returning to the caller, which is usually accomplished by
  2382. saving the value to the stack in the prelude of the function and
  2383. restoring the value in the conclusion of the function.
  2384. \end{itemize}
  2385. The next question is how these calling conventions impact register
  2386. allocation. Consider the $R_1$ program in
  2387. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2388. example from the caller point of view and then from the callee point
  2389. of view.
  2390. The program makes two calls to the \code{read} function. Also, the
  2391. variable \code{x} is in-use during the second call to \code{read}, so
  2392. we need to make sure that the value in \code{x} does not get
  2393. accidentally wiped out by the call to \code{read}. One obvious
  2394. approach is to save all the values in caller-saved registers to the
  2395. stack prior to each function call, and restore them after each
  2396. call. That way, if the register allocator chooses to assign \code{x}
  2397. to a caller-saved register, its value will be preserved accross the
  2398. call to \code{read}. However, the disadvantage of this approach is
  2399. that saving and restoring to the stack is relatively slow. If \code{x}
  2400. is not used many times, it may be better to assign \code{x} to a stack
  2401. location in the first place. Or better yet, if we can arrange for
  2402. \code{x} to be placed in a callee-saved register, then it won't need
  2403. to be saved and restored during function calls.
  2404. The approach that we recommend is to treat variables differently
  2405. depending on whether they are in-use during a function call. If a
  2406. variable is in-use during a function call, then we never assign it to
  2407. a caller-saved register: we either assign it to a callee-saved
  2408. register or we spill it to the stack. If a variable is not in-use
  2409. during any function call, then we try the following alternatives in
  2410. order 1) look for an available caller-saved register (to leave room
  2411. for other variables in the callee-saved register), 2) look for a
  2412. callee-saved register, and 3) spill the variable to the stack.
  2413. It is straightforward to implement this approach in a graph coloring
  2414. register allocator. First, we know which variables are in-use during
  2415. every function call because we compute that information for every
  2416. instruciton (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2417. build the interference graph (Section~\ref{sec:build-interference}),
  2418. we can place an edge between each of these variables and the
  2419. caller-saved registers in the interference graph. This will prevent
  2420. the graph coloring algorithm from assigning those variables to
  2421. caller-saved registers.
  2422. Returning to the example in
  2423. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2424. generated x86 code on the right-hand side, focusing on the
  2425. \code{start} block. Notice that variable \code{x} is assigned to
  2426. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2427. place during the second call to \code{read\_int}. Next, notice that
  2428. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2429. because there are no function calls in the remainder of the block.
  2430. Next we analyze the example from the callee point of view, focusing on
  2431. the prelude and conclusion of the \code{main} function. As usual the
  2432. prelude begins with saving the \code{rbp} register to the stack and
  2433. setting the \code{rbp} to the current stack pointer. We now know why
  2434. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2435. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2436. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2437. variable (\code{x}). There are several more callee-saved register that
  2438. are not saved in the prelude because they were not assigned to
  2439. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2440. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2441. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2442. from the stack with a \code{popq} instruction.
  2443. \index{prelude}\index{conclusion}
  2444. \begin{figure}[tp]
  2445. \begin{minipage}{0.45\textwidth}
  2446. Example $R_1$ program:
  2447. %s0_14.rkt
  2448. \begin{lstlisting}
  2449. (let ([x (read)])
  2450. (let ([y (read)])
  2451. (+ (+ x y) 42)))
  2452. \end{lstlisting}
  2453. \end{minipage}
  2454. \begin{minipage}{0.45\textwidth}
  2455. Generated x86 assembly:
  2456. \begin{lstlisting}
  2457. start:
  2458. callq read_int
  2459. movq %rax, %rbx
  2460. callq read_int
  2461. movq %rax, %rcx
  2462. addq %rcx, %rbx
  2463. movq %rbx, %rax
  2464. addq $42, %rax
  2465. jmp _conclusion
  2466. .globl main
  2467. main:
  2468. pushq %rbp
  2469. movq %rsp, %rbp
  2470. pushq %rbx
  2471. subq $8, %rsp
  2472. jmp start
  2473. conclusion:
  2474. addq $8, %rsp
  2475. popq %rbx
  2476. popq %rbp
  2477. retq
  2478. \end{lstlisting}
  2479. \end{minipage}
  2480. \caption{An example with function calls.}
  2481. \label{fig:example-calling-conventions}
  2482. \end{figure}
  2483. \section{Liveness Analysis}
  2484. \label{sec:liveness-analysis-r1}
  2485. \index{liveness analysis}
  2486. A variable is \emph{live} if the variable is used at some later point
  2487. in the program and there is not an intervening assignment to the
  2488. variable.
  2489. %
  2490. To understand the latter condition, consider the following code
  2491. fragment in which there are two writes to \code{b}. Are \code{a} and
  2492. \code{b} both live at the same time?
  2493. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2494. movq $5, a
  2495. movq $30, b
  2496. movq a, c
  2497. movq $10, b
  2498. addq b, c
  2499. \end{lstlisting}
  2500. The answer is no because the integer \code{30} written to \code{b} on
  2501. line 2 is never used. The variable \code{b} is read on line 5 and
  2502. there is an intervening write to \code{b} on line 4, so the read on
  2503. line 5 receives the value written on line 4, not line 2.
  2504. \begin{wrapfigure}[20]{l}[1.0in]{0.6\textwidth}
  2505. \small
  2506. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2507. A \emph{set} is an unordered collection of elements without duplicates.
  2508. \index{set}
  2509. \begin{description}
  2510. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2511. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2512. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2513. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2514. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2515. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2516. \end{description}
  2517. \end{tcolorbox}
  2518. \end{wrapfigure}
  2519. The live variables can be computed by traversing the instruction
  2520. sequence back to front (i.e., backwards in execution order). Let
  2521. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2522. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2523. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2524. variables before instruction $I_k$. The live variables after an
  2525. instruction are always the same as the live variables before the next
  2526. instruction.
  2527. \index{live-after}
  2528. \index{live-before}
  2529. \begin{equation} \label{eq:live-after-before-next}
  2530. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2531. \end{equation}
  2532. To start things off, there are no live variables after the last
  2533. instruction, so
  2534. \begin{equation}\label{eq:live-last-empty}
  2535. L_{\mathsf{after}}(n) = \emptyset
  2536. \end{equation}
  2537. We then apply the following rule repeatedly, traversing the
  2538. instruction sequence back to front.
  2539. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2540. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2541. \end{equation}
  2542. where $W(k)$ are the variables written to by instruction $I_k$ and
  2543. $R(k)$ are the variables read by instruction $I_k$.
  2544. Let us walk through the above example, applying these formulas
  2545. starting with the instruction on line 5. We collect the answers in the
  2546. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2547. instruction is $\emptyset$ because it is the last instruction
  2548. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2549. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2550. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2551. is
  2552. \[
  2553. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2554. \]
  2555. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2556. the live-before set from line 5 to be the live-after set for this
  2557. instruction (formula~\ref{eq:live-after-before-next}).
  2558. \[
  2559. L_{\mathsf{after}}(4) = \{ b, c \}
  2560. \]
  2561. This move instruction writes to $b$ and does not read from any
  2562. variables, so we have the following live-before set
  2563. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2564. \[
  2565. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2566. \]
  2567. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2568. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2569. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2570. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2571. variable that is not live and does not read from a variable.
  2572. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2573. because it writes to variable $a$.
  2574. \begin{center}
  2575. \begin{minipage}{0.45\textwidth}
  2576. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2577. movq $5, a
  2578. movq $30, b
  2579. movq a, c
  2580. movq $10, b
  2581. addq b, c
  2582. \end{lstlisting}
  2583. \end{minipage}
  2584. \vrule\hspace{10pt}
  2585. \begin{minipage}{0.45\textwidth}
  2586. \begin{align*}
  2587. L_{\mathsf{before}}(1)= \emptyset,
  2588. L_{\mathsf{after}}(1)= \{a\}\\
  2589. L_{\mathsf{before}}(2)= \{a\},
  2590. L_{\mathsf{after}}(2)= \{a\}\\
  2591. L_{\mathsf{before}}(3)= \{a\},
  2592. L_{\mathsf{after}}(2)= \{c\}\\
  2593. L_{\mathsf{before}}(4)= \{c\},
  2594. L_{\mathsf{after}}(4)= \{b,c\}\\
  2595. L_{\mathsf{before}}(5)= \{b,c\},
  2596. L_{\mathsf{after}}(5)= \emptyset
  2597. \end{align*}
  2598. \end{minipage}
  2599. \end{center}
  2600. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2601. for the running example program, with the live-before and live-after
  2602. sets shown between each instruction to make the figure easy to read.
  2603. \begin{figure}[tp]
  2604. \hspace{20pt}
  2605. \begin{minipage}{0.45\textwidth}
  2606. \begin{lstlisting}
  2607. |$\{\}$|
  2608. movq $1, v
  2609. |$\{v\}$|
  2610. movq $42, w
  2611. |$\{v,w\}$|
  2612. movq v, x
  2613. |$\{w,x\}$|
  2614. addq $7, x
  2615. |$\{w,x\}$|
  2616. movq x, y
  2617. |$\{w,x,y\}$|
  2618. movq x, z
  2619. |$\{w,y,z\}$|
  2620. addq w, z
  2621. |$\{y,z\}$|
  2622. movq y, t
  2623. |$\{t,z\}$|
  2624. negq t
  2625. |$\{t,z\}$|
  2626. movq z, %rax
  2627. |$\{t\}$|
  2628. addq t, %rax
  2629. |$\{\}$|
  2630. jmp conclusion
  2631. |$\{\}$|
  2632. \end{lstlisting}
  2633. \end{minipage}
  2634. \caption{The running example annotated with live-after sets.}
  2635. \label{fig:live-eg}
  2636. \end{figure}
  2637. \begin{exercise}\normalfont
  2638. Implement the compiler pass named \code{uncover-live} that computes
  2639. the live-after sets. We recommend storing the live-after sets (a list
  2640. of a set of variables) in the $\itm{info}$ field of the \key{Block}
  2641. structure. We recommend using the
  2642. \href{https://docs.racket-lang.org/reference/sets.html}{\code{racket/set}}
  2643. package for representing sets of variables.
  2644. %
  2645. We recommend organizing your code to use a helper function that takes
  2646. a list of instructions and an initial live-after set (typically empty)
  2647. and returns the list of live-after sets.
  2648. %
  2649. We recommend creating helper functions to 1) compute the set of
  2650. variables that appear in an argument (of an instruction), 2) compute
  2651. the variables read by an instruction which corresponds to the $R$
  2652. function discussed above, and 3) the variables written by an
  2653. instruction which corresponds to $W$.
  2654. \end{exercise}
  2655. \section{Building the Interference Graph}
  2656. \label{sec:build-interference}
  2657. Based on the liveness analysis, we know where each variable is needed.
  2658. However, during register allocation, we need to answer questions of
  2659. the specific form: are variables $u$ and $v$ live at the same time?
  2660. (And therefore cannot be assigned to the same register.) To make this
  2661. question easier to answer, we create an explicit data structure, an
  2662. \emph{interference graph}\index{interference graph}. An interference
  2663. graph is an undirected graph that has an edge between two variables if
  2664. they are live at the same time, that is, if they interfere with each
  2665. other.
  2666. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2667. \small
  2668. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2669. A \emph{graph} is a collection of vertices and edges where each
  2670. edge connects two vertices. A graph is \emph{directed} if each
  2671. edge points from a source to a target. Otherwise the graph is
  2672. \emph{undirected}.
  2673. \index{graph}\index{directed graph}\index{undirected graph}
  2674. \begin{description}
  2675. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2676. directed graph from a list of edges. Each edge is a list
  2677. containing the source and target vertex.
  2678. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2679. undirected graph from a list of edges. Each edge is represented by
  2680. a list containing two vertices.
  2681. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2682. inserts a vertex into the graph.
  2683. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2684. inserts an edge between the two vertices into the graph.
  2685. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2686. returns a sequence of all the neighbors of the given vertex.
  2687. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2688. returns a sequence of all the vertices in the graph.
  2689. \end{description}
  2690. \end{tcolorbox}
  2691. \end{wrapfigure}
  2692. The most obvious way to compute the interference graph is to look at
  2693. the set of live variables between each statement in the program and
  2694. add an edge to the graph for every pair of variables in the same set.
  2695. This approach is less than ideal for two reasons. First, it can be
  2696. expensive because it takes $O(n^2)$ time to look at every pair in a
  2697. set of $n$ live variables. Second, there is a special case in which
  2698. two variables that are live at the same time do not actually interfere
  2699. with each other: when they both contain the same value because we have
  2700. assigned one to the other.
  2701. A better way to compute the interference graph is to focus on the
  2702. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2703. instruction to overwrite something in a live variable. So for each
  2704. instruction, we create an edge between the variable being written to
  2705. and all the \emph{other} live variables. (One should not create self
  2706. edges.) For a \key{callq} instruction, think of all caller-saved
  2707. registers as being written to, so an edge must be added between every
  2708. live variable and every caller-saved register. For \key{movq}, we deal
  2709. with the above-mentioned special case by not adding an edge between a
  2710. live variable $v$ and destination $d$ if $v$ matches the source of the
  2711. move. So we have the following three rules.
  2712. \begin{enumerate}
  2713. \item If instruction $I_k$ is an arithmetic instruction such as
  2714. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2715. L_{\mathsf{after}}(k)$ unless $v = d$.
  2716. \item If instruction $I_k$ is of the form \key{callq}
  2717. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2718. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2719. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2720. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2721. d$ or $v = s$.
  2722. \end{enumerate}
  2723. Working from the top to bottom of Figure~\ref{fig:live-eg}, apply the
  2724. above rules to each instruction. We highlight a few of the
  2725. instructions and then refer the reader to
  2726. Figure~\ref{fig:interference-results} all the interference results.
  2727. The first instruction is \lstinline{movq $1, v}, so rule 3 applies,
  2728. and the live-after set is $\{v\}$. We do not add any interference
  2729. edges because the one live variable $v$ is also the destination of
  2730. this instruction.
  2731. %
  2732. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2733. again, and the live-after set is $\{v,w\}$. So the target $w$ of
  2734. \key{movq} interferes with $v$.
  2735. %
  2736. Next we skip forward to the instruction \lstinline{movq x, y}.
  2737. \begin{figure}[tbp]
  2738. \begin{quote}
  2739. \begin{tabular}{ll}
  2740. \lstinline{movq $1, v}& no interference by rule 3,\\
  2741. \lstinline{movq $42, w}& $w$ interferes with $v$ by rule 3,\\
  2742. \lstinline{movq v, x}& $x$ interferes with $w$ by rule 3,\\
  2743. \lstinline{addq $7, x}& $x$ interferes with $w$ by rule 1,\\
  2744. \lstinline{movq x, y}& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2745. \lstinline{movq x, z}& $z$ interferes with $w$ and $y$ by rule 3,\\
  2746. \lstinline{addq w, z}& $z$ interferes with $y$ by rule 1, \\
  2747. \lstinline{movq y, t}& $t$ interferes with $z$ by rule 3, \\
  2748. \lstinline{negq t}& $t$ interferes with $z$ by rule 1, \\
  2749. \lstinline{movq z, %rax} & no interference (ignore rax), \\
  2750. \lstinline{addq t, %rax} & no interference (ignore rax). \\
  2751. \lstinline{jmp conclusion}& no interference.
  2752. \end{tabular}
  2753. \end{quote}
  2754. \caption{Interference results for the running example.}
  2755. \label{fig:interference-results}
  2756. \end{figure}
  2757. The resulting interference graph is shown in
  2758. Figure~\ref{fig:interfere}.
  2759. \begin{figure}[tbp]
  2760. \large
  2761. \[
  2762. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2763. \node (t1) at (0,2) {$t$};
  2764. \node (z) at (3,2) {$z$};
  2765. \node (x) at (6,2) {$x$};
  2766. \node (y) at (3,0) {$y$};
  2767. \node (w) at (6,0) {$w$};
  2768. \node (v) at (9,0) {$v$};
  2769. \draw (t1) to (z);
  2770. \draw (z) to (y);
  2771. \draw (z) to (w);
  2772. \draw (x) to (w);
  2773. \draw (y) to (w);
  2774. \draw (v) to (w);
  2775. \end{tikzpicture}
  2776. \]
  2777. \caption{The interference graph of the example program.}
  2778. \label{fig:interfere}
  2779. \end{figure}
  2780. %% Our next concern is to choose a data structure for representing the
  2781. %% interference graph. There are many choices for how to represent a
  2782. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2783. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2784. %% data structure is to study the algorithm that uses the data structure,
  2785. %% determine what operations need to be performed, and then choose the
  2786. %% data structure that provide the most efficient implementations of
  2787. %% those operations. Often times the choice of data structure can have an
  2788. %% effect on the time complexity of the algorithm, as it does here. If
  2789. %% you skim the next section, you will see that the register allocation
  2790. %% algorithm needs to ask the graph for all of its vertices and, given a
  2791. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2792. %% correct choice of graph representation is that of an adjacency
  2793. %% list. There are helper functions in \code{utilities.rkt} for
  2794. %% representing graphs using the adjacency list representation:
  2795. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2796. %% (Appendix~\ref{appendix:utilities}).
  2797. %% %
  2798. %% \margincomment{\footnotesize To do: change to use the
  2799. %% Racket graph library. \\ --Jeremy}
  2800. %% %
  2801. %% In particular, those functions use a hash table to map each vertex to
  2802. %% the set of adjacent vertices, and the sets are represented using
  2803. %% Racket's \key{set}, which is also a hash table.
  2804. \begin{exercise}\normalfont
  2805. Implement the compiler pass named \code{build-interference} according
  2806. to the algorithm suggested above. We recommend using the \code{graph}
  2807. package to create and inspect the interference graph. The output
  2808. graph of this pass should be stored in the $\itm{info}$ field of the
  2809. program, under the key \code{conflicts}.
  2810. \end{exercise}
  2811. \section{Graph Coloring via Sudoku}
  2812. \label{sec:graph-coloring}
  2813. \index{graph coloring}
  2814. \index{Sudoku}
  2815. \index{color}
  2816. We come to the main event, mapping variables to registers (or to stack
  2817. locations in the event that we run out of registers). We need to make
  2818. sure that two variables do not get mapped to the same register if the
  2819. two variables interfere with each other. Thinking about the
  2820. interference graph, this means that adjacent vertices must be mapped
  2821. to different registers. If we think of registers as colors, the
  2822. register allocation problem becomes the widely-studied graph coloring
  2823. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2824. The reader may be more familiar with the graph coloring problem than he
  2825. or she realizes; the popular game of Sudoku is an instance of the
  2826. graph coloring problem. The following describes how to build a graph
  2827. out of an initial Sudoku board.
  2828. \begin{itemize}
  2829. \item There is one vertex in the graph for each Sudoku square.
  2830. \item There is an edge between two vertices if the corresponding squares
  2831. are in the same row, in the same column, or if the squares are in
  2832. the same $3\times 3$ region.
  2833. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2834. \item Based on the initial assignment of numbers to squares in the
  2835. Sudoku board, assign the corresponding colors to the corresponding
  2836. vertices in the graph.
  2837. \end{itemize}
  2838. If you can color the remaining vertices in the graph with the nine
  2839. colors, then you have also solved the corresponding game of Sudoku.
  2840. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2841. the corresponding graph with colored vertices. We map the Sudoku
  2842. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2843. sampling of the vertices (the colored ones) because showing edges for
  2844. all of the vertices would make the graph unreadable.
  2845. \begin{figure}[tbp]
  2846. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2847. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2848. \caption{A Sudoku game board and the corresponding colored graph.}
  2849. \label{fig:sudoku-graph}
  2850. \end{figure}
  2851. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2852. strategies to come up with an algorithm for allocating registers. For
  2853. example, one of the basic techniques for Sudoku is called Pencil
  2854. Marks. The idea is to use a process of elimination to determine what
  2855. numbers no longer make sense for a square and write down those
  2856. numbers in the square (writing very small). For example, if the number
  2857. $1$ is assigned to a square, then by process of elimination, you can
  2858. write the pencil mark $1$ in all the squares in the same row, column,
  2859. and region. Many Sudoku computer games provide automatic support for
  2860. Pencil Marks.
  2861. %
  2862. The Pencil Marks technique corresponds to the notion of
  2863. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2864. The saturation of a
  2865. vertex, in Sudoku terms, is the set of numbers that are no longer
  2866. available. In graph terminology, we have the following definition:
  2867. \begin{equation*}
  2868. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2869. \text{ and } \mathrm{color}(v) = c \}
  2870. \end{equation*}
  2871. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2872. edge with $u$.
  2873. Using the Pencil Marks technique leads to a simple strategy for
  2874. filling in numbers: if there is a square with only one possible number
  2875. left, then choose that number! But what if there are no squares with
  2876. only one possibility left? One brute-force approach is to try them
  2877. all: choose the first and if it ultimately leads to a solution,
  2878. great. If not, backtrack and choose the next possibility. One good
  2879. thing about Pencil Marks is that it reduces the degree of branching in
  2880. the search tree. Nevertheless, backtracking can be horribly time
  2881. consuming. One way to reduce the amount of backtracking is to use the
  2882. most-constrained-first heuristic. That is, when choosing a square,
  2883. always choose one with the fewest possibilities left (the vertex with
  2884. the highest saturation). The idea is that choosing highly constrained
  2885. squares earlier rather than later is better because later on there may
  2886. not be any possibilities left for those squares.
  2887. However, register allocation is easier than Sudoku because the
  2888. register allocator can map variables to stack locations when the
  2889. registers run out. Thus, it makes sense to drop backtracking in favor
  2890. of greedy search, that is, make the best choice at the time and keep
  2891. going. We still wish to minimize the number of colors needed, so
  2892. keeping the most-constrained-first heuristic is a good idea.
  2893. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2894. algorithm for register allocation based on saturation and the
  2895. most-constrained-first heuristic. It is roughly equivalent to the
  2896. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2897. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2898. Sudoku, the algorithm represents colors with integers. The first $k$
  2899. colors corresponding to the $k$ registers in a given machine and the
  2900. rest of the integers corresponding to stack locations.
  2901. \begin{figure}[btp]
  2902. \centering
  2903. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2904. Algorithm: DSATUR
  2905. Input: a graph |$G$|
  2906. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2907. |$W \gets \mathit{vertices}(G)$|
  2908. while |$W \neq \emptyset$| do
  2909. pick a vertex |$u$| from |$W$| with the highest saturation,
  2910. breaking ties randomly
  2911. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2912. |$\mathrm{color}[u] \gets c$|
  2913. |$W \gets W - \{u\}$|
  2914. \end{lstlisting}
  2915. \caption{The saturation-based greedy graph coloring algorithm.}
  2916. \label{fig:satur-algo}
  2917. \end{figure}
  2918. With this algorithm in hand, let us return to the running example and
  2919. consider how to color the interference graph in
  2920. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2921. colored and they are unsaturated, so we annotate each of them with a
  2922. dash for their color and an empty set for the saturation.
  2923. \[
  2924. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2925. \node (t1) at (0,2) {$t:-,\{\}$};
  2926. \node (z) at (3,2) {$z:-,\{\}$};
  2927. \node (x) at (6,2) {$x:-,\{\}$};
  2928. \node (y) at (3,0) {$y:-,\{\}$};
  2929. \node (w) at (6,0) {$w:-,\{\}$};
  2930. \node (v) at (9,0) {$v:-,\{\}$};
  2931. \draw (t1) to (z);
  2932. \draw (z) to (y);
  2933. \draw (z) to (w);
  2934. \draw (x) to (w);
  2935. \draw (y) to (w);
  2936. \draw (v) to (w);
  2937. \end{tikzpicture}
  2938. \]
  2939. The algorithm says to select a maximally saturated vertex and color it
  2940. $0$. In this case we have a 6-way tie, so we arbitrarily pick
  2941. $t$. We then mark color $0$ as no longer available for $z$ because
  2942. it interferes with $t$.
  2943. \[
  2944. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2945. \node (t1) at (0,2) {$t:0,\{\}$};
  2946. \node (z) at (3,2) {$z:-,\{0\}$};
  2947. \node (x) at (6,2) {$x:-,\{\}$};
  2948. \node (y) at (3,0) {$y:-,\{\}$};
  2949. \node (w) at (6,0) {$w:-,\{\}$};
  2950. \node (v) at (9,0) {$v:-,\{\}$};
  2951. \draw (t1) to (z);
  2952. \draw (z) to (y);
  2953. \draw (z) to (w);
  2954. \draw (x) to (w);
  2955. \draw (y) to (w);
  2956. \draw (v) to (w);
  2957. \end{tikzpicture}
  2958. \]
  2959. Next we repeat the process, selecting another maximally saturated
  2960. vertex, which is $z$, and color it with the first available number,
  2961. which is $1$.
  2962. \[
  2963. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2964. \node (t1) at (0,2) {$t:0,\{1\}$};
  2965. \node (z) at (3,2) {$z:1,\{0\}$};
  2966. \node (x) at (6,2) {$x:-,\{\}$};
  2967. \node (y) at (3,0) {$y:-,\{1\}$};
  2968. \node (w) at (6,0) {$w:-,\{1\}$};
  2969. \node (v) at (9,0) {$v:-,\{\}$};
  2970. \draw (t1) to (z);
  2971. \draw (z) to (y);
  2972. \draw (z) to (w);
  2973. \draw (x) to (w);
  2974. \draw (y) to (w);
  2975. \draw (v) to (w);
  2976. \end{tikzpicture}
  2977. \]
  2978. The most saturated vertices are now $w$ and $y$. We color $w$ with the
  2979. first available color, which is $0$.
  2980. \[
  2981. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2982. \node (t1) at (0,2) {$t:0,\{1\}$};
  2983. \node (z) at (3,2) {$z:1,\{0\}$};
  2984. \node (x) at (6,2) {$x:-,\{0\}$};
  2985. \node (y) at (3,0) {$y:-,\{0,1\}$};
  2986. \node (w) at (6,0) {$w:0,\{1\}$};
  2987. \node (v) at (9,0) {$v:-,\{0\}$};
  2988. \draw (t1) to (z);
  2989. \draw (z) to (y);
  2990. \draw (z) to (w);
  2991. \draw (x) to (w);
  2992. \draw (y) to (w);
  2993. \draw (v) to (w);
  2994. \end{tikzpicture}
  2995. \]
  2996. Vertex $y$ is now the most highly saturated, so we color $y$ with $2$.
  2997. We cannot choose $0$ or $1$ because those numbers are in $y$'s
  2998. saturation set. Indeed, $y$ interferes with $w$ and $z$, whose colors
  2999. are $0$ and $1$ respectively.
  3000. \[
  3001. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3002. \node (t1) at (0,2) {$t:0,\{1\}$};
  3003. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3004. \node (x) at (6,2) {$x:-,\{0\}$};
  3005. \node (y) at (3,0) {$y:2,\{0,1\}$};
  3006. \node (w) at (6,0) {$w:0,\{1,2\}$};
  3007. \node (v) at (9,0) {$v:-,\{0\}$};
  3008. \draw (t1) to (z);
  3009. \draw (z) to (y);
  3010. \draw (z) to (w);
  3011. \draw (x) to (w);
  3012. \draw (y) to (w);
  3013. \draw (v) to (w);
  3014. \end{tikzpicture}
  3015. \]
  3016. Now $x$ and $v$ are the most saturated, so we color $v$ it $1$.
  3017. \[
  3018. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3019. \node (t1) at (0,2) {$t:0,\{1\}$};
  3020. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3021. \node (x) at (6,2) {$x:-,\{0\}$};
  3022. \node (y) at (3,0) {$y:2,\{0,1\}$};
  3023. \node (w) at (6,0) {$w:0,\{1,2\}$};
  3024. \node (v) at (9,0) {$v:1,\{0\}$};
  3025. \draw (t1) to (z);
  3026. \draw (z) to (y);
  3027. \draw (z) to (w);
  3028. \draw (x) to (w);
  3029. \draw (y) to (w);
  3030. \draw (v) to (w);
  3031. \end{tikzpicture}
  3032. \]
  3033. In the last step of the algorithm, we color $x$ with $1$.
  3034. \[
  3035. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3036. \node (t1) at (0,2) {$t:0,\{1,\}$};
  3037. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3038. \node (x) at (6,2) {$x:1,\{0\}$};
  3039. \node (y) at (3,0) {$y:2,\{0,1\}$};
  3040. \node (w) at (6,0) {$w:0,\{1,2\}$};
  3041. \node (v) at (9,0) {$v:1,\{0\}$};
  3042. \draw (t1) to (z);
  3043. \draw (z) to (y);
  3044. \draw (z) to (w);
  3045. \draw (x) to (w);
  3046. \draw (y) to (w);
  3047. \draw (v) to (w);
  3048. \end{tikzpicture}
  3049. \]
  3050. With the coloring complete, we finalize the assignment of variables to
  3051. registers and stack locations. Recall that if we have $k$ registers,
  3052. we map the first $k$ colors to registers and the rest to stack
  3053. locations. Suppose for the moment that we have just one register to
  3054. use for register allocation, \key{rcx}. Then the following is the
  3055. mapping of colors to registers and stack allocations.
  3056. \[
  3057. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3058. \]
  3059. Putting this mapping together with the above coloring of the
  3060. variables, we arrive at the following assignment of variables to
  3061. registers and stack locations.
  3062. \begin{gather*}
  3063. \{ v \mapsto \key{\%rcx}, \,
  3064. w \mapsto \key{\%rcx}, \,
  3065. x \mapsto \key{-8(\%rbp)}, \\
  3066. y \mapsto \key{-16(\%rbp)}, \,
  3067. z\mapsto \key{-8(\%rbp)},
  3068. t\mapsto \key{\%rcx} \}
  3069. \end{gather*}
  3070. Applying this assignment to our running example, on the left, yields
  3071. the program on the right.
  3072. % why frame size of 32? -JGS
  3073. \begin{center}
  3074. \begin{minipage}{0.3\textwidth}
  3075. \begin{lstlisting}
  3076. movq $1, v
  3077. movq $42, w
  3078. movq v, x
  3079. addq $7, x
  3080. movq x, y
  3081. movq x, z
  3082. addq w, z
  3083. movq y, t
  3084. negq t
  3085. movq z, %rax
  3086. addq t, %rax
  3087. jmp conclusion
  3088. \end{lstlisting}
  3089. \end{minipage}
  3090. $\Rightarrow\qquad$
  3091. \begin{minipage}{0.45\textwidth}
  3092. \begin{lstlisting}
  3093. movq $1, %rcx
  3094. movq $42, %rcx
  3095. movq %rcx, -8(%rbp)
  3096. addq $7, -8(%rbp)
  3097. movq -8(%rbp), -16(%rbp)
  3098. movq -8(%rbp), -8(%rbp)
  3099. addq %rcx, -8(%rbp)
  3100. movq -16(%rbp), %rcx
  3101. negq %rcx
  3102. movq -8(%rbp), %rax
  3103. addq %rcx, %rax
  3104. jmp conclusion
  3105. \end{lstlisting}
  3106. \end{minipage}
  3107. \end{center}
  3108. The resulting program is almost an x86 program. The remaining step is
  3109. the patch instructions pass. In this example, the trivial move of
  3110. \code{-8(\%rbp)} to itself is deleted and the addition of
  3111. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3112. \code{rax} as follows.
  3113. \begin{lstlisting}
  3114. movq -8(%rbp), %rax
  3115. addq %rax, -16(%rbp)
  3116. \end{lstlisting}
  3117. An overview of all of the passes involved in register allocation is
  3118. shown in Figure~\ref{fig:reg-alloc-passes}.
  3119. \begin{figure}[tbp]
  3120. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3121. \node (R1) at (0,2) {\large $R_1$};
  3122. \node (R1-2) at (3,2) {\large $R_1$};
  3123. \node (R1-3) at (6,2) {\large $R_1$};
  3124. \node (C0-1) at (3,0) {\large $C_0$};
  3125. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3126. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3127. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3128. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3129. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3130. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3131. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3132. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3133. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3134. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3135. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3136. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3137. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3138. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3139. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3140. \end{tikzpicture}
  3141. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3142. \label{fig:reg-alloc-passes}
  3143. \end{figure}
  3144. \begin{exercise}\normalfont
  3145. Implement the pass \code{allocate-registers}, which should come
  3146. after the \code{build-interference} pass. The three new passes,
  3147. \code{uncover-live}, \code{build-interference}, and
  3148. \code{allocate-registers} replace the \code{assign-homes} pass of
  3149. Section~\ref{sec:assign-r1}.
  3150. We recommend that you create a helper function named
  3151. \code{color-graph} that takes an interference graph and a list of
  3152. all the variables in the program. This function should return a
  3153. mapping of variables to their colors (represented as natural
  3154. numbers). By creating this helper function, you will be able to
  3155. reuse it in Chapter~\ref{ch:functions} when you add support for
  3156. functions. The support code includes an implementation of the
  3157. priority queue data structure in the file
  3158. \code{priority\_queue.rkt}, which might come in handy for
  3159. prioritizing highly saturated nodes inside your \code{color-graph}
  3160. function.
  3161. Once you have obtained the coloring from \code{color-graph}, you can
  3162. assign the variables to registers or stack locations and then reuse
  3163. code from the \code{assign-homes} pass from
  3164. Section~\ref{sec:assign-r1} to replace the variables with their
  3165. assigned location.
  3166. Test your updated compiler by creating new example programs that
  3167. exercise all of the register allocation algorithm, such as forcing
  3168. variables to be spilled to the stack.
  3169. \end{exercise}
  3170. \section{Print x86 and Conventions for Registers}
  3171. \label{sec:print-x86-reg-alloc}
  3172. \index{calling conventions}
  3173. \index{prelude}\index{conclusion}
  3174. Recall that the \code{print-x86} pass generates the prelude and
  3175. conclusion instructions for the \code{main} function.
  3176. %
  3177. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3178. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3179. reason for this is that our \code{main} function must adhere to the
  3180. x86 calling conventions that we described in
  3181. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3182. allocator assigned variables to other callee-saved registers
  3183. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3184. saved to the stack in the prelude and restored in the conclusion. The
  3185. simplest approach is to save and restore all of the callee-saved
  3186. registers. The more efficient approach is to keep track of which
  3187. callee-saved registers were used and only save and restore
  3188. them. Either way, make sure to take this use of stack space into
  3189. account when you are calculating the size of the frame and adjusting
  3190. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3191. frame needs to be a multiple of 16 bytes!
  3192. \section{Challenge: Move Biasing}
  3193. \label{sec:move-biasing}
  3194. \index{move biasing}
  3195. This section describes an optional enhancement to register allocation
  3196. for those students who are looking for an extra challenge or who have
  3197. a deeper interest in register allocation.
  3198. We return to the running example, but we remove the supposition that
  3199. we only have one register to use. So we have the following mapping of
  3200. color numbers to registers.
  3201. \[
  3202. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3203. \]
  3204. Using the same assignment of variables to color numbers that was
  3205. produced by the register allocator described in the last section, we
  3206. get the following program.
  3207. \begin{minipage}{0.3\textwidth}
  3208. \begin{lstlisting}
  3209. movq $1, v
  3210. movq $42, w
  3211. movq v, x
  3212. addq $7, x
  3213. movq x, y
  3214. movq x, z
  3215. addq w, z
  3216. movq y, t
  3217. negq t
  3218. movq z, %rax
  3219. addq t, %rax
  3220. jmp conclusion
  3221. \end{lstlisting}
  3222. \end{minipage}
  3223. $\Rightarrow\qquad$
  3224. \begin{minipage}{0.45\textwidth}
  3225. \begin{lstlisting}
  3226. movq $1, %rcx
  3227. movq $42, $rbx
  3228. movq %rcx, %rcx
  3229. addq $7, %rcx
  3230. movq %rcx, %rdx
  3231. movq %rcx, %rcx
  3232. addq %rbx, %rcx
  3233. movq %rdx, %rbx
  3234. negq %rbx
  3235. movq %rcx, %rax
  3236. addq %rbx, %rax
  3237. jmp conclusion
  3238. \end{lstlisting}
  3239. \end{minipage}
  3240. In the above output code there are two \key{movq} instructions that
  3241. can be removed because their source and target are the same. However,
  3242. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3243. register, we could instead remove three \key{movq} instructions. We
  3244. can accomplish this by taking into account which variables appear in
  3245. \key{movq} instructions with which other variables.
  3246. We say that two variables $p$ and $q$ are \emph{move related}\index{move related}
  3247. if they participate together in a \key{movq} instruction, that is, \key{movq}
  3248. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  3249. allocator chooses a color for a variable, it should prefer a color
  3250. that has already been used for a move-related variable (assuming that
  3251. they do not interfere). Of course, this preference should not override
  3252. the preference for registers over stack locations. This preference
  3253. should be used as a tie breaker when choosing between registers or
  3254. when choosing between stack locations.
  3255. We recommend representing the move relationships in a graph, similar
  3256. to how we represented interference. The following is the \emph{move
  3257. graph} for our running example.
  3258. \[
  3259. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3260. \node (t) at (0,2) {$t$};
  3261. \node (z) at (3,2) {$z$};
  3262. \node (x) at (6,2) {$x$};
  3263. \node (y) at (3,0) {$y$};
  3264. \node (w) at (6,0) {$w$};
  3265. \node (v) at (9,0) {$v$};
  3266. \draw (v) to (x);
  3267. \draw (x) to (y);
  3268. \draw (x) to (z);
  3269. \draw (y) to (t);
  3270. \end{tikzpicture}
  3271. \]
  3272. Now we replay the graph coloring, pausing to see the coloring of
  3273. $y$. Recall the following configuration. The most saturated vertices
  3274. were $w$ and $y$.
  3275. \[
  3276. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3277. \node (t1) at (0,2) {$t:0,\{1\}$};
  3278. \node (z) at (3,2) {$z:1,\{0\}$};
  3279. \node (x) at (6,2) {$x:-,\{\}$};
  3280. \node (y) at (3,0) {$y:-,\{1\}$};
  3281. \node (w) at (6,0) {$w:-,\{1\}$};
  3282. \node (v) at (9,0) {$v:-,\{\}$};
  3283. \draw (t1) to (z);
  3284. \draw (z) to (y);
  3285. \draw (z) to (w);
  3286. \draw (x) to (w);
  3287. \draw (y) to (w);
  3288. \draw (v) to (w);
  3289. \end{tikzpicture}
  3290. \]
  3291. %
  3292. Last time we chose to color $w$ with $0$. But this time we note that
  3293. $w$ is not move related to any vertex, and $y$ is move related to $t$.
  3294. So we choose to color $y$ the same color, $0$.
  3295. \[
  3296. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3297. \node (t1) at (0,2) {$t:0,\{1\}$};
  3298. \node (z) at (3,2) {$z:1,\{0\}$};
  3299. \node (x) at (6,2) {$x:-,\{\}$};
  3300. \node (y) at (3,0) {$y:0,\{1\}$};
  3301. \node (w) at (6,0) {$w:-,\{0,1\}$};
  3302. \node (v) at (9,0) {$v:-,\{\}$};
  3303. \draw (t1) to (z);
  3304. \draw (z) to (y);
  3305. \draw (z) to (w);
  3306. \draw (x) to (w);
  3307. \draw (y) to (w);
  3308. \draw (v) to (w);
  3309. \end{tikzpicture}
  3310. \]
  3311. Now $w$ is the most saturated, so we color it $2$.
  3312. \[
  3313. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3314. \node (t1) at (0,2) {$t:0,\{1\}$};
  3315. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3316. \node (x) at (6,2) {$x:-,\{2\}$};
  3317. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3318. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3319. \node (v) at (9,0) {$v:-,\{2\}$};
  3320. \draw (t1) to (z);
  3321. \draw (z) to (y);
  3322. \draw (z) to (w);
  3323. \draw (x) to (w);
  3324. \draw (y) to (w);
  3325. \draw (v) to (w);
  3326. \end{tikzpicture}
  3327. \]
  3328. At this point, vertices $x$ and $v$ are most saturated,
  3329. but $x$ is move related to $y$ and $z$, so we color $x$ to $0$
  3330. to match $y$. Finally, we color $v$ to $0$.
  3331. \[
  3332. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3333. \node (t) at (0,2) {$t:0,\{1\}$};
  3334. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3335. \node (x) at (6,2) {$x:0,\{2\}$};
  3336. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3337. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3338. \node (v) at (9,0) {$v:0,\{2\}$};
  3339. \draw (t) to (z);
  3340. \draw (z) to (y);
  3341. \draw (z) to (w);
  3342. \draw (x) to (w);
  3343. \draw (y) to (w);
  3344. \draw (v) to (w);
  3345. \end{tikzpicture}
  3346. \]
  3347. So we have the following assignment of variables to registers.
  3348. \begin{gather*}
  3349. \{ v \mapsto \key{\%rbx}, \,
  3350. w \mapsto \key{\%rdx}, \,
  3351. x \mapsto \key{\%rbx}, \\
  3352. y \mapsto \key{\%rbx}, \,
  3353. z\mapsto \key{\%rcx},
  3354. t\mapsto \key{\%rbx} \}
  3355. \end{gather*}
  3356. We apply this register assignment to the running example, on the left,
  3357. to obtain the code on right.
  3358. \begin{minipage}{0.3\textwidth}
  3359. \begin{lstlisting}
  3360. movq $1, v
  3361. movq $42, w
  3362. movq v, x
  3363. addq $7, x
  3364. movq x, y
  3365. movq x, z
  3366. addq w, z
  3367. movq y, t
  3368. negq t
  3369. movq z, %rax
  3370. addq t, %rax
  3371. jmp conclusion
  3372. \end{lstlisting}
  3373. \end{minipage}
  3374. $\Rightarrow\qquad$
  3375. \begin{minipage}{0.45\textwidth}
  3376. \begin{lstlisting}
  3377. movq $1, %rbx
  3378. movq $42, %rdx
  3379. movq %rbx, %rbx
  3380. addq $7, %rbx
  3381. movq %rbx, %rbx
  3382. movq %rbx, %rcx
  3383. addq %rdx, %rcx
  3384. movq %rbx, %rbx
  3385. negq %rbx
  3386. movq %rcx, %rax
  3387. addq %rbx, %rax
  3388. jmp conclusion
  3389. \end{lstlisting}
  3390. \end{minipage}
  3391. The \code{patch-instructions} then removes the three trivial moves
  3392. from \key{rbx} to \key{rbx} to obtain the following result.
  3393. \begin{minipage}{0.45\textwidth}
  3394. \begin{lstlisting}
  3395. movq $1, %rbx
  3396. movq $42, %rdx
  3397. addq $7, %rbx
  3398. movq %rbx, %rcx
  3399. addq %rdx, %rcx
  3400. negq %rbx
  3401. movq %rcx, %rax
  3402. addq %rbx, %rax
  3403. jmp conclusion
  3404. \end{lstlisting}
  3405. \end{minipage}
  3406. \begin{exercise}\normalfont
  3407. Change your implementation of \code{allocate-registers} to take move
  3408. biasing into account. Make sure that your compiler still passes all of
  3409. the previous tests. Create two new tests that include at least one
  3410. opportunity for move biasing and visually inspect the output x86
  3411. programs to make sure that your move biasing is working properly.
  3412. \end{exercise}
  3413. \margincomment{\footnotesize To do: another neat challenge would be to do
  3414. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3415. \section{Output of the Running Example}
  3416. \label{sec:reg-alloc-output}
  3417. \index{prelude}\index{conclusion}
  3418. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3419. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3420. and move biasing. To demonstrate both the use of registers and the
  3421. stack, we have limited the register allocator to use just two
  3422. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3423. \code{main} function, we push \code{rbx} onto the stack because it is
  3424. a callee-saved register and it was assigned to variable by the
  3425. register allocator. We substract \code{8} from the \code{rsp} at the
  3426. end of the prelude to reserve space for the one spilled variable.
  3427. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3428. Moving on the the \code{start} block, we see how the registers were
  3429. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3430. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3431. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3432. that the prelude saved the callee-save register \code{rbx} onto the
  3433. stack. The spilled variables must be placed lower on the stack than
  3434. the saved callee-save registers, so in this case \code{w} is placed at
  3435. \code{-16(\%rbp)}.
  3436. In the \code{conclusion}, we undo the work that was done in the
  3437. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3438. spilled variables), then we pop the old values of \code{rbx} and
  3439. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3440. return control to the operating system.
  3441. \begin{figure}[tbp]
  3442. % s0_28.rkt
  3443. % (use-minimal-set-of-registers! #t)
  3444. % and only rbx rcx
  3445. % tmp 0 rbx
  3446. % z 1 rcx
  3447. % y 0 rbx
  3448. % w 2 16(%rbp)
  3449. % v 0 rbx
  3450. % x 0 rbx
  3451. \begin{lstlisting}
  3452. start:
  3453. movq $1, %rbx
  3454. movq $42, -16(%rbp)
  3455. addq $7, %rbx
  3456. movq %rbx, %rcx
  3457. addq -16(%rbp), %rcx
  3458. negq %rbx
  3459. movq %rcx, %rax
  3460. addq %rbx, %rax
  3461. jmp conclusion
  3462. .globl main
  3463. main:
  3464. pushq %rbp
  3465. movq %rsp, %rbp
  3466. pushq %rbx
  3467. subq $8, %rsp
  3468. jmp start
  3469. conclusion:
  3470. addq $8, %rsp
  3471. popq %rbx
  3472. popq %rbp
  3473. retq
  3474. \end{lstlisting}
  3475. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3476. \label{fig:running-example-x86}
  3477. \end{figure}
  3478. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3479. \chapter{Booleans and Control Flow}
  3480. \label{ch:bool-types}
  3481. \index{Boolean}
  3482. \index{control flow}
  3483. \index{conditional expression}
  3484. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3485. integers. In this chapter we add a second kind of value, the Booleans,
  3486. to create the $R_2$ language. The Boolean values \emph{true} and
  3487. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3488. Racket. The $R_2$ language includes several operations that involve
  3489. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3490. conditional \key{if} expression. With the addition of \key{if}
  3491. expressions, programs can have non-trivial control flow which which
  3492. significantly impacts the \code{explicate-control} and the liveness
  3493. analysis for register allocation. Also, because we now have two kinds
  3494. of values, we need to handle programs that apply an operation to the
  3495. wrong kind of value, such as \code{(not 1)}.
  3496. There are two language design options for such situations. One option
  3497. is to signal an error and the other is to provide a wider
  3498. interpretation of the operation. The Racket language uses a mixture of
  3499. these two options, depending on the operation and the kind of
  3500. value. For example, the result of \code{(not 1)} in Racket is
  3501. \code{\#f} because Racket treats non-zero integers as if they were
  3502. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3503. error in Racket stating that \code{car} expects a pair.
  3504. The Typed Racket language makes similar design choices as Racket,
  3505. except much of the error detection happens at compile time instead of
  3506. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3507. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3508. reports a compile-time error because Typed Racket expects the type of
  3509. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3510. For the $R_2$ language we choose to be more like Typed Racket in that
  3511. we shall perform type checking during compilation. In
  3512. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3513. is, how to compile a dynamically typed language like Racket. The
  3514. $R_2$ language is a subset of Typed Racket but by no means includes
  3515. all of Typed Racket. For many operations we take a narrower
  3516. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3517. This chapter is organized as follows. We begin by defining the syntax
  3518. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3519. then introduce the idea of type checking and build a type checker for
  3520. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3521. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3522. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3523. how our compiler passes need to change to accommodate Booleans and
  3524. conditional control flow.
  3525. \section{The $R_2$ Language}
  3526. \label{sec:r2-lang}
  3527. The concrete syntax of the $R_2$ language is defined in
  3528. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3529. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3530. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3531. and the conditional \code{if} expression. Also, we expand the
  3532. operators to include
  3533. \begin{enumerate}
  3534. \item subtraction on integers,
  3535. \item the logical operators \key{and}, \key{or} and \key{not},
  3536. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3537. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3538. comparing integers.
  3539. \end{enumerate}
  3540. \begin{figure}[tp]
  3541. \centering
  3542. \fbox{
  3543. \begin{minipage}{0.96\textwidth}
  3544. \[
  3545. \begin{array}{lcl}
  3546. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3547. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3548. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3549. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3550. &\mid& \itm{bool}
  3551. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3552. \mid (\key{not}\;\Exp) \\
  3553. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3554. R_2 &::=& \Exp
  3555. \end{array}
  3556. \]
  3557. \end{minipage}
  3558. }
  3559. \caption{The concrete syntax of $R_2$, extending $R_1$
  3560. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3561. \label{fig:r2-concrete-syntax}
  3562. \end{figure}
  3563. \begin{figure}[tp]
  3564. \centering
  3565. \fbox{
  3566. \begin{minipage}{0.96\textwidth}
  3567. \[
  3568. \begin{array}{lcl}
  3569. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3570. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3571. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3572. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3573. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3574. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3575. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3576. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3577. &\mid& \BINOP{\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3578. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3579. \end{array}
  3580. \]
  3581. \end{minipage}
  3582. }
  3583. \caption{The abstract syntax of $R_2$.}
  3584. \label{fig:r2-syntax}
  3585. \end{figure}
  3586. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3587. the parts that are the same as the interpreter for $R_1$
  3588. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3589. evaluate to the corresponding Boolean values. The conditional
  3590. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3591. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3592. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3593. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3594. you might expect, but note that the \code{and} operation is
  3595. short-circuiting. That is, given the expression
  3596. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3597. $e_1$ evaluates to \code{\#f}.
  3598. With the addition of the comparison operations, there are quite a few
  3599. primitive operations and the interpreter code for them could become
  3600. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3601. out the different parts of the code for primitive operations into the
  3602. \code{interp-op} function and the similar parts of the code into the
  3603. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3604. do not use \code{interp-op} for the \code{and} operation because of
  3605. the short-circuiting behavior in the order of evaluation of its
  3606. arguments.
  3607. \begin{figure}[tbp]
  3608. \begin{lstlisting}
  3609. (define (interp-op op)
  3610. (match op
  3611. ...
  3612. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3613. ['eq? (lambda (v1 v2)
  3614. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3615. (and (boolean? v1) (boolean? v2)))
  3616. (eq? v1 v2)]))]
  3617. ['< (lambda (v1 v2)
  3618. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3619. ['<= (lambda (v1 v2)
  3620. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3621. ['> (lambda (v1 v2)
  3622. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3623. ['>= (lambda (v1 v2)
  3624. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3625. [else (error 'interp-op "unknown operator")]))
  3626. (define (interp-exp env)
  3627. (lambda (e)
  3628. (define recur (interp-exp env))
  3629. (match e
  3630. ...
  3631. [(Bool b) b]
  3632. [(If cnd thn els)
  3633. (define b (recur cnd))
  3634. (match b
  3635. [#t (recur thn)]
  3636. [#f (recur els)])]
  3637. [(Prim 'and (list e1 e2))
  3638. (define v1 (recur e1))
  3639. (match v1
  3640. [#t (match (recur e2) [#t #t] [#f #f])]
  3641. [#f #f])]
  3642. [(Prim op args)
  3643. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3644. )))
  3645. (define (interp-R2 p)
  3646. (match p
  3647. [(Program info e)
  3648. ((interp-exp '()) e)]
  3649. ))
  3650. \end{lstlisting}
  3651. \caption{Interpreter for the $R_2$ language.}
  3652. \label{fig:interp-R2}
  3653. \end{figure}
  3654. \section{Type Checking $R_2$ Programs}
  3655. \label{sec:type-check-r2}
  3656. It is helpful to think about type checking in two complementary
  3657. ways. A type checker predicts the type of value that will be produced
  3658. by each expression in the program. For $R_2$, we have just two types,
  3659. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3660. \begin{lstlisting}
  3661. (+ 10 (- (+ 12 20)))
  3662. \end{lstlisting}
  3663. produces an \key{Integer} while
  3664. \begin{lstlisting}
  3665. (and (not #f) #t)
  3666. \end{lstlisting}
  3667. produces a \key{Boolean}.
  3668. Another way to think about type checking is that it enforces a set of
  3669. rules about which operators can be applied to which kinds of
  3670. values. For example, our type checker for $R_2$ will signal an error
  3671. for the below expression because, as we have seen above, the
  3672. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3673. checker enforces the rule that the argument of \code{not} must be a
  3674. \key{Boolean}.
  3675. \begin{lstlisting}
  3676. (not (+ 10 (- (+ 12 20))))
  3677. \end{lstlisting}
  3678. The type checker for $R_2$ is a structurally recursive function over
  3679. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3680. the \code{type-check-exp} function. Given an input expression
  3681. \code{e}, the type checker either returns a type (\key{Integer} or
  3682. \key{Boolean}) or it signals an error. The type of an integer literal
  3683. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3684. To handle variables, the type checker uses an environment that maps
  3685. variables to types. Consider the clause for \key{let}. We type check
  3686. the initializing expression to obtain its type \key{T} and then
  3687. associate type \code{T} with the variable \code{x} in the
  3688. environment. When the type checker encounters a use of variable
  3689. \code{x} in the body of the \key{let}, it can find its type in the
  3690. environment.
  3691. \begin{figure}[tbp]
  3692. \begin{lstlisting}
  3693. (define (type-check-exp env)
  3694. (lambda (e)
  3695. (match e
  3696. [(Var x) (dict-ref env x)]
  3697. [(Int n) 'Integer]
  3698. [(Bool b) 'Boolean]
  3699. [(Let x e body)
  3700. (define Te ((type-check-exp env) e))
  3701. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3702. Tb]
  3703. ...
  3704. [else
  3705. (error "type-check-exp couldn't match" e)])))
  3706. (define (type-check env)
  3707. (lambda (e)
  3708. (match e
  3709. [(Program info body)
  3710. (define Tb ((type-check-exp '()) body))
  3711. (unless (equal? Tb 'Integer)
  3712. (error "result of the program must be an integer, not " Tb))
  3713. (Program info body)]
  3714. )))
  3715. \end{lstlisting}
  3716. \caption{Skeleton of a type checker for the $R_2$ language.}
  3717. \label{fig:type-check-R2}
  3718. \end{figure}
  3719. \begin{exercise}\normalfont
  3720. Complete the implementation of \code{type-check}. Test your type
  3721. checker using \code{interp-tests} and \code{compiler-tests} by passing
  3722. the \code{type-check} function as the second argument. Create 10 new
  3723. example programs in $R_2$ that you choose based on how thoroughly they
  3724. test you type checking function. Half of the example programs should
  3725. have a type error to make sure that your type checker properly rejects
  3726. them. For those programs, to signal that a type error is expected,
  3727. create an empty file with the same base name but with file extension
  3728. \code{.tyerr}. For example, if the test \code{r2\_14.rkt} is expected
  3729. to error, then create an empty file named \code{r2\_14.tyerr}. The
  3730. other half of the example programs should not have type errors. Note
  3731. that if your type checker does not signal an error for a program, then
  3732. interpreting that program should not encounter an error. If it does,
  3733. there is something wrong with your type checker.
  3734. \end{exercise}
  3735. \section{Shrink the $R_2$ Language}
  3736. \label{sec:shrink-r2}
  3737. The $R_2$ language includes several operators that are easily
  3738. expressible in terms of other operators. For example, subtraction is
  3739. expressible in terms of addition and negation.
  3740. \[
  3741. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3742. \]
  3743. Several of the comparison operations are expressible in terms of
  3744. less-than and logical negation.
  3745. \[
  3746. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3747. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3748. \]
  3749. The \key{let} is needed in the above translation to ensure that
  3750. expression $e_1$ is evaluated before $e_2$.
  3751. By performing these translations near the front-end of the compiler,
  3752. the later passes of the compiler do not need to deal with these
  3753. constructs, making those passes shorter. On the other hand, sometimes
  3754. these translations make it more difficult to generate the most
  3755. efficient code with respect to the number of instructions. However,
  3756. these differences typically do not affect the number of accesses to
  3757. memory, which is the primary factor that determines execution time on
  3758. modern computer architectures.
  3759. \begin{exercise}\normalfont
  3760. Implement the pass \code{shrink} that removes subtraction,
  3761. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3762. by translating them to other constructs in $R_2$. Create tests to
  3763. make sure that the behavior of all of these constructs stays the
  3764. same after translation.
  3765. \end{exercise}
  3766. \section{The x86$_1$ Language}
  3767. \label{sec:x86-1}
  3768. \index{x86}
  3769. To implement the new logical operations, the comparison operations,
  3770. and the \key{if} expression, we need to delve further into the x86
  3771. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3772. the concrete and abstract syntax for a larger subset of x86 that
  3773. includes instructions for logical operations, comparisons, and
  3774. conditional jumps.
  3775. One small challenge is that x86 does not provide an instruction that
  3776. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3777. However, the \code{xorq} instruction can be used to encode \code{not}.
  3778. The \key{xorq} instruction takes two arguments, performs a pairwise
  3779. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3780. and writes the results into its second argument. Recall the truth
  3781. table for exclusive-or:
  3782. \begin{center}
  3783. \begin{tabular}{l|cc}
  3784. & 0 & 1 \\ \hline
  3785. 0 & 0 & 1 \\
  3786. 1 & 1 & 0
  3787. \end{tabular}
  3788. \end{center}
  3789. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3790. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3791. for the bit $1$, the result is the opposite of the second bit. Thus,
  3792. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3793. the first argument:
  3794. \[
  3795. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3796. \qquad\Rightarrow\qquad
  3797. \begin{array}{l}
  3798. \key{movq}~ \Arg\key{,} \Var\\
  3799. \key{xorq}~ \key{\$1,} \Var
  3800. \end{array}
  3801. \]
  3802. \begin{figure}[tp]
  3803. \fbox{
  3804. \begin{minipage}{0.96\textwidth}
  3805. \[
  3806. \begin{array}{lcl}
  3807. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3808. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3809. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3810. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3811. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3812. \key{subq} \; \Arg\key{,} \Arg \mid
  3813. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3814. && \gray{ \key{callq} \; \itm{label} \mid
  3815. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3816. && \gray{ \itm{label}\key{:}\; \Instr }
  3817. \mid \key{xorq}~\Arg\key{,}~\Arg
  3818. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3819. && \key{set}cc~\Arg
  3820. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3821. \mid \key{j}cc~\itm{label}
  3822. \\
  3823. x86_1 &::= & \gray{ \key{.globl main} }\\
  3824. & & \gray{ \key{main:} \; \Instr\ldots }
  3825. \end{array}
  3826. \]
  3827. \end{minipage}
  3828. }
  3829. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3830. \label{fig:x86-1-concrete}
  3831. \end{figure}
  3832. \begin{figure}[tp]
  3833. \fbox{
  3834. \begin{minipage}{0.96\textwidth}
  3835. \small
  3836. \[
  3837. \begin{array}{lcl}
  3838. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3839. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3840. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3841. \mid \BYTEREG{\itm{bytereg}} \\
  3842. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3843. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3844. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3845. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3846. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3847. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3848. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3849. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3850. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3851. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3852. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3853. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3854. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3855. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3856. \end{array}
  3857. \]
  3858. \end{minipage}
  3859. }
  3860. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3861. \label{fig:x86-1}
  3862. \end{figure}
  3863. Next we consider the x86 instructions that are relevant for compiling
  3864. the comparison operations. The \key{cmpq} instruction compares its two
  3865. arguments to determine whether one argument is less than, equal, or
  3866. greater than the other argument. The \key{cmpq} instruction is unusual
  3867. regarding the order of its arguments and where the result is
  3868. placed. The argument order is backwards: if you want to test whether
  3869. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3870. \key{cmpq} is placed in the special EFLAGS register. This register
  3871. cannot be accessed directly but it can be queried by a number of
  3872. instructions, including the \key{set} instruction. The \key{set}
  3873. instruction puts a \key{1} or \key{0} into its destination depending
  3874. on whether the comparison came out according to the condition code
  3875. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3876. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3877. The \key{set} instruction has an annoying quirk in that its
  3878. destination argument must be single byte register, such as \code{al}
  3879. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  3880. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  3881. then be used to move from a single byte register to a normal 64-bit
  3882. register.
  3883. The x86 instruction for conditional jump are relevant to the
  3884. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3885. updates the program counter to point to the instruction after the
  3886. indicated label depending on whether the result in the EFLAGS register
  3887. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3888. instruction falls through to the next instruction. The abstract
  3889. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3890. that it separates the instruction name from the condition code. For
  3891. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3892. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3893. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3894. instruction to set the EFLAGS register.
  3895. \section{The $C_1$ Intermediate Language}
  3896. \label{sec:c1}
  3897. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3898. we need to grow that intermediate language to handle the new features
  3899. in $R_2$: Booleans and conditional expressions.
  3900. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3901. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3902. particular, we add logical and comparison operators to the $\Exp$
  3903. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3904. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3905. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3906. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3907. sequence of statements may now end with a \code{goto} or a conditional
  3908. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3909. depending on the outcome of the comparison. In
  3910. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3911. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3912. and \key{goto}'s.
  3913. \begin{figure}[tbp]
  3914. \fbox{
  3915. \begin{minipage}{0.96\textwidth}
  3916. \small
  3917. \[
  3918. \begin{array}{lcl}
  3919. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3920. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3921. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3922. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3923. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3924. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3925. \mid \key{goto}~\itm{label}\key{;}\\
  3926. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3927. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  3928. \end{array}
  3929. \]
  3930. \end{minipage}
  3931. }
  3932. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3933. \label{fig:c1-concrete-syntax}
  3934. \end{figure}
  3935. \begin{figure}[tp]
  3936. \fbox{
  3937. \begin{minipage}{0.96\textwidth}
  3938. \small
  3939. \[
  3940. \begin{array}{lcl}
  3941. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3942. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3943. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3944. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3945. &\mid& \UNIOP{\key{'not}}{\Atm}
  3946. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3947. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3948. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3949. \mid \GOTO{\itm{label}} \\
  3950. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3951. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  3952. \end{array}
  3953. \]
  3954. \end{minipage}
  3955. }
  3956. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  3957. (Figure~\ref{fig:c0-syntax}).}
  3958. \label{fig:c1-syntax}
  3959. \end{figure}
  3960. \clearpage
  3961. \section{Remove Complex Operands}
  3962. \label{sec:remove-complex-opera-R2}
  3963. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  3964. \code{rco-atom} functions according to the definition of the output
  3965. language for this pass, $R_2^{\dagger}$, the administrative normal
  3966. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  3967. \code{Bool} form is an atomic expressions but \code{If} is not. All
  3968. three sub-expressions of an \code{If} are allowed to be complex
  3969. expressions in the output of \code{remove-complex-opera*}, but the
  3970. operands of \code{not} and the comparisons must be atoms. Regarding
  3971. the \code{If} form, it is particularly important to \textbf{not}
  3972. replace its condition with a temporary variable because that would
  3973. interfere with the generation of high-quality output in the
  3974. \code{explicate-control} pass.
  3975. \begin{figure}[tp]
  3976. \centering
  3977. \fbox{
  3978. \begin{minipage}{0.96\textwidth}
  3979. \[
  3980. \begin{array}{rcl}
  3981. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  3982. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  3983. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3984. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  3985. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  3986. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3987. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3988. \end{array}
  3989. \]
  3990. \end{minipage}
  3991. }
  3992. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  3993. \label{fig:r2-anf-syntax}
  3994. \end{figure}
  3995. \section{Explicate Control}
  3996. \label{sec:explicate-control-r2}
  3997. Recall that the purpose of \code{explicate-control} is to make the
  3998. order of evaluation explicit in the syntax of the program. With the
  3999. addition of \key{if} in $R_2$ this get more interesting.
  4000. As a motivating example, consider the following program that has an
  4001. \key{if} expression nested in the predicate of another \key{if}.
  4002. % s1_41.rkt
  4003. \begin{center}
  4004. \begin{minipage}{0.96\textwidth}
  4005. \begin{lstlisting}
  4006. (let ([x (read)])
  4007. (let ([y (read)])
  4008. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4009. (+ y 2)
  4010. (+ y 10))))
  4011. \end{lstlisting}
  4012. \end{minipage}
  4013. \end{center}
  4014. %
  4015. The naive way to compile \key{if} and the comparison would be to
  4016. handle each of them in isolation, regardless of their context. Each
  4017. comparison would be translated into a \key{cmpq} instruction followed
  4018. by a couple instructions to move the result from the EFLAGS register
  4019. into a general purpose register or stack location. Each \key{if} would
  4020. be translated into the combination of a \key{cmpq} and a conditional
  4021. jump. The generated code for the inner \key{if} in the above example
  4022. would be as follows.
  4023. \begin{center}
  4024. \begin{minipage}{0.96\textwidth}
  4025. \begin{lstlisting}
  4026. ...
  4027. cmpq $1, x ;; (< x 1)
  4028. setl %al
  4029. movzbq %al, tmp
  4030. cmpq $1, tmp ;; (if (< x 1) ...)
  4031. je then_branch_1
  4032. jmp else_branch_1
  4033. ...
  4034. \end{lstlisting}
  4035. \end{minipage}
  4036. \end{center}
  4037. However, if we take context into account we can do better and reduce
  4038. the use of \key{cmpq} and EFLAG-accessing instructions.
  4039. One idea is to try and reorganize the code at the level of $R_2$,
  4040. pushing the outer \key{if} inside the inner one. This would yield the
  4041. following code.
  4042. \begin{center}
  4043. \begin{minipage}{0.96\textwidth}
  4044. \begin{lstlisting}
  4045. (let ([x (read)])
  4046. (let ([y (read)])
  4047. (if (< x 1)
  4048. (if (eq? x 0)
  4049. (+ y 2)
  4050. (+ y 10))
  4051. (if (eq? x 2)
  4052. (+ y 2)
  4053. (+ y 10)))))
  4054. \end{lstlisting}
  4055. \end{minipage}
  4056. \end{center}
  4057. Unfortunately, this approach duplicates the two branches, and a
  4058. compiler must never duplicate code!
  4059. We need a way to perform the above transformation, but without
  4060. duplicating code. The solution is straightforward if we think at the
  4061. level of x86 assembly: we can label the code for each of the branches
  4062. and insert jumps in all the places that need to execute the
  4063. branches. Put another way, we need to move away from abstract syntax
  4064. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  4065. use a standard program representation called a \emph{control flow
  4066. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4067. \index{control-flow graph}
  4068. Each vertex is a labeled sequence of code, called a \emph{basic block}, and
  4069. each edge represents a jump to another block. The \key{Program}
  4070. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4071. as an alist mapping labels to basic blocks. Each basic block is
  4072. represented by the $\Tail$ non-terminal.
  4073. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4074. \code{remove-complex-opera*} pass and then the
  4075. \code{explicate-control} pass on the example program. We walk through
  4076. the output program and then discuss the algorithm.
  4077. %
  4078. Following the order of evaluation in the output of
  4079. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4080. and then the less-than-comparison to \code{1} in the predicate of the
  4081. inner \key{if}. In the output of \code{explicate-control}, in the
  4082. block labeled \code{start}, this becomes two assignment statements
  4083. followed by a conditional \key{goto} to label \code{block96} or
  4084. \code{block97}. The blocks associated with those labels contain the
  4085. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4086. respectively. Regarding the block labeled with \code{block96}, we
  4087. start with the comparison to \code{0} and then have a conditional
  4088. goto, either to label \code{block92} or label \code{block93}, which
  4089. indirectly take us to labels \code{block90} and \code{block91}, the
  4090. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4091. y 10)}. The story for the block labeled \code{block97} is similar.
  4092. \begin{figure}[tbp]
  4093. \begin{tabular}{lll}
  4094. \begin{minipage}{0.4\textwidth}
  4095. % s1_41.rkt
  4096. \begin{lstlisting}
  4097. (let ([x (read)])
  4098. (let ([y (read)])
  4099. (if (if (< x 1)
  4100. (eq? x 0)
  4101. (eq? x 2))
  4102. (+ y 2)
  4103. (+ y 10))))
  4104. \end{lstlisting}
  4105. \hspace{40pt}$\Downarrow$
  4106. \begin{lstlisting}
  4107. (let ([x (read)])
  4108. (let ([y (read)])
  4109. (if (if (< x 1)
  4110. (eq? x 0)
  4111. (eq? x 2))
  4112. (+ y 2)
  4113. (+ y 10))))
  4114. \end{lstlisting}
  4115. \end{minipage}
  4116. &
  4117. $\Rightarrow$
  4118. &
  4119. \begin{minipage}{0.55\textwidth}
  4120. \begin{lstlisting}
  4121. start:
  4122. x = (read);
  4123. y = (read);
  4124. if (< x 1)
  4125. goto block96;
  4126. else
  4127. goto block97;
  4128. block96:
  4129. if (eq? x 0)
  4130. goto block92;
  4131. else
  4132. goto block93;
  4133. block97:
  4134. if (eq? x 2)
  4135. goto block94;
  4136. else
  4137. goto block95;
  4138. block92:
  4139. goto block90;
  4140. block93:
  4141. goto block91;
  4142. block94:
  4143. goto block90;
  4144. block95:
  4145. goto block91;
  4146. block90:
  4147. return (+ y 2);
  4148. block91:
  4149. return (+ y 10);
  4150. \end{lstlisting}
  4151. \end{minipage}
  4152. \end{tabular}
  4153. \caption{Example translation from $R_2$ to $C_1$
  4154. via the \code{explicate-control}.}
  4155. \label{fig:explicate-control-s1-38}
  4156. \end{figure}
  4157. The nice thing about the output of \code{explicate-control} is that
  4158. there are no unnecessary comparisons and every comparison is part of a
  4159. conditional jump. The down-side of this output is that it includes
  4160. trivial blocks, such as the blocks labeled \code{block92} through
  4161. \code{block95}, that only jump to another block. We discuss a solution
  4162. to this problem in Section~\ref{sec:opt-jumps}.
  4163. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4164. \code{explicate-control} for $R_1$ using two mutually recursive
  4165. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4166. former function translates expressions in tail position whereas the
  4167. later function translates expressions on the right-hand-side of a
  4168. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4169. new kind of context to deal with: the predicate position of the
  4170. \key{if}. We need another function, \code{explicate-pred}, that takes
  4171. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4172. the then-branch and else-branch. The output of \code{explicate-pred}
  4173. is a block and a list of formerly \key{let}-bound variables.
  4174. Note that the three explicate functions need to construct a
  4175. control-flow graph, which we recommend they do via updates to a global
  4176. variable.
  4177. In the following paragraphs we consider the specific additions to the
  4178. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4179. of cases for the \code{explicate-pred} function.
  4180. The \code{explicate-tail} function needs an additional case for
  4181. \key{if}. The branches of the \key{if} inherit the current context, so
  4182. they are in tail position. Let $B_1$ be the result of
  4183. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4184. is a $\Tail$ AST node. Let $B_2$ be the result of apply
  4185. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4186. the $\Tail$ that results fromapplying \code{explicate-pred} to the
  4187. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4188. \key{if} as a whole translates to block $B_3$.
  4189. \[
  4190. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4191. \]
  4192. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4193. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4194. should not be confused with the labels for the blocks that appear in
  4195. the generated code. We initially construct unlabeled blocks; we only
  4196. attach labels to blocks when we add them to the control-flow graph, as
  4197. we shall see in the next case.
  4198. Next consider the case for \key{if} in the \code{explicate-assign}
  4199. function. The context of the \key{if} is an assignment to some
  4200. variable $x$ and then the control continues to some block $B_1$. The
  4201. code that we generate for both the ``then'' and ``else'' branches
  4202. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4203. add it to the control flow graph with a fresh label $\ell_1$. The
  4204. branches of the \key{if} inherit the current context, so that are in
  4205. assignment positions. Let $B_2$ be the result of applying
  4206. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4207. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4208. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4209. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4210. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4211. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4212. $B_4$.
  4213. \[
  4214. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4215. \]
  4216. The function \code{explicate-pred} will need a case for every
  4217. expression that can have type \code{Boolean}. We detail a few cases
  4218. here and leave the rest for the reader. The input to this function is
  4219. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4220. the enclosing \key{if}. Suppose the expression is the Boolean
  4221. \code{\#t}. Then we can perform a kind of partial evaluation and
  4222. translate it to the ``then'' branch $B_1$. Likewise, we translate
  4223. \code{\#f} to the ``else`` branch $B_2$.
  4224. \[
  4225. \key{\#t} \quad\Rightarrow\quad B_1,
  4226. \qquad\qquad\qquad
  4227. \key{\#f} \quad\Rightarrow\quad B_2
  4228. \]
  4229. Next, suppose the expression is a less-than comparison. We translate
  4230. it to a conditional \code{goto}. We need labels for the two branches
  4231. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4232. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4233. less-than comparison is as follows.
  4234. \[
  4235. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4236. \begin{array}{l}
  4237. \key{if}~(\key{<}~e_1~e_2) \\
  4238. \qquad\key{goto}~\ell_1\key{;}\\
  4239. \key{else}\\
  4240. \qquad\key{goto}~\ell_2\key{;}
  4241. \end{array}
  4242. \]
  4243. The case for \key{if} in \code{explicate-pred} is particularly
  4244. illuminating as it deals with the challenges that we discussed above
  4245. regarding the example of the nested \key{if} expressions. Again, we
  4246. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4247. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4248. branches of the current \key{if} inherit their context from the
  4249. current one, that is, predicate context. So we apply
  4250. \code{explicate-pred} to the ``then'' branch with the two blocks
  4251. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4252. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4253. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4254. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4255. \[
  4256. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4257. \quad\Rightarrow\quad
  4258. B_5
  4259. \]
  4260. \begin{exercise}\normalfont
  4261. Implement the pass \code{explicate-control} by adding the cases for
  4262. \key{if} to the functions for tail and assignment contexts, and
  4263. implement \code{explicate-pred} for predicate contexts. Create test
  4264. cases that exercise all of the new cases in the code for this pass.
  4265. \end{exercise}
  4266. \section{Select Instructions}
  4267. \label{sec:select-r2}
  4268. \index{instruction selection}
  4269. Recall that the \code{select-instructions} pass lowers from our
  4270. $C$-like intermediate representation to the pseudo-x86 language, which
  4271. is suitable for conducting register allocation. The pass is
  4272. implemented using three auxiliary functions, one for each of the
  4273. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4274. For $\Atm$, we have new cases for the Booleans. We take the usual
  4275. approach of encoding them as integers, with true as 1 and false as 0.
  4276. \[
  4277. \key{\#t} \Rightarrow \key{1}
  4278. \qquad
  4279. \key{\#f} \Rightarrow \key{0}
  4280. \]
  4281. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4282. be implemented in terms of \code{xorq} as we discussed at the
  4283. beginning of this section. Given an assignment
  4284. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4285. if the left-hand side $\itm{var}$ is
  4286. the same as $\Atm$, then just the \code{xorq} suffices.
  4287. \[
  4288. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4289. \quad\Rightarrow\quad
  4290. \key{xorq}~\key{\$}1\key{,}~\Var
  4291. \]
  4292. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4293. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4294. x86. Then we have
  4295. \[
  4296. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4297. \quad\Rightarrow\quad
  4298. \begin{array}{l}
  4299. \key{movq}~\Arg\key{,}~\Var\\
  4300. \key{xorq}~\key{\$}1\key{,}~\Var
  4301. \end{array}
  4302. \]
  4303. Next consider the cases for \code{eq?} and less-than comparison.
  4304. Translating these operations to x86 is slightly involved due to the
  4305. unusual nature of the \key{cmpq} instruction discussed above. We
  4306. recommend translating an assignment from \code{eq?} into the following
  4307. sequence of three instructions. \\
  4308. \begin{tabular}{lll}
  4309. \begin{minipage}{0.4\textwidth}
  4310. \begin{lstlisting}
  4311. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4312. \end{lstlisting}
  4313. \end{minipage}
  4314. &
  4315. $\Rightarrow$
  4316. &
  4317. \begin{minipage}{0.4\textwidth}
  4318. \begin{lstlisting}
  4319. cmpq |$\Arg_2$|, |$\Arg_1$|
  4320. sete %al
  4321. movzbq %al, |$\Var$|
  4322. \end{lstlisting}
  4323. \end{minipage}
  4324. \end{tabular} \\
  4325. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4326. and conditional \key{goto}. Both are straightforward to handle. A
  4327. \key{goto} becomes a jump instruction.
  4328. \[
  4329. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4330. \]
  4331. A conditional \key{goto} becomes a compare instruction followed
  4332. by a conditional jump (for ``then'') and the fall-through is
  4333. to a regular jump (for ``else'').\\
  4334. \begin{tabular}{lll}
  4335. \begin{minipage}{0.4\textwidth}
  4336. \begin{lstlisting}
  4337. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4338. goto |$\ell_1$|;
  4339. else
  4340. goto |$\ell_2$|;
  4341. \end{lstlisting}
  4342. \end{minipage}
  4343. &
  4344. $\Rightarrow$
  4345. &
  4346. \begin{minipage}{0.4\textwidth}
  4347. \begin{lstlisting}
  4348. cmpq |$\Arg_2$|, |$\Arg_1$|
  4349. je |$\ell_1$|
  4350. jmp |$\ell_2$|
  4351. \end{lstlisting}
  4352. \end{minipage}
  4353. \end{tabular} \\
  4354. \begin{exercise}\normalfont
  4355. Expand your \code{select-instructions} pass to handle the new features
  4356. of the $R_2$ language. Test the pass on all the examples you have
  4357. created and make sure that you have some test programs that use the
  4358. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4359. the output using the \code{interp-x86} interpreter
  4360. (Appendix~\ref{appendix:interp}).
  4361. \end{exercise}
  4362. \section{Register Allocation}
  4363. \label{sec:register-allocation-r2}
  4364. \index{register allocation}
  4365. The changes required for $R_2$ affect liveness analysis, building the
  4366. interference graph, and assigning homes, but the graph coloring
  4367. algorithm itself does not change.
  4368. \subsection{Liveness Analysis}
  4369. \label{sec:liveness-analysis-r2}
  4370. Recall that for $R_1$ we implemented liveness analysis for a single
  4371. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4372. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4373. produces many basic blocks arranged in a control-flow graph. The first
  4374. question we need to consider is: what order should we process the
  4375. basic blocks? Recall that to perform liveness analysis, we need to
  4376. know the live-after set. If a basic block has no successor blocks
  4377. (i.e. no out-edges in the control flow graph), then it has an empty
  4378. live-after set and we can immediately apply liveness analysis to
  4379. it. If a basic block has some successors, then we need to complete
  4380. liveness analysis on those blocks first. Furthermore, we know that
  4381. the control flow graph does not contain any cycles because $R_2$ does
  4382. not include loops
  4383. %
  4384. \footnote{If we were to add loops to the language, then the CFG could
  4385. contain cycles and we would instead need to use the classic worklist
  4386. algorithm for computing the fixed point of the liveness
  4387. analysis~\citep{Aho:1986qf}.}.
  4388. %
  4389. Returning to the question of what order should we process the basic
  4390. blocks, the answer is reverse topological order. We recommend using
  4391. the \code{tsort} (topological sort) and \code{transpose} functions of
  4392. the Racket \code{graph} package to obtain this ordering.
  4393. \index{topological order}
  4394. \index{topological sort}
  4395. The next question is how to compute the live-after set of a block
  4396. given the live-before sets of all its successor blocks. (There can be
  4397. more than one because of conditional jumps.) During compilation we do
  4398. not know which way a conditional jump will go, so we do not know which
  4399. of the successor's live-before set to use. The solution to this
  4400. challenge is based on the observation that there is no harm to the
  4401. correctness of the compiler if we classify more variables as live than
  4402. the ones that are truly live during a particular execution of the
  4403. block. Thus, we can take the union of the live-before sets from all
  4404. the successors to be the live-after set for the block. Once we have
  4405. computed the live-after set, we can proceed to perform liveness
  4406. analysis on the block just as we did in
  4407. Section~\ref{sec:liveness-analysis-r1}.
  4408. The helper functions for computing the variables in an instruction's
  4409. argument and for computing the variables read-from ($R$) or written-to
  4410. ($W$) by an instruction need to be updated to handle the new kinds of
  4411. arguments and instructions in x86$_1$.
  4412. \subsection{Build Interference}
  4413. \label{sec:build-interference-r2}
  4414. Many of the new instructions in x86$_1$ can be handled in the same way
  4415. as the instructions in x86$_0$. Thus, if your code was already quite
  4416. general, it will not need to be changed to handle the new
  4417. instructions. If you code is not general enough, I recommend that you
  4418. change your code to be more general. For example, you can factor out
  4419. the computing of the the read and write sets for each kind of
  4420. instruction into two auxiliary functions.
  4421. Note that the \key{movzbq} instruction requires some special care,
  4422. just like the \key{movq} instruction. See rule number 3 in
  4423. Section~\ref{sec:build-interference}.
  4424. %% \subsection{Assign Homes}
  4425. %% \label{sec:assign-homes-r2}
  4426. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4427. %% to be updated to handle the \key{if} statement, simply by recursively
  4428. %% processing the child nodes. Hopefully your code already handles the
  4429. %% other new instructions, but if not, you can generalize your code.
  4430. \begin{exercise}\normalfont
  4431. Update the \code{register-allocation} pass so that it works for $R_2$
  4432. and test your compiler using your previously created programs on the
  4433. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4434. \end{exercise}
  4435. \section{Patch Instructions}
  4436. The second argument of the \key{cmpq} instruction must not be an
  4437. immediate value (such as an integer). So if you are comparing two
  4438. immediates, we recommend inserting a \key{movq} instruction to put the
  4439. second argument in \key{rax}.
  4440. %
  4441. The second argument of the \key{movzbq} must be a register.
  4442. %
  4443. There are no special restrictions on the x86 instructions \key{JmpIf}
  4444. and \key{Jmp}.
  4445. \begin{exercise}\normalfont
  4446. Update \code{patch-instructions} to handle the new x86 instructions.
  4447. Test your compiler using your previously created programs on the
  4448. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4449. \end{exercise}
  4450. \section{An Example Translation}
  4451. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4452. $R_2$ translated to x86, showing the results of
  4453. \code{explicate-control}, \code{select-instructions}, and the final
  4454. x86 assembly code.
  4455. \begin{figure}[tbp]
  4456. \begin{tabular}{lll}
  4457. \begin{minipage}{0.5\textwidth}
  4458. % s1_20.rkt
  4459. \begin{lstlisting}
  4460. (if (eq? (read) 1) 42 0)
  4461. \end{lstlisting}
  4462. $\Downarrow$
  4463. \begin{lstlisting}
  4464. start:
  4465. tmp7951 = (read);
  4466. if (eq? tmp7951 1) then
  4467. goto block7952;
  4468. else
  4469. goto block7953;
  4470. block7952:
  4471. return 42;
  4472. block7953:
  4473. return 0;
  4474. \end{lstlisting}
  4475. $\Downarrow$
  4476. \begin{lstlisting}
  4477. start:
  4478. callq read_int
  4479. movq %rax, tmp7951
  4480. cmpq $1, tmp7951
  4481. je block7952
  4482. jmp block7953
  4483. block7953:
  4484. movq $0, %rax
  4485. jmp conclusion
  4486. block7952:
  4487. movq $42, %rax
  4488. jmp conclusion
  4489. \end{lstlisting}
  4490. \end{minipage}
  4491. &
  4492. $\Rightarrow\qquad$
  4493. \begin{minipage}{0.4\textwidth}
  4494. \begin{lstlisting}
  4495. start:
  4496. callq read_int
  4497. movq %rax, %rcx
  4498. cmpq $1, %rcx
  4499. je block7952
  4500. jmp block7953
  4501. block7953:
  4502. movq $0, %rax
  4503. jmp conclusion
  4504. block7952:
  4505. movq $42, %rax
  4506. jmp conclusion
  4507. .globl main
  4508. main:
  4509. pushq %rbp
  4510. movq %rsp, %rbp
  4511. pushq %r13
  4512. pushq %r12
  4513. pushq %rbx
  4514. pushq %r14
  4515. subq $0, %rsp
  4516. jmp start
  4517. conclusion:
  4518. addq $0, %rsp
  4519. popq %r14
  4520. popq %rbx
  4521. popq %r12
  4522. popq %r13
  4523. popq %rbp
  4524. retq
  4525. \end{lstlisting}
  4526. \end{minipage}
  4527. \end{tabular}
  4528. \caption{Example compilation of an \key{if} expression to x86.}
  4529. \label{fig:if-example-x86}
  4530. \end{figure}
  4531. \begin{figure}[p]
  4532. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4533. \node (R2) at (0,2) {\large $R_2$};
  4534. \node (R2-2) at (3,2) {\large $R_2$};
  4535. \node (R2-3) at (6,2) {\large $R_2$};
  4536. \node (R2-4) at (9,2) {\large $R_2$};
  4537. \node (R2-5) at (9,0) {\large $R_2$};
  4538. \node (C1-1) at (3,-2) {\large $C_1$};
  4539. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4540. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4541. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4542. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4543. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4544. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4545. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4546. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4547. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4548. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4549. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4550. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4551. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4552. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4553. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4554. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4555. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4556. \end{tikzpicture}
  4557. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4558. \label{fig:R2-passes}
  4559. \end{figure}
  4560. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4561. compilation of $R_2$.
  4562. \section{Challenge: Optimize and Remove Jumps}
  4563. \label{sec:opt-jumps}
  4564. Recall that in the example output of \code{explicate-control} in
  4565. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4566. \code{block60} are trivial blocks, they do nothing but jump to another
  4567. block. The first goal of this challenge assignment is to remove those
  4568. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4569. \code{explicate-control} on the left and shows the result of bypassing
  4570. the trivial blocks on the right. Let us focus on \code{block61}. The
  4571. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4572. \code{block55}. The optimized code on the right of
  4573. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4574. \code{then} branch jumping directly to \code{block55}. The story is
  4575. similar for the \code{else} branch, as well as for the two branches in
  4576. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4577. have been optimized in this way, there are no longer any jumps to
  4578. blocks \code{block57} through \code{block60}, so they can be removed.
  4579. \begin{figure}[tbp]
  4580. \begin{tabular}{lll}
  4581. \begin{minipage}{0.4\textwidth}
  4582. \begin{lstlisting}
  4583. block62:
  4584. tmp54 = (read);
  4585. if (eq? tmp54 2) then
  4586. goto block59;
  4587. else
  4588. goto block60;
  4589. block61:
  4590. tmp53 = (read);
  4591. if (eq? tmp53 0) then
  4592. goto block57;
  4593. else
  4594. goto block58;
  4595. block60:
  4596. goto block56;
  4597. block59:
  4598. goto block55;
  4599. block58:
  4600. goto block56;
  4601. block57:
  4602. goto block55;
  4603. block56:
  4604. return (+ 700 77);
  4605. block55:
  4606. return (+ 10 32);
  4607. start:
  4608. tmp52 = (read);
  4609. if (eq? tmp52 1) then
  4610. goto block61;
  4611. else
  4612. goto block62;
  4613. \end{lstlisting}
  4614. \end{minipage}
  4615. &
  4616. $\Rightarrow$
  4617. &
  4618. \begin{minipage}{0.55\textwidth}
  4619. \begin{lstlisting}
  4620. block62:
  4621. tmp54 = (read);
  4622. if (eq? tmp54 2) then
  4623. goto block55;
  4624. else
  4625. goto block56;
  4626. block61:
  4627. tmp53 = (read);
  4628. if (eq? tmp53 0) then
  4629. goto block55;
  4630. else
  4631. goto block56;
  4632. block56:
  4633. return (+ 700 77);
  4634. block55:
  4635. return (+ 10 32);
  4636. start:
  4637. tmp52 = (read);
  4638. if (eq? tmp52 1) then
  4639. goto block61;
  4640. else
  4641. goto block62;
  4642. \end{lstlisting}
  4643. \end{minipage}
  4644. \end{tabular}
  4645. \caption{Optimize jumps by removing trivial blocks.}
  4646. \label{fig:optimize-jumps}
  4647. \end{figure}
  4648. The name of this pass is \code{optimize-jumps}. We recommend
  4649. implementing this pass in two phases. The first phrase builds a hash
  4650. table that maps labels to possibly improved labels. The second phase
  4651. changes the target of each \code{goto} to use the improved label. If
  4652. the label is for a trivial block, then the hash table should map the
  4653. label to the first non-trivial block that can be reached from this
  4654. label by jumping through trivial blocks. If the label is for a
  4655. non-trivial block, then the hash table should map the label to itself;
  4656. we do not want to change jumps to non-trivial blocks.
  4657. The first phase can be accomplished by constructing an empty hash
  4658. table, call it \code{short-cut}, and then iterating over the control
  4659. flow graph. Each time you encouter a block that is just a \code{goto},
  4660. then update the hash table, mapping the block's source to the target
  4661. of the \code{goto}. Also, the hash table may already have mapped some
  4662. labels to the block's source, to you must iterate through the hash
  4663. table and update all of those so that they instead map to the target
  4664. of the \code{goto}.
  4665. For the second phase, we recommend iterating through the $\Tail$ of
  4666. each block in the program, updating the target of every \code{goto}
  4667. according to the mapping in \code{short-cut}.
  4668. \begin{exercise}\normalfont
  4669. Implement the \code{optimize-jumps} pass as a transformation from
  4670. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4671. Check that \code{optimize-jumps} removes trivial blocks in a few
  4672. example programs. Then check that your compiler still passes all of
  4673. your tests.
  4674. \end{exercise}
  4675. There is another opportunity for optimizing jumps that is apparent in
  4676. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4677. end with a jump to \code{block7953} and there are no other jumps to
  4678. \code{block7953} in the rest of the program. In this situation we can
  4679. avoid the runtime overhead of this jump by merging \code{block7953}
  4680. into the preceeding block, in this case the \code{start} block.
  4681. Figure~\ref{fig:remove-jumps} shows the output of
  4682. \code{select-instructions} on the left and the result of this
  4683. optimization on the right.
  4684. \begin{figure}[tbp]
  4685. \begin{tabular}{lll}
  4686. \begin{minipage}{0.5\textwidth}
  4687. % s1_20.rkt
  4688. \begin{lstlisting}
  4689. start:
  4690. callq read_int
  4691. movq %rax, tmp7951
  4692. cmpq $1, tmp7951
  4693. je block7952
  4694. jmp block7953
  4695. block7953:
  4696. movq $0, %rax
  4697. jmp conclusion
  4698. block7952:
  4699. movq $42, %rax
  4700. jmp conclusion
  4701. \end{lstlisting}
  4702. \end{minipage}
  4703. &
  4704. $\Rightarrow\qquad$
  4705. \begin{minipage}{0.4\textwidth}
  4706. \begin{lstlisting}
  4707. start:
  4708. callq read_int
  4709. movq %rax, tmp7951
  4710. cmpq $1, tmp7951
  4711. je block7952
  4712. movq $0, %rax
  4713. jmp conclusion
  4714. block7952:
  4715. movq $42, %rax
  4716. jmp conclusion
  4717. \end{lstlisting}
  4718. \end{minipage}
  4719. \end{tabular}
  4720. \caption{Merging basic blocks by removing unnecessary jumps.}
  4721. \label{fig:remove-jumps}
  4722. \end{figure}
  4723. \begin{exercise}\normalfont
  4724. Implement a pass named \code{remove-jumps} that merges basic blocks
  4725. into their preceeding basic block, when there is only one preceeding
  4726. block. The pass should translate from psuedo $x86_1$ to pseudo
  4727. $x86_1$ and it should come immediately after
  4728. \code{select-instructions}. Check that \code{remove-jumps}
  4729. accomplishes the goal of merging basic blocks on several test
  4730. programs and check that your compiler passes all of your tests.
  4731. \end{exercise}
  4732. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4733. \chapter{Tuples and Garbage Collection}
  4734. \label{ch:tuples}
  4735. \index{tuple}
  4736. \index{vector}
  4737. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4738. add simple structures. \\ --Jeremy}
  4739. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4740. things to discuss in this chapter. \\ --Jeremy}
  4741. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4742. all the IR grammars are spelled out! \\ --Jeremy}
  4743. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4744. but keep type annotations on vector creation and local variables, function
  4745. parameters, etc. \\ --Jeremy}
  4746. \margincomment{\scriptsize Be more explicit about how to deal with
  4747. the root stack. \\ --Jeremy}
  4748. In this chapter we study the implementation of mutable tuples (called
  4749. ``vectors'' in Racket). This language feature is the first to use the
  4750. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  4751. indefinite, that is, a tuple lives forever from the programmer's
  4752. viewpoint. Of course, from an implementer's viewpoint, it is important
  4753. to reclaim the space associated with a tuple when it is no longer
  4754. needed, which is why we also study \emph{garbage collection}
  4755. \emph{garbage collection}
  4756. techniques in this chapter.
  4757. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4758. interpreter and type checker. The $R_3$ language extends the $R_2$
  4759. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4760. \code{void} value. The reason for including the later is that the
  4761. \code{vector-set!} operation returns a value of type
  4762. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4763. called the \code{Unit} type in the programming languages
  4764. literature. Racket's \code{Void} type is inhabited by a single value
  4765. \code{void} which corresponds to \code{unit} or \code{()} in the
  4766. literature~\citep{Pierce:2002hj}.}.
  4767. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4768. copying live objects back and forth between two halves of the
  4769. heap. The garbage collector requires coordination with the compiler so
  4770. that it can see all of the \emph{root} pointers, that is, pointers in
  4771. registers or on the procedure call stack.
  4772. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4773. discuss all the necessary changes and additions to the compiler
  4774. passes, including a new compiler pass named \code{expose-allocation}.
  4775. \section{The $R_3$ Language}
  4776. \label{sec:r3}
  4777. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4778. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4779. $R_3$ language includes three new forms: \code{vector} for creating a
  4780. tuple, \code{vector-ref} for reading an element of a tuple, and
  4781. \code{vector-set!} for writing to an element of a tuple. The program
  4782. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4783. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4784. the 3-tuple, demonstrating that tuples are first-class values. The
  4785. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4786. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4787. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4788. 1-tuple. So the result of the program is \code{42}.
  4789. \begin{figure}[tbp]
  4790. \centering
  4791. \fbox{
  4792. \begin{minipage}{0.96\textwidth}
  4793. \[
  4794. \begin{array}{lcl}
  4795. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4796. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4797. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4798. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4799. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4800. \mid (\key{and}\;\Exp\;\Exp)
  4801. \mid (\key{or}\;\Exp\;\Exp)
  4802. \mid (\key{not}\;\Exp) } \\
  4803. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4804. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4805. &\mid& (\key{vector}\;\Exp\ldots)
  4806. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4807. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4808. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4809. R_3 &::=& \Exp
  4810. \end{array}
  4811. \]
  4812. \end{minipage}
  4813. }
  4814. \caption{The concrete syntax of $R_3$, extending $R_2$
  4815. (Figure~\ref{fig:r2-concrete-syntax}).}
  4816. \label{fig:r3-concrete-syntax}
  4817. \end{figure}
  4818. \begin{figure}[tbp]
  4819. \begin{lstlisting}
  4820. (let ([t (vector 40 #t (vector 2))])
  4821. (if (vector-ref t 1)
  4822. (+ (vector-ref t 0)
  4823. (vector-ref (vector-ref t 2) 0))
  4824. 44))
  4825. \end{lstlisting}
  4826. \caption{Example program that creates tuples and reads from them.}
  4827. \label{fig:vector-eg}
  4828. \end{figure}
  4829. \begin{figure}[tp]
  4830. \centering
  4831. \fbox{
  4832. \begin{minipage}{0.96\textwidth}
  4833. \[
  4834. \begin{array}{lcl}
  4835. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4836. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4837. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4838. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4839. &\mid& \gray{ \BOOL{\itm{bool}}
  4840. \mid \AND{\Exp}{\Exp} }\\
  4841. &\mid& \gray{ \OR{\Exp}{\Exp}
  4842. \mid \NOT{\Exp} } \\
  4843. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  4844. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4845. &\mid& \VECTOR{\Exp} \\
  4846. &\mid& \VECREF{\Exp}{\Int}\\
  4847. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4848. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  4849. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4850. \end{array}
  4851. \]
  4852. \end{minipage}
  4853. }
  4854. \caption{The abstract syntax of $R_3$.}
  4855. \label{fig:r3-syntax}
  4856. \end{figure}
  4857. Tuples are our first encounter with heap-allocated data, which raises
  4858. several interesting issues. First, variable binding performs a
  4859. shallow-copy when dealing with tuples, which means that different
  4860. variables can refer to the same tuple, that is, different variables
  4861. can be \emph{aliases} for the same entity. Consider the following
  4862. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4863. Thus, the mutation through \code{t2} is visible when referencing the
  4864. tuple from \code{t1}, so the result of this program is \code{42}.
  4865. \begin{center}
  4866. \begin{minipage}{0.96\textwidth}
  4867. \begin{lstlisting}
  4868. (let ([t1 (vector 3 7)])
  4869. (let ([t2 t1])
  4870. (let ([_ (vector-set! t2 0 42)])
  4871. (vector-ref t1 0))))
  4872. \end{lstlisting}
  4873. \end{minipage}
  4874. \end{center}
  4875. The next issue concerns the lifetime of tuples. Of course, they are
  4876. created by the \code{vector} form, but when does their lifetime end?
  4877. Notice that $R_3$ does not include an operation for deleting
  4878. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  4879. of static scoping. For example, the following program returns
  4880. \code{42} even though the variable \code{w} goes out of scope prior to
  4881. the \code{vector-ref} that reads from the vector it was bound to.
  4882. \begin{center}
  4883. \begin{minipage}{0.96\textwidth}
  4884. \begin{lstlisting}
  4885. (let ([v (vector (vector 44))])
  4886. (let ([x (let ([w (vector 42)])
  4887. (let ([_ (vector-set! v 0 w)])
  4888. 0))])
  4889. (+ x (vector-ref (vector-ref v 0) 0))))
  4890. \end{lstlisting}
  4891. \end{minipage}
  4892. \end{center}
  4893. From the perspective of programmer-observable behavior, tuples live
  4894. forever. Of course, if they really lived forever, then many programs
  4895. would run out of memory.\footnote{The $R_3$ language does not have
  4896. looping or recursive functions, so it is nigh impossible to write a
  4897. program in $R_3$ that will run out of memory. However, we add
  4898. recursive functions in the next Chapter!} A Racket implementation
  4899. must therefore perform automatic garbage collection.
  4900. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4901. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4902. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4903. operations in Racket. One subtle point is that the \code{vector-set!}
  4904. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4905. can be passed around just like other values inside an $R_3$ program
  4906. and a \code{\#<void>} value can be compared for equality with another
  4907. \code{\#<void>} value. However, there are no other operations specific
  4908. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  4909. the \code{void?} predicate that returns \code{\#t} when applied to
  4910. \code{\#<void>} and \code{\#f} otherwise.
  4911. \begin{figure}[tbp]
  4912. \begin{lstlisting}
  4913. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4914. (define (interp-op op)
  4915. (match op
  4916. ...
  4917. ['vector vector]
  4918. ['vector-ref vector-ref]
  4919. ['vector-set! vector-set!]
  4920. [else (error 'interp-op "unknown operator")]))
  4921. (define (interp-exp env)
  4922. (lambda (e)
  4923. (define recur (interp-exp env))
  4924. (match e
  4925. ...
  4926. )))
  4927. (define (interp-R3 p)
  4928. (match p
  4929. [(Program '() e)
  4930. ((interp-exp '()) e)]
  4931. ))
  4932. \end{lstlisting}
  4933. \caption{Interpreter for the $R_3$ language.}
  4934. \label{fig:interp-R3}
  4935. \end{figure}
  4936. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4937. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4938. need to know which variables contain pointers into the heap, that is,
  4939. which variables contain vectors. Also, when allocating a vector, we
  4940. need to know which elements of the vector are pointers. We can obtain
  4941. this information during type checking. The type checker in
  4942. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4943. expression, it also wraps every sub-expression $e$ with the form
  4944. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4945. Subsequently, in the \code{uncover-locals} pass
  4946. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4947. propagated to all variables (including the temporaries generated by
  4948. \code{remove-complex-opera*}).
  4949. \begin{figure}[tp]
  4950. \begin{lstlisting}
  4951. (define (type-check-exp env)
  4952. (lambda (e)
  4953. (define recur (type-check-exp env))
  4954. (match e
  4955. ...
  4956. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4957. [(Prim 'vector es)
  4958. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  4959. (let ([t `(Vector ,@t*)])
  4960. (values (HasType (Prim 'vector e*) t) t))]
  4961. [(Prim 'vector-ref (list e (Int i)))
  4962. (define-values (e^ t) (recur e))
  4963. (match t
  4964. [`(Vector ,ts ...)
  4965. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4966. (error 'type-check-exp "invalid index ~a" i))
  4967. (let ([t (list-ref ts i)])
  4968. (values
  4969. (HasType (Prim 'vector-ref
  4970. (list e^ (HasType (Int i) 'Integer)))
  4971. t)
  4972. t))]
  4973. [else (error "expected a vector in vector-ref, not" t)])]
  4974. [(Prim 'eq? (list e1 e2))
  4975. (define-values (e1^ T1) (recur e1))
  4976. (define-values (e2^ T2) (recur e2))
  4977. (unless (equal? T1 T2)
  4978. (error "arguments of eq? must have the same type, but are not"
  4979. (list T1 T2)))
  4980. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4981. ...
  4982. )))
  4983. \end{lstlisting}
  4984. \caption{Type checker for the $R_3$ language.}
  4985. \label{fig:typecheck-R3}
  4986. \end{figure}
  4987. \section{Garbage Collection}
  4988. \label{sec:GC}
  4989. Here we study a relatively simple algorithm for garbage collection
  4990. that is the basis of state-of-the-art garbage
  4991. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4992. particular, we describe a two-space copying
  4993. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4994. perform the
  4995. copy~\citep{Cheney:1970aa}.
  4996. \index{copying collector}
  4997. \index{two-space copying collector}
  4998. Figure~\ref{fig:copying-collector} gives a
  4999. coarse-grained depiction of what happens in a two-space collector,
  5000. showing two time steps, prior to garbage collection (on the top) and
  5001. after garbage collection (on the bottom). In a two-space collector,
  5002. the heap is divided into two parts named the FromSpace and the
  5003. ToSpace. Initially, all allocations go to the FromSpace until there is
  5004. not enough room for the next allocation request. At that point, the
  5005. garbage collector goes to work to make more room.
  5006. \index{ToSpace}
  5007. \index{FromSpace}
  5008. The garbage collector must be careful not to reclaim tuples that will
  5009. be used by the program in the future. Of course, it is impossible in
  5010. general to predict what a program will do, but we can over approximate
  5011. the will-be-used tuples by preserving all tuples that could be
  5012. accessed by \emph{any} program given the current computer state. A
  5013. program could access any tuple whose address is in a register or on
  5014. the procedure call stack. These addresses are called the \emph{root
  5015. set}\index{root set}. In addition, a program could access any tuple that is
  5016. transitively reachable from the root set. Thus, it is safe for the
  5017. garbage collector to reclaim the tuples that are not reachable in this
  5018. way.
  5019. So the goal of the garbage collector is twofold:
  5020. \begin{enumerate}
  5021. \item preserve all tuple that are reachable from the root set via a
  5022. path of pointers, that is, the \emph{live} tuples, and
  5023. \item reclaim the memory of everything else, that is, the
  5024. \emph{garbage}.
  5025. \end{enumerate}
  5026. A copying collector accomplishes this by copying all of the live
  5027. objects from the FromSpace into the ToSpace and then performs a slight
  5028. of hand, treating the ToSpace as the new FromSpace and the old
  5029. FromSpace as the new ToSpace. In the example of
  5030. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5031. root set, one in a register and two on the stack. All of the live
  5032. objects have been copied to the ToSpace (the right-hand side of
  5033. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5034. pointer relationships. For example, the pointer in the register still
  5035. points to a 2-tuple whose first element is a 3-tuple and whose second
  5036. element is a 2-tuple. There are four tuples that are not reachable
  5037. from the root set and therefore do not get copied into the ToSpace.
  5038. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5039. created by a well-typed program in $R_3$ because it contains a
  5040. cycle. However, creating cycles will be possible once we get to $R_6$.
  5041. We design the garbage collector to deal with cycles to begin with so
  5042. we will not need to revisit this issue.
  5043. \begin{figure}[tbp]
  5044. \centering
  5045. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5046. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5047. \caption{A copying collector in action.}
  5048. \label{fig:copying-collector}
  5049. \end{figure}
  5050. There are many alternatives to copying collectors (and their bigger
  5051. siblings, the generational collectors) when its comes to garbage
  5052. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5053. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5054. collectors are that allocation is fast (just a comparison and pointer
  5055. increment), there is no fragmentation, cyclic garbage is collected,
  5056. and the time complexity of collection only depends on the amount of
  5057. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5058. main disadvantages of a two-space copying collector is that it uses a
  5059. lot of space and takes a long time to perform the copy, though these
  5060. problems are ameliorated in generational collectors. Racket and
  5061. Scheme programs tend to allocate many small objects and generate a lot
  5062. of garbage, so copying and generational collectors are a good fit.
  5063. Garbage collection is an active research topic, especially concurrent
  5064. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5065. developing new techniques and revisiting old
  5066. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5067. meet every year at the International Symposium on Memory Management to
  5068. present these findings.
  5069. \subsection{Graph Copying via Cheney's Algorithm}
  5070. \label{sec:cheney}
  5071. \index{Cheney's algorithm}
  5072. Let us take a closer look at the copying of the live objects. The
  5073. allocated objects and pointers can be viewed as a graph and we need to
  5074. copy the part of the graph that is reachable from the root set. To
  5075. make sure we copy all of the reachable vertices in the graph, we need
  5076. an exhaustive graph traversal algorithm, such as depth-first search or
  5077. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5078. such algorithms take into account the possibility of cycles by marking
  5079. which vertices have already been visited, so as to ensure termination
  5080. of the algorithm. These search algorithms also use a data structure
  5081. such as a stack or queue as a to-do list to keep track of the vertices
  5082. that need to be visited. We shall use breadth-first search and a trick
  5083. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5084. and copying tuples into the ToSpace.
  5085. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5086. copy progresses. The queue is represented by a chunk of contiguous
  5087. memory at the beginning of the ToSpace, using two pointers to track
  5088. the front and the back of the queue. The algorithm starts by copying
  5089. all tuples that are immediately reachable from the root set into the
  5090. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5091. old tuple to indicate that it has been visited. We discuss how this
  5092. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5093. pointers inside the copied tuples in the queue still point back to the
  5094. FromSpace. Once the initial queue has been created, the algorithm
  5095. enters a loop in which it repeatedly processes the tuple at the front
  5096. of the queue and pops it off the queue. To process a tuple, the
  5097. algorithm copies all the tuple that are directly reachable from it to
  5098. the ToSpace, placing them at the back of the queue. The algorithm then
  5099. updates the pointers in the popped tuple so they point to the newly
  5100. copied tuples.
  5101. \begin{figure}[tbp]
  5102. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5103. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5104. \label{fig:cheney}
  5105. \end{figure}
  5106. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5107. tuple whose second element is $42$ to the back of the queue. The other
  5108. pointer goes to a tuple that has already been copied, so we do not
  5109. need to copy it again, but we do need to update the pointer to the new
  5110. location. This can be accomplished by storing a \emph{forwarding
  5111. pointer} to the new location in the old tuple, back when we initially
  5112. copied the tuple into the ToSpace. This completes one step of the
  5113. algorithm. The algorithm continues in this way until the front of the
  5114. queue is empty, that is, until the front catches up with the back.
  5115. \subsection{Data Representation}
  5116. \label{sec:data-rep-gc}
  5117. The garbage collector places some requirements on the data
  5118. representations used by our compiler. First, the garbage collector
  5119. needs to distinguish between pointers and other kinds of data. There
  5120. are several ways to accomplish this.
  5121. \begin{enumerate}
  5122. \item Attached a tag to each object that identifies what type of
  5123. object it is~\citep{McCarthy:1960dz}.
  5124. \item Store different types of objects in different
  5125. regions~\citep{Steele:1977ab}.
  5126. \item Use type information from the program to either generate
  5127. type-specific code for collecting or to generate tables that can
  5128. guide the
  5129. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5130. \end{enumerate}
  5131. Dynamically typed languages, such as Lisp, need to tag objects
  5132. anyways, so option 1 is a natural choice for those languages.
  5133. However, $R_3$ is a statically typed language, so it would be
  5134. unfortunate to require tags on every object, especially small and
  5135. pervasive objects like integers and Booleans. Option 3 is the
  5136. best-performing choice for statically typed languages, but comes with
  5137. a relatively high implementation complexity. To keep this chapter
  5138. within a 2-week time budget, we recommend a combination of options 1
  5139. and 2, using separate strategies for the stack and the heap.
  5140. Regarding the stack, we recommend using a separate stack for pointers,
  5141. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5142. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5143. is, when a local variable needs to be spilled and is of type
  5144. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5145. stack instead of the normal procedure call stack. Furthermore, we
  5146. always spill vector-typed variables if they are live during a call to
  5147. the collector, thereby ensuring that no pointers are in registers
  5148. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5149. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5150. the data layout using a root stack. The root stack contains the two
  5151. pointers from the regular stack and also the pointer in the second
  5152. register.
  5153. \begin{figure}[tbp]
  5154. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5155. \caption{Maintaining a root stack to facilitate garbage collection.}
  5156. \label{fig:shadow-stack}
  5157. \end{figure}
  5158. The problem of distinguishing between pointers and other kinds of data
  5159. also arises inside of each tuple on the heap. We solve this problem by
  5160. attaching a tag, an extra 64-bits, to each
  5161. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5162. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5163. that we have drawn the bits in a big-endian way, from right-to-left,
  5164. with bit location 0 (the least significant bit) on the far right,
  5165. which corresponds to the direction of the x86 shifting instructions
  5166. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5167. is dedicated to specifying which elements of the tuple are pointers,
  5168. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5169. indicates there is a pointer and a 0 bit indicates some other kind of
  5170. data. The pointer mask starts at bit location 7. We have limited
  5171. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5172. the pointer mask. The tag also contains two other pieces of
  5173. information. The length of the tuple (number of elements) is stored in
  5174. bits location 1 through 6. Finally, the bit at location 0 indicates
  5175. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5176. value 1, then this tuple has not yet been copied. If the bit has
  5177. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5178. of a pointer are always zero anyways because our tuples are 8-byte
  5179. aligned.)
  5180. \begin{figure}[tbp]
  5181. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5182. \caption{Representation of tuples in the heap.}
  5183. \label{fig:tuple-rep}
  5184. \end{figure}
  5185. \subsection{Implementation of the Garbage Collector}
  5186. \label{sec:organize-gz}
  5187. \index{prelude}
  5188. An implementation of the copying collector is provided in the
  5189. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5190. interface to the garbage collector that is used by the compiler. The
  5191. \code{initialize} function creates the FromSpace, ToSpace, and root
  5192. stack and should be called in the prelude of the \code{main}
  5193. function. The \code{initialize} function puts the address of the
  5194. beginning of the FromSpace into the global variable
  5195. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5196. the address that is 1-past the last element of the FromSpace. (We use
  5197. half-open intervals to represent chunks of
  5198. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5199. points to the first element of the root stack.
  5200. As long as there is room left in the FromSpace, your generated code
  5201. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5202. %
  5203. The amount of room left in FromSpace is the difference between the
  5204. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5205. function should be called when there is not enough room left in the
  5206. FromSpace for the next allocation. The \code{collect} function takes
  5207. a pointer to the current top of the root stack (one past the last item
  5208. that was pushed) and the number of bytes that need to be
  5209. allocated. The \code{collect} function performs the copying collection
  5210. and leaves the heap in a state such that the next allocation will
  5211. succeed.
  5212. \begin{figure}[tbp]
  5213. \begin{lstlisting}
  5214. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5215. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5216. int64_t* free_ptr;
  5217. int64_t* fromspace_begin;
  5218. int64_t* fromspace_end;
  5219. int64_t** rootstack_begin;
  5220. \end{lstlisting}
  5221. \caption{The compiler's interface to the garbage collector.}
  5222. \label{fig:gc-header}
  5223. \end{figure}
  5224. %% \begin{exercise}
  5225. %% In the file \code{runtime.c} you will find the implementation of
  5226. %% \code{initialize} and a partial implementation of \code{collect}.
  5227. %% The \code{collect} function calls another function, \code{cheney},
  5228. %% to perform the actual copy, and that function is left to the reader
  5229. %% to implement. The following is the prototype for \code{cheney}.
  5230. %% \begin{lstlisting}
  5231. %% static void cheney(int64_t** rootstack_ptr);
  5232. %% \end{lstlisting}
  5233. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5234. %% rootstack (which is an array of pointers). The \code{cheney} function
  5235. %% also communicates with \code{collect} through the global
  5236. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5237. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5238. %% the ToSpace:
  5239. %% \begin{lstlisting}
  5240. %% static int64_t* tospace_begin;
  5241. %% static int64_t* tospace_end;
  5242. %% \end{lstlisting}
  5243. %% The job of the \code{cheney} function is to copy all the live
  5244. %% objects (reachable from the root stack) into the ToSpace, update
  5245. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5246. %% update the root stack so that it points to the objects in the
  5247. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5248. %% and ToSpace.
  5249. %% \end{exercise}
  5250. %% \section{Compiler Passes}
  5251. %% \label{sec:code-generation-gc}
  5252. The introduction of garbage collection has a non-trivial impact on our
  5253. compiler passes. We introduce two new compiler passes named
  5254. \code{expose-allocation} and \code{uncover-locals}. We make
  5255. significant changes to \code{select-instructions},
  5256. \code{build-interference}, \code{allocate-registers}, and
  5257. \code{print-x86} and make minor changes in severl more passes. The
  5258. following program will serve as our running example. It creates two
  5259. tuples, one nested inside the other. Both tuples have length one. The
  5260. program accesses the element in the inner tuple tuple via two vector
  5261. references.
  5262. % tests/s2_17.rkt
  5263. \begin{lstlisting}
  5264. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5265. \end{lstlisting}
  5266. \section{Shrink}
  5267. \label{sec:shrink-R3}
  5268. Recall that the \code{shrink} pass translates the primitives operators
  5269. into a smaller set of primitives. Because this pass comes after type
  5270. checking, but before the passes that require the type information in
  5271. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5272. to wrap \code{HasType} around each AST node that it generates.
  5273. \section{Expose Allocation}
  5274. \label{sec:expose-allocation}
  5275. The pass \code{expose-allocation} lowers the \code{vector} creation
  5276. form into a conditional call to the collector followed by the
  5277. allocation. We choose to place the \code{expose-allocation} pass
  5278. before \code{remove-complex-opera*} because the code generated by
  5279. \code{expose-allocation} contains complex operands. We also place
  5280. \code{expose-allocation} before \code{explicate-control} because
  5281. \code{expose-allocation} introduces new variables using \code{let},
  5282. but \code{let} is gone after \code{explicate-control}.
  5283. The output of \code{expose-allocation} is a language $R'_3$ that
  5284. extends $R_3$ with the three new forms that we use in the translation
  5285. of the \code{vector} form.
  5286. \[
  5287. \begin{array}{lcl}
  5288. \Exp &::=& \cdots
  5289. \mid (\key{collect} \,\itm{int})
  5290. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5291. \mid (\key{global-value} \,\itm{name})
  5292. \end{array}
  5293. \]
  5294. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5295. $n$ bytes. It will become a call to the \code{collect} function in
  5296. \code{runtime.c} in \code{select-instructions}. The
  5297. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements. The
  5298. $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5299. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5300. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5301. a global variable, such as \code{free\_ptr}.
  5302. In the following, we show the transformation for the \code{vector}
  5303. form into 1) a sequence of let-bindings for the initializing
  5304. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5305. \code{allocate}, and 4) the initialization of the vector. In the
  5306. following, \itm{len} refers to the length of the vector and
  5307. \itm{bytes} is how many total bytes need to be allocated for the
  5308. vector, which is 8 for the tag plus \itm{len} times 8.
  5309. \begin{lstlisting}
  5310. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5311. |$\Longrightarrow$|
  5312. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5313. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5314. (global-value fromspace_end))
  5315. (void)
  5316. (collect |\itm{bytes}|))])
  5317. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5318. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5319. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5320. |$v$|) ... )))) ...)
  5321. \end{lstlisting}
  5322. In the above, we suppressed all of the \code{has-type} forms in the
  5323. output for the sake of readability. The placement of the initializing
  5324. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5325. sequence of \code{vector-set!} is important, as those expressions may
  5326. trigger garbage collection and we cannot have an allocated but
  5327. uninitialized tuple on the heap during a collection.
  5328. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5329. \code{expose-allocation} pass on our running example.
  5330. \begin{figure}[tbp]
  5331. % tests/s2_17.rkt
  5332. \begin{lstlisting}
  5333. (vector-ref
  5334. (vector-ref
  5335. (let ([vecinit7976
  5336. (let ([vecinit7972 42])
  5337. (let ([collectret7974
  5338. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5339. (void)
  5340. (collect 16)
  5341. )])
  5342. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5343. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5344. alloc7971)
  5345. )
  5346. )
  5347. )
  5348. ])
  5349. (let ([collectret7978
  5350. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5351. (void)
  5352. (collect 16)
  5353. )])
  5354. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5355. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5356. alloc7975)
  5357. )
  5358. )
  5359. )
  5360. 0)
  5361. 0)
  5362. \end{lstlisting}
  5363. \caption{Output of the \code{expose-allocation} pass, minus
  5364. all of the \code{has-type} forms.}
  5365. \label{fig:expose-alloc-output}
  5366. \end{figure}
  5367. \section{Remove Complex Operands}
  5368. \label{sec:remove-complex-opera-R3}
  5369. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5370. should all be treated as complex operands. A new case for
  5371. \code{HasType} is needed and the case for \code{Prim} needs to be
  5372. handled carefully to prevent the \code{Prim} node from being separated
  5373. from its enclosing \code{HasType}.
  5374. \section{Explicate Control and the $C_2$ language}
  5375. \label{sec:explicate-control-r3}
  5376. \begin{figure}[tbp]
  5377. \fbox{
  5378. \begin{minipage}{0.96\textwidth}
  5379. \small
  5380. \[
  5381. \begin{array}{lcl}
  5382. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5383. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5384. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5385. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5386. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5387. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5388. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5389. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5390. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5391. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5392. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5393. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5394. \end{array}
  5395. \]
  5396. \end{minipage}
  5397. }
  5398. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5399. \label{fig:c2-concrete-syntax}
  5400. \end{figure}
  5401. \begin{figure}[tp]
  5402. \fbox{
  5403. \begin{minipage}{0.96\textwidth}
  5404. \small
  5405. \[
  5406. \begin{array}{lcl}
  5407. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5408. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5409. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5410. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5411. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5412. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5413. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  5414. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  5415. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5416. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5417. \mid (\key{Collect} \,\itm{int}) \\
  5418. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5419. \mid \GOTO{\itm{label}} } \\
  5420. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5421. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5422. \end{array}
  5423. \]
  5424. \end{minipage}
  5425. }
  5426. \caption{The abstract syntax of $C_2$, an extention of $C_1$
  5427. (Figure~\ref{fig:c1-syntax}).}
  5428. \label{fig:c2-syntax}
  5429. \end{figure}
  5430. The output of \code{explicate-control} is a program in the
  5431. intermediate language $C_2$, whose concrete syntax is defined in
  5432. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5433. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5434. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5435. \key{global-value} expressions and the \code{collect} statement. The
  5436. \code{explicate-control} pass can treat these new forms much like the
  5437. other forms.
  5438. \section{Uncover Locals}
  5439. \label{sec:uncover-locals-r3}
  5440. Recall that the \code{explicate-control} function collects all of the
  5441. local variables so that it can store them in the $\itm{info}$ field of
  5442. the \code{Program} structure. Also recall that we need to know the
  5443. types of all the local variables for purposes of identifying the root
  5444. set for the garbage collector. Thus, we create a pass named
  5445. \code{uncover-locals} to collect not just the variables but the
  5446. variables and their types in the form of an alist. Thanks to the
  5447. \code{HasType} nodes, the types are readily available at every
  5448. assignment to a variable. We recommend storing the resulting alist in
  5449. the $\itm{info}$ field of the program, associated with the
  5450. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5451. of the \code{uncover-locals} pass on the running example.
  5452. \begin{figure}[tbp]
  5453. % tests/s2_17.rkt
  5454. \begin{lstlisting}
  5455. locals:
  5456. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5457. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5458. collectret7974 : 'Void, initret7977 : 'Void,
  5459. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5460. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5461. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5462. vecinit7972 : 'Integer, initret7973 : 'Void,
  5463. block91:
  5464. (collect 16)
  5465. goto block89;
  5466. block90:
  5467. collectret7974 = (void);
  5468. goto block89;
  5469. block89:
  5470. alloc7971 = (allocate 1 (Vector Integer));
  5471. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5472. vecinit7976 = alloc7971;
  5473. tmp7982 = (global-value free_ptr);
  5474. tmp7983 = (+ tmp7982 16);
  5475. tmp7984 = (global-value fromspace_end);
  5476. if (< tmp7983 tmp7984) then
  5477. goto block87;
  5478. else
  5479. goto block88;
  5480. block88:
  5481. (collect 16)
  5482. goto block86;
  5483. block87:
  5484. collectret7978 = (void);
  5485. goto block86;
  5486. block86:
  5487. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5488. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5489. tmp7985 = (vector-ref alloc7975 0);
  5490. return (vector-ref tmp7985 0);
  5491. start:
  5492. vecinit7972 = 42;
  5493. tmp7979 = (global-value free_ptr);
  5494. tmp7980 = (+ tmp7979 16);
  5495. tmp7981 = (global-value fromspace_end);
  5496. if (< tmp7980 tmp7981) then
  5497. goto block90;
  5498. else
  5499. goto block91;
  5500. \end{lstlisting}
  5501. \caption{Output of \code{uncover-locals} for the running example.}
  5502. \label{fig:uncover-locals-r3}
  5503. \end{figure}
  5504. \clearpage
  5505. \section{Select Instructions and the x86$_2$ Language}
  5506. \label{sec:select-instructions-gc}
  5507. \index{instruction selection}
  5508. %% void (rep as zero)
  5509. %% allocate
  5510. %% collect (callq collect)
  5511. %% vector-ref
  5512. %% vector-set!
  5513. %% global (postpone)
  5514. In this pass we generate x86 code for most of the new operations that
  5515. were needed to compile tuples, including \code{Allocate},
  5516. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5517. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5518. the later has a different concrete syntax (see
  5519. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5520. \index{x86}
  5521. The \code{vector-ref} and \code{vector-set!} forms translate into
  5522. \code{movq} instructions. (The plus one in the offset is to get past
  5523. the tag at the beginning of the tuple representation.)
  5524. \begin{lstlisting}
  5525. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5526. |$\Longrightarrow$|
  5527. movq |$\itm{vec}'$|, %r11
  5528. movq |$-8(n+1)$|(%r11), |$\itm{lhs'}$|
  5529. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5530. |$\Longrightarrow$|
  5531. movq |$\itm{vec}'$|, %r11
  5532. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5533. movq $0, |$\itm{lhs'}$|
  5534. \end{lstlisting}
  5535. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5536. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5537. register \code{r11} ensures that offset expression
  5538. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5539. removing \code{r11} from consideration by the register allocating.
  5540. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5541. \code{rax}. Then the generated code for \code{vector-set!} would be
  5542. \begin{lstlisting}
  5543. movq |$\itm{vec}'$|, %rax
  5544. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5545. movq $0, |$\itm{lhs}'$|
  5546. \end{lstlisting}
  5547. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5548. \code{patch-instructions} would insert a move through \code{rax}
  5549. as follows.
  5550. \begin{lstlisting}
  5551. movq |$\itm{vec}'$|, %rax
  5552. movq |$\itm{arg}'$|, %rax
  5553. movq %rax, |$8(n+1)$|(%rax)
  5554. movq $0, |$\itm{lhs}'$|
  5555. \end{lstlisting}
  5556. But the above sequence of instructions does not work because we're
  5557. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5558. $\itm{arg}'$) at the same time!
  5559. We compile the \code{allocate} form to operations on the
  5560. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5561. is the next free address in the FromSpace, so we move it into the
  5562. \itm{lhs} and then move it forward by enough space for the tuple being
  5563. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5564. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5565. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5566. how the tag is organized. We recommend using the Racket operations
  5567. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5568. during compilation. The type annotation in the \code{vector} form is
  5569. used to determine the pointer mask region of the tag.
  5570. \begin{lstlisting}
  5571. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5572. |$\Longrightarrow$|
  5573. movq free_ptr(%rip), |$\itm{lhs}'$|
  5574. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5575. movq |$\itm{lhs}'$|, %r11
  5576. movq $|$\itm{tag}$|, 0(%r11)
  5577. \end{lstlisting}
  5578. The \code{collect} form is compiled to a call to the \code{collect}
  5579. function in the runtime. The arguments to \code{collect} are 1) the
  5580. top of the root stack and 2) the number of bytes that need to be
  5581. allocated. We shall use another dedicated register, \code{r15}, to
  5582. store the pointer to the top of the root stack. So \code{r15} is not
  5583. available for use by the register allocator.
  5584. \begin{lstlisting}
  5585. (collect |$\itm{bytes}$|)
  5586. |$\Longrightarrow$|
  5587. movq %r15, %rdi
  5588. movq $|\itm{bytes}|, %rsi
  5589. callq collect
  5590. \end{lstlisting}
  5591. \begin{figure}[tp]
  5592. \fbox{
  5593. \begin{minipage}{0.96\textwidth}
  5594. \[
  5595. \begin{array}{lcl}
  5596. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5597. x86_1 &::= & \gray{ \key{.globl main} }\\
  5598. & & \gray{ \key{main:} \; \Instr\ldots }
  5599. \end{array}
  5600. \]
  5601. \end{minipage}
  5602. }
  5603. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5604. \label{fig:x86-2-concrete}
  5605. \end{figure}
  5606. \begin{figure}[tp]
  5607. \fbox{
  5608. \begin{minipage}{0.96\textwidth}
  5609. \small
  5610. \[
  5611. \begin{array}{lcl}
  5612. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5613. \mid \BYTEREG{\Reg}} \\
  5614. &\mid& (\key{Global}~\Var) \\
  5615. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5616. \end{array}
  5617. \]
  5618. \end{minipage}
  5619. }
  5620. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5621. \label{fig:x86-2}
  5622. \end{figure}
  5623. The concrete and abstract syntax of the $x86_2$ language is defined in
  5624. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5625. x86$_1$ just in the addition of the form for global variables.
  5626. %
  5627. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5628. \code{select-instructions} pass on the running example.
  5629. \begin{figure}[tbp]
  5630. \centering
  5631. % tests/s2_17.rkt
  5632. \begin{minipage}[t]{0.5\textwidth}
  5633. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5634. block35:
  5635. movq free_ptr(%rip), alloc9024
  5636. addq $16, free_ptr(%rip)
  5637. movq alloc9024, %r11
  5638. movq $131, 0(%r11)
  5639. movq alloc9024, %r11
  5640. movq vecinit9025, 8(%r11)
  5641. movq $0, initret9026
  5642. movq alloc9024, %r11
  5643. movq 8(%r11), tmp9034
  5644. movq tmp9034, %r11
  5645. movq 8(%r11), %rax
  5646. jmp conclusion
  5647. block36:
  5648. movq $0, collectret9027
  5649. jmp block35
  5650. block38:
  5651. movq free_ptr(%rip), alloc9020
  5652. addq $16, free_ptr(%rip)
  5653. movq alloc9020, %r11
  5654. movq $3, 0(%r11)
  5655. movq alloc9020, %r11
  5656. movq vecinit9021, 8(%r11)
  5657. movq $0, initret9022
  5658. movq alloc9020, vecinit9025
  5659. movq free_ptr(%rip), tmp9031
  5660. movq tmp9031, tmp9032
  5661. addq $16, tmp9032
  5662. movq fromspace_end(%rip), tmp9033
  5663. cmpq tmp9033, tmp9032
  5664. jl block36
  5665. jmp block37
  5666. block37:
  5667. movq %r15, %rdi
  5668. movq $16, %rsi
  5669. callq 'collect
  5670. jmp block35
  5671. block39:
  5672. movq $0, collectret9023
  5673. jmp block38
  5674. \end{lstlisting}
  5675. \end{minipage}
  5676. \begin{minipage}[t]{0.45\textwidth}
  5677. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5678. start:
  5679. movq $42, vecinit9021
  5680. movq free_ptr(%rip), tmp9028
  5681. movq tmp9028, tmp9029
  5682. addq $16, tmp9029
  5683. movq fromspace_end(%rip), tmp9030
  5684. cmpq tmp9030, tmp9029
  5685. jl block39
  5686. jmp block40
  5687. block40:
  5688. movq %r15, %rdi
  5689. movq $16, %rsi
  5690. callq 'collect
  5691. jmp block38
  5692. \end{lstlisting}
  5693. \end{minipage}
  5694. \caption{Output of the \code{select-instructions} pass.}
  5695. \label{fig:select-instr-output-gc}
  5696. \end{figure}
  5697. \clearpage
  5698. \section{Register Allocation}
  5699. \label{sec:reg-alloc-gc}
  5700. \index{register allocation}
  5701. As discussed earlier in this chapter, the garbage collector needs to
  5702. access all the pointers in the root set, that is, all variables that
  5703. are vectors. It will be the responsibility of the register allocator
  5704. to make sure that:
  5705. \begin{enumerate}
  5706. \item the root stack is used for spilling vector-typed variables, and
  5707. \item if a vector-typed variable is live during a call to the
  5708. collector, it must be spilled to ensure it is visible to the
  5709. collector.
  5710. \end{enumerate}
  5711. The later responsibility can be handled during construction of the
  5712. inference graph, by adding interference edges between the call-live
  5713. vector-typed variables and all the callee-saved registers. (They
  5714. already interfere with the caller-saved registers.) The type
  5715. information for variables is in the \code{program} form, so we
  5716. recommend adding another parameter to the \code{build-interference}
  5717. function to communicate this alist.
  5718. The spilling of vector-typed variables to the root stack can be
  5719. handled after graph coloring, when choosing how to assign the colors
  5720. (integers) to registers and stack locations. The \code{program} output
  5721. of this pass changes to also record the number of spills to the root
  5722. stack.
  5723. % build-interference
  5724. %
  5725. % callq
  5726. % extra parameter for var->type assoc. list
  5727. % update 'program' and 'if'
  5728. % allocate-registers
  5729. % allocate spilled vectors to the rootstack
  5730. % don't change color-graph
  5731. \section{Print x86}
  5732. \label{sec:print-x86-gc}
  5733. \index{prelude}\index{conclusion}
  5734. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5735. \code{print-x86} pass on the running example. In the prelude and
  5736. conclusion of the \code{main} function, we treat the root stack very
  5737. much like the regular stack in that we move the root stack pointer
  5738. (\code{r15}) to make room for the spills to the root stack, except
  5739. that the root stack grows up instead of down. For the running
  5740. example, there was just one spill so we increment \code{r15} by 8
  5741. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5742. One issue that deserves special care is that there may be a call to
  5743. \code{collect} prior to the initializing assignments for all the
  5744. variables in the root stack. We do not want the garbage collector to
  5745. accidentally think that some uninitialized variable is a pointer that
  5746. needs to be followed. Thus, we zero-out all locations on the root
  5747. stack in the prelude of \code{main}. In
  5748. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5749. %
  5750. \lstinline{movq $0, (%r15)}
  5751. %
  5752. accomplishes this task. The garbage collector tests each root to see
  5753. if it is null prior to dereferencing it.
  5754. \begin{figure}[htbp]
  5755. \begin{minipage}[t]{0.5\textwidth}
  5756. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5757. block35:
  5758. movq free_ptr(%rip), %rcx
  5759. addq $16, free_ptr(%rip)
  5760. movq %rcx, %r11
  5761. movq $131, 0(%r11)
  5762. movq %rcx, %r11
  5763. movq -8(%r15), %rax
  5764. movq %rax, 8(%r11)
  5765. movq $0, %rdx
  5766. movq %rcx, %r11
  5767. movq 8(%r11), %rcx
  5768. movq %rcx, %r11
  5769. movq 8(%r11), %rax
  5770. jmp conclusion
  5771. block36:
  5772. movq $0, %rcx
  5773. jmp block35
  5774. block38:
  5775. movq free_ptr(%rip), %rcx
  5776. addq $16, free_ptr(%rip)
  5777. movq %rcx, %r11
  5778. movq $3, 0(%r11)
  5779. movq %rcx, %r11
  5780. movq %rbx, 8(%r11)
  5781. movq $0, %rdx
  5782. movq %rcx, -8(%r15)
  5783. movq free_ptr(%rip), %rcx
  5784. addq $16, %rcx
  5785. movq fromspace_end(%rip), %rdx
  5786. cmpq %rdx, %rcx
  5787. jl block36
  5788. movq %r15, %rdi
  5789. movq $16, %rsi
  5790. callq collect
  5791. jmp block35
  5792. block39:
  5793. movq $0, %rcx
  5794. jmp block38
  5795. \end{lstlisting}
  5796. \end{minipage}
  5797. \begin{minipage}[t]{0.45\textwidth}
  5798. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5799. start:
  5800. movq $42, %rbx
  5801. movq free_ptr(%rip), %rdx
  5802. addq $16, %rdx
  5803. movq fromspace_end(%rip), %rcx
  5804. cmpq %rcx, %rdx
  5805. jl block39
  5806. movq %r15, %rdi
  5807. movq $16, %rsi
  5808. callq collect
  5809. jmp block38
  5810. .globl main
  5811. main:
  5812. pushq %rbp
  5813. movq %rsp, %rbp
  5814. pushq %r13
  5815. pushq %r12
  5816. pushq %rbx
  5817. pushq %r14
  5818. subq $0, %rsp
  5819. movq $16384, %rdi
  5820. movq $16, %rsi
  5821. callq initialize
  5822. movq rootstack_begin(%rip), %r15
  5823. movq $0, (%r15)
  5824. addq $8, %r15
  5825. jmp start
  5826. conclusion:
  5827. subq $8, %r15
  5828. addq $0, %rsp
  5829. popq %r14
  5830. popq %rbx
  5831. popq %r12
  5832. popq %r13
  5833. popq %rbp
  5834. retq
  5835. \end{lstlisting}
  5836. \end{minipage}
  5837. \caption{Output of the \code{print-x86} pass.}
  5838. \label{fig:print-x86-output-gc}
  5839. \end{figure}
  5840. \begin{figure}[p]
  5841. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5842. \node (R3) at (0,2) {\large $R_3$};
  5843. \node (R3-2) at (3,2) {\large $R_3$};
  5844. \node (R3-3) at (6,2) {\large $R_3$};
  5845. \node (R3-4) at (9,2) {\large $R_3$};
  5846. \node (R3-5) at (9,0) {\large $R'_3$};
  5847. \node (R3-6) at (6,0) {\large $R'_3$};
  5848. \node (C2-4) at (3,-2) {\large $C_2$};
  5849. \node (C2-3) at (0,-2) {\large $C_2$};
  5850. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5851. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5852. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5853. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5854. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5855. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5856. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5857. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5858. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5859. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5860. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5861. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5862. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5863. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5864. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5865. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5866. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5867. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5868. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5869. \end{tikzpicture}
  5870. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5871. \label{fig:R3-passes}
  5872. \end{figure}
  5873. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5874. for the compilation of $R_3$.
  5875. \section{Challenge: Simple Structures}
  5876. \label{sec:simple-structures}
  5877. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  5878. $R^s_3$, which extends $R^3$ with support for simple structures.
  5879. Recall that a \code{struct} in Typed Racket is a user-defined data
  5880. type that contains named fields and that is heap allocated, similar to
  5881. a vector. The following is an example of a structure definition, in
  5882. this case the definition of a \code{point} type.
  5883. \begin{lstlisting}
  5884. (struct point ([x : Integer] [y : Integer]) #:mutable)
  5885. \end{lstlisting}
  5886. \begin{figure}[tbp]
  5887. \centering
  5888. \fbox{
  5889. \begin{minipage}{0.96\textwidth}
  5890. \[
  5891. \begin{array}{lcl}
  5892. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5893. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void}\\
  5894. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5895. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  5896. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  5897. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5898. \mid (\key{and}\;\Exp\;\Exp)
  5899. \mid (\key{or}\;\Exp\;\Exp)
  5900. \mid (\key{not}\;\Exp) } \\
  5901. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5902. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  5903. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  5904. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  5905. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  5906. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  5907. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  5908. R_3 &::=& \Def \ldots \; \Exp
  5909. \end{array}
  5910. \]
  5911. \end{minipage}
  5912. }
  5913. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  5914. (Figure~\ref{fig:r3-concrete-syntax}).}
  5915. \label{fig:r3s-concrete-syntax}
  5916. \end{figure}
  5917. An instance of a structure is created using function call syntax, with
  5918. the name of the structure in the function position:
  5919. \begin{lstlisting}
  5920. (point 7 12)
  5921. \end{lstlisting}
  5922. Function-call syntax is also used to read the value in a field of a
  5923. structure. The function name is formed by the structure name, a dash,
  5924. and the field name. The following example uses \code{point-x} and
  5925. \code{point-y} to access the \code{x} and \code{y} fields of two point
  5926. instances.
  5927. \begin{center}
  5928. \begin{lstlisting}
  5929. (let ([pt1 (point 7 12)])
  5930. (let ([pt2 (point 4 3)])
  5931. (+ (- (point-x pt1) (point-x pt2))
  5932. (- (point-y pt1) (point-y pt2)))))
  5933. \end{lstlisting}
  5934. \end{center}
  5935. Similarly, to write to a field of a structure, use its set function,
  5936. whose name starts with \code{set-}, followed by the structure name,
  5937. then a dash, then the field name, and conclused with an exclamation
  5938. mark. The folowing example uses \code{set-point-x!} to change the
  5939. \code{x} field from \code{7} to \code{42}.
  5940. \begin{center}
  5941. \begin{lstlisting}
  5942. (let ([pt (point 7 12)])
  5943. (let ([_ (set-point-x! pt 42)])
  5944. (point-x pt)))
  5945. \end{lstlisting}
  5946. \end{center}
  5947. \begin{exercise}\normalfont
  5948. Extend your compiler with support for simple structures, compiling
  5949. $R^s_3$ to x86 assembly code. Create five new test cases that use
  5950. structures and test your compiler.
  5951. \end{exercise}
  5952. \section{Challenge: Generational Collection}
  5953. The copying collector described in Section~\ref{sec:GC} can incur
  5954. significant runtime overhead because the call to \code{collect} takes
  5955. time proportional to all of the live data. One way to reduce this
  5956. overhead is to reduce how much data is inspected in each call to
  5957. \code{collect}. In particular, researchers have observed that recently
  5958. allocated data is more likely to become garbage then data that has
  5959. survived one or more previous calls to \code{collect}. This insight
  5960. motivated the creation of \emph{generational garbage collectors}
  5961. \index{generational garbage collector} that
  5962. 1) segragates data according to its age into two or more generations,
  5963. 2) allocates less space for younger generations, so collecting them is
  5964. faster, and more space for the older generations, and 3) performs
  5965. collection on the younger generations more frequently then for older
  5966. generations~\citep{Wilson:1992fk}.
  5967. For this challenge assignment, the goal is to adapt the copying
  5968. collector implemented in \code{runtime.c} to use two generations, one
  5969. for young data and one for old data. Each generation consists of a
  5970. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  5971. \code{collect} function to use the two generations.
  5972. \begin{enumerate}
  5973. \item Copy the young generation's FromSpace to its ToSpace then switch
  5974. the role of the ToSpace and FromSpace
  5975. \item If there is enough space for the requested number of bytes in
  5976. the young FromSpace, then return from \code{collect}.
  5977. \item If there is not enough space in the young FromSpace for the
  5978. requested bytes, then move the data from the young generation to the
  5979. old one with the following steps:
  5980. \begin{enumerate}
  5981. \item If there is enough room in the old FromSpace, copy the young
  5982. FromSpace to the old FromSpace and then return.
  5983. \item If there is not enough room in the old FromSpace, then collect
  5984. the old generation by copying the old FromSpace to the old ToSpace
  5985. and swap the roles of the old FromSpace and ToSpace.
  5986. \item If there is enough room now, copy the young FromSpace to the
  5987. old FromSpace and return. Otherwise, allocate a larger FromSpace
  5988. and ToSpace for the old generation. Copy the young FromSpace and
  5989. the old FromSpace into the larger FromSpace for the old
  5990. generation and then return.
  5991. \end{enumerate}
  5992. \end{enumerate}
  5993. We recommend that you generalize the \code{cheney} function so that it
  5994. can be used for all the copies mentioned above: between the young
  5995. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  5996. between the young FromSpace and old FromSpace. This can be
  5997. accomplished by adding parameters to \code{cheney} that replace its
  5998. use of the global variables \code{fromspace\_begin},
  5999. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6000. Note that the collection of the young generation does not traverse the
  6001. old generation. This introduces a potential problem: there may be
  6002. young data that is only reachable through pointers in the old
  6003. generation. If these pointers are not taken into account, the
  6004. collector could throw away young data that is live! One solution,
  6005. called \emph{pointer recording}, is to maintain a set of all the
  6006. pointers from the old generation into the new generation and consider
  6007. this set as part of the root set. To maintain this set, the compiler
  6008. must insert extra instructions around every \code{vector-set!}. If the
  6009. vector being modified is in the old generation, and if the value being
  6010. written is a pointer into the new generation, than that pointer must
  6011. be added to the set. Also, if the value being overwritten was a
  6012. pointer into the new generation, then that pointer should be removed
  6013. from the set.
  6014. \begin{exercise}\normalfont
  6015. Adapt the \code{collect} function in \code{runtime.c} to implement
  6016. generational garbage collection, as outlined in this section.
  6017. Update the code generation for \code{vector-set!} to implement
  6018. pointer recording. Make sure that your new compiler and runtime
  6019. passes your test suite.
  6020. \end{exercise}
  6021. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6022. \chapter{Functions}
  6023. \label{ch:functions}
  6024. \index{function}
  6025. This chapter studies the compilation of functions similar to those
  6026. found in the C language. This corresponds to a subset of Typed Racket
  6027. in which only top-level function definitions are allowed. This kind of
  6028. function is an important stepping stone to implementing
  6029. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6030. is the topic of Chapter~\ref{ch:lambdas}.
  6031. \section{The $R_4$ Language}
  6032. The concrete and abstract syntax for function definitions and function
  6033. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6034. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6035. $R_4$ begin with zero or more function definitions. The function
  6036. names from these definitions are in-scope for the entire program,
  6037. including all other function definitions (so the ordering of function
  6038. definitions does not matter). The concrete syntax for function
  6039. application is $(\Exp \; \Exp \ldots)$ where the first expression must
  6040. evaluate to a function and the rest are the arguments.
  6041. The abstract syntax for function application is
  6042. $\APPLY{\Exp}{\Exp\ldots}$.
  6043. %% The syntax for function application does not include an explicit
  6044. %% keyword, which is error prone when using \code{match}. To alleviate
  6045. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6046. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6047. Functions are first-class in the sense that a function pointer
  6048. \index{function pointer} is data and can be stored in memory or passed
  6049. as a parameter to another function. Thus, we introduce a function
  6050. type, written
  6051. \begin{lstlisting}
  6052. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6053. \end{lstlisting}
  6054. for a function whose $n$ parameters have the types $\Type_1$ through
  6055. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6056. these functions (with respect to Racket functions) is that they are
  6057. not lexically scoped. That is, the only external entities that can be
  6058. referenced from inside a function body are other globally-defined
  6059. functions. The syntax of $R_4$ prevents functions from being nested
  6060. inside each other.
  6061. \begin{figure}[tp]
  6062. \centering
  6063. \fbox{
  6064. \begin{minipage}{0.96\textwidth}
  6065. \small
  6066. \[
  6067. \begin{array}{lcl}
  6068. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6069. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6070. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6071. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  6072. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  6073. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6074. \mid (\key{and}\;\Exp\;\Exp)
  6075. \mid (\key{or}\;\Exp\;\Exp)
  6076. \mid (\key{not}\;\Exp)} \\
  6077. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6078. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6079. (\key{vector-ref}\;\Exp\;\Int)} \\
  6080. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6081. \mid (\key{has-type}~\Exp~\Type)} \\
  6082. &\mid& (\Exp \; \Exp \ldots) \\
  6083. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp) \\
  6084. R_4 &::=& \Def \ldots \; \Exp
  6085. \end{array}
  6086. \]
  6087. \end{minipage}
  6088. }
  6089. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6090. \label{fig:r4-concrete-syntax}
  6091. \end{figure}
  6092. \begin{figure}[tp]
  6093. \centering
  6094. \fbox{
  6095. \begin{minipage}{0.96\textwidth}
  6096. \small
  6097. \[
  6098. \begin{array}{lcl}
  6099. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6100. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6101. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6102. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6103. &\mid& \gray{ \BOOL{\itm{bool}}
  6104. \mid \AND{\Exp}{\Exp} }\\
  6105. &\mid& \gray{ \OR{\Exp}{\Exp}
  6106. \mid \NOT{\Exp} } \\
  6107. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6108. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6109. &\mid& \gray{ \VECTOR{\Exp} } \\
  6110. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  6111. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  6112. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6113. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6114. \Def &::=& \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp}\\
  6115. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp}
  6116. \end{array}
  6117. \]
  6118. \end{minipage}
  6119. }
  6120. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6121. \label{fig:r4-syntax}
  6122. \end{figure}
  6123. The program in Figure~\ref{fig:r4-function-example} is a
  6124. representative example of defining and using functions in $R_4$. We
  6125. define a function \code{map-vec} that applies some other function
  6126. \code{f} to both elements of a vector and returns a new
  6127. vector containing the results. We also define a function \code{add1}.
  6128. The program applies
  6129. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6130. \code{(vector 1 42)}, from which we return the \code{42}.
  6131. \begin{figure}[tbp]
  6132. \begin{lstlisting}
  6133. (define (map-vec [f : (Integer -> Integer)]
  6134. [v : (Vector Integer Integer)])
  6135. : (Vector Integer Integer)
  6136. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6137. (define (add1 [x : Integer]) : Integer
  6138. (+ x 1))
  6139. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6140. \end{lstlisting}
  6141. \caption{Example of using functions in $R_4$.}
  6142. \label{fig:r4-function-example}
  6143. \end{figure}
  6144. The definitional interpreter for $R_4$ is in
  6145. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6146. responsible for setting up the mutual recursion between the top-level
  6147. function definitions. We use the classic back-patching approach that
  6148. uses mutable variables and makes two passes over the function
  6149. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6150. top-level environment using a mutable cons cell for each function
  6151. definition. Note that the \code{lambda} value for each function is
  6152. incomplete; it does not yet include the environment. Once the
  6153. top-level environment is constructed, we then iterate over it and
  6154. update the \code{lambda} values to use the top-level environment.
  6155. \begin{figure}[tp]
  6156. \begin{lstlisting}
  6157. (define (interp-exp env)
  6158. (lambda (e)
  6159. (define recur (interp-exp env))
  6160. (match e
  6161. ...
  6162. [(Apply fun args)
  6163. (define fun-val (recur fun))
  6164. (define arg-vals (for/list ([e args]) (recur e)))
  6165. (match fun-val
  6166. [`(lambda (,xs ...) ,body ,fun-env)
  6167. (define new-env (append (map cons xs arg-vals) fun-env))
  6168. ((interp-exp new-env) body)])]
  6169. ...
  6170. )))
  6171. (define (interp-def d)
  6172. (match d
  6173. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6174. (mcons f `(lambda ,xs ,body ()))]
  6175. ))
  6176. (define (interp-R4 p)
  6177. (match p
  6178. [(ProgramDefsExp info ds body)
  6179. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6180. (for/list ([b top-level])
  6181. (set-mcdr! b (match (mcdr b)
  6182. [`(lambda ,xs ,body ())
  6183. `(lambda ,xs ,body ,top-level)])))
  6184. ((interp-exp top-level) body))]
  6185. ))
  6186. \end{lstlisting}
  6187. \caption{Interpreter for the $R_4$ language.}
  6188. \label{fig:interp-R4}
  6189. \end{figure}
  6190. \section{Functions in x86}
  6191. \label{sec:fun-x86}
  6192. \margincomment{\tiny Make sure callee-saved registers are discussed
  6193. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6194. \margincomment{\tiny Talk about the return address on the
  6195. stack and what callq and retq does.\\ --Jeremy }
  6196. The x86 architecture provides a few features to support the
  6197. implementation of functions. We have already seen that x86 provides
  6198. labels so that one can refer to the location of an instruction, as is
  6199. needed for jump instructions. Labels can also be used to mark the
  6200. beginning of the instructions for a function. Going further, we can
  6201. obtain the address of a label by using the \key{leaq} instruction and
  6202. \key{rip}-relative addressing. For example, the following puts the
  6203. address of the \code{add1} label into the \code{rbx} register.
  6204. \begin{lstlisting}
  6205. leaq add1(%rip), %rbx
  6206. \end{lstlisting}
  6207. The instruction pointer register \key{rip} (aka. the program counter
  6208. or PC) always points to the next instruction to be executed. When
  6209. combined with an label, as in \code{add1(\%rip)}, the linker computes
  6210. the distance $d$ between the address of \code{add1} and where the
  6211. \code{rip} would be at that moment and then changes \code{add1(\%rip)}
  6212. to \code{$d$(\%rip)}, which at runtime will compute the address of
  6213. \code{add1}.
  6214. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6215. jump to a function whose location is given by a label. To support
  6216. function calls in this chapter we instead will be jumping to a
  6217. function whose location is given by an address in a register, that is,
  6218. we need to make an \emph{indirect function call}. The x86 syntax for
  6219. this is a \code{callq} instruction but with an asterisk before the
  6220. register name.\index{indirect function call}
  6221. \begin{lstlisting}
  6222. callq *%rbx
  6223. \end{lstlisting}
  6224. \subsection{Calling Conventions}
  6225. \index{calling conventions}
  6226. The \code{callq} instruction provides partial support for implementing
  6227. functions: it pushes the return address on the stack and it jumps to
  6228. the target. However, \code{callq} does not handle
  6229. \begin{enumerate}
  6230. \item parameter passing,
  6231. \item pushing frames on the procedure call stack and popping them off,
  6232. or
  6233. \item determining how registers are shared by different functions.
  6234. \end{enumerate}
  6235. These issues require coordination between the caller and the callee,
  6236. which is often assembly code written by different programmers or
  6237. generated by different compilers. As a result, people have developed
  6238. \emph{conventions} that govern how functions calls are performed.
  6239. Here we use conventions that are compatible with those of the
  6240. \code{gcc} compiler~\citep{Matz:2013aa}.
  6241. Regarding (1) parameter passing, the convention is to use the
  6242. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  6243. \code{rcx}, \code{r8}, and \code{r9}, in that order, to pass arguments
  6244. to a function. If there are more than six arguments, then the
  6245. convention is to use space on the frame of the caller for the rest of
  6246. the arguments. However, to ease the implementation of efficient tail
  6247. calls (Section~\ref{sec:tail-call}), we arrange to never need more
  6248. than six arguments.
  6249. %
  6250. The register \code{rax} is for the return value of the function.
  6251. \index{prelude}\index{conclusion}
  6252. Regarding (2) frames and the procedure call stack, recall from
  6253. Section~\ref{sec:x86} that the stack grows down, with each function
  6254. call using a chunk of space called a frame. The caller sets the stack
  6255. pointer, register \code{rsp}, to the last data item in its frame. The
  6256. callee must not change anything in the caller's frame, that is,
  6257. anything that is at or above the stack pointer. The callee is free to
  6258. use locations that are below the stack pointer.
  6259. Recall that we are storing variables of vector type on the root stack.
  6260. So the prelude needs to move the root stack pointer \code{r15} up and
  6261. the conclusion needs to move the root stack pointer back down. Also,
  6262. the prelude must initialize to \code{0} this frame's slots in the root
  6263. stack to signal to the garbage collector that those slots do not yet
  6264. contain a pointer to a vector. Otherwise the garbage collector will
  6265. interpret the garbage bits in those slots as memory addresses and try
  6266. to traverse them, causing serious mayhem!
  6267. Regarding (3) the sharing of registers between different functions,
  6268. recall from Section~\ref{sec:calling-conventions} that the registers
  6269. are divided into two groups, the caller-saved registers and the
  6270. callee-saved registers. The caller should assume that all the
  6271. caller-saved registers get overwritten with arbitrary values by the
  6272. callee. That is why we recommend in
  6273. Section~\ref{sec:calling-conventions} that variables that are live
  6274. during a function call should not be assigned to caller-saved
  6275. registers.
  6276. On the flip side, if the callee wants to use a callee-saved register,
  6277. the callee must save the contents of those registers on their stack
  6278. frame and then put them back prior to returning to the caller. That
  6279. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6280. the register allocator assigns a variable to a callee-saved register,
  6281. then the prelude of the \code{main} function must save that register
  6282. to the stack and the conclusion of \code{main} must restore it. This
  6283. recommendation now generalizes to all functions.
  6284. Also recall that the base pointer, register \code{rbp}, is used as a
  6285. point-of-reference within a frame, so that each local variable can be
  6286. accessed at a fixed offset from the base pointer
  6287. (Section~\ref{sec:x86}).
  6288. %
  6289. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6290. and callee frames.
  6291. \begin{figure}[tbp]
  6292. \centering
  6293. \begin{tabular}{r|r|l|l} \hline
  6294. Caller View & Callee View & Contents & Frame \\ \hline
  6295. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6296. 0(\key{\%rbp}) & & old \key{rbp} \\
  6297. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6298. \ldots & & \ldots \\
  6299. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6300. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6301. \ldots & & \ldots \\
  6302. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6303. %% & & \\
  6304. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6305. %% & \ldots & \ldots \\
  6306. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6307. \hline
  6308. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6309. & 0(\key{\%rbp}) & old \key{rbp} \\
  6310. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6311. & \ldots & \ldots \\
  6312. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6313. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6314. & \ldots & \ldots \\
  6315. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6316. \end{tabular}
  6317. \caption{Memory layout of caller and callee frames.}
  6318. \label{fig:call-frames}
  6319. \end{figure}
  6320. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6321. %% local variables and for storing the values of callee-saved registers
  6322. %% (we shall refer to all of these collectively as ``locals''), and that
  6323. %% at the beginning of a function we move the stack pointer \code{rsp}
  6324. %% down to make room for them.
  6325. %% We recommend storing the local variables
  6326. %% first and then the callee-saved registers, so that the local variables
  6327. %% can be accessed using \code{rbp} the same as before the addition of
  6328. %% functions.
  6329. %% To make additional room for passing arguments, we shall
  6330. %% move the stack pointer even further down. We count how many stack
  6331. %% arguments are needed for each function call that occurs inside the
  6332. %% body of the function and find their maximum. Adding this number to the
  6333. %% number of locals gives us how much the \code{rsp} should be moved at
  6334. %% the beginning of the function. In preparation for a function call, we
  6335. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6336. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6337. %% so on.
  6338. %% Upon calling the function, the stack arguments are retrieved by the
  6339. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6340. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6341. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6342. %% the layout of the caller and callee frames. Notice how important it is
  6343. %% that we correctly compute the maximum number of arguments needed for
  6344. %% function calls; if that number is too small then the arguments and
  6345. %% local variables will smash into each other!
  6346. \subsection{Efficient Tail Calls}
  6347. \label{sec:tail-call}
  6348. In general, the amount of stack space used by a program is determined
  6349. by the longest chain of nested function calls. That is, if function
  6350. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6351. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6352. $n$ can grow quite large in the case of recursive or mutually
  6353. recursive functions. However, in some cases we can arrange to use only
  6354. constant space, i.e. $O(1)$, instead of $O(n)$.
  6355. If a function call is the last action in a function body, then that
  6356. call is said to be a \emph{tail call}\index{tail call}.
  6357. For example, in the following
  6358. program, the recursive call to \code{tail-sum} is a tail call.
  6359. \begin{center}
  6360. \begin{lstlisting}
  6361. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6362. (if (eq? n 0)
  6363. r
  6364. (tail-sum (- n 1) (+ n r))))
  6365. (+ (tail-sum 5 0) 27)
  6366. \end{lstlisting}
  6367. \end{center}
  6368. At a tail call, the frame of the caller is no longer needed, so we
  6369. can pop the caller's frame before making the tail call. With this
  6370. approach, a recursive function that only makes tail calls will only
  6371. use $O(1)$ stack space. Functional languages like Racket typically
  6372. rely heavily on recursive functions, so they typically guarantee that
  6373. all tail calls will be optimized in this way.
  6374. However, some care is needed with regards to argument passing in tail
  6375. calls. As mentioned above, for arguments beyond the sixth, the
  6376. convention is to use space in the caller's frame for passing
  6377. arguments. But for a tail call we pop the caller's frame and can no
  6378. longer use it. Another alternative is to use space in the callee's
  6379. frame for passing arguments. However, this option is also problematic
  6380. because the caller and callee's frame overlap in memory. As we begin
  6381. to copy the arguments from their sources in the caller's frame, the
  6382. target locations in the callee's frame might overlap with the sources
  6383. for later arguments! We solve this problem by not using the stack for
  6384. passing more than six arguments but instead using the heap, as we
  6385. describe in the Section~\ref{sec:limit-functions-r4}.
  6386. As mentioned above, for a tail call we pop the caller's frame prior to
  6387. making the tail call. The instructions for popping a frame are the
  6388. instructions that we usually place in the conclusion of a
  6389. function. Thus, we also need to place such code immediately before
  6390. each tail call. These instructions include restoring the callee-saved
  6391. registers, so it is good that the argument passing registers are all
  6392. caller-saved registers.
  6393. One last note regarding which instruction to use to make the tail
  6394. call. When the callee is finished, it should not return to the current
  6395. function, but it should return to the function that called the current
  6396. one. Thus, the return address that is already on the stack is the
  6397. right one, and we should not use \key{callq} to make the tail call, as
  6398. that would unnecessarily overwrite the return address. Instead we can
  6399. simply use the \key{jmp} instruction. Like the indirect function call,
  6400. we write an \emph{indirect jump}\index{indirect jump} with a register
  6401. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6402. jump target because the preceding conclusion overwrites just about
  6403. everything else.
  6404. \begin{lstlisting}
  6405. jmp *%rax
  6406. \end{lstlisting}
  6407. \section{Shrink $R_4$}
  6408. \label{sec:shrink-r4}
  6409. The \code{shrink} pass performs a minor modification to ease the
  6410. later passes. This pass introduces an explicit \code{main} function
  6411. and changes the top \code{ProgramDefsExp} form to
  6412. \code{ProgramDefs} as follows.
  6413. \begin{lstlisting}
  6414. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6415. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6416. \end{lstlisting}
  6417. where $\itm{mainDef}$ is
  6418. \begin{lstlisting}
  6419. (Def main () Integer () |$\Exp'$|)
  6420. \end{lstlisting}
  6421. \section{Reveal Functions and the $F_1$ language}
  6422. \label{sec:reveal-functions-r4}
  6423. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6424. respect: it conflates the use of function names and local
  6425. variables. This is a problem because we need to compile the use of a
  6426. function name differently than the use of a local variable; we need to
  6427. use \code{leaq} to convert the function name (a label in x86) to an
  6428. address in a register. Thus, it is a good idea to create a new pass
  6429. that changes function references from just a symbol $f$ to
  6430. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6431. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6432. \begin{figure}[tp]
  6433. \centering
  6434. \fbox{
  6435. \begin{minipage}{0.96\textwidth}
  6436. \[
  6437. \begin{array}{lcl}
  6438. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6439. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6440. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6441. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6442. &\mid& \gray{ \BOOL{\itm{bool}}
  6443. \mid \AND{\Exp}{\Exp} }\\
  6444. &\mid& \gray{ \OR{\Exp}{\Exp}
  6445. \mid \NOT{\Exp} } \\
  6446. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6447. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6448. &\mid& \gray{ \VECTOR{\Exp} } \\
  6449. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  6450. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  6451. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6452. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6453. &\mid& \FUNREF{\Var}\\
  6454. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6455. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6456. \end{array}
  6457. \]
  6458. \end{minipage}
  6459. }
  6460. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6461. (Figure~\ref{fig:r4-syntax}).}
  6462. \label{fig:f1-syntax}
  6463. \end{figure}
  6464. %% Distinguishing between calls in tail position and non-tail position
  6465. %% requires the pass to have some notion of context. We recommend using
  6466. %% two mutually recursive functions, one for processing expressions in
  6467. %% tail position and another for the rest.
  6468. Placing this pass after \code{uniquify} will make sure that there are
  6469. no local variables and functions that share the same name. On the
  6470. other hand, \code{reveal-functions} needs to come before the
  6471. \code{explicate-control} pass because that pass helps us compile
  6472. \code{FunRef} forms into assignment statements.
  6473. \section{Limit Functions}
  6474. \label{sec:limit-functions-r4}
  6475. Recall that we wish to limit the number of function parameters to six
  6476. so that we do not need to use the stack for argument passing, which
  6477. makes it easier to implement efficient tail calls. However, because
  6478. the input language $R_4$ supports arbitrary numbers of function
  6479. arguments, we have some work to do!
  6480. This pass transforms functions and function calls that involve more
  6481. than six arguments to pass the first five arguments as usual, but it
  6482. packs the rest of the arguments into a vector and passes it as the
  6483. sixth argument. So for any function call with $n$ arguments more than
  6484. six, the \code{limit-functions} pass transforms it in the following
  6485. way.
  6486. \begin{tabular}{lll}
  6487. \begin{minipage}{0.2\textwidth}
  6488. \begin{lstlisting}
  6489. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6490. \end{lstlisting}
  6491. \end{minipage}
  6492. &
  6493. $\Rightarrow$
  6494. &
  6495. \begin{minipage}{0.4\textwidth}
  6496. \begin{lstlisting}
  6497. (|$e_0$| |$e_1$| |$\ldots$| |$e_5$| (vector |$e_6$| |$\ldots$| |$e_n$|))
  6498. \end{lstlisting}
  6499. \end{minipage}
  6500. \end{tabular}
  6501. \margincomment{UNDER CONSTRUCTION --Jeremy}
  6502. In the body of the function, all occurrences of the $i$th argument in
  6503. which $i>5$ must be replaced with a \code{vector-ref}.
  6504. \section{Remove Complex Operators and Operands}
  6505. \label{sec:rco-r4}
  6506. The primary decisions to make for this pass is whether to classify
  6507. \code{fun-ref} and \code{app} as either simple or complex
  6508. expressions. Recall that a simple expression will eventually end up as
  6509. just an ``immediate'' argument of an x86 instruction. Function
  6510. application will be translated to a sequence of instructions, so
  6511. \code{app} must be classified as complex expression. Regarding
  6512. \code{fun-ref}, as discussed above, the function label needs to
  6513. be converted to an address using the \code{leaq} instruction. Thus,
  6514. even though \code{fun-ref} seems rather simple, it needs to be
  6515. classified as a complex expression so that we generate an assignment
  6516. statement with a left-hand side that can serve as the target of the
  6517. \code{leaq}.
  6518. \section{Explicate Control and the $C_3$ language}
  6519. \label{sec:explicate-control-r4}
  6520. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  6521. \key{explicate-control}. The three mutually recursive functions for
  6522. this pass, for assignment, tail, and predicate contexts, must all be
  6523. updated with cases for \code{fun-ref} and \code{app}. In
  6524. assignment and predicate contexts, \code{app} becomes \code{call},
  6525. whereas in tail position \code{app} becomes \code{tailcall}. We
  6526. recommend defining a new function for processing function definitions.
  6527. This code is similar to the case for \code{program} in $R_3$. The
  6528. top-level \code{explicate-control} function that handles the
  6529. \code{program} form of $R_4$ can then apply this new function to all
  6530. the function definitions.
  6531. \begin{figure}[tp]
  6532. \fbox{
  6533. \begin{minipage}{0.96\textwidth}
  6534. \[
  6535. \begin{array}{lcl}
  6536. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6537. \\
  6538. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6539. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  6540. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  6541. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6542. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  6543. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6544. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg\ldots) \\
  6545. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6546. \mid (\key{collect} \,\itm{int}) }\\
  6547. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6548. &\mid& \gray{(\key{goto}\,\itm{label})
  6549. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6550. &\mid& (\key{tailcall} \,\Arg\,\Arg\ldots) \\
  6551. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6552. C_3 & ::= & (\key{program}\;\itm{info}\;\Def\ldots)
  6553. \end{array}
  6554. \]
  6555. \end{minipage}
  6556. }
  6557. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  6558. \label{fig:c3-syntax}
  6559. \end{figure}
  6560. \section{Uncover Locals}
  6561. \label{sec:uncover-locals-r4}
  6562. The function for processing $\Tail$ should be updated with a case for
  6563. \code{tailcall}. We also recommend creating a new function for
  6564. processing function definitions. Each function definition in $C_3$ has
  6565. its own set of local variables, so the code for function definitions
  6566. should be similar to the case for the \code{program} form in $C_2$.
  6567. \section{Select Instructions and the x86$_3$ Language}
  6568. \label{sec:select-r4}
  6569. \index{instruction selection}
  6570. The output of select instructions is a program in the x86$_3$
  6571. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6572. \index{x86}
  6573. \begin{figure}[tp]
  6574. \fbox{
  6575. \begin{minipage}{0.96\textwidth}
  6576. \[
  6577. \begin{array}{lcl}
  6578. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6579. \mid (\key{deref}\,\Reg\,\Int) } \\
  6580. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6581. \mid (\key{global}\; \itm{name}) } \\
  6582. &\mid& (\key{fun-ref}\; \itm{label})\\
  6583. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6584. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6585. (\key{subq} \; \Arg\; \Arg) \mid
  6586. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6587. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6588. (\key{pushq}\;\Arg) \mid
  6589. (\key{popq}\;\Arg) \mid
  6590. (\key{retq}) } \\
  6591. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6592. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6593. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6594. \mid (\key{jmp} \; \itm{label})
  6595. \mid (\key{j}\itm{cc} \; \itm{label})
  6596. \mid (\key{label} \; \itm{label}) } \\
  6597. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6598. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  6599. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6600. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6601. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6602. \end{array}
  6603. \]
  6604. \end{minipage}
  6605. }
  6606. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6607. \label{fig:x86-3}
  6608. \end{figure}
  6609. \margincomment{TODO: abstract syntax for $x86_3$. -Jeremy}
  6610. An assignment of \code{FunRef} becomes a \code{leaq} instruction
  6611. as follows: \\
  6612. \begin{tabular}{lll}
  6613. \begin{minipage}{0.45\textwidth}
  6614. \begin{lstlisting}
  6615. (Assign |$\itm{lhs}$| (FunRef |$f$|))
  6616. \end{lstlisting}
  6617. \end{minipage}
  6618. &
  6619. $\Rightarrow$
  6620. &
  6621. \begin{minipage}{0.4\textwidth}
  6622. \begin{lstlisting}
  6623. (Instr 'leaq (list (FunRef |$f$|) |$\itm{lhs}'$|))
  6624. \end{lstlisting}
  6625. \end{minipage}
  6626. \end{tabular} \\
  6627. Regarding function definitions, we need to remove their parameters and
  6628. instead perform parameter passing in terms of the conventions
  6629. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  6630. in the argument passing registers, and inside the function we should
  6631. generate a \code{movq} instruction for each parameter, to move the
  6632. argument value from the appropriate register to a new local variable
  6633. with the same name as the old parameter.
  6634. Next, consider the compilation of function calls, which have the
  6635. following form upon input to \code{select-instructions}.
  6636. \begin{lstlisting}
  6637. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  6638. \end{lstlisting}
  6639. In the mirror image of handling the parameters of function
  6640. definitions, the arguments \itm{args} need to be moved to the argument
  6641. passing registers.
  6642. %
  6643. Once the instructions for parameter passing have been generated, the
  6644. function call itself can be performed with an indirect function call,
  6645. for which I recommend creating the new instruction
  6646. \code{indirect-callq}. Of course, the return value from the function
  6647. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  6648. \begin{lstlisting}
  6649. (indirect-callq |\itm{fun}|)
  6650. (movq (reg rax) |\itm{lhs}|)
  6651. \end{lstlisting}
  6652. Regarding tail calls, the parameter passing is the same as non-tail
  6653. calls: generate instructions to move the arguments into to the
  6654. argument passing registers. After that we need to pop the frame from
  6655. the procedure call stack. However, we do not yet know how big the
  6656. frame is; that gets determined during register allocation. So instead
  6657. of generating those instructions here, we invent a new instruction
  6658. that means ``pop the frame and then do an indirect jump'', which we
  6659. name \code{tail-jmp}.
  6660. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6661. using the label \code{start} for the initial block of a program, and
  6662. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6663. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  6664. can be compiled to an assignment to \code{rax} followed by a jump to
  6665. \code{conclusion}. With the addition of function definitions, we will
  6666. have a starting block and conclusion for each function, but their
  6667. labels need to be unique. We recommend prepending the function's name
  6668. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6669. labels. (Alternatively, one could \code{gensym} labels for the start
  6670. and conclusion and store them in the $\itm{info}$ field of the
  6671. function definition.)
  6672. \section{Uncover Live}
  6673. %% The rest of the passes need only minor modifications to handle the new
  6674. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6675. %% \code{leaq}.
  6676. Inside \code{uncover-live}, when computing the $W$ set (written
  6677. variables) for an \code{indirect-callq} instruction, we recommend
  6678. including all the caller-saved registers, which will have the affect
  6679. of making sure that no caller-saved register actually needs to be
  6680. saved.
  6681. \section{Build Interference Graph}
  6682. With the addition of function definitions, we compute an interference
  6683. graph for each function (not just one for the whole program).
  6684. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6685. spill vector-typed variables that are live during a call to the
  6686. \code{collect}. With the addition of functions to our language, we
  6687. need to revisit this issue. Many functions will perform allocation and
  6688. therefore have calls to the collector inside of them. Thus, we should
  6689. not only spill a vector-typed variable when it is live during a call
  6690. to \code{collect}, but we should spill the variable if it is live
  6691. during any function call. Thus, in the \code{build-interference} pass,
  6692. we recommend adding interference edges between call-live vector-typed
  6693. variables and the callee-saved registers (in addition to the usual
  6694. addition of edges between call-live variables and the caller-saved
  6695. registers).
  6696. \section{Patch Instructions}
  6697. In \code{patch-instructions}, you should deal with the x86
  6698. idiosyncrasy that the destination argument of \code{leaq} must be a
  6699. register. Additionally, you should ensure that the argument of
  6700. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  6701. code generation more convenient, because we will be trampling many
  6702. registers before the tail call (as explained below).
  6703. \section{Print x86}
  6704. For the \code{print-x86} pass, we recommend the following translations:
  6705. \begin{lstlisting}
  6706. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6707. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6708. \end{lstlisting}
  6709. Handling \code{tail-jmp} requires a bit more care. A straightforward
  6710. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  6711. is what we will want to do, but before the jump we need to pop the
  6712. current frame. So we need to restore the state of the registers to the
  6713. point they were at when the current function was called. This
  6714. sequence of instructions is the same as the code for the conclusion of
  6715. a function.
  6716. Note that your \code{print-x86} pass needs to add the code for saving
  6717. and restoring callee-saved registers, if you have not already
  6718. implemented that. This is necessary when generating code for function
  6719. definitions.
  6720. \section{An Example Translation}
  6721. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6722. function in $R_4$ to x86. The figure also includes the results of the
  6723. \code{explicate-control} and \code{select-instructions} passes. We
  6724. have omitted the \code{has-type} AST nodes for readability. Can you
  6725. see any ways to improve the translation?
  6726. \begin{figure}[tbp]
  6727. \begin{tabular}{ll}
  6728. \begin{minipage}{0.45\textwidth}
  6729. % s3_2.rkt
  6730. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6731. (program
  6732. (define (add [x : Integer]
  6733. [y : Integer])
  6734. : Integer (+ x y))
  6735. (add 40 2))
  6736. \end{lstlisting}
  6737. $\Downarrow$
  6738. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6739. (program ()
  6740. (define (add86 [x87 : Integer]
  6741. [y88 : Integer]) : Integer ()
  6742. ((add86start . (return (+ x87 y88)))))
  6743. (define (main) : Integer ()
  6744. ((mainstart .
  6745. (seq (assign tmp89 (fun-ref add86))
  6746. (tailcall tmp89 40 2))))))
  6747. \end{lstlisting}
  6748. \end{minipage}
  6749. &
  6750. $\Rightarrow$
  6751. \begin{minipage}{0.5\textwidth}
  6752. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6753. (program ()
  6754. (define (add86)
  6755. ((locals (x87 . Integer) (y88 . Integer))
  6756. (num-params . 2))
  6757. ((add86start .
  6758. (block ()
  6759. (movq (reg rcx) (var x87))
  6760. (movq (reg rdx) (var y88))
  6761. (movq (var x87) (reg rax))
  6762. (addq (var y88) (reg rax))
  6763. (jmp add86conclusion)))))
  6764. (define (main)
  6765. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6766. (num-params . 0))
  6767. ((mainstart .
  6768. (block ()
  6769. (leaq (fun-ref add86) (var tmp89))
  6770. (movq (int 40) (reg rcx))
  6771. (movq (int 2) (reg rdx))
  6772. (tail-jmp (var tmp89))))))
  6773. \end{lstlisting}
  6774. $\Downarrow$
  6775. \end{minipage}
  6776. \end{tabular}
  6777. \begin{tabular}{lll}
  6778. \begin{minipage}{0.3\textwidth}
  6779. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6780. _add90start:
  6781. movq %rcx, %rsi
  6782. movq %rdx, %rcx
  6783. movq %rsi, %rax
  6784. addq %rcx, %rax
  6785. jmp _add90conclusion
  6786. .globl _add90
  6787. .align 16
  6788. _add90:
  6789. pushq %rbp
  6790. movq %rsp, %rbp
  6791. pushq %r12
  6792. pushq %rbx
  6793. pushq %r13
  6794. pushq %r14
  6795. subq $0, %rsp
  6796. jmp _add90start
  6797. _add90conclusion:
  6798. addq $0, %rsp
  6799. popq %r14
  6800. popq %r13
  6801. popq %rbx
  6802. popq %r12
  6803. subq $0, %r15
  6804. popq %rbp
  6805. retq
  6806. \end{lstlisting}
  6807. \end{minipage}
  6808. &
  6809. \begin{minipage}{0.3\textwidth}
  6810. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6811. _mainstart:
  6812. leaq _add90(%rip), %rsi
  6813. movq $40, %rcx
  6814. movq $2, %rdx
  6815. movq %rsi, %rax
  6816. addq $0, %rsp
  6817. popq %r14
  6818. popq %r13
  6819. popq %rbx
  6820. popq %r12
  6821. subq $0, %r15
  6822. popq %rbp
  6823. jmp *%rax
  6824. .globl _main
  6825. .align 16
  6826. _main:
  6827. pushq %rbp
  6828. movq %rsp, %rbp
  6829. pushq %r12
  6830. pushq %rbx
  6831. pushq %r13
  6832. pushq %r14
  6833. subq $0, %rsp
  6834. movq $16384, %rdi
  6835. movq $16, %rsi
  6836. callq _initialize
  6837. movq _rootstack_begin(%rip), %r15
  6838. jmp _mainstart
  6839. \end{lstlisting}
  6840. \end{minipage}
  6841. &
  6842. \begin{minipage}{0.3\textwidth}
  6843. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6844. _mainconclusion:
  6845. addq $0, %rsp
  6846. popq %r14
  6847. popq %r13
  6848. popq %rbx
  6849. popq %r12
  6850. subq $0, %r15
  6851. popq %rbp
  6852. retq
  6853. \end{lstlisting}
  6854. \end{minipage}
  6855. \end{tabular}
  6856. \caption{Example compilation of a simple function to x86.}
  6857. \label{fig:add-fun}
  6858. \end{figure}
  6859. \begin{exercise}\normalfont
  6860. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6861. Create 5 new programs that use functions, including examples that pass
  6862. functions and return functions from other functions and including
  6863. recursive functions. Test your compiler on these new programs and all
  6864. of your previously created test programs.
  6865. \end{exercise}
  6866. \begin{figure}[p]
  6867. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6868. \node (R4) at (0,2) {\large $R_4$};
  6869. \node (R4-2) at (3,2) {\large $R_4$};
  6870. \node (R4-3) at (6,2) {\large $R_4$};
  6871. \node (F1-1) at (12,0) {\large $F_1$};
  6872. \node (F1-2) at (9,0) {\large $F_1$};
  6873. \node (F1-3) at (6,0) {\large $F_1$};
  6874. \node (F1-4) at (3,0) {\large $F_1$};
  6875. \node (C3-1) at (6,-2) {\large $C_3$};
  6876. \node (C3-2) at (3,-2) {\large $C_3$};
  6877. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6878. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6879. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  6880. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6881. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6882. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6883. \path[->,bend left=15] (R4) edge [above] node
  6884. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6885. \path[->,bend left=15] (R4-2) edge [above] node
  6886. {\ttfamily\footnotesize uniquify} (R4-3);
  6887. \path[->,bend left=15] (R4-3) edge [right] node
  6888. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6889. \path[->,bend left=15] (F1-1) edge [below] node
  6890. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6891. \path[->,bend right=15] (F1-2) edge [above] node
  6892. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6893. \path[->,bend right=15] (F1-3) edge [above] node
  6894. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6895. \path[->,bend left=15] (F1-4) edge [right] node
  6896. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6897. \path[->,bend left=15] (C3-1) edge [below] node
  6898. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6899. \path[->,bend right=15] (C3-2) edge [left] node
  6900. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6901. \path[->,bend left=15] (x86-2) edge [left] node
  6902. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6903. \path[->,bend right=15] (x86-2-1) edge [below] node
  6904. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6905. \path[->,bend right=15] (x86-2-2) edge [left] node
  6906. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6907. \path[->,bend left=15] (x86-3) edge [above] node
  6908. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6909. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6910. \end{tikzpicture}
  6911. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6912. \label{fig:R4-passes}
  6913. \end{figure}
  6914. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6915. the compilation of $R_4$.
  6916. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6917. \chapter{Lexically Scoped Functions}
  6918. \label{ch:lambdas}
  6919. \index{lambda}
  6920. \index{lexical scoping}
  6921. This chapter studies lexically scoped functions as they appear in
  6922. functional languages such as Racket. By lexical scoping we mean that a
  6923. function's body may refer to variables whose binding site is outside
  6924. of the function, in an enclosing scope.
  6925. %
  6926. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6927. anonymous function defined using the \key{lambda} form. The body of
  6928. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6929. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6930. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6931. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6932. returned from the function \code{f}. Below the definition of \code{f},
  6933. we have two calls to \code{f} with different arguments for \code{x},
  6934. first \code{5} then \code{3}. The functions returned from \code{f} are
  6935. bound to variables \code{g} and \code{h}. Even though these two
  6936. functions were created by the same \code{lambda}, they are really
  6937. different functions because they use different values for
  6938. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6939. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6940. the result of this program is \code{42}.
  6941. \begin{figure}[btp]
  6942. % s4_6.rkt
  6943. \begin{lstlisting}
  6944. (define (f [x : Integer]) : (Integer -> Integer)
  6945. (let ([y 4])
  6946. (lambda: ([z : Integer]) : Integer
  6947. (+ x (+ y z)))))
  6948. (let ([g (f 5)])
  6949. (let ([h (f 3)])
  6950. (+ (g 11) (h 15))))
  6951. \end{lstlisting}
  6952. \caption{Example of a lexically scoped function.}
  6953. \label{fig:lexical-scoping}
  6954. \end{figure}
  6955. \section{The $R_5$ Language}
  6956. The syntax for this language with anonymous functions and lexical
  6957. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6958. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6959. for function application. In this chapter we shall describe how to
  6960. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6961. into a combination of functions (as in $R_4$) and tuples (as in
  6962. $R_3$).
  6963. \begin{figure}[tp]
  6964. \centering
  6965. \fbox{
  6966. \begin{minipage}{0.96\textwidth}
  6967. \[
  6968. \begin{array}{lcl}
  6969. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6970. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  6971. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  6972. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6973. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6974. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6975. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6976. \mid (\key{and}\;\Exp\;\Exp)
  6977. \mid (\key{or}\;\Exp\;\Exp)
  6978. \mid (\key{not}\;\Exp) } \\
  6979. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6980. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6981. (\key{vector-ref}\;\Exp\;\Int)} \\
  6982. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6983. &\mid& \gray{(\Exp \; \Exp\ldots)} \\
  6984. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp) \\
  6985. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  6986. R_5 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  6987. \end{array}
  6988. \]
  6989. \end{minipage}
  6990. }
  6991. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6992. with \key{lambda}.}
  6993. \label{fig:r5-syntax}
  6994. \end{figure}
  6995. To compile lexically-scoped functions to top-level function
  6996. definitions, the compiler will need to provide special treatment to
  6997. variable occurrences such as \code{x} and \code{y} in the body of the
  6998. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6999. of $R_4$ may not refer to variables defined outside the function. To
  7000. identify such variable occurrences, we review the standard notion of
  7001. free variable.
  7002. \begin{definition}
  7003. A variable is \emph{free with respect to an expression} $e$ if the
  7004. variable occurs inside $e$ but does not have an enclosing binding in
  7005. $e$.\index{free variable}
  7006. \end{definition}
  7007. For example, the variables \code{x}, \code{y}, and \code{z} are all
  7008. free with respect to the expression \code{(+ x (+ y z))}. On the
  7009. other hand, only \code{x} and \code{y} are free with respect to the
  7010. following expression because \code{z} is bound by the \code{lambda}.
  7011. \begin{lstlisting}
  7012. (lambda: ([z : Integer]) : Integer
  7013. (+ x (+ y z)))
  7014. \end{lstlisting}
  7015. Once we have identified the free variables of a \code{lambda}, we need
  7016. to arrange for some way to transport, at runtime, the values of those
  7017. variables from the point where the \code{lambda} was created to the
  7018. point where the \code{lambda} is applied. Referring again to
  7019. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  7020. needs to be used in the application of \code{g} to \code{11}, but the
  7021. binding of \code{x} to \code{3} needs to be used in the application of
  7022. \code{h} to \code{15}. An efficient solution to the problem, due to
  7023. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7024. free variables together with the function pointer for the lambda's
  7025. code, an arrangement called a \emph{flat closure} (which we shorten to
  7026. just ``closure'').
  7027. \index{closure}\index{flat closure}
  7028. Fortunately, we have all the ingredients to make
  7029. closures, Chapter~\ref{ch:tuples} gave us vectors and
  7030. Chapter~\ref{ch:functions} gave us function pointers. The function
  7031. pointer shall reside at index $0$ and the values for free variables
  7032. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  7033. the two closures created by the two calls to \code{f} in
  7034. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  7035. the same \key{lambda}, they share the same function pointer but differ
  7036. in the values for the free variable \code{x}.
  7037. \begin{figure}[tbp]
  7038. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7039. \caption{Example closure representation for the \key{lambda}'s
  7040. in Figure~\ref{fig:lexical-scoping}.}
  7041. \label{fig:closures}
  7042. \end{figure}
  7043. \section{Interpreting $R_5$}
  7044. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7045. $R_5$. The clause for \key{lambda} saves the current environment
  7046. inside the returned \key{lambda}. Then the clause for \key{app} uses
  7047. the environment from the \key{lambda}, the \code{lam-env}, when
  7048. interpreting the body of the \key{lambda}. The \code{lam-env}
  7049. environment is extended with the mapping of parameters to argument
  7050. values.
  7051. \begin{figure}[tbp]
  7052. \begin{lstlisting}
  7053. (define (interp-exp env)
  7054. (lambda (e)
  7055. (define recur (interp-exp env))
  7056. (match e
  7057. ...
  7058. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  7059. `(lambda ,xs ,body ,env)]
  7060. [`(app ,fun ,args ...)
  7061. (define fun-val ((interp-exp env) fun))
  7062. (define arg-vals (map (interp-exp env) args))
  7063. (match fun-val
  7064. [`(lambda (,xs ...) ,body ,lam-env)
  7065. (define new-env (append (map cons xs arg-vals) lam-env))
  7066. ((interp-exp new-env) body)]
  7067. [else (error "interp-exp, expected function, not" fun-val)])]
  7068. [else (error 'interp-exp "unrecognized expression")]
  7069. )))
  7070. \end{lstlisting}
  7071. \caption{Interpreter for $R_5$.}
  7072. \label{fig:interp-R5}
  7073. \end{figure}
  7074. \section{Type Checking $R_5$}
  7075. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  7076. \key{lambda} form. The body of the \key{lambda} is checked in an
  7077. environment that includes the current environment (because it is
  7078. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7079. require the body's type to match the declared return type.
  7080. \begin{figure}[tbp]
  7081. \begin{lstlisting}
  7082. (define (typecheck-R5 env)
  7083. (lambda (e)
  7084. (match e
  7085. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  7086. (define new-env (append (map cons xs Ts) env))
  7087. (define bodyT ((typecheck-R5 new-env) body))
  7088. (cond [(equal? rT bodyT)
  7089. `(,@Ts -> ,rT)]
  7090. [else
  7091. (error "mismatch in return type" bodyT rT)])]
  7092. ...
  7093. )))
  7094. \end{lstlisting}
  7095. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7096. \label{fig:typecheck-R5}
  7097. \end{figure}
  7098. \section{Closure Conversion}
  7099. The compiling of lexically-scoped functions into top-level function
  7100. definitions is accomplished in the pass \code{convert-to-closures}
  7101. that comes after \code{reveal-functions} and before
  7102. \code{limit-functions}.
  7103. As usual, we shall implement the pass as a recursive function over the
  7104. AST. All of the action is in the clauses for \key{lambda} and
  7105. \key{app}. We transform a \key{lambda} expression into an expression
  7106. that creates a closure, that is, creates a vector whose first element
  7107. is a function pointer and the rest of the elements are the free
  7108. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7109. generated to identify the function.
  7110. \begin{tabular}{lll}
  7111. \begin{minipage}{0.4\textwidth}
  7112. \begin{lstlisting}
  7113. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7114. \end{lstlisting}
  7115. \end{minipage}
  7116. &
  7117. $\Rightarrow$
  7118. &
  7119. \begin{minipage}{0.4\textwidth}
  7120. \begin{lstlisting}
  7121. (vector |\itm{name}| |\itm{fvs}| ...)
  7122. \end{lstlisting}
  7123. \end{minipage}
  7124. \end{tabular} \\
  7125. %
  7126. In addition to transforming each \key{lambda} into a \key{vector}, we
  7127. must create a top-level function definition for each \key{lambda}, as
  7128. shown below.\\
  7129. \begin{minipage}{0.8\textwidth}
  7130. \begin{lstlisting}
  7131. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7132. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7133. ...
  7134. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7135. |\itm{body'}|)...))
  7136. \end{lstlisting}
  7137. \end{minipage}\\
  7138. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7139. parameters are the normal parameters of the \key{lambda}. The types
  7140. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7141. underscore is a dummy type because it is rather difficult to give a
  7142. type to the function in the closure's type, and it does not matter.
  7143. The sequence of \key{let} forms bind the free variables to their
  7144. values obtained from the closure.
  7145. We transform function application into code that retrieves the
  7146. function pointer from the closure and then calls the function, passing
  7147. in the closure as the first argument. We bind $e'$ to a temporary
  7148. variable to avoid code duplication.
  7149. \begin{tabular}{lll}
  7150. \begin{minipage}{0.3\textwidth}
  7151. \begin{lstlisting}
  7152. (app |$e$| |\itm{es}| ...)
  7153. \end{lstlisting}
  7154. \end{minipage}
  7155. &
  7156. $\Rightarrow$
  7157. &
  7158. \begin{minipage}{0.5\textwidth}
  7159. \begin{lstlisting}
  7160. (let ([|\itm{tmp}| |$e'$|])
  7161. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7162. \end{lstlisting}
  7163. \end{minipage}
  7164. \end{tabular} \\
  7165. There is also the question of what to do with top-level function
  7166. definitions. To maintain a uniform translation of function
  7167. application, we turn function references into closures.
  7168. \begin{tabular}{lll}
  7169. \begin{minipage}{0.3\textwidth}
  7170. \begin{lstlisting}
  7171. (fun-ref |$f$|)
  7172. \end{lstlisting}
  7173. \end{minipage}
  7174. &
  7175. $\Rightarrow$
  7176. &
  7177. \begin{minipage}{0.5\textwidth}
  7178. \begin{lstlisting}
  7179. (vector (fun-ref |$f$|))
  7180. \end{lstlisting}
  7181. \end{minipage}
  7182. \end{tabular} \\
  7183. %
  7184. The top-level function definitions need to be updated as well to take
  7185. an extra closure parameter.
  7186. \section{An Example Translation}
  7187. \label{sec:example-lambda}
  7188. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  7189. conversion for the example program demonstrating lexical scoping that
  7190. we discussed at the beginning of this chapter.
  7191. \begin{figure}[h]
  7192. \begin{minipage}{0.8\textwidth}
  7193. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7194. (program
  7195. (define (f [x : Integer]) : (Integer -> Integer)
  7196. (let ([y 4])
  7197. (lambda: ([z : Integer]) : Integer
  7198. (+ x (+ y z)))))
  7199. (let ([g (f 5)])
  7200. (let ([h (f 3)])
  7201. (+ (g 11) (h 15)))))
  7202. \end{lstlisting}
  7203. $\Downarrow$
  7204. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7205. (program (type Integer)
  7206. (define (f (x : Integer)) : (Integer -> Integer)
  7207. (let ((y 4))
  7208. (lambda: ((z : Integer)) : Integer
  7209. (+ x (+ y z)))))
  7210. (let ((g (app (fun-ref f) 5)))
  7211. (let ((h (app (fun-ref f) 3)))
  7212. (+ (app g 11) (app h 15)))))
  7213. \end{lstlisting}
  7214. $\Downarrow$
  7215. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7216. (program (type Integer)
  7217. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  7218. (let ((y 4))
  7219. (vector (fun-ref lam.1) x y)))
  7220. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  7221. (let ((x (vector-ref clos.2 1)))
  7222. (let ((y (vector-ref clos.2 2)))
  7223. (+ x (+ y z)))))
  7224. (let ((g (let ((t.1 (vector (fun-ref f))))
  7225. (app (vector-ref t.1 0) t.1 5))))
  7226. (let ((h (let ((t.2 (vector (fun-ref f))))
  7227. (app (vector-ref t.2 0) t.2 3))))
  7228. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  7229. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  7230. \end{lstlisting}
  7231. \end{minipage}
  7232. \caption{Example of closure conversion.}
  7233. \label{fig:lexical-functions-example}
  7234. \end{figure}
  7235. \begin{figure}[p]
  7236. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7237. \node (R4) at (0,2) {\large $R_4$};
  7238. \node (R4-2) at (3,2) {\large $R_4$};
  7239. \node (R4-3) at (6,2) {\large $R_4$};
  7240. \node (F1-1) at (12,0) {\large $F_1$};
  7241. \node (F1-2) at (9,0) {\large $F_1$};
  7242. \node (F1-3) at (6,0) {\large $F_1$};
  7243. \node (F1-4) at (3,0) {\large $F_1$};
  7244. \node (F1-5) at (0,0) {\large $F_1$};
  7245. \node (C3-1) at (6,-2) {\large $C_3$};
  7246. \node (C3-2) at (3,-2) {\large $C_3$};
  7247. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7248. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7249. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7250. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7251. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7252. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7253. \path[->,bend left=15] (R4) edge [above] node
  7254. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7255. \path[->,bend left=15] (R4-2) edge [above] node
  7256. {\ttfamily\footnotesize uniquify} (R4-3);
  7257. \path[->] (R4-3) edge [right] node
  7258. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7259. \path[->,bend left=15] (F1-1) edge [below] node
  7260. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7261. \path[->,bend right=15] (F1-2) edge [above] node
  7262. {\ttfamily\footnotesize limit-functions} (F1-3);
  7263. \path[->,bend right=15] (F1-3) edge [above] node
  7264. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7265. \path[->,bend right=15] (F1-4) edge [above] node
  7266. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7267. \path[->] (F1-5) edge [left] node
  7268. {\ttfamily\footnotesize explicate-control} (C3-1);
  7269. \path[->,bend left=15] (C3-1) edge [below] node
  7270. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7271. \path[->,bend right=15] (C3-2) edge [left] node
  7272. {\ttfamily\footnotesize select-instr.} (x86-2);
  7273. \path[->,bend left=15] (x86-2) edge [left] node
  7274. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7275. \path[->,bend right=15] (x86-2-1) edge [below] node
  7276. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7277. \path[->,bend right=15] (x86-2-2) edge [left] node
  7278. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7279. \path[->,bend left=15] (x86-3) edge [above] node
  7280. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7281. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7282. \end{tikzpicture}
  7283. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7284. functions.}
  7285. \label{fig:R5-passes}
  7286. \end{figure}
  7287. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7288. for the compilation of $R_5$.
  7289. \begin{exercise}\normalfont
  7290. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7291. Create 5 new programs that use \key{lambda} functions and make use of
  7292. lexical scoping. Test your compiler on these new programs and all of
  7293. your previously created test programs.
  7294. \end{exercise}
  7295. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7296. \chapter{Dynamic Typing}
  7297. \label{ch:type-dynamic}
  7298. \index{dynamic typing}
  7299. In this chapter we discuss the compilation of a dynamically typed
  7300. language, named $R_7$, that is a subset of the Racket
  7301. language. (Recall that in the previous chapters we have studied
  7302. subsets of the \emph{Typed} Racket language.) In dynamically typed
  7303. languages, an expression may produce values of differing
  7304. type. Consider the following example with a conditional expression
  7305. that may return a Boolean or an integer depending on the input to the
  7306. program.
  7307. \begin{lstlisting}
  7308. (not (if (eq? (read) 1) #f 0))
  7309. \end{lstlisting}
  7310. Languages that allow expressions to produce different kinds of values
  7311. are called \emph{polymorphic}. There are many kinds of polymorphism,
  7312. such as subtype polymorphism and parametric
  7313. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we are
  7314. talking about here does not have a special name, but it is the usual
  7315. kind that arises in dynamically typed languages.
  7316. Another characteristic of dynamically typed languages is that
  7317. primitive operations, such as \code{not}, are often defined to operate
  7318. on many different types of values. In fact, in Racket, the \code{not}
  7319. operator produces a result for any kind of value: given \code{\#f} it
  7320. returns \code{\#t} and given anything else it returns \code{\#f}.
  7321. Furthermore, even when primitive operations restrict their inputs to
  7322. values of a certain type, this restriction is enforced at runtime
  7323. instead of during compilation. For example, the following vector
  7324. reference results in a run-time contract violation.
  7325. \begin{lstlisting}
  7326. (vector-ref (vector 42) #t)
  7327. \end{lstlisting}
  7328. \begin{figure}[tp]
  7329. \centering
  7330. \fbox{
  7331. \begin{minipage}{0.97\textwidth}
  7332. \[
  7333. \begin{array}{rcl}
  7334. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7335. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7336. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  7337. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  7338. &\mid& \key{\#t} \mid \key{\#f}
  7339. \mid (\key{and}\;\Exp\;\Exp)
  7340. \mid (\key{or}\;\Exp\;\Exp)
  7341. \mid (\key{not}\;\Exp) \\
  7342. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  7343. &\mid& (\key{vector}\;\Exp\ldots) \mid
  7344. (\key{vector-ref}\;\Exp\;\Exp) \\
  7345. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  7346. &\mid& (\Exp \; \Exp\ldots) \mid (\key{lambda}\; (\Var\ldots) \; \Exp) \\
  7347. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7348. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7349. \Def &::=& (\key{define}\; (\Var \; \Var\ldots) \; \Exp) \\
  7350. R_7 &::=& (\key{program} \; \Def\ldots\; \Exp)
  7351. \end{array}
  7352. \]
  7353. \end{minipage}
  7354. }
  7355. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7356. \label{fig:r7-syntax}
  7357. \end{figure}
  7358. The syntax of $R_7$, our subset of Racket, is defined in
  7359. Figure~\ref{fig:r7-syntax}.
  7360. %
  7361. The definitional interpreter for $R_7$ is given in
  7362. Figure~\ref{fig:interp-R7}.
  7363. \begin{figure}[tbp]
  7364. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7365. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  7366. (define (valid-op? op) (member op '(+ - and or not)))
  7367. (define (interp-r7 env)
  7368. (lambda (ast)
  7369. (define recur (interp-r7 env))
  7370. (match ast
  7371. [(? symbol?) (lookup ast env)]
  7372. [(? integer?) `(inject ,ast Integer)]
  7373. [#t `(inject #t Boolean)]
  7374. [#f `(inject #f Boolean)]
  7375. [`(read) `(inject ,(read-fixnum) Integer)]
  7376. [`(lambda (,xs ...) ,body)
  7377. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  7378. [`(define (,f ,xs ...) ,body)
  7379. (mcons f `(lambda ,xs ,body))]
  7380. [`(program ,ds ... ,body)
  7381. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  7382. (for/list ([b top-level])
  7383. (set-mcdr! b (match (mcdr b)
  7384. [`(lambda ,xs ,body)
  7385. `(inject (lambda ,xs ,body ,top-level)
  7386. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  7387. ((interp-r7 top-level) body))]
  7388. [`(vector ,(app recur elts) ...)
  7389. (define tys (map get-tagged-type elts))
  7390. `(inject ,(apply vector elts) (Vector ,@tys))]
  7391. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  7392. (match v1
  7393. [`(inject ,vec ,ty)
  7394. (vector-set! vec n v2)
  7395. `(inject (void) Void)])]
  7396. [`(vector-ref ,(app recur v) ,n)
  7397. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  7398. [`(let ([,x ,(app recur v)]) ,body)
  7399. ((interp-r7 (cons (cons x v) env)) body)]
  7400. [`(,op ,es ...) #:when (valid-op? op)
  7401. (interp-r7-op op (for/list ([e es]) (recur e)))]
  7402. [`(eq? ,(app recur l) ,(app recur r))
  7403. `(inject ,(equal? l r) Boolean)]
  7404. [`(if ,(app recur q) ,t ,f)
  7405. (match q
  7406. [`(inject #f Boolean) (recur f)]
  7407. [else (recur t)])]
  7408. [`(,(app recur f-val) ,(app recur vs) ...)
  7409. (match f-val
  7410. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  7411. (define new-env (append (map cons xs vs) lam-env))
  7412. ((interp-r7 new-env) body)]
  7413. [else (error "interp-r7, expected function, not" f-val)])])))
  7414. \end{lstlisting}
  7415. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  7416. \label{fig:interp-R7}
  7417. \end{figure}
  7418. Let us consider how we might compile $R_7$ to x86, thinking about the
  7419. first example above. Our bit-level representation of the Boolean
  7420. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7421. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7422. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7423. general, cannot be determined at compile time, but depends on the
  7424. runtime type of its input, as in the example above that depends on the
  7425. result of \code{(read)}.
  7426. The way around this problem is to include information about a value's
  7427. runtime type in the value itself, so that this information can be
  7428. inspected by operators such as \code{not}. In particular, we shall
  7429. steal the 3 right-most bits from our 64-bit values to encode the
  7430. runtime type. We shall use $001$ to identify integers, $100$ for
  7431. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7432. void value. We shall refer to these 3 bits as the \emph{tag} and we
  7433. define the following auxiliary function.
  7434. \begin{align*}
  7435. \itm{tagof}(\key{Integer}) &= 001 \\
  7436. \itm{tagof}(\key{Boolean}) &= 100 \\
  7437. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7438. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7439. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7440. \itm{tagof}(\key{Void}) &= 101
  7441. \end{align*}
  7442. (We shall say more about the new \key{Vectorof} type shortly.)
  7443. This stealing of 3 bits comes at some
  7444. price: our integers are reduced to ranging from $-2^{60}$ to
  7445. $2^{60}$. The stealing does not adversely affect vectors and
  7446. procedures because those values are addresses, and our addresses are
  7447. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7448. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7449. bits with the tag and we can simply zero-out the tag to recover the
  7450. original address.
  7451. In some sense, these tagged values are a new kind of value. Indeed,
  7452. we can extend our \emph{typed} language with tagged values by adding a
  7453. new type to classify them, called \key{Any}, and with operations for
  7454. creating and using tagged values, yielding the $R_6$ language that we
  7455. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7456. fundamental support for polymorphism and runtime types that we need to
  7457. support dynamic typing.
  7458. There is an interesting interaction between tagged values and garbage
  7459. collection. A variable of type \code{Any} might refer to a vector and
  7460. therefore it might be a root that needs to be inspected and copied
  7461. during garbage collection. Thus, we need to treat variables of type
  7462. \code{Any} in a similar way to variables of type \code{Vector} for
  7463. purposes of register allocation, which we discuss in
  7464. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7465. variable of type \code{Any} is spilled, it must be spilled to the root
  7466. stack. But this means that the garbage collector needs to be able to
  7467. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7468. value that points to a tuple, and (3) a tagged value that is not a
  7469. tuple. We enable this differentiation by choosing not to use the tag
  7470. $000$. Instead, that bit pattern is reserved for identifying plain old
  7471. pointers to tuples. On the other hand, if one of the first three bits
  7472. is set, then we have a tagged value, and inspecting the tag can
  7473. differentiation between vectors ($010$) and the other kinds of values.
  7474. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  7475. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7476. extend our compiler to handle the new features of $R_6$
  7477. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7478. \ref{sec:register-allocation-r6}).
  7479. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7480. \label{sec:r6-lang}
  7481. \begin{figure}[tp]
  7482. \centering
  7483. \fbox{
  7484. \begin{minipage}{0.97\textwidth}
  7485. \[
  7486. \begin{array}{lcl}
  7487. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7488. \mid (\key{Vector}\;\Type\ldots) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7489. &\mid& \gray{(\Type\ldots \; \key{->}\; \Type)} \mid \key{Any} \\
  7490. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}\ldots) \\
  7491. &\mid& (\key{Any}\ldots \; \key{->}\; \key{Any})\\
  7492. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7493. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7494. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7495. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7496. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7497. \mid (\key{and}\;\Exp\;\Exp)
  7498. \mid (\key{or}\;\Exp\;\Exp)
  7499. \mid (\key{not}\;\Exp)} \\
  7500. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7501. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7502. (\key{vector-ref}\;\Exp\;\Int)} \\
  7503. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7504. &\mid& \gray{(\Exp \; \Exp\ldots)
  7505. \mid (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7506. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7507. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7508. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7509. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7510. R_6 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7511. \end{array}
  7512. \]
  7513. \end{minipage}
  7514. }
  7515. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7516. with \key{Any}.}
  7517. \label{fig:r6-syntax}
  7518. \end{figure}
  7519. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7520. $(\key{inject}\; e\; T)$ form converts the value produced by
  7521. expression $e$ of type $T$ into a tagged value. The
  7522. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7523. expression $e$ into a value of type $T$ or else halts the program if
  7524. the type tag is equivalent to $T$. We treat
  7525. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7526. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7527. Note that in both \key{inject} and
  7528. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7529. which simplifies the implementation and corresponds with what is
  7530. needed for compiling untyped Racket. The type predicates,
  7531. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7532. if the tag corresponds to the predicate, and return \key{\#t}
  7533. otherwise.
  7534. %
  7535. Selections from the type checker for $R_6$ are shown in
  7536. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7537. Figure~\ref{fig:interp-R6}.
  7538. \begin{figure}[btp]
  7539. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7540. (define (flat-ty? ty) ...)
  7541. (define (typecheck-R6 env)
  7542. (lambda (e)
  7543. (define recur (typecheck-R6 env))
  7544. (match e
  7545. [`(inject ,e ,ty)
  7546. (unless (flat-ty? ty)
  7547. (error "may only inject a value of flat type, not ~a" ty))
  7548. (define-values (new-e e-ty) (recur e))
  7549. (cond
  7550. [(equal? e-ty ty)
  7551. (values `(inject ,new-e ,ty) 'Any)]
  7552. [else
  7553. (error "inject expected ~a to have type ~a" e ty)])]
  7554. [`(project ,e ,ty)
  7555. (unless (flat-ty? ty)
  7556. (error "may only project to a flat type, not ~a" ty))
  7557. (define-values (new-e e-ty) (recur e))
  7558. (cond
  7559. [(equal? e-ty 'Any)
  7560. (values `(project ,new-e ,ty) ty)]
  7561. [else
  7562. (error "project expected ~a to have type Any" e)])]
  7563. [`(vector-ref ,e ,i)
  7564. (define-values (new-e e-ty) (recur e))
  7565. (match e-ty
  7566. [`(Vector ,ts ...) ...]
  7567. [`(Vectorof ,ty)
  7568. (unless (exact-nonnegative-integer? i)
  7569. (error 'type-check "invalid index ~a" i))
  7570. (values `(vector-ref ,new-e ,i) ty)]
  7571. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7572. ...
  7573. )))
  7574. \end{lstlisting}
  7575. \caption{Type checker for parts of the $R_6$ language.}
  7576. \label{fig:typecheck-R6}
  7577. \end{figure}
  7578. % to do: add rules for vector-ref, etc. for Vectorof
  7579. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7580. \begin{figure}[btp]
  7581. \begin{lstlisting}
  7582. (define primitives (set 'boolean? ...))
  7583. (define (interp-op op)
  7584. (match op
  7585. ['boolean? (lambda (v)
  7586. (match v
  7587. [`(tagged ,v1 Boolean) #t]
  7588. [else #f]))]
  7589. ...))
  7590. ;; Equivalence of flat types
  7591. (define (tyeq? t1 t2)
  7592. (match `(,t1 ,t2)
  7593. [`((Vectorof Any) (Vector ,t2s ...))
  7594. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7595. [`((Vector ,t1s ...) (Vectorof Any))
  7596. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7597. [else (equal? t1 t2)]))
  7598. (define (interp-R6 env)
  7599. (lambda (ast)
  7600. (match ast
  7601. [`(inject ,e ,t)
  7602. `(tagged ,((interp-R6 env) e) ,t)]
  7603. [`(project ,e ,t2)
  7604. (define v ((interp-R6 env) e))
  7605. (match v
  7606. [`(tagged ,v1 ,t1)
  7607. (cond [(tyeq? t1 t2)
  7608. v1]
  7609. [else
  7610. (error "in project, type mismatch" t1 t2)])]
  7611. [else
  7612. (error "in project, expected tagged value" v)])]
  7613. ...)))
  7614. \end{lstlisting}
  7615. \caption{Interpreter for $R_6$.}
  7616. \label{fig:interp-R6}
  7617. \end{figure}
  7618. %\clearpage
  7619. \section{Shrinking $R_6$}
  7620. \label{sec:shrink-r6}
  7621. In the \code{shrink} pass we recommend compiling \code{project} into
  7622. an explicit \code{if} expression that uses three new operations:
  7623. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7624. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7625. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7626. value from a tagged value. Finally, the \code{exit} operation ends the
  7627. execution of the program by invoking the operating system's
  7628. \code{exit} function. So the translation for \code{project} is as
  7629. follows. (We have omitted the \code{has-type} AST nodes to make this
  7630. output more readable.)
  7631. \begin{tabular}{lll}
  7632. \begin{minipage}{0.3\textwidth}
  7633. \begin{lstlisting}
  7634. (project |$e$| |$\Type$|)
  7635. \end{lstlisting}
  7636. \end{minipage}
  7637. &
  7638. $\Rightarrow$
  7639. &
  7640. \begin{minipage}{0.5\textwidth}
  7641. \begin{lstlisting}
  7642. (let ([|$\itm{tmp}$| |$e'$|])
  7643. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7644. (value-of-any |$\itm{tmp}$|)
  7645. (exit)))
  7646. \end{lstlisting}
  7647. \end{minipage}
  7648. \end{tabular} \\
  7649. Similarly, we recommend translating the type predicates
  7650. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7651. \section{Instruction Selection for $R_6$}
  7652. \label{sec:select-r6}
  7653. \paragraph{Inject}
  7654. We recommend compiling an \key{inject} as follows if the type is
  7655. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7656. destination to the left by the number of bits specified its source
  7657. argument (in this case $3$, the length of the tag) and it preserves
  7658. the sign of the integer. We use the \key{orq} instruction to combine
  7659. the tag and the value to form the tagged value. \\
  7660. \begin{tabular}{lll}
  7661. \begin{minipage}{0.4\textwidth}
  7662. \begin{lstlisting}
  7663. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7664. \end{lstlisting}
  7665. \end{minipage}
  7666. &
  7667. $\Rightarrow$
  7668. &
  7669. \begin{minipage}{0.5\textwidth}
  7670. \begin{lstlisting}
  7671. (movq |$e'$| |\itm{lhs}'|)
  7672. (salq (int 3) |\itm{lhs}'|)
  7673. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7674. \end{lstlisting}
  7675. \end{minipage}
  7676. \end{tabular} \\
  7677. The instruction selection for vectors and procedures is different
  7678. because their is no need to shift them to the left. The rightmost 3
  7679. bits are already zeros as described above. So we just combine the
  7680. value and the tag using \key{orq}. \\
  7681. \begin{tabular}{lll}
  7682. \begin{minipage}{0.4\textwidth}
  7683. \begin{lstlisting}
  7684. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7685. \end{lstlisting}
  7686. \end{minipage}
  7687. &
  7688. $\Rightarrow$
  7689. &
  7690. \begin{minipage}{0.5\textwidth}
  7691. \begin{lstlisting}
  7692. (movq |$e'$| |\itm{lhs}'|)
  7693. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7694. \end{lstlisting}
  7695. \end{minipage}
  7696. \end{tabular}
  7697. \paragraph{Tag of Any}
  7698. Recall that the \code{tag-of-any} operation extracts the type tag from
  7699. a value of type \code{Any}. The type tag is the bottom three bits, so
  7700. we obtain the tag by taking the bitwise-and of the value with $111$
  7701. ($7$ in decimal).
  7702. \begin{tabular}{lll}
  7703. \begin{minipage}{0.4\textwidth}
  7704. \begin{lstlisting}
  7705. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7706. \end{lstlisting}
  7707. \end{minipage}
  7708. &
  7709. $\Rightarrow$
  7710. &
  7711. \begin{minipage}{0.5\textwidth}
  7712. \begin{lstlisting}
  7713. (movq |$e'$| |\itm{lhs}'|)
  7714. (andq (int 7) |\itm{lhs}'|)
  7715. \end{lstlisting}
  7716. \end{minipage}
  7717. \end{tabular}
  7718. \paragraph{Value of Any}
  7719. Like \key{inject}, the instructions for \key{value-of-any} are
  7720. different depending on whether the type $T$ is a pointer (vector or
  7721. procedure) or not (Integer or Boolean). The following shows the
  7722. instruction selection for Integer and Boolean. We produce an untagged
  7723. value by shifting it to the right by 3 bits.
  7724. %
  7725. \\
  7726. \begin{tabular}{lll}
  7727. \begin{minipage}{0.4\textwidth}
  7728. \begin{lstlisting}
  7729. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7730. \end{lstlisting}
  7731. \end{minipage}
  7732. &
  7733. $\Rightarrow$
  7734. &
  7735. \begin{minipage}{0.5\textwidth}
  7736. \begin{lstlisting}
  7737. (movq |$e'$| |\itm{lhs}'|)
  7738. (sarq (int 3) |\itm{lhs}'|)
  7739. \end{lstlisting}
  7740. \end{minipage}
  7741. \end{tabular} \\
  7742. %
  7743. In the case for vectors and procedures, there is no need to
  7744. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7745. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7746. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7747. \code{movq} into the destination $\itm{lhs}$. We then generate
  7748. \code{andq} with the tagged value to get the desired result. \\
  7749. %
  7750. \begin{tabular}{lll}
  7751. \begin{minipage}{0.4\textwidth}
  7752. \begin{lstlisting}
  7753. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7754. \end{lstlisting}
  7755. \end{minipage}
  7756. &
  7757. $\Rightarrow$
  7758. &
  7759. \begin{minipage}{0.5\textwidth}
  7760. \begin{lstlisting}
  7761. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7762. (andq |$e'$| |\itm{lhs}'|)
  7763. \end{lstlisting}
  7764. \end{minipage}
  7765. \end{tabular}
  7766. %% \paragraph{Type Predicates} We leave it to the reader to
  7767. %% devise a sequence of instructions to implement the type predicates
  7768. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7769. \section{Register Allocation for $R_6$}
  7770. \label{sec:register-allocation-r6}
  7771. \index{register allocation}
  7772. As mentioned above, a variable of type \code{Any} might refer to a
  7773. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7774. of type \code{Any} in the same way that it treats variables of type
  7775. \code{Vector} for purposes of garbage collection. In particular,
  7776. \begin{itemize}
  7777. \item If a variable of type \code{Any} is live during a function call,
  7778. then it must be spilled. One way to accomplish this is to augment
  7779. the pass \code{build-interference} to mark all variables that are
  7780. live after a \code{callq} as interfering with all the registers.
  7781. \item If a variable of type \code{Any} is spilled, it must be spilled
  7782. to the root stack instead of the normal procedure call stack.
  7783. \end{itemize}
  7784. \begin{exercise}\normalfont
  7785. Expand your compiler to handle $R_6$ as discussed in the last few
  7786. sections. Create 5 new programs that use the \code{Any} type and the
  7787. new operations (\code{inject}, \code{project}, \code{boolean?},
  7788. etc.). Test your compiler on these new programs and all of your
  7789. previously created test programs.
  7790. \end{exercise}
  7791. \section{Compiling $R_7$ to $R_6$}
  7792. \label{sec:compile-r7}
  7793. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7794. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7795. given a subexpression $e$ of $R_7$, the pass will produce an
  7796. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7797. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7798. the Boolean \code{\#t}, which must be injected to produce an
  7799. expression of type \key{Any}.
  7800. %
  7801. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7802. addition, is representative of compilation for many operations: the
  7803. arguments have type \key{Any} and must be projected to \key{Integer}
  7804. before the addition can be performed.
  7805. The compilation of \key{lambda} (third row of
  7806. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7807. produce type annotations: we simply use \key{Any}.
  7808. %
  7809. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7810. has to account for some differences in behavior between $R_7$ and
  7811. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7812. kind of values can be used in various places. For example, the
  7813. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7814. the arguments need not be of the same type (but in that case, the
  7815. result will be \code{\#f}).
  7816. \begin{figure}[btp]
  7817. \centering
  7818. \begin{tabular}{|lll|} \hline
  7819. \begin{minipage}{0.25\textwidth}
  7820. \begin{lstlisting}
  7821. #t
  7822. \end{lstlisting}
  7823. \end{minipage}
  7824. &
  7825. $\Rightarrow$
  7826. &
  7827. \begin{minipage}{0.6\textwidth}
  7828. \begin{lstlisting}
  7829. (inject #t Boolean)
  7830. \end{lstlisting}
  7831. \end{minipage}
  7832. \\[2ex]\hline
  7833. \begin{minipage}{0.25\textwidth}
  7834. \begin{lstlisting}
  7835. (+ |$e_1$| |$e_2$|)
  7836. \end{lstlisting}
  7837. \end{minipage}
  7838. &
  7839. $\Rightarrow$
  7840. &
  7841. \begin{minipage}{0.6\textwidth}
  7842. \begin{lstlisting}
  7843. (inject
  7844. (+ (project |$e'_1$| Integer)
  7845. (project |$e'_2$| Integer))
  7846. Integer)
  7847. \end{lstlisting}
  7848. \end{minipage}
  7849. \\[2ex]\hline
  7850. \begin{minipage}{0.25\textwidth}
  7851. \begin{lstlisting}
  7852. (lambda (|$x_1 \ldots$|) |$e$|)
  7853. \end{lstlisting}
  7854. \end{minipage}
  7855. &
  7856. $\Rightarrow$
  7857. &
  7858. \begin{minipage}{0.6\textwidth}
  7859. \begin{lstlisting}
  7860. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7861. (Any|$\ldots$|Any -> Any))
  7862. \end{lstlisting}
  7863. \end{minipage}
  7864. \\[2ex]\hline
  7865. \begin{minipage}{0.25\textwidth}
  7866. \begin{lstlisting}
  7867. (app |$e_0$| |$e_1 \ldots e_n$|)
  7868. \end{lstlisting}
  7869. \end{minipage}
  7870. &
  7871. $\Rightarrow$
  7872. &
  7873. \begin{minipage}{0.6\textwidth}
  7874. \begin{lstlisting}
  7875. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7876. |$e'_1 \ldots e'_n$|)
  7877. \end{lstlisting}
  7878. \end{minipage}
  7879. \\[2ex]\hline
  7880. \begin{minipage}{0.25\textwidth}
  7881. \begin{lstlisting}
  7882. (vector-ref |$e_1$| |$e_2$|)
  7883. \end{lstlisting}
  7884. \end{minipage}
  7885. &
  7886. $\Rightarrow$
  7887. &
  7888. \begin{minipage}{0.6\textwidth}
  7889. \begin{lstlisting}
  7890. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7891. (let ([tmp2 (project |$e'_2$| Integer)])
  7892. (vector-ref tmp1 tmp2)))
  7893. \end{lstlisting}
  7894. \end{minipage}
  7895. \\[2ex]\hline
  7896. \begin{minipage}{0.25\textwidth}
  7897. \begin{lstlisting}
  7898. (if |$e_1$| |$e_2$| |$e_3$|)
  7899. \end{lstlisting}
  7900. \end{minipage}
  7901. &
  7902. $\Rightarrow$
  7903. &
  7904. \begin{minipage}{0.6\textwidth}
  7905. \begin{lstlisting}
  7906. (if (eq? |$e'_1$| (inject #f Boolean))
  7907. |$e'_3$|
  7908. |$e'_2$|)
  7909. \end{lstlisting}
  7910. \end{minipage}
  7911. \\[2ex]\hline
  7912. \begin{minipage}{0.25\textwidth}
  7913. \begin{lstlisting}
  7914. (eq? |$e_1$| |$e_2$|)
  7915. \end{lstlisting}
  7916. \end{minipage}
  7917. &
  7918. $\Rightarrow$
  7919. &
  7920. \begin{minipage}{0.6\textwidth}
  7921. \begin{lstlisting}
  7922. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7923. \end{lstlisting}
  7924. \end{minipage}
  7925. \\[2ex]\hline
  7926. \end{tabular}
  7927. \caption{Compiling $R_7$ to $R_6$.}
  7928. \label{fig:compile-r7-r6}
  7929. \end{figure}
  7930. \begin{exercise}\normalfont
  7931. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7932. Create tests for $R_7$ by adapting all of your previous test programs
  7933. by removing type annotations. Add 5 more tests programs that
  7934. specifically rely on the language being dynamically typed. That is,
  7935. they should not be legal programs in a statically typed language, but
  7936. nevertheless, they should be valid $R_7$ programs that run to
  7937. completion without error.
  7938. \end{exercise}
  7939. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7940. \chapter{Gradual Typing}
  7941. \label{ch:gradual-typing}
  7942. \index{gradual typing}
  7943. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7944. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7945. \chapter{Parametric Polymorphism}
  7946. \label{ch:parametric-polymorphism}
  7947. \index{parametric polymorphism}
  7948. \index{generics}
  7949. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7950. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7951. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7952. \chapter{High-level Optimization}
  7953. \label{ch:high-level-optimization}
  7954. This chapter will present a procedure inlining pass based on the
  7955. algorithm of \citet{Waddell:1997fk}.
  7956. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7957. \chapter{Appendix}
  7958. \section{Interpreters}
  7959. \label{appendix:interp}
  7960. \index{interpreter}
  7961. We provide interpreters for each of the source languages $R_0$, $R_1$,
  7962. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  7963. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  7964. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  7965. the rest of the intermediate languages, including pseudo-x86 and x86
  7966. are in the \key{interp.rkt} file.
  7967. \section{Utility Functions}
  7968. \label{appendix:utilities}
  7969. The utility functions described here are in the \key{utilities.rkt}
  7970. file.
  7971. \paragraph{\code{interp-tests}}
  7972. The \key{interp-tests} function runs the compiler passes and the
  7973. interpreters on each of the specified tests to check whether each pass
  7974. is correct. The \key{interp-tests} function has the following
  7975. parameters:
  7976. \begin{description}
  7977. \item[name (a string)] a name to identify the compiler,
  7978. \item[typechecker] a function of exactly one argument that either
  7979. raises an error using the \code{error} function when it encounters a
  7980. type error, or returns \code{\#f} when it encounters a type
  7981. error. If there is no type error, the type checker returns the
  7982. program.
  7983. \item[passes] a list with one entry per pass. An entry is a list with
  7984. three things: a string giving the name of the pass, the function
  7985. that implements the pass (a translator from AST to AST), and a
  7986. function that implements the interpreter (a function from AST to
  7987. result value) for the language of the output of the pass.
  7988. \item[source-interp] an interpreter for the source language. The
  7989. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  7990. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  7991. \item[tests] a list of test numbers that specifies which tests to
  7992. run. (see below)
  7993. \end{description}
  7994. %
  7995. The \key{interp-tests} function assumes that the subdirectory
  7996. \key{tests} has a collection of Racket programs whose names all start
  7997. with the family name, followed by an underscore and then the test
  7998. number, ending with the file extension \key{.rkt}. Also, for each test
  7999. program that calls \code{read} one or more times, there is a file with
  8000. the same name except that the file extension is \key{.in} that
  8001. provides the input for the Racket program. If the test program is
  8002. expected to fail type checking, then there should be an empty file of
  8003. the same name but with extension \key{.tyerr}.
  8004. \paragraph{\code{compiler-tests}}
  8005. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8006. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8007. machine code and checks that the output is $42$. The parameters to the
  8008. \code{compiler-tests} function are similar to those of the
  8009. \code{interp-tests} function, and consist of
  8010. \begin{itemize}
  8011. \item a compiler name (a string),
  8012. \item a type checker,
  8013. \item description of the passes,
  8014. \item name of a test-family, and
  8015. \item a list of test numbers.
  8016. \end{itemize}
  8017. \paragraph{\code{compile-file}}
  8018. takes a description of the compiler passes (see the comment for
  8019. \key{interp-tests}) and returns a function that, given a program file
  8020. name (a string ending in \key{.rkt}), applies all of the passes and
  8021. writes the output to a file whose name is the same as the program file
  8022. name but with \key{.rkt} replaced with \key{.s}.
  8023. \paragraph{\code{read-program}}
  8024. takes a file path and parses that file (it must be a Racket program)
  8025. into an abstract syntax tree.
  8026. \paragraph{\code{parse-program}}
  8027. takes an S-expression representation of an abstract syntax tree and converts it into
  8028. the struct-based representation.
  8029. \paragraph{\code{assert}}
  8030. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8031. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8032. \paragraph{\code{lookup}}
  8033. % remove discussion of lookup? -Jeremy
  8034. takes a key and an alist, and returns the first value that is
  8035. associated with the given key, if there is one. If not, an error is
  8036. triggered. The alist may contain both immutable pairs (built with
  8037. \key{cons}) and mutable pairs (built with \key{mcons}).
  8038. %The \key{map2} function ...
  8039. \section{x86 Instruction Set Quick-Reference}
  8040. \label{sec:x86-quick-reference}
  8041. \index{x86}
  8042. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8043. do. We write $A \to B$ to mean that the value of $A$ is written into
  8044. location $B$. Address offsets are given in bytes. The instruction
  8045. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8046. registers (such as \code{\%rax}), or memory references (such as
  8047. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8048. reference per instruction. Other operands must be immediates or
  8049. registers.
  8050. \begin{table}[tbp]
  8051. \centering
  8052. \begin{tabular}{l|l}
  8053. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8054. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8055. \texttt{negq} $A$ & $- A \to A$ \\
  8056. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8057. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8058. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8059. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8060. \texttt{retq} & Pops the return address and jumps to it \\
  8061. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8062. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8063. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8064. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8065. be an immediate) \\
  8066. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8067. matches the condition code of the instruction, otherwise go to the
  8068. next instructions. The condition codes are \key{e} for ``equal'',
  8069. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8070. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8071. \texttt{jl} $L$ & \\
  8072. \texttt{jle} $L$ & \\
  8073. \texttt{jg} $L$ & \\
  8074. \texttt{jge} $L$ & \\
  8075. \texttt{jmp} $L$ & Jump to label $L$ \\
  8076. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8077. \texttt{movzbq} $A$, $B$ &
  8078. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8079. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8080. and the extra bytes of $B$ are set to zero.} \\
  8081. & \\
  8082. & \\
  8083. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8084. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8085. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8086. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8087. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8088. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8089. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8090. description of the condition codes. $A$ must be a single byte register
  8091. (e.g., \texttt{al} or \texttt{cl}).} \\
  8092. \texttt{setl} $A$ & \\
  8093. \texttt{setle} $A$ & \\
  8094. \texttt{setg} $A$ & \\
  8095. \texttt{setge} $A$ &
  8096. \end{tabular}
  8097. \vspace{5pt}
  8098. \caption{Quick-reference for the x86 instructions used in this book.}
  8099. \label{tab:x86-instr}
  8100. \end{table}
  8101. \cleardoublepage
  8102. \addcontentsline{toc}{chapter}{Index}
  8103. \printindex
  8104. \cleardoublepage
  8105. \bibliographystyle{plainnat}
  8106. \bibliography{all}
  8107. \addcontentsline{toc}{chapter}{Bibliography}
  8108. \end{document}
  8109. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8110. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8111. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8112. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8113. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8114. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8115. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8116. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8117. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8118. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8119. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8120. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8121. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  8122. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8123. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8124. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8125. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8126. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8127. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8128. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8129. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8130. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8131. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8132. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8133. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8134. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8135. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8136. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8137. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8138. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8139. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8140. % LocalWords: struct symtab