book.tex 343 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  76. deletekeywords={read},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge An Incremental Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses about programming languages by Daniel Friedman in
  151. the 1970's and 1980's. Dan conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, Kent returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Kent continued development of Chez
  162. Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Dan's ideas was to split the compiler into many small ``passes'' so
  166. that the code for each pass would be easy to understood in isolation.
  167. (In contrast, most compilers of the time were organized into only a
  168. few monolithic passes for reasons of compile-time efficiency.) Kent,
  169. with later help from his students Dipanwita Sarkar and Andrew Keep,
  170. developed infrastructure to support this approach and evolved the
  171. course, first to use micro-sized passes and then into even smaller
  172. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  173. student in this compiler course in the early 2000's, as part of his
  174. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  175. the course immensely!
  176. During that time, another student named Abdulaziz Ghuloum observed
  177. that the front-to-back organization of the course made it difficult
  178. for students to understand the rationale for the compiler
  179. design. Abdulaziz proposed an incremental approach in which the
  180. students build the compiler in stages; they start by implementing a
  181. complete compiler for a very small subset of the input language and in
  182. each subsequent stage they add a language feature and add or modify
  183. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  184. the students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, Jeremy went on to
  187. teach at the University of Colorado. He adapted the nano pass and
  188. incremental approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  190. on the surface but there is a large overlap in the compiler techniques
  191. required for the two languages. Thus, Jeremy was able to teach much of
  192. the same content from the Indiana compiler course. He very much
  193. enjoyed teaching the course organized in this way, and even better,
  194. many of the students learned a lot and got excited about compilers.
  195. Jeremy returned to teach at Indiana University in 2013. In his
  196. absence the compiler course had switched from the front-to-back
  197. organization to a back-to-front organization. Seeing how well the
  198. incremental approach worked at Colorado, he started porting and
  199. adapting the structure of the Colorado course back into the land of
  200. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  201. the course is now about compiling a subset of Racket (and Typed
  202. Racket) to the x86 assembly language. The compiler is implemented in
  203. Racket 7.1~\citep{plt-tr}.
  204. This is the textbook for the incremental version of the compiler
  205. course at Indiana University (Spring 2016 - present) and it is the
  206. first open textbook for an Indiana compiler course. With this book we
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study in Bloomington in person. Many of the
  209. compiler design decisions in this book are drawn from the assignment
  210. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  211. are the most important topics from \cite{Dybvig:2010aa} but we have
  212. omitted topics that we think are less interesting conceptually and we
  213. have made simplifications to reduce complexity. In this way, this
  214. book leans more towards pedagogy than towards the efficiency of the
  215. generated code. Also, the book differs in places where we saw the
  216. opportunity to make the topics more fun, such as in relating register
  217. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  218. \section*{Prerequisites}
  219. The material in this book is challenging but rewarding. It is meant to
  220. prepare students for a lifelong career in programming languages.
  221. The book uses the Racket language both for the implementation of the
  222. compiler and for the language that is compiled, so a student should be
  223. proficient with Racket (or Scheme) prior to reading this book. There
  224. are many excellent resources for learning Scheme and
  225. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  226. is helpful but not necessary for the student to have prior exposure to
  227. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  228. obtain from a computer systems
  229. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %\section*{Structure of book}
  232. % You might want to add short description about each chapter in this book.
  233. %\section*{About the companion website}
  234. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  235. %\begin{itemize}
  236. % \item A link to (freely downlodable) latest version of this document.
  237. % \item Link to download LaTeX source for this document.
  238. % \item Miscellaneous material (e.g. suggested readings etc).
  239. %\end{itemize}
  240. \section*{Acknowledgments}
  241. Many people have contributed to the ideas, techniques, organization,
  242. and teaching of the materials in this book. We especially thank the
  243. following people.
  244. \begin{itemize}
  245. \item Bor-Yuh Evan Chang
  246. \item Kent Dybvig
  247. \item Daniel P. Friedman
  248. \item Ronald Garcia
  249. \item Abdulaziz Ghuloum
  250. \item Jay McCarthy
  251. \item Dipanwita Sarkar
  252. \item Andrew Keep
  253. \item Oscar Waddell
  254. \item Michael Wollowski
  255. \end{itemize}
  256. \mbox{}\\
  257. \noindent Jeremy G. Siek \\
  258. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  259. %\noindent Spring 2016
  260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  261. \chapter{Preliminaries}
  262. \label{ch:trees-recur}
  263. In this chapter we review the basic tools that are needed to implement
  264. a compiler. Programs are typically input by a programmer as text,
  265. i.e., a sequence of characters. The program-as-text representation is
  266. called \emph{concrete syntax}. We use concrete syntax to concisely
  267. write down and talk about programs. Inside the compiler, we use
  268. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  269. that efficiently supports the operations that the compiler needs to
  270. perform.
  271. \index{concrete syntax}
  272. \index{abstract syntax}
  273. \index{abstract syntax tree}
  274. \index{AST}
  275. \index{program}
  276. \index{parse}
  277. %
  278. The translation from concrete syntax to abstract syntax is a process
  279. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  280. and implementation of parsing in this book. A parser is provided in
  281. the supporting materials for translating from concrete syntax to
  282. abstract syntax for the languages used in this book.
  283. ASTs can be represented in many different ways inside the compiler,
  284. depending on the programming language used to write the compiler.
  285. %
  286. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  287. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  288. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  289. and pattern matching to inspect individual nodes in an AST
  290. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  291. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  292. chapter provides an brief introduction to these ideas.
  293. \index{struct}
  294. \section{Abstract Syntax Trees and Racket Structures}
  295. \label{sec:ast}
  296. Compilers use abstract syntax trees to represent programs because
  297. compilers often need to ask questions like: for a given part of a
  298. program, what kind of language feature is it? What are the sub-parts
  299. of this part of the program? Consider the program on the left and its
  300. AST on the right. This program is an addition and it has two
  301. sub-parts, a read operation and a negation. The negation has another
  302. sub-part, the integer constant \code{8}. By using a tree to represent
  303. the program, we can easily follow the links to go from one part of a
  304. program to its sub-parts.
  305. \begin{center}
  306. \begin{minipage}{0.4\textwidth}
  307. \begin{lstlisting}
  308. (+ (read) (- 8))
  309. \end{lstlisting}
  310. \end{minipage}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{equation}
  313. \begin{tikzpicture}
  314. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  315. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  316. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  317. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  318. \draw[->] (plus) to (read);
  319. \draw[->] (plus) to (minus);
  320. \draw[->] (minus) to (8);
  321. \end{tikzpicture}
  322. \label{eq:arith-prog}
  323. \end{equation}
  324. \end{minipage}
  325. \end{center}
  326. We use the standard terminology for trees to describe ASTs: each
  327. circle above is called a \emph{node}. The arrows connect a node to its
  328. \emph{children} (which are also nodes). The top-most node is the
  329. \emph{root}. Every node except for the root has a \emph{parent} (the
  330. node it is the child of). If a node has no children, it is a
  331. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  332. \index{node}
  333. \index{children}
  334. \index{root}
  335. \index{parent}
  336. \index{leaf}
  337. \index{internal node}
  338. %% Recall that an \emph{symbolic expression} (S-expression) is either
  339. %% \begin{enumerate}
  340. %% \item an atom, or
  341. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  342. %% where $e_1$ and $e_2$ are each an S-expression.
  343. %% \end{enumerate}
  344. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  345. %% null value \code{'()}, etc. We can create an S-expression in Racket
  346. %% simply by writing a backquote (called a quasi-quote in Racket)
  347. %% followed by the textual representation of the S-expression. It is
  348. %% quite common to use S-expressions to represent a list, such as $a, b
  349. %% ,c$ in the following way:
  350. %% \begin{lstlisting}
  351. %% `(a . (b . (c . ())))
  352. %% \end{lstlisting}
  353. %% Each element of the list is in the first slot of a pair, and the
  354. %% second slot is either the rest of the list or the null value, to mark
  355. %% the end of the list. Such lists are so common that Racket provides
  356. %% special notation for them that removes the need for the periods
  357. %% and so many parenthesis:
  358. %% \begin{lstlisting}
  359. %% `(a b c)
  360. %% \end{lstlisting}
  361. %% The following expression creates an S-expression that represents AST
  362. %% \eqref{eq:arith-prog}.
  363. %% \begin{lstlisting}
  364. %% `(+ (read) (- 8))
  365. %% \end{lstlisting}
  366. %% When using S-expressions to represent ASTs, the convention is to
  367. %% represent each AST node as a list and to put the operation symbol at
  368. %% the front of the list. The rest of the list contains the children. So
  369. %% in the above case, the root AST node has operation \code{`+} and its
  370. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  371. %% diagram \eqref{eq:arith-prog}.
  372. %% To build larger S-expressions one often needs to splice together
  373. %% several smaller S-expressions. Racket provides the comma operator to
  374. %% splice an S-expression into a larger one. For example, instead of
  375. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  376. %% we could have first created an S-expression for AST
  377. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  378. %% S-expression.
  379. %% \begin{lstlisting}
  380. %% (define ast1.4 `(- 8))
  381. %% (define ast1.1 `(+ (read) ,ast1.4))
  382. %% \end{lstlisting}
  383. %% In general, the Racket expression that follows the comma (splice)
  384. %% can be any expression that produces an S-expression.
  385. We define a Racket \code{struct} for each kind of node. For this
  386. chapter we require just two kinds of nodes: one for integer constants
  387. and one for primitive operations. The following is the \code{struct}
  388. definition for integer constants.
  389. \begin{lstlisting}
  390. (struct Int (value))
  391. \end{lstlisting}
  392. An integer node includes just one thing: the integer value.
  393. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  394. \begin{lstlisting}
  395. (define eight (Int 8))
  396. \end{lstlisting}
  397. We say that the value created by \code{(Int 8)} is an
  398. \emph{instance} of the \code{Int} structure.
  399. The following is the \code{struct} definition for primitives operations.
  400. \begin{lstlisting}
  401. (struct Prim (op arg*))
  402. \end{lstlisting}
  403. A primitive operation node includes an operator symbol \code{op}
  404. and a list of children \code{arg*}. For example, to create
  405. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  406. \begin{lstlisting}
  407. (define neg-eight (Prim '- (list eight)))
  408. \end{lstlisting}
  409. Primitive operations may have zero or more children. The \code{read}
  410. operator has zero children:
  411. \begin{lstlisting}
  412. (define rd (Prim 'read '()))
  413. \end{lstlisting}
  414. whereas the addition operator has two children:
  415. \begin{lstlisting}
  416. (define ast1.1 (Prim '+ (list rd neg-eight)))
  417. \end{lstlisting}
  418. We have made a design choice regarding the \code{Prim} structure.
  419. Instead of using one structure for many different operations
  420. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  421. structure for each operation, as follows.
  422. \begin{lstlisting}
  423. (struct Read ())
  424. (struct Add (left right))
  425. (struct Neg (value))
  426. \end{lstlisting}
  427. The reason we choose to use just one structure is that in many parts
  428. of the compiler the code for the different primitive operators is the
  429. same, so we might as well just write that code once, which is enabled
  430. by using a single structure.
  431. When compiling a program such as \eqref{eq:arith-prog}, we need to
  432. know that the operation associated with the root node is addition and
  433. we need to be able to access its two children. Racket provides pattern
  434. matching over structures to support these kinds of queries, as we
  435. shall see in Section~\ref{sec:pattern-matching}.
  436. In this book, we often write down the concrete syntax of a program
  437. even when we really have in mind the AST because the concrete syntax
  438. is more concise. We recommend that, in your mind, you always think of
  439. programs as abstract syntax trees.
  440. \section{Grammars}
  441. \label{sec:grammar}
  442. \index{integer}
  443. \index{literal}
  444. \index{constant}
  445. A programming language can be thought of as a \emph{set} of programs.
  446. The set is typically infinite (one can always create larger and larger
  447. programs), so one cannot simply describe a language by listing all of
  448. the programs in the language. Instead we write down a set of rules, a
  449. \emph{grammar}, for building programs. Grammars are often used to
  450. define the concrete syntax of a language, but they can also be used to
  451. describe the abstract syntax. We shall write our rules in a variant of
  452. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  453. \index{Backus-Naur Form}\index{BNF}
  454. As an example, we describe a small language, named $R_0$, that consists of
  455. integers and arithmetic operations.
  456. \index{grammar}
  457. The first grammar rule for the abstract syntax of $R_0$ says that an
  458. instance of the \code{Int} structure is an expression:
  459. \begin{equation}
  460. \Exp ::= \INT{\Int} \label{eq:arith-int}
  461. \end{equation}
  462. %
  463. Each rule has a left-hand-side and a right-hand-side. The way to read
  464. a rule is that if you have all the program parts on the
  465. right-hand-side, then you can create an AST node and categorize it
  466. according to the left-hand-side.
  467. %
  468. A name such as $\Exp$ that is
  469. defined by the grammar rules is a \emph{non-terminal}.
  470. \index{non-terminal}
  471. %
  472. The name $\Int$ is a also a non-terminal, but instead of defining it
  473. with a grammar rule, we define it with the following explanation. We
  474. make the simplifying design decision that all of the languages in this
  475. book only handle machine-representable integers. On most modern
  476. machines this corresponds to integers represented with 64-bits, i.e.,
  477. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  478. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  479. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  480. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  481. that the sequence of decimals represent an integer in range $-2^{62}$
  482. to $2^{62}-1$.
  483. The second grammar rule is the \texttt{read} operation that receives
  484. an input integer from the user of the program.
  485. \begin{equation}
  486. \Exp ::= \READ{} \label{eq:arith-read}
  487. \end{equation}
  488. The third rule says that, given an $\Exp$ node, you can build another
  489. $\Exp$ node by negating it.
  490. \begin{equation}
  491. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  492. \end{equation}
  493. Symbols in typewriter font such as \key{-} and \key{read} are
  494. \emph{terminal} symbols and must literally appear in the program for
  495. the rule to be applicable.
  496. \index{terminal}
  497. We can apply the rules to build ASTs in the $R_0$
  498. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  499. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  500. an $\Exp$.
  501. \begin{center}
  502. \begin{minipage}{0.4\textwidth}
  503. \begin{lstlisting}
  504. (Prim '- (list (Int 8)))
  505. \end{lstlisting}
  506. \end{minipage}
  507. \begin{minipage}{0.25\textwidth}
  508. \begin{equation}
  509. \begin{tikzpicture}
  510. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  511. \node[draw, circle] (8) at (0, -1.2) {$8$};
  512. \draw[->] (minus) to (8);
  513. \end{tikzpicture}
  514. \label{eq:arith-neg8}
  515. \end{equation}
  516. \end{minipage}
  517. \end{center}
  518. The next grammar rule defines addition expressions:
  519. \begin{equation}
  520. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  521. \end{equation}
  522. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  523. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  524. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  525. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  526. to show that
  527. \begin{lstlisting}
  528. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  529. \end{lstlisting}
  530. is an $\Exp$ in the $R_0$ language.
  531. If you have an AST for which the above rules do not apply, then the
  532. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  533. is not in $R_0$ because there are no rules for \code{+} with only one
  534. argument, nor for \key{-} with two arguments. Whenever we define a
  535. language with a grammar, the language only includes those programs
  536. that are justified by the rules.
  537. The last grammar rule for $R_0$ states that there is a \code{Program}
  538. node to mark the top of the whole program:
  539. \[
  540. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  541. \]
  542. The \code{Program} structure is defined as follows
  543. \begin{lstlisting}
  544. (struct Program (info body))
  545. \end{lstlisting}
  546. where \code{body} is an expression. In later chapters, the \code{info}
  547. part will be used to store auxiliary information but for now it is
  548. just the empty list.
  549. It is common to have many grammar rules with the same left-hand side
  550. but different right-hand sides, such as the rules for $\Exp$ in the
  551. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  552. combine several right-hand-sides into a single rule.
  553. We collect all of the grammar rules for the abstract syntax of $R_0$
  554. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  555. defined in Figure~\ref{fig:r0-concrete-syntax}.
  556. The \code{read-program} function provided in \code{utilities.rkt} of
  557. the support materials reads a program in from a file (the sequence of
  558. characters in the concrete syntax of Racket) and parses it into an
  559. abstract syntax tree. See the description of \code{read-program} in
  560. Appendix~\ref{appendix:utilities} for more details.
  561. \begin{figure}[tp]
  562. \fbox{
  563. \begin{minipage}{0.96\textwidth}
  564. \[
  565. \begin{array}{rcl}
  566. \begin{array}{rcl}
  567. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  568. R_0 &::=& \Exp
  569. \end{array}
  570. \end{array}
  571. \]
  572. \end{minipage}
  573. }
  574. \caption{The concrete syntax of $R_0$.}
  575. \label{fig:r0-concrete-syntax}
  576. \end{figure}
  577. \begin{figure}[tp]
  578. \fbox{
  579. \begin{minipage}{0.96\textwidth}
  580. \[
  581. \begin{array}{rcl}
  582. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  583. &\mid& \ADD{\Exp}{\Exp} \\
  584. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  585. \end{array}
  586. \]
  587. \end{minipage}
  588. }
  589. \caption{The abstract syntax of $R_0$.}
  590. \label{fig:r0-syntax}
  591. \end{figure}
  592. \section{Pattern Matching}
  593. \label{sec:pattern-matching}
  594. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  595. the parts of an AST node. Racket provides the \texttt{match} form to
  596. access the parts of a structure. Consider the following example and
  597. the output on the right. \index{match} \index{pattern matching}
  598. \begin{center}
  599. \begin{minipage}{0.5\textwidth}
  600. \begin{lstlisting}
  601. (match ast1.1
  602. [(Prim op (list child1 child2))
  603. (print op)])
  604. \end{lstlisting}
  605. \end{minipage}
  606. \vrule
  607. \begin{minipage}{0.25\textwidth}
  608. \begin{lstlisting}
  609. '+
  610. \end{lstlisting}
  611. \end{minipage}
  612. \end{center}
  613. In the above example, the \texttt{match} form takes the AST
  614. \eqref{eq:arith-prog} and binds its parts to the three pattern
  615. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  616. general, a match clause consists of a \emph{pattern} and a
  617. \emph{body}.
  618. \index{pattern}
  619. Patterns are recursively defined to be either a pattern
  620. variable, a structure name followed by a pattern for each of the
  621. structure's arguments, or an S-expression (symbols, lists, etc.).
  622. (See Chapter 12 of The Racket
  623. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  624. and Chapter 9 of The Racket
  625. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  626. for a complete description of \code{match}.)
  627. %
  628. The body of a match clause may contain arbitrary Racket code. The
  629. pattern variables can be used in the scope of the body.
  630. A \code{match} form may contain several clauses, as in the following
  631. function \code{leaf?} that recognizes when an $R_0$ node is
  632. a leaf. The \code{match} proceeds through the clauses in order,
  633. checking whether the pattern can match the input AST. The
  634. body of the first clause that matches is executed. The output of
  635. \code{leaf?} for several ASTs is shown on the right.
  636. \begin{center}
  637. \begin{minipage}{0.6\textwidth}
  638. \begin{lstlisting}
  639. (define (leaf? arith)
  640. (match arith
  641. [(Int n) #t]
  642. [(Prim 'read '()) #t]
  643. [(Prim '- (list c1)) #f]
  644. [(Prim '+ (list c1 c2)) #f]))
  645. (leaf? (Prim 'read '()))
  646. (leaf? (Prim '- (list (Int 8))))
  647. (leaf? (Int 8))
  648. \end{lstlisting}
  649. \end{minipage}
  650. \vrule
  651. \begin{minipage}{0.25\textwidth}
  652. \begin{lstlisting}
  653. #t
  654. #f
  655. #t
  656. \end{lstlisting}
  657. \end{minipage}
  658. \end{center}
  659. When writing a \code{match}, we refer to the grammar definition to
  660. identify which non-terminal we are expecting to match against, then we
  661. make sure that 1) we have one clause for each alternative of that
  662. non-terminal and 2) that the pattern in each clause corresponds to the
  663. corresponding right-hand side of a grammar rule. For the \code{match}
  664. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  665. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  666. alternatives, so the \code{match} has 4 clauses. The pattern in each
  667. clause corresponds to the right-hand side of a grammar rule. For
  668. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  669. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  670. patterns, replace non-terminals such as $\Exp$ with pattern variables
  671. of your choice (e.g. \code{c1} and \code{c2}).
  672. \section{Recursion}
  673. \label{sec:recursion}
  674. \index{recursive function}
  675. Programs are inherently recursive. For example, an $R_0$ expression is
  676. often made of smaller expressions. Thus, the natural way to process an
  677. entire program is with a recursive function. As a first example of
  678. such a recursive function, we define \texttt{exp?} below, which takes
  679. an arbitrary value and determines whether or not it is an $R_0$
  680. expression.
  681. %
  682. When a recursive function is defined using a sequence of match clauses
  683. that correspond to a grammar, and the body of each clause makes a
  684. recursive call on each child node, then we say the function is defined
  685. by \emph{structural recursion}\footnote{This principle of structuring
  686. code according to the data definition is advocated in the book
  687. \emph{How to Design Programs}
  688. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  689. define a second function, named \code{R0?}, that determines whether a
  690. value is an $R_0$ program. In general we can expect to write one
  691. recursive function to handle each non-terminal in a grammar.
  692. \index{structural recursion}
  693. %
  694. \begin{center}
  695. \begin{minipage}{0.7\textwidth}
  696. \begin{lstlisting}
  697. (define (exp? ast)
  698. (match ast
  699. [(Int n) #t]
  700. [(Prim 'read '()) #t]
  701. [(Prim '- (list e)) (exp? e)]
  702. [(Prim '+ (list e1 e2))
  703. (and (exp? e1) (exp? e2))]
  704. [else #f]))
  705. (define (R0? ast)
  706. (match ast
  707. [(Program '() e) (exp? e)]
  708. [else #f]))
  709. (R0? (Program '() ast1.1)
  710. (R0? (Program '()
  711. (Prim '- (list (Prim 'read '())
  712. (Prim '+ (list (Num 8)))))))
  713. \end{lstlisting}
  714. \end{minipage}
  715. \vrule
  716. \begin{minipage}{0.25\textwidth}
  717. \begin{lstlisting}
  718. #t
  719. #f
  720. \end{lstlisting}
  721. \end{minipage}
  722. \end{center}
  723. You may be tempted to merge the two functions into one, like this:
  724. \begin{center}
  725. \begin{minipage}{0.5\textwidth}
  726. \begin{lstlisting}
  727. (define (R0? ast)
  728. (match ast
  729. [(Int n) #t]
  730. [(Prim 'read '()) #t]
  731. [(Prim '- (list e)) (R0? e)]
  732. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  733. [(Program '() e) (R0? e)]
  734. [else #f]))
  735. \end{lstlisting}
  736. \end{minipage}
  737. \end{center}
  738. %
  739. Sometimes such a trick will save a few lines of code, especially when
  740. it comes to the \code{Program} wrapper. Yet this style is generally
  741. \emph{not} recommended because it can get you into trouble.
  742. %
  743. For example, the above function is subtly wrong:
  744. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  745. will return true, when it should return false.
  746. %% NOTE FIXME - must check for consistency on this issue throughout.
  747. \section{Interpreters}
  748. \label{sec:interp-R0}
  749. \index{interpreter}
  750. The meaning, or semantics, of a program is typically defined in the
  751. specification of the language. For example, the Scheme language is
  752. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  753. defined in its reference manual~\citep{plt-tr}. In this book we use an
  754. interpreter to define the meaning of each language that we consider,
  755. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  756. interpreter that is designated (by some people) as the definition of a
  757. language is called a \emph{definitional interpreter}.
  758. \index{definitional interpreter}
  759. We warm up by creating a definitional interpreter for the $R_0$ language, which
  760. serves as a second example of structural recursion. The
  761. \texttt{interp-R0} function is defined in
  762. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  763. input program followed by a call to the \lstinline{interp-exp} helper
  764. function, which in turn has one match clause per grammar rule for
  765. $R_0$ expressions.
  766. \begin{figure}[tp]
  767. \begin{lstlisting}
  768. (define (interp-exp e)
  769. (match e
  770. [(Int n) n]
  771. [(Prim 'read '())
  772. (define r (read))
  773. (cond [(fixnum? r) r]
  774. [else (error 'interp-R0 "expected an integer" r)])]
  775. [(Prim '- (list e))
  776. (define v (interp-exp e))
  777. (fx- 0 v)]
  778. [(Prim '+ (list e1 e2))
  779. (define v1 (interp-exp e1))
  780. (define v2 (interp-exp e2))
  781. (fx+ v1 v2)]
  782. ))
  783. (define (interp-R0 p)
  784. (match p
  785. [(Program '() e) (interp-exp e)]
  786. ))
  787. \end{lstlisting}
  788. \caption{Interpreter for the $R_0$ language.}
  789. \label{fig:interp-R0}
  790. \end{figure}
  791. Let us consider the result of interpreting a few $R_0$ programs. The
  792. following program adds two integers.
  793. \begin{lstlisting}
  794. (+ 10 32)
  795. \end{lstlisting}
  796. The result is \key{42}. We wrote the above program in concrete syntax,
  797. whereas the parsed abstract syntax is:
  798. \begin{lstlisting}
  799. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  800. \end{lstlisting}
  801. The next example demonstrates that expressions may be nested within
  802. each other, in this case nesting several additions and negations.
  803. \begin{lstlisting}
  804. (+ 10 (- (+ 12 20)))
  805. \end{lstlisting}
  806. What is the result of the above program?
  807. As mentioned previously, the $R_0$ language does not support
  808. arbitrarily-large integers, but only $63$-bit integers, so we
  809. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  810. in Racket.
  811. Suppose
  812. \[
  813. n = 999999999999999999
  814. \]
  815. which indeed fits in $63$-bits. What happens when we run the
  816. following program in our interpreter?
  817. \begin{lstlisting}
  818. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  819. \end{lstlisting}
  820. It produces an error:
  821. \begin{lstlisting}
  822. fx+: result is not a fixnum
  823. \end{lstlisting}
  824. We establish the convention that if running the definitional
  825. interpreter on a program produces an error, then the meaning of that
  826. program is \emph{unspecified}. That means a compiler for the language
  827. is under no obligations regarding that program; it may or may not
  828. produce an executable, and if it does, that executable can do
  829. anything. This convention applies to the languages defined in this
  830. book, as a way to simplify the student's task of implementing them,
  831. but this convention is not applicable to all programming languages.
  832. \index{unspecified behavior}
  833. Moving on to the last feature of the $R_0$ language, the \key{read}
  834. operation prompts the user of the program for an integer. Recall that
  835. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  836. \code{8}. So if we run
  837. \begin{lstlisting}
  838. (interp-R0 (Program '() ast1.1))
  839. \end{lstlisting}
  840. and if the input is \code{50}, then we get the answer to life, the
  841. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  842. Guide to the Galaxy} by Douglas Adams.}
  843. We include the \key{read} operation in $R_0$ so a clever student
  844. cannot implement a compiler for $R_0$ that simply runs the interpreter
  845. during compilation to obtain the output and then generates the trivial
  846. code to produce the output. (Yes, a clever student did this in the
  847. first instance of this course.)
  848. The job of a compiler is to translate a program in one language into a
  849. program in another language so that the output program behaves the
  850. same way as the input program does according to its definitional
  851. interpreter. This idea is depicted in the following diagram. Suppose
  852. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  853. interpreter for each language. Suppose that the compiler translates
  854. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  855. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  856. respective interpreters with input $i$ should yield the same output
  857. $o$.
  858. \begin{equation} \label{eq:compile-correct}
  859. \begin{tikzpicture}[baseline=(current bounding box.center)]
  860. \node (p1) at (0, 0) {$P_1$};
  861. \node (p2) at (3, 0) {$P_2$};
  862. \node (o) at (3, -2.5) {$o$};
  863. \path[->] (p1) edge [above] node {compile} (p2);
  864. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  865. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  866. \end{tikzpicture}
  867. \end{equation}
  868. In the next section we see our first example of a compiler.
  869. \section{Example Compiler: a Partial Evaluator}
  870. \label{sec:partial-evaluation}
  871. In this section we consider a compiler that translates $R_0$ programs
  872. into $R_0$ programs that may be more efficient, that is, this compiler
  873. is an optimizer. This optimizer eagerly computes the parts of the
  874. program that do not depend on any inputs, a process known as
  875. \emph{partial evaluation}~\cite{Jones:1993uq}.
  876. \index{partial evaluation}
  877. For example, given the following program
  878. \begin{lstlisting}
  879. (+ (read) (- (+ 5 3)))
  880. \end{lstlisting}
  881. our compiler will translate it into the program
  882. \begin{lstlisting}
  883. (+ (read) -8)
  884. \end{lstlisting}
  885. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  886. evaluator for the $R_0$ language. The output of the partial evaluator
  887. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  888. recursion over $\Exp$ is captured in the \code{pe-exp} function
  889. whereas the code for partially evaluating the negation and addition
  890. operations is factored into two separate helper functions:
  891. \code{pe-neg} and \code{pe-add}. The input to these helper
  892. functions is the output of partially evaluating the children.
  893. \begin{figure}[tp]
  894. \begin{lstlisting}
  895. (define (pe-neg r)
  896. (match r
  897. [(Int n) (Int (fx- 0 n))]
  898. [else (Prim '- (list r))]))
  899. (define (pe-add r1 r2)
  900. (match* (r1 r2)
  901. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  902. [(_ _) (Prim '+ (list r1 r2))]))
  903. (define (pe-exp e)
  904. (match e
  905. [(Int n) (Int n)]
  906. [(Prim 'read '()) (Prim 'read '())]
  907. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  908. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  909. ))
  910. (define (pe-R0 p)
  911. (match p
  912. [(Program '() e) (Program '() (pe-exp e))]
  913. ))
  914. \end{lstlisting}
  915. \caption{A partial evaluator for $R_0$ expressions.}
  916. \label{fig:pe-arith}
  917. \end{figure}
  918. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  919. arguments are integers and if they are, perform the appropriate
  920. arithmetic. Otherwise, they create an AST node for the operation
  921. (either negation or addition).
  922. To gain some confidence that the partial evaluator is correct, we can
  923. test whether it produces programs that get the same result as the
  924. input programs. That is, we can test whether it satisfies Diagram
  925. \eqref{eq:compile-correct}. The following code runs the partial
  926. evaluator on several examples and tests the output program. The
  927. \texttt{parse-program} and \texttt{assert} functions are defined in
  928. Appendix~\ref{appendix:utilities}.\\
  929. \begin{minipage}{1.0\textwidth}
  930. \begin{lstlisting}
  931. (define (test-pe p)
  932. (assert "testing pe-R0"
  933. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  934. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  935. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  936. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  937. \end{lstlisting}
  938. \end{minipage}
  939. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  940. \chapter{Integers and Variables}
  941. \label{ch:int-exp}
  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. \index{variable}
  964. The $R_1$ language extends the $R_0$ language with variable
  965. definitions. The concrete syntax of the $R_1$ language is defined by
  966. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  967. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  968. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  969. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  970. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  971. \key{Program} struct to mark the top of the program.
  972. %% The $\itm{info}$
  973. %% field of the \key{Program} structure contains an \emph{association
  974. %% list} (a list of key-value pairs) that is used to communicate
  975. %% auxiliary data from one compiler pass the next.
  976. Despite the simplicity of the $R_1$ language, it is rich enough to
  977. exhibit several compilation techniques.
  978. \begin{figure}[tp]
  979. \centering
  980. \fbox{
  981. \begin{minipage}{0.96\textwidth}
  982. \[
  983. \begin{array}{rcl}
  984. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  985. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  986. R_1 &::=& \Exp
  987. \end{array}
  988. \]
  989. \end{minipage}
  990. }
  991. \caption{The concrete syntax of $R_1$.}
  992. \label{fig:r1-concrete-syntax}
  993. \end{figure}
  994. \begin{figure}[tp]
  995. \centering
  996. \fbox{
  997. \begin{minipage}{0.96\textwidth}
  998. \[
  999. \begin{array}{rcl}
  1000. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1001. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1002. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1003. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1004. \end{array}
  1005. \]
  1006. \end{minipage}
  1007. }
  1008. \caption{The abstract syntax of $R_1$.}
  1009. \label{fig:r1-syntax}
  1010. \end{figure}
  1011. Let us dive further into the syntax and semantics of the $R_1$
  1012. language. The \key{Let} feature defines a variable for use within its
  1013. body and initializes the variable with the value of an expression.
  1014. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1015. The concrete syntax for \key{Let} is
  1016. \begin{lstlisting}
  1017. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1018. \end{lstlisting}
  1019. For example, the following program initializes \code{x} to $32$ and then
  1020. evaluates the body \code{(+ 10 x)}, producing $42$.
  1021. \begin{lstlisting}
  1022. (let ([x (+ 12 20)]) (+ 10 x))
  1023. \end{lstlisting}
  1024. When there are multiple \key{let}'s for the same variable, the closest
  1025. enclosing \key{let} is used. That is, variable definitions overshadow
  1026. prior definitions. Consider the following program with two \key{let}'s
  1027. that define variables named \code{x}. Can you figure out the result?
  1028. \begin{lstlisting}
  1029. (let ([x 32]) (+ (let ([x 10]) x) x))
  1030. \end{lstlisting}
  1031. For the purposes of depicting which variable uses correspond to which
  1032. definitions, the following shows the \code{x}'s annotated with
  1033. subscripts to distinguish them. Double check that your answer for the
  1034. above is the same as your answer for this annotated version of the
  1035. program.
  1036. \begin{lstlisting}
  1037. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1038. \end{lstlisting}
  1039. The initializing expression is always evaluated before the body of the
  1040. \key{let}, so in the following, the \key{read} for \code{x} is
  1041. performed before the \key{read} for \code{y}. Given the input
  1042. $52$ then $10$, the following produces $42$ (not $-42$).
  1043. \begin{lstlisting}
  1044. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1045. \end{lstlisting}
  1046. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1047. \small
  1048. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1049. An \emph{association list} (alist) is a list of key-value pairs.
  1050. For example, we can map people to their ages with an alist.
  1051. \index{alist}\index{association list}
  1052. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1053. (define ages
  1054. '((jane . 25) (sam . 24) (kate . 45)))
  1055. \end{lstlisting}
  1056. The \emph{dictionary} interface is for mapping keys to values.
  1057. Every alist implements this interface. \index{dictionary} The package
  1058. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1059. provides many functions for working with dictionaries. Here
  1060. are a few of them:
  1061. \begin{description}
  1062. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1063. returns the value associated with the given $\itm{key}$.
  1064. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1065. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1066. but otherwise is the same as $\itm{dict}$.
  1067. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1068. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1069. of keys and values in $\itm{dict}$. For example, the following
  1070. creates a new alist in which the ages are incremented.
  1071. \end{description}
  1072. \vspace{-10pt}
  1073. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1074. (for/list ([(k v) (in-dict ages)])
  1075. (cons k (add1 v)))
  1076. \end{lstlisting}
  1077. \end{tcolorbox}
  1078. \end{wrapfigure}
  1079. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1080. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1081. \key{match} clauses for variables and for \key{let}. For \key{let},
  1082. we need a way to communicate the value of a variable to all the uses
  1083. of a variable. To accomplish this, we maintain a mapping from
  1084. variables to values. Throughout the compiler we often need to map
  1085. variables to information about them. We refer to these mappings as
  1086. \emph{environments}\index{environment}
  1087. \footnote{Another common term for environment in the compiler
  1088. literature is \emph{symbol table}\index{symbol table}.}.
  1089. For simplicity, we use an
  1090. association list (alist) to represent the environment. The sidebar to
  1091. the right gives a brief introduction to alists and the
  1092. \code{racket/dict} package. The \code{interp-R1} function takes the
  1093. current environment, \code{env}, as an extra parameter. When the
  1094. interpreter encounters a variable, it finds the corresponding value
  1095. using the \code{dict-ref} function. When the interpreter encounters a
  1096. \key{Let}, it evaluates the initializing expression, extends the
  1097. environment with the result value bound to the variable, using
  1098. \code{dict-set}, then evaluates the body of the \key{Let}.
  1099. \begin{figure}[tp]
  1100. \begin{lstlisting}
  1101. (define (interp-exp env)
  1102. (lambda (e)
  1103. (match e
  1104. [(Int n) n]
  1105. [(Prim 'read '())
  1106. (define r (read))
  1107. (cond [(fixnum? r) r]
  1108. [else (error 'interp-R1 "expected an integer" r)])]
  1109. [(Prim '- (list e))
  1110. (define v ((interp-exp env) e))
  1111. (fx- 0 v)]
  1112. [(Prim '+ (list e1 e2))
  1113. (define v1 ((interp-exp env) e1))
  1114. (define v2 ((interp-exp env) e2))
  1115. (fx+ v1 v2)]
  1116. [(Var x) (dict-ref env x)]
  1117. [(Let x e body)
  1118. (define new-env (dict-set env x ((interp-exp env) e)))
  1119. ((interp-exp new-env) body)]
  1120. )))
  1121. (define (interp-R1 p)
  1122. (match p
  1123. [(Program '() e) ((interp-exp '()) e)]
  1124. ))
  1125. \end{lstlisting}
  1126. \caption{Interpreter for the $R_1$ language.}
  1127. \label{fig:interp-R1}
  1128. \end{figure}
  1129. The goal for this chapter is to implement a compiler that translates
  1130. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1131. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1132. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1133. is, they both output the same integer $n$. We depict this correctness
  1134. criteria in the following diagram.
  1135. \[
  1136. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1137. \node (p1) at (0, 0) {$P_1$};
  1138. \node (p2) at (4, 0) {$P_2$};
  1139. \node (o) at (4, -2) {$n$};
  1140. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1141. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1142. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1143. \end{tikzpicture}
  1144. \]
  1145. In the next section we introduce enough of the x86 assembly
  1146. language to compile $R_1$.
  1147. \section{The x86$_0$ Assembly Language}
  1148. \label{sec:x86}
  1149. \index{x86}
  1150. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1151. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1152. %
  1153. An x86 program begins with a \code{main} label followed by a sequence
  1154. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1155. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1156. instructions.\index{instruction}
  1157. %
  1158. An x86 program is stored in the computer's memory and the computer has
  1159. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1160. that points to the address of the next
  1161. instruction to be executed. For most instructions, once the
  1162. instruction is executed, the program counter is incremented to point
  1163. to the immediately following instruction in memory. Most x86
  1164. instructions take two operands, where each operand is either an
  1165. integer constant (called \emph{immediate value}\index{immediate value}),
  1166. a \emph{register}\index{register}, or a memory location.
  1167. A register is a special kind of variable. Each
  1168. one holds a 64-bit value; there are 16 registers in the computer and
  1169. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1170. as a mapping of 64-bit addresses to 64-bit values%
  1171. \footnote{This simple story suffices for describing how sequential
  1172. programs access memory but is not sufficient for multi-threaded
  1173. programs. However, multi-threaded execution is beyond the scope of
  1174. this book.}.
  1175. %
  1176. We use the AT\&T syntax expected by the GNU assembler, which comes
  1177. with the \key{gcc} compiler that we use for compiling assembly code to
  1178. machine code.
  1179. %
  1180. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1181. the x86 instructions used in this book.
  1182. % to do: finish treatment of imulq
  1183. % it's needed for vector's in R6/R7
  1184. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1185. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1186. && \key{r8} \mid \key{r9} \mid \key{r10}
  1187. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1188. \mid \key{r14} \mid \key{r15}}
  1189. \begin{figure}[tp]
  1190. \fbox{
  1191. \begin{minipage}{0.96\textwidth}
  1192. \[
  1193. \begin{array}{lcl}
  1194. \Reg &::=& \allregisters{} \\
  1195. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1196. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1197. \key{subq} \; \Arg\key{,} \Arg \mid
  1198. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1199. && \key{callq} \; \mathit{label} \mid
  1200. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1201. && \itm{label}\key{:}\; \Instr \\
  1202. x86_0 &::= & \key{.globl main}\\
  1203. & & \key{main:} \; \Instr\ldots
  1204. \end{array}
  1205. \]
  1206. \end{minipage}
  1207. }
  1208. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1209. \label{fig:x86-0-concrete}
  1210. \end{figure}
  1211. An immediate value is written using the notation \key{\$}$n$ where $n$
  1212. is an integer.
  1213. %
  1214. A register is written with a \key{\%} followed by the register name,
  1215. such as \key{\%rax}.
  1216. %
  1217. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1218. which obtains the address stored in register $r$ and then adds $n$
  1219. bytes to the address. The resulting address is used to either load or
  1220. store to memory depending on whether it occurs as a source or
  1221. destination argument of an instruction.
  1222. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1223. source $s$ and destination $d$, applies the arithmetic operation, then
  1224. writes the result back to the destination $d$.
  1225. %
  1226. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1227. stores the result in $d$.
  1228. %
  1229. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1230. specified by the label and $\key{retq}$ returns from a procedure to
  1231. its caller. We discuss procedure calls in more detail later in this
  1232. chapter and in Chapter~\ref{ch:functions}. The
  1233. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1234. the address of the instruction after the specified label.
  1235. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1236. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1237. \key{main} procedure is externally visible, which is necessary so
  1238. that the operating system can call it. The label \key{main:}
  1239. indicates the beginning of the \key{main} procedure which is where
  1240. the operating system starts executing this program. The instruction
  1241. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1242. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1243. $10$ in \key{rax} and puts the result, $42$, back into
  1244. \key{rax}.
  1245. %
  1246. The last instruction, \key{retq}, finishes the \key{main} function by
  1247. returning the integer in \key{rax} to the operating system. The
  1248. operating system interprets this integer as the program's exit
  1249. code. By convention, an exit code of 0 indicates that a program
  1250. completed successfully, and all other exit codes indicate various
  1251. errors. Nevertheless, we return the result of the program as the exit
  1252. code.
  1253. %\begin{wrapfigure}{r}{2.25in}
  1254. \begin{figure}[tbp]
  1255. \begin{lstlisting}
  1256. .globl main
  1257. main:
  1258. movq $10, %rax
  1259. addq $32, %rax
  1260. retq
  1261. \end{lstlisting}
  1262. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1263. \label{fig:p0-x86}
  1264. %\end{wrapfigure}
  1265. \end{figure}
  1266. Unfortunately, x86 varies in a couple ways depending on what operating
  1267. system it is assembled in. The code examples shown here are correct on
  1268. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1269. labels like \key{main} must be prefixed with an underscore, as in
  1270. \key{\_main}.
  1271. We exhibit the use of memory for storing intermediate results in the
  1272. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1273. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1274. memory called the \emph{procedure call stack} (or \emph{stack} for
  1275. short). \index{stack}\index{procedure call stack} The stack consists
  1276. of a separate \emph{frame}\index{frame} for each procedure call. The
  1277. memory layout for an individual frame is shown in
  1278. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1279. \emph{stack pointer}\index{stack pointer} and points to the item at
  1280. the top of the stack. The stack grows downward in memory, so we
  1281. increase the size of the stack by subtracting from the stack pointer.
  1282. In the context of a procedure call, the \emph{return
  1283. address}\index{return address} is the next instruction after the
  1284. call instruction on the caller side. During a function call, the
  1285. return address is pushed onto the stack. The register \key{rbp} is
  1286. the \emph{base pointer}\index{base pointer} and is used to access
  1287. variables associated with the current procedure call. The base
  1288. pointer of the caller is pushed onto the stack after the return
  1289. address. We number the variables from $1$ to $n$. Variable $1$ is
  1290. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1291. $-16\key{(\%rbp)}$, etc.
  1292. \begin{figure}[tbp]
  1293. \begin{lstlisting}
  1294. start:
  1295. movq $10, -8(%rbp)
  1296. negq -8(%rbp)
  1297. movq -8(%rbp), %rax
  1298. addq $52, %rax
  1299. jmp conclusion
  1300. .globl main
  1301. main:
  1302. pushq %rbp
  1303. movq %rsp, %rbp
  1304. subq $16, %rsp
  1305. jmp start
  1306. conclusion:
  1307. addq $16, %rsp
  1308. popq %rbp
  1309. retq
  1310. \end{lstlisting}
  1311. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1312. \label{fig:p1-x86}
  1313. \end{figure}
  1314. \begin{figure}[tbp]
  1315. \centering
  1316. \begin{tabular}{|r|l|} \hline
  1317. Position & Contents \\ \hline
  1318. 8(\key{\%rbp}) & return address \\
  1319. 0(\key{\%rbp}) & old \key{rbp} \\
  1320. -8(\key{\%rbp}) & variable $1$ \\
  1321. -16(\key{\%rbp}) & variable $2$ \\
  1322. \ldots & \ldots \\
  1323. 0(\key{\%rsp}) & variable $n$\\ \hline
  1324. \end{tabular}
  1325. \caption{Memory layout of a frame.}
  1326. \label{fig:frame}
  1327. \end{figure}
  1328. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1329. control is transfered from the operating system to the \code{main}
  1330. function. The operating system issues a \code{callq main} instruction
  1331. which pushes its return address on the stack and then jumps to
  1332. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1333. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1334. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1335. alignment (because the \code{callq} pushed the return address). The
  1336. first three instructions are the typical \emph{prelude}\index{prelude}
  1337. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1338. pointer for the caller onto the stack and subtracts $8$ from the stack
  1339. pointer. At this point the stack pointer is back to being 16-byte
  1340. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1341. base pointer so that it points the location of the old base
  1342. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1343. pointer down to make enough room for storing variables. This program
  1344. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1345. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1346. we are ready to make calls to other functions. The last instruction of
  1347. the prelude is \code{jmp start}, which transfers control to the
  1348. instructions that were generated from the Racket expression \code{(+
  1349. 10 32)}.
  1350. The four instructions under the label \code{start} carry out the work
  1351. of computing \code{(+ 52 (- 10)))}. The first instruction
  1352. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1353. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1354. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1355. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1356. \code{rax}, at which point \code{rax} contains $42$.
  1357. The three instructions under the label \code{conclusion} are the
  1358. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1359. two instructions are necessary to get the state of the machine back to
  1360. where it was at the beginning of the procedure. The instruction
  1361. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1362. old base pointer. The amount added here needs to match the amount that
  1363. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1364. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1365. pointer. The last instruction, \key{retq}, jumps back to the
  1366. procedure that called this one and adds 8 to the stack pointer, which
  1367. returns the stack pointer to where it was prior to the procedure call.
  1368. The compiler needs a convenient representation for manipulating x86
  1369. programs, so we define an abstract syntax for x86 in
  1370. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1371. a subscript $0$ because later we introduce extended versions of this
  1372. assembly language. The main difference compared to the concrete syntax
  1373. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1374. labeled instructions to appear anywhere, but instead organizes
  1375. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1376. and associates a label with every block, which is why the \key{CFG} struct
  1377. (for control-flow graph) includes an alist mapping labels to
  1378. blocks. The reason for this organization becomes apparent in
  1379. Chapter~\ref{ch:bool-types} when we introduce conditional
  1380. branching. The \code{Block} structure includes an $\itm{info}$ field
  1381. that is not needed for this chapter, but will become useful in
  1382. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1383. field should just contain an empty list.
  1384. \begin{figure}[tp]
  1385. \fbox{
  1386. \begin{minipage}{0.96\textwidth}
  1387. \small
  1388. \[
  1389. \begin{array}{lcl}
  1390. \Reg &::=& \allregisters{} \\
  1391. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1392. \mid \DEREF{\Reg}{\Int} \\
  1393. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1394. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1395. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1396. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1397. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1398. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1399. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1400. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1401. \end{array}
  1402. \]
  1403. \end{minipage}
  1404. }
  1405. \caption{The abstract syntax of x86$_0$ assembly.}
  1406. \label{fig:x86-0-ast}
  1407. \end{figure}
  1408. \section{Planning the trip to x86 via the $C_0$ language}
  1409. \label{sec:plan-s0-x86}
  1410. To compile one language to another it helps to focus on the
  1411. differences between the two languages because the compiler will need
  1412. to bridge those differences. What are the differences between $R_1$
  1413. and x86 assembly? Here are some of the most important ones:
  1414. \begin{enumerate}
  1415. \item[(a)] x86 arithmetic instructions typically have two arguments
  1416. and update the second argument in place. In contrast, $R_1$
  1417. arithmetic operations take two arguments and produce a new value.
  1418. An x86 instruction may have at most one memory-accessing argument.
  1419. Furthermore, some instructions place special restrictions on their
  1420. arguments.
  1421. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1422. whereas x86 instructions restrict their arguments to be integers
  1423. constants, registers, and memory locations.
  1424. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1425. sequence of instructions and jumps to labeled positions, whereas in
  1426. $R_1$ the order of evaluation is a left-to-right depth-first
  1427. traversal of the abstract syntax tree.
  1428. \item[(d)] An $R_1$ program can have any number of variables whereas
  1429. x86 has 16 registers and the procedure calls stack.
  1430. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1431. same name. The registers and memory locations of x86 all have unique
  1432. names or addresses.
  1433. \end{enumerate}
  1434. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1435. the problem into several steps, dealing with the above differences one
  1436. at a time. Each of these steps is called a \emph{pass} of the
  1437. compiler.\index{pass}\index{compiler pass}
  1438. %
  1439. This terminology comes from each step traverses (i.e. passes over) the
  1440. AST of the program.
  1441. %
  1442. We begin by sketching how we might implement each pass, and give them
  1443. names. We then figure out an ordering of the passes and the
  1444. input/output language for each pass. The very first pass has $R_1$ as
  1445. its input language and the last pass has x86 as its output
  1446. language. In between we can choose whichever language is most
  1447. convenient for expressing the output of each pass, whether that be
  1448. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1449. Finally, to implement each pass we write one recursive function per
  1450. non-terminal in the grammar of the input language of the pass.
  1451. \index{intermediate language}
  1452. \begin{description}
  1453. \item[Pass \key{select-instructions}] To handle the difference between
  1454. $R_1$ operations and x86 instructions we convert each $R_1$
  1455. operation to a short sequence of instructions that accomplishes the
  1456. same task.
  1457. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1458. subexpression (i.e. operator and operand, and hence the name
  1459. \key{opera*}) is an \emph{atomic} expression (a variable or
  1460. integer), we introduce temporary variables to hold the results
  1461. of subexpressions.\index{atomic expression}
  1462. \item[Pass \key{explicate-control}] To make the execution order of the
  1463. program explicit, we convert from the abstract syntax tree
  1464. representation into a control-flow graph in which each node
  1465. contains a sequence of statements and the edges between nodes say
  1466. where to go at the end of the sequence.
  1467. \item[Pass \key{assign-homes}] To handle the difference between the
  1468. variables in $R_1$ versus the registers and stack locations in x86,
  1469. we map each variable to a register or stack location.
  1470. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1471. by renaming every variable to a unique name, so that shadowing no
  1472. longer occurs.
  1473. \end{description}
  1474. The next question is: in what order should we apply these passes? This
  1475. question can be challenging because it is difficult to know ahead of
  1476. time which orders will be better (easier to implement, produce more
  1477. efficient code, etc.) so oftentimes trial-and-error is
  1478. involved. Nevertheless, we can try to plan ahead and make educated
  1479. choices regarding the ordering.
  1480. Let us consider the ordering of \key{uniquify} and
  1481. \key{remove-complex-opera*}. The assignment of subexpressions to
  1482. temporary variables involves introducing new variables and moving
  1483. subexpressions, which might change the shadowing of variables and
  1484. inadvertently change the behavior of the program. But if we apply
  1485. \key{uniquify} first, this will not be an issue. Of course, this means
  1486. that in \key{remove-complex-opera*}, we need to ensure that the
  1487. temporary variables that it creates are unique.
  1488. What should be the ordering of \key{explicate-control} with respect to
  1489. \key{uniquify}? The \key{uniquify} pass should come first because
  1490. \key{explicate-control} changes all the \key{let}-bound variables to
  1491. become local variables whose scope is the entire program, which would
  1492. confuse variables with the same name.
  1493. %
  1494. Likewise, we place \key{explicate-control} after
  1495. \key{remove-complex-opera*} because \key{explicate-control} removes
  1496. the \key{let} form, but it is convenient to use \key{let} in the
  1497. output of \key{remove-complex-opera*}.
  1498. %
  1499. Regarding \key{assign-homes}, it is helpful to place
  1500. \key{explicate-control} first because \key{explicate-control} changes
  1501. \key{let}-bound variables into program-scope variables. This means
  1502. that the \key{assign-homes} pass can read off the variables from the
  1503. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1504. entire program in search of \key{let}-bound variables.
  1505. Last, we need to decide on the ordering of \key{select-instructions}
  1506. and \key{assign-homes}. These two passes are intertwined, creating a
  1507. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1508. have already determined which instructions will be used, because x86
  1509. instructions have restrictions about which of their arguments can be
  1510. registers versus stack locations. One might want to give preferential
  1511. treatment to variables that occur in register-argument positions. On
  1512. the other hand, it may turn out to be impossible to make sure that all
  1513. such variables are assigned to registers, and then one must redo the
  1514. selection of instructions. Some compilers handle this problem by
  1515. iteratively repeating these two passes until a good solution is found.
  1516. We shall use a simpler approach in which \key{select-instructions}
  1517. comes first, followed by the \key{assign-homes}, then a third
  1518. pass named \key{patch-instructions} that uses a reserved register to
  1519. patch-up outstanding problems regarding instructions with too many
  1520. memory accesses. The disadvantage of this approach is some programs
  1521. may not execute as efficiently as they would if we used the iterative
  1522. approach and used all of the registers for variables.
  1523. \begin{figure}[tbp]
  1524. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1525. \node (R1) at (0,2) {\large $R_1$};
  1526. \node (R1-2) at (3,2) {\large $R_1$};
  1527. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1528. %\node (C0-1) at (6,0) {\large $C_0$};
  1529. \node (C0-2) at (3,0) {\large $C_0$};
  1530. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1531. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1532. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1533. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1534. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1535. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1536. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1537. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1538. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1539. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1540. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1541. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1542. \end{tikzpicture}
  1543. \caption{Overview of the passes for compiling $R_1$. }
  1544. \label{fig:R1-passes}
  1545. \end{figure}
  1546. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1547. passes in the form of a graph. Each pass is an edge and the
  1548. input/output language of each pass is a node in the graph. The output
  1549. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1550. are still in the $R_1$ language, but the output of the pass
  1551. \key{explicate-control} is in a different language $C_0$ that is
  1552. designed to make the order of evaluation explicit in its syntax, which
  1553. we introduce in the next section. The \key{select-instruction} pass
  1554. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1555. \key{patch-instructions} passes input and output variants of x86
  1556. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1557. \key{print-x86}, which converts from the abstract syntax of
  1558. $\text{x86}_0$ to the concrete syntax of x86.
  1559. In the next sections we discuss the $C_0$ language and the
  1560. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1561. remainder of this chapter gives hints regarding the implementation of
  1562. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1563. \subsection{The $C_0$ Intermediate Language}
  1564. The output of \key{explicate-control} is similar to the $C$
  1565. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1566. categories for expressions and statements, so we name it $C_0$. The
  1567. concrete syntax for $C_0$ is defined in
  1568. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1569. is defined in Figure~\ref{fig:c0-syntax}.
  1570. %
  1571. The $C_0$ language supports the same operators as $R_1$ but the
  1572. arguments of operators are restricted to atomic expressions (variables
  1573. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1574. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1575. executed in sequence using the \key{Seq} form. A sequence of
  1576. statements always ends with \key{Return}, a guarantee that is baked
  1577. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1578. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1579. which refers to an expression that is the last one to execute within a
  1580. function. (A expression in tail position may contain subexpressions,
  1581. and those may or may not be in tail position depending on the kind of
  1582. expression.)
  1583. A $C_0$ program consists of a control-flow graph (represented as an
  1584. alist mapping labels to tails). This is more general than
  1585. necessary for the present chapter, as we do not yet need to introduce
  1586. \key{goto} for jumping to labels, but it saves us from having to
  1587. change the syntax of the program construct in
  1588. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1589. \key{start}, and the whole program is its tail.
  1590. %
  1591. The $\itm{info}$ field of the \key{Program} form, after the
  1592. \key{explicate-control} pass, contains a mapping from the symbol
  1593. \key{locals} to a list of variables, that is, a list of all the
  1594. variables used in the program. At the start of the program, these
  1595. variables are uninitialized; they become initialized on their first
  1596. assignment.
  1597. \begin{figure}[tbp]
  1598. \fbox{
  1599. \begin{minipage}{0.96\textwidth}
  1600. \[
  1601. \begin{array}{lcl}
  1602. \Atm &::=& \Int \mid \Var \\
  1603. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1604. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1605. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1606. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1607. \end{array}
  1608. \]
  1609. \end{minipage}
  1610. }
  1611. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1612. \label{fig:c0-concrete-syntax}
  1613. \end{figure}
  1614. \begin{figure}[tbp]
  1615. \fbox{
  1616. \begin{minipage}{0.96\textwidth}
  1617. \[
  1618. \begin{array}{lcl}
  1619. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1620. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1621. &\mid& \ADD{\Atm}{\Atm}\\
  1622. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1623. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1624. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1625. \end{array}
  1626. \]
  1627. \end{minipage}
  1628. }
  1629. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1630. \label{fig:c0-syntax}
  1631. \end{figure}
  1632. %% The \key{select-instructions} pass is optimistic in the sense that it
  1633. %% treats variables as if they were all mapped to registers. The
  1634. %% \key{select-instructions} pass generates a program that consists of
  1635. %% x86 instructions but that still uses variables, so it is an
  1636. %% intermediate language that is technically different than x86, which
  1637. %% explains the asterisks in the diagram above.
  1638. %% In this Chapter we shall take the easy road to implementing
  1639. %% \key{assign-homes} and simply map all variables to stack locations.
  1640. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1641. %% smarter approach in which we make a best-effort to map variables to
  1642. %% registers, resorting to the stack only when necessary.
  1643. %% Once variables have been assigned to their homes, we can finalize the
  1644. %% instruction selection by dealing with an idiosyncrasy of x86
  1645. %% assembly. Many x86 instructions have two arguments but only one of the
  1646. %% arguments may be a memory reference (and the stack is a part of
  1647. %% memory). Because some variables may get mapped to stack locations,
  1648. %% some of our generated instructions may violate this restriction. The
  1649. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1650. %% replacing every violating instruction with a short sequence of
  1651. %% instructions that use the \key{rax} register. Once we have implemented
  1652. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1653. %% need to patch instructions will be relatively rare.
  1654. \subsection{The dialects of x86}
  1655. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1656. the pass \key{select-instructions}. It extends x86$_0$ with an
  1657. unbounded number of program-scope variables and has looser rules
  1658. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1659. output of \key{print-x86}, is the concrete syntax for x86.
  1660. \section{Uniquify Variables}
  1661. \label{sec:uniquify-s0}
  1662. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1663. programs in which every \key{let} uses a unique variable name. For
  1664. example, the \code{uniquify} pass should translate the program on the
  1665. left into the program on the right. \\
  1666. \begin{tabular}{lll}
  1667. \begin{minipage}{0.4\textwidth}
  1668. \begin{lstlisting}
  1669. (let ([x 32])
  1670. (+ (let ([x 10]) x) x))
  1671. \end{lstlisting}
  1672. \end{minipage}
  1673. &
  1674. $\Rightarrow$
  1675. &
  1676. \begin{minipage}{0.4\textwidth}
  1677. \begin{lstlisting}
  1678. (let ([x.1 32])
  1679. (+ (let ([x.2 10]) x.2) x.1))
  1680. \end{lstlisting}
  1681. \end{minipage}
  1682. \end{tabular} \\
  1683. %
  1684. The following is another example translation, this time of a program
  1685. with a \key{let} nested inside the initializing expression of another
  1686. \key{let}.\\
  1687. \begin{tabular}{lll}
  1688. \begin{minipage}{0.4\textwidth}
  1689. \begin{lstlisting}
  1690. (let ([x (let ([x 4])
  1691. (+ x 1))])
  1692. (+ x 2))
  1693. \end{lstlisting}
  1694. \end{minipage}
  1695. &
  1696. $\Rightarrow$
  1697. &
  1698. \begin{minipage}{0.4\textwidth}
  1699. \begin{lstlisting}
  1700. (let ([x.2 (let ([x.1 4])
  1701. (+ x.1 1))])
  1702. (+ x.2 2))
  1703. \end{lstlisting}
  1704. \end{minipage}
  1705. \end{tabular}
  1706. We recommend implementing \code{uniquify} by creating a function named
  1707. \code{uniquify-exp} that is structurally recursive function and mostly
  1708. just copies the input program. However, when encountering a \key{let},
  1709. it should generate a unique name for the variable (the Racket function
  1710. \code{gensym} is handy for this) and associate the old name with the
  1711. new unique name in an alist. The \code{uniquify-exp}
  1712. function will need to access this alist when it gets to a
  1713. variable reference, so we add another parameter to \code{uniquify-exp}
  1714. for the alist.
  1715. The skeleton of the \code{uniquify-exp} function is shown in
  1716. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1717. convenient to partially apply it to a symbol table and then apply it
  1718. to different expressions, as in the last clause for primitive
  1719. 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}}
  1720. form is useful for applying a function to each element of a list to produce
  1721. a new list.
  1722. \index{for/list}
  1723. \begin{exercise}
  1724. \normalfont % I don't like the italics for exercises. -Jeremy
  1725. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1726. implement the clauses for variables and for the \key{let} form.
  1727. \end{exercise}
  1728. \begin{figure}[tbp]
  1729. \begin{lstlisting}
  1730. (define (uniquify-exp symtab)
  1731. (lambda (e)
  1732. (match e
  1733. [(Var x) ___]
  1734. [(Int n) (Int n)]
  1735. [(Let x e body) ___]
  1736. [(Prim op es)
  1737. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1738. )))
  1739. (define (uniquify p)
  1740. (match p
  1741. [(Program '() e)
  1742. (Program '() ((uniquify-exp '()) e))]
  1743. )))
  1744. \end{lstlisting}
  1745. \caption{Skeleton for the \key{uniquify} pass.}
  1746. \label{fig:uniquify-s0}
  1747. \end{figure}
  1748. \begin{exercise}
  1749. \normalfont % I don't like the italics for exercises. -Jeremy
  1750. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1751. and checking whether the output programs produce the same result as
  1752. the input programs. The $R_1$ programs should be designed to test the
  1753. most interesting parts of the \key{uniquify} pass, that is, the
  1754. programs should include \key{let} forms, variables, and variables
  1755. that overshadow each other. The five programs should be in a
  1756. subdirectory named \key{tests} and they should have the same file name
  1757. except for a different integer at the end of the name, followed by the
  1758. ending \key{.rkt}. Use the \key{interp-tests} function
  1759. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1760. your \key{uniquify} pass on the example programs. See the
  1761. \key{run-tests.rkt} script in the student support code for an example
  1762. of how to use \key{interp-tests}.
  1763. \end{exercise}
  1764. \section{Remove Complex Operands}
  1765. \label{sec:remove-complex-opera-R1}
  1766. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1767. $R_1$ programs in which the arguments of operations are atomic
  1768. expressions. Put another way, this pass removes complex
  1769. operands\index{complex operand}, such as the expression \code{(- 10)}
  1770. in the program below. This is accomplished by introducing a new
  1771. \key{let}-bound variable, binding the complex operand to the new
  1772. variable, and then using the new variable in place of the complex
  1773. operand, as shown in the output of \code{remove-complex-opera*} on the
  1774. right.\\
  1775. \begin{tabular}{lll}
  1776. \begin{minipage}{0.4\textwidth}
  1777. % s0_19.rkt
  1778. \begin{lstlisting}
  1779. (+ 52 (- 10))
  1780. \end{lstlisting}
  1781. \end{minipage}
  1782. &
  1783. $\Rightarrow$
  1784. &
  1785. \begin{minipage}{0.4\textwidth}
  1786. \begin{lstlisting}
  1787. (let ([tmp.1 (- 10)])
  1788. (+ 52 tmp.1))
  1789. \end{lstlisting}
  1790. \end{minipage}
  1791. \end{tabular}
  1792. \begin{figure}[tp]
  1793. \centering
  1794. \fbox{
  1795. \begin{minipage}{0.96\textwidth}
  1796. \[
  1797. \begin{array}{rcl}
  1798. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1799. \Exp &::=& \Atm \mid \READ{} \\
  1800. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1801. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1802. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1803. \end{array}
  1804. \]
  1805. \end{minipage}
  1806. }
  1807. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1808. \label{fig:r1-anf-syntax}
  1809. \end{figure}
  1810. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1811. this pass, language $R_1^{\dagger}$. The main difference is that
  1812. operator arguments are required to be atomic expressions. In the
  1813. literature this is called \emph{administrative normal form}, or ANF
  1814. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1815. \index{administrative normal form}
  1816. \index{ANF}
  1817. We recommend implementing this pass with two mutually recursive
  1818. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1819. \code{rco-atom} to subexpressions that are required to be atomic and
  1820. to apply \code{rco-exp} to subexpressions that can be atomic or
  1821. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1822. $R_1$ expression as input. The \code{rco-exp} function returns an
  1823. expression. The \code{rco-atom} function returns two things: an
  1824. atomic expression and alist mapping temporary variables to complex
  1825. subexpressions. You can return multiple things from a function using
  1826. Racket's \key{values} form and you can receive multiple things from a
  1827. function call using the \key{define-values} form. If you are not
  1828. familiar with these features, review the Racket documentation. Also,
  1829. 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}}
  1830. form is useful for applying a function to each
  1831. element of a list, in the case where the function returns multiple
  1832. values.
  1833. \index{for/lists}
  1834. The following shows the output of \code{rco-atom} on the expression
  1835. \code{(- 10)} (using concrete syntax to be concise).
  1836. \begin{tabular}{lll}
  1837. \begin{minipage}{0.4\textwidth}
  1838. \begin{lstlisting}
  1839. (- 10)
  1840. \end{lstlisting}
  1841. \end{minipage}
  1842. &
  1843. $\Rightarrow$
  1844. &
  1845. \begin{minipage}{0.4\textwidth}
  1846. \begin{lstlisting}
  1847. tmp.1
  1848. ((tmp.1 . (- 10)))
  1849. \end{lstlisting}
  1850. \end{minipage}
  1851. \end{tabular}
  1852. Take special care of programs such as the next one that \key{let}-bind
  1853. variables with integers or other variables. You should leave them
  1854. unchanged, as shown in to the program on the right \\
  1855. \begin{tabular}{lll}
  1856. \begin{minipage}{0.4\textwidth}
  1857. % s0_20.rkt
  1858. \begin{lstlisting}
  1859. (let ([a 42])
  1860. (let ([b a])
  1861. b))
  1862. \end{lstlisting}
  1863. \end{minipage}
  1864. &
  1865. $\Rightarrow$
  1866. &
  1867. \begin{minipage}{0.4\textwidth}
  1868. \begin{lstlisting}
  1869. (let ([a 42])
  1870. (let ([b a])
  1871. b))
  1872. \end{lstlisting}
  1873. \end{minipage}
  1874. \end{tabular} \\
  1875. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1876. produce the following output.\\
  1877. \begin{minipage}{0.4\textwidth}
  1878. \begin{lstlisting}
  1879. (let ([tmp.1 42])
  1880. (let ([a tmp.1])
  1881. (let ([tmp.2 a])
  1882. (let ([b tmp.2])
  1883. b))))
  1884. \end{lstlisting}
  1885. \end{minipage}
  1886. \begin{exercise}
  1887. \normalfont Implement the \code{remove-complex-opera*} pass.
  1888. Test the new pass on all of the example programs that you created to test the
  1889. \key{uniquify} pass and create three new example programs that are
  1890. designed to exercise the interesting code in the
  1891. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1892. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1893. your passes on the example programs.
  1894. \end{exercise}
  1895. \section{Explicate Control}
  1896. \label{sec:explicate-control-r1}
  1897. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1898. programs that make the order of execution explicit in their
  1899. syntax. For now this amounts to flattening \key{let} constructs into a
  1900. sequence of assignment statements. For example, consider the following
  1901. $R_1$ program.\\
  1902. % s0_11.rkt
  1903. \begin{minipage}{0.96\textwidth}
  1904. \begin{lstlisting}
  1905. (let ([y (let ([x 20])
  1906. (+ x (let ([x 22]) x)))])
  1907. y)
  1908. \end{lstlisting}
  1909. \end{minipage}\\
  1910. %
  1911. The output of the previous pass and of \code{explicate-control} is
  1912. shown below. Recall that the right-hand-side of a \key{let} executes
  1913. before its body, so the order of evaluation for this program is to
  1914. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1915. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1916. output of \code{explicate-control} makes this ordering explicit.\\
  1917. \begin{tabular}{lll}
  1918. \begin{minipage}{0.4\textwidth}
  1919. \begin{lstlisting}
  1920. (let ([y (let ([x.1 20])
  1921. (let ([x.2 22])
  1922. (+ x.1 x.2)))])
  1923. y)
  1924. \end{lstlisting}
  1925. \end{minipage}
  1926. &
  1927. $\Rightarrow$
  1928. &
  1929. \begin{minipage}{0.4\textwidth}
  1930. \begin{lstlisting}
  1931. locals: y x.1 x.2
  1932. start:
  1933. x.1 = 20;
  1934. x.2 = 22;
  1935. y = (+ x.1 x.2);
  1936. return y;
  1937. \end{lstlisting}
  1938. \end{minipage}
  1939. \end{tabular}
  1940. We recommend implementing \code{explicate-control} using two mutually
  1941. recursive functions: \code{explicate-tail} and
  1942. \code{explicate-assign}. The first function should be applied to
  1943. expressions in tail position whereas the second should be applied to
  1944. expressions that occur on the right-hand-side of a \key{let}.
  1945. %
  1946. The \code{explicate-tail} function takes an $R_1$ expression as input
  1947. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1948. list of formerly \key{let}-bound variables.
  1949. %
  1950. The \code{explicate-assign} function takes an $R_1$ expression, the
  1951. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1952. should come after the assignment (e.g., the code generated for the
  1953. body of the \key{let}). It returns a $\Tail$ and a list of
  1954. variables. The \code{explicate-assign} function is in
  1955. accumulator-passing style in that its third parameter is some $C_0$
  1956. code which it then adds to and returns. The reader might be tempted to
  1957. instead organize \code{explicate-assign} in a more direct fashion,
  1958. without the third parameter and perhaps using \code{append} to combine
  1959. statements. We warn against that alternative because the
  1960. accumulator-passing style is key to how we generate high-quality code
  1961. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1962. The top-level \code{explicate-control} function should invoke
  1963. \code{explicate-tail} on the body of the \key{program} and then
  1964. associate the \code{locals} symbol with the resulting list of
  1965. variables in the $\itm{info}$ field, as in the above example.
  1966. \section{Select Instructions}
  1967. \label{sec:select-r1}
  1968. \index{instruction selection}
  1969. In the \code{select-instructions} pass we begin the work of
  1970. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1971. this pass is a variant of x86 that still uses variables, so we add an
  1972. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1973. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1974. \code{select-instructions} in terms of three auxiliary functions, one
  1975. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1976. The cases for $\Atm$ are straightforward, variables stay
  1977. the same and integer constants are changed to immediates:
  1978. $\INT{n}$ changes to $\IMM{n}$.
  1979. Next we consider the cases for $\Stmt$, starting with arithmetic
  1980. operations. For example, in $C_0$ an addition operation can take the
  1981. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1982. need to use the \key{addq} instruction which does an in-place
  1983. update. So we must first move \code{10} to \code{x}. \\
  1984. \begin{tabular}{lll}
  1985. \begin{minipage}{0.4\textwidth}
  1986. \begin{lstlisting}
  1987. x = (+ 10 32);
  1988. \end{lstlisting}
  1989. \end{minipage}
  1990. &
  1991. $\Rightarrow$
  1992. &
  1993. \begin{minipage}{0.4\textwidth}
  1994. \begin{lstlisting}
  1995. movq $10, x
  1996. addq $32, x
  1997. \end{lstlisting}
  1998. \end{minipage}
  1999. \end{tabular} \\
  2000. %
  2001. There are cases that require special care to avoid generating
  2002. needlessly complicated code. If one of the arguments of the addition
  2003. is the same as the left-hand side of the assignment, then there is no
  2004. need for the extra move instruction. For example, the following
  2005. assignment statement can be translated into a single \key{addq}
  2006. instruction.\\
  2007. \begin{tabular}{lll}
  2008. \begin{minipage}{0.4\textwidth}
  2009. \begin{lstlisting}
  2010. x = (+ 10 x);
  2011. \end{lstlisting}
  2012. \end{minipage}
  2013. &
  2014. $\Rightarrow$
  2015. &
  2016. \begin{minipage}{0.4\textwidth}
  2017. \begin{lstlisting}
  2018. addq $10, x
  2019. \end{lstlisting}
  2020. \end{minipage}
  2021. \end{tabular} \\
  2022. The \key{read} operation does not have a direct counterpart in x86
  2023. assembly, so we have instead implemented this functionality in the C
  2024. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2025. in the file \code{runtime.c}. In general, we refer to all of the
  2026. functionality in this file as the \emph{runtime system}\index{runtime system},
  2027. or simply the \emph{runtime} for short. When compiling your generated x86
  2028. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2029. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2030. the executable. For our purposes of code generation, all you need to
  2031. do is translate an assignment of \key{read} into some variable
  2032. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2033. function followed by a move from \code{rax} to the left-hand side.
  2034. The move from \code{rax} is needed because the return value from
  2035. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2036. \begin{tabular}{lll}
  2037. \begin{minipage}{0.3\textwidth}
  2038. \begin{lstlisting}
  2039. |$\itm{var}$| = (read);
  2040. \end{lstlisting}
  2041. \end{minipage}
  2042. &
  2043. $\Rightarrow$
  2044. &
  2045. \begin{minipage}{0.3\textwidth}
  2046. \begin{lstlisting}
  2047. callq read_int
  2048. movq %rax, |$\itm{var}$|
  2049. \end{lstlisting}
  2050. \end{minipage}
  2051. \end{tabular} \\
  2052. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2053. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2054. assignment to the \key{rax} register followed by a jump to the
  2055. conclusion of the program (so the conclusion needs to be labeled).
  2056. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2057. recursively and append the resulting instructions.
  2058. \begin{exercise}
  2059. \normalfont
  2060. Implement the \key{select-instructions} pass and test it on all of the
  2061. example programs that you created for the previous passes and create
  2062. three new example programs that are designed to exercise all of the
  2063. interesting code in this pass. Use the \key{interp-tests} function
  2064. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2065. your passes on the example programs.
  2066. \end{exercise}
  2067. \section{Assign Homes}
  2068. \label{sec:assign-r1}
  2069. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2070. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2071. Thus, the \key{assign-homes} pass is responsible for placing all of
  2072. the program variables in registers or on the stack. For runtime
  2073. efficiency, it is better to place variables in registers, but as there
  2074. are only 16 registers, some programs must necessarily resort to
  2075. placing some variables on the stack. In this chapter we focus on the
  2076. mechanics of placing variables on the stack. We study an algorithm for
  2077. placing variables in registers in
  2078. Chapter~\ref{ch:register-allocation-r1}.
  2079. Consider again the following $R_1$ program.
  2080. % s0_20.rkt
  2081. \begin{lstlisting}
  2082. (let ([a 42])
  2083. (let ([b a])
  2084. b))
  2085. \end{lstlisting}
  2086. For reference, we repeat the output of \code{select-instructions} on
  2087. the left and show the output of \code{assign-homes} on the right.
  2088. Recall that \key{explicate-control} associated the list of
  2089. variables with the \code{locals} symbol in the program's $\itm{info}$
  2090. field, so \code{assign-homes} has convenient access to the them. In
  2091. this example, we assign variable \code{a} to stack location
  2092. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2093. \begin{tabular}{l}
  2094. \begin{minipage}{0.4\textwidth}
  2095. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2096. locals: a b
  2097. start:
  2098. movq $42, a
  2099. movq a, b
  2100. movq b, %rax
  2101. jmp conclusion
  2102. \end{lstlisting}
  2103. \end{minipage}
  2104. {$\Rightarrow$}
  2105. \begin{minipage}{0.4\textwidth}
  2106. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2107. stack-space: 16
  2108. start:
  2109. movq $42, -8(%rbp)
  2110. movq -8(%rbp), -16(%rbp)
  2111. movq -16(%rbp), %rax
  2112. jmp conclusion
  2113. \end{lstlisting}
  2114. \end{minipage}
  2115. \end{tabular} \\
  2116. In the process of assigning variables to stack locations, it is
  2117. convenient to compute and store the size of the frame (in bytes) in
  2118. the $\itm{info}$ field of the \key{Program} node, with the key
  2119. \code{stack-space}, which will be needed later to generate the
  2120. procedure conclusion. The x86-64 standard requires the frame size to
  2121. be a multiple of 16 bytes.
  2122. \index{frame}
  2123. \begin{exercise}
  2124. \normalfont Implement the \key{assign-homes} pass and test it on all
  2125. of the example programs that you created for the previous passes pass.
  2126. We recommend that \key{assign-homes} take an extra parameter that is a
  2127. mapping of variable names to homes (stack locations for now). Use the
  2128. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2129. \key{utilities.rkt} to test your passes on the example programs.
  2130. \end{exercise}
  2131. \section{Patch Instructions}
  2132. \label{sec:patch-s0}
  2133. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2134. programs to $\text{x86}_0$ programs by making sure that each
  2135. instruction adheres to the restrictions of the x86 assembly language.
  2136. In particular, at most one argument of an instruction may be a memory
  2137. reference.
  2138. We return to the following running example.
  2139. % s0_20.rkt
  2140. \begin{lstlisting}
  2141. (let ([a 42])
  2142. (let ([b a])
  2143. b))
  2144. \end{lstlisting}
  2145. After the \key{assign-homes} pass, the above program has been translated to
  2146. the following. \\
  2147. \begin{minipage}{0.5\textwidth}
  2148. \begin{lstlisting}
  2149. stack-space: 16
  2150. start:
  2151. movq $42, -8(%rbp)
  2152. movq -8(%rbp), -16(%rbp)
  2153. movq -16(%rbp), %rax
  2154. jmp conclusion
  2155. \end{lstlisting}
  2156. \end{minipage}\\
  2157. The second \key{movq} instruction is problematic because both
  2158. arguments are stack locations. We suggest fixing this problem by
  2159. moving from the source location to the register \key{rax} and then
  2160. from \key{rax} to the destination location, as follows.
  2161. \begin{lstlisting}
  2162. movq -8(%rbp), %rax
  2163. movq %rax, -16(%rbp)
  2164. \end{lstlisting}
  2165. \begin{exercise}
  2166. \normalfont
  2167. Implement the \key{patch-instructions} pass and test it on all of the
  2168. example programs that you created for the previous passes and create
  2169. three new example programs that are designed to exercise all of the
  2170. interesting code in this pass. Use the \key{interp-tests} function
  2171. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2172. your passes on the example programs.
  2173. \end{exercise}
  2174. \section{Print x86}
  2175. \label{sec:print-x86}
  2176. The last step of the compiler from $R_1$ to x86 is to convert the
  2177. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2178. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2179. \key{format} and \key{string-append} functions are useful in this
  2180. regard. The main work that this step needs to perform is to create the
  2181. \key{main} function and the standard instructions for its prelude and
  2182. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2183. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2184. variables, so we suggest computing it in the \key{assign-homes} pass
  2185. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2186. of the \key{program} node.
  2187. %% Your compiled code should print the result of the program's execution
  2188. %% by using the \code{print\_int} function provided in
  2189. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2190. %% far, this final result should be stored in the \key{rax} register.
  2191. %% We'll talk more about how to perform function calls with arguments in
  2192. %% general later on, but for now, place the following after the compiled
  2193. %% code for the $R_1$ program but before the conclusion:
  2194. %% \begin{lstlisting}
  2195. %% movq %rax, %rdi
  2196. %% callq print_int
  2197. %% \end{lstlisting}
  2198. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2199. %% stores the first argument to be passed into \key{print\_int}.
  2200. If you want your program to run on Mac OS X, your code needs to
  2201. determine whether or not it is running on a Mac, and prefix
  2202. underscores to labels like \key{main}. You can determine the platform
  2203. with the Racket call \code{(system-type 'os)}, which returns
  2204. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2205. %% In addition to
  2206. %% placing underscores on \key{main}, you need to put them in front of
  2207. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2208. %% \_print\_int}).
  2209. \begin{exercise}
  2210. \normalfont Implement the \key{print-x86} pass and test it on all of
  2211. the example programs that you created for the previous passes. Use the
  2212. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2213. \key{utilities.rkt} to test your complete compiler on the example
  2214. programs. See the \key{run-tests.rkt} script in the student support
  2215. code for an example of how to use \key{compiler-tests}. Also, remember
  2216. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2217. \key{gcc}.
  2218. \end{exercise}
  2219. \section{Challenge: Partial Evaluator for $R_1$}
  2220. \label{sec:pe-R1}
  2221. \index{partial evaluation}
  2222. This section describes optional challenge exercises that involve
  2223. adapting and improving the partial evaluator for $R_0$ that was
  2224. introduced in Section~\ref{sec:partial-evaluation}.
  2225. \begin{exercise}\label{ex:pe-R1}
  2226. \normalfont
  2227. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2228. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2229. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2230. and variables to the $R_0$ language, so you will need to add cases for
  2231. them in the \code{pe-exp} function. Also, note that the \key{program}
  2232. form changes slightly to include an $\itm{info}$ field. Once
  2233. complete, add the partial evaluation pass to the front of your
  2234. compiler and make sure that your compiler still passes all of the
  2235. tests.
  2236. \end{exercise}
  2237. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2238. \begin{exercise}
  2239. \normalfont
  2240. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2241. \code{pe-add} auxiliary functions with functions that know more about
  2242. arithmetic. For example, your partial evaluator should translate
  2243. \begin{lstlisting}
  2244. (+ 1 (+ (read) 1))
  2245. \end{lstlisting}
  2246. into
  2247. \begin{lstlisting}
  2248. (+ 2 (read))
  2249. \end{lstlisting}
  2250. To accomplish this, the \code{pe-exp} function should produce output
  2251. in the form of the $\itm{residual}$ non-terminal of the following
  2252. grammar.
  2253. \[
  2254. \begin{array}{lcl}
  2255. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2256. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2257. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2258. \end{array}
  2259. \]
  2260. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2261. that their inputs are $\itm{residual}$ expressions and they should
  2262. return $\itm{residual}$ expressions. Once the improvements are
  2263. complete, make sure that your compiler still passes all of the tests.
  2264. After all, fast code is useless if it produces incorrect results!
  2265. \end{exercise}
  2266. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2267. \chapter{Register Allocation}
  2268. \label{ch:register-allocation-r1}
  2269. \index{register allocation}
  2270. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2271. make our life easier. However, we can improve the performance of the
  2272. generated code if we instead place some variables into registers. The
  2273. CPU can access a register in a single cycle, whereas accessing the
  2274. stack takes many cycles if the relevant data is in cache or many more
  2275. to access main memory if the data is not in cache.
  2276. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2277. serves as a running example. We show the source program and also the
  2278. output of instruction selection. At that point the program is almost
  2279. x86 assembly but not quite; it still contains variables instead of
  2280. stack locations or registers.
  2281. \begin{figure}
  2282. \begin{minipage}{0.45\textwidth}
  2283. Example $R_1$ program:
  2284. % s0_28.rkt
  2285. \begin{lstlisting}
  2286. (let ([v 1])
  2287. (let ([w 42])
  2288. (let ([x (+ v 7)])
  2289. (let ([y x])
  2290. (let ([z (+ x w)])
  2291. (+ z (- y)))))))
  2292. \end{lstlisting}
  2293. \end{minipage}
  2294. \begin{minipage}{0.45\textwidth}
  2295. After instruction selection:
  2296. \begin{lstlisting}
  2297. locals: (v w x y z t)
  2298. start:
  2299. movq $1, v
  2300. movq $42, w
  2301. movq v, x
  2302. addq $7, x
  2303. movq x, y
  2304. movq x, z
  2305. addq w, z
  2306. movq y, t
  2307. negq t
  2308. movq z, %rax
  2309. addq t, %rax
  2310. jmp conclusion
  2311. \end{lstlisting}
  2312. \end{minipage}
  2313. \caption{An example program for register allocation.}
  2314. \label{fig:reg-eg}
  2315. \end{figure}
  2316. The goal of register allocation is to fit as many variables into
  2317. registers as possible. A program sometimes has more variables than
  2318. registers, so we cannot map each variable to a different
  2319. register. Fortunately, it is common for different variables to be
  2320. needed during different periods of time during program execution, and
  2321. in such cases several variables can be mapped to the same register.
  2322. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2323. After the variable \code{x} is moved to \code{z} it is no longer
  2324. needed. Variable \code{y}, on the other hand, is used only after this
  2325. point, so \code{x} and \code{y} could share the same register. The
  2326. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2327. where a variable is needed. Once we have that information, we compute
  2328. which variables are needed at the same time, i.e., which ones
  2329. \emph{interfere} with each other, and represent this relation as an
  2330. undirected graph whose vertices are variables and edges indicate when
  2331. two variables interfere (Section~\ref{sec:build-interference}). We
  2332. then model register allocation as a graph coloring problem, which we
  2333. discuss in Section~\ref{sec:graph-coloring}.
  2334. In the event that we run out of registers despite these efforts, we
  2335. place the remaining variables on the stack, similar to what we did in
  2336. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2337. for assigning a variable to a stack location. The process of spilling
  2338. variables is handled as part of the graph coloring process described
  2339. in \ref{sec:graph-coloring}.
  2340. We make the simplifying assumption that each variable is assigned to
  2341. one location (a register or stack address). A more sophisticated
  2342. approach is to assign a variable to one or more locations in different
  2343. regions of the program. For example, if a variable is used many times
  2344. in short sequence and then only used again after many other
  2345. instructions, it could be more efficient to assign the variable to a
  2346. register during the intial sequence and then move it to the stack for
  2347. the rest of its lifetime. We refer the interested reader to
  2348. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2349. about this approach.
  2350. % discuss prioritizing variables based on how much they are used.
  2351. \section{Registers and Calling Conventions}
  2352. \label{sec:calling-conventions}
  2353. \index{calling conventions}
  2354. As we perform register allocation, we need to be aware of the
  2355. conventions that govern the way in which registers interact with
  2356. function calls, such as calls to the \code{read\_int} function in our
  2357. generated code and even the call that the operating system makes to
  2358. execute our \code{main} function. The convention for x86 is that the
  2359. caller is responsible for freeing up some registers, the
  2360. \emph{caller-saved registers}, prior to the function call, and the
  2361. callee is responsible for preserving the values in some other
  2362. registers, the \emph{callee-saved registers}.
  2363. \index{caller-saved registers}
  2364. \index{callee-saved registers}
  2365. The caller-saved registers are
  2366. \begin{lstlisting}
  2367. rax rcx rdx rsi rdi r8 r9 r10 r11
  2368. \end{lstlisting}
  2369. while the callee-saved registers are
  2370. \begin{lstlisting}
  2371. rsp rbp rbx r12 r13 r14 r15
  2372. \end{lstlisting}
  2373. We can think about this caller/callee convention from two points of
  2374. view, the caller view and the callee view:
  2375. \begin{itemize}
  2376. \item The caller should assume that all the caller-saved registers get
  2377. overwritten with arbitrary values by the callee. On the other hand,
  2378. the caller can safely assume that all the callee-saved registers
  2379. contain the same values after the call that they did before the
  2380. call.
  2381. \item The callee can freely use any of the caller-saved registers.
  2382. However, if the callee wants to use a callee-saved register, the
  2383. callee must arrange to put the original value back in the register
  2384. prior to returning to the caller, which is usually accomplished by
  2385. saving the value to the stack in the prelude of the function and
  2386. restoring the value in the conclusion of the function.
  2387. \end{itemize}
  2388. The next question is how these calling conventions impact register
  2389. allocation. Consider the $R_1$ program in
  2390. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2391. example from the caller point of view and then from the callee point
  2392. of view.
  2393. The program makes two calls to the \code{read} function. Also, the
  2394. variable \code{x} is in-use during the second call to \code{read}, so
  2395. we need to make sure that the value in \code{x} does not get
  2396. accidentally wiped out by the call to \code{read}. One obvious
  2397. approach is to save all the values in caller-saved registers to the
  2398. stack prior to each function call, and restore them after each
  2399. call. That way, if the register allocator chooses to assign \code{x}
  2400. to a caller-saved register, its value will be preserved accross the
  2401. call to \code{read}. However, the disadvantage of this approach is
  2402. that saving and restoring to the stack is relatively slow. If \code{x}
  2403. is not used many times, it may be better to assign \code{x} to a stack
  2404. location in the first place. Or better yet, if we can arrange for
  2405. \code{x} to be placed in a callee-saved register, then it won't need
  2406. to be saved and restored during function calls.
  2407. The approach that we recommend for variables that are in-use during a
  2408. function call is to either assign them to callee-saved registers or to
  2409. spill them to the stack. On the other hand, for variables that are not
  2410. in-use during a function call, we try the following alternatives in
  2411. order 1) look for an available caller-saved register (to leave room
  2412. for other variables in the callee-saved register), 2) look for a
  2413. callee-saved register, and 3) spill the variable to the stack.
  2414. It is straightforward to implement this approach in a graph coloring
  2415. register allocator. First, we know which variables are in-use during
  2416. every function call because we compute that information for every
  2417. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2418. build the interference graph (Section~\ref{sec:build-interference}),
  2419. we can place an edge between each of these variables and the
  2420. caller-saved registers in the interference graph. This will prevent
  2421. the graph coloring algorithm from assigning those variables to
  2422. caller-saved registers.
  2423. Returning to the example in
  2424. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2425. generated x86 code on the right-hand side, focusing on the
  2426. \code{start} block. Notice that variable \code{x} is assigned to
  2427. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2428. place during the second call to \code{read\_int}. Next, notice that
  2429. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2430. because there are no function calls in the remainder of the block.
  2431. Next we analyze the example from the callee point of view, focusing on
  2432. the prelude and conclusion of the \code{main} function. As usual the
  2433. prelude begins with saving the \code{rbp} register to the stack and
  2434. setting the \code{rbp} to the current stack pointer. We now know why
  2435. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2436. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2437. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2438. variable (\code{x}). There are several more callee-saved register that
  2439. are not saved in the prelude because they were not assigned to
  2440. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2441. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2442. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2443. from the stack with a \code{popq} instruction.
  2444. \index{prelude}\index{conclusion}
  2445. \begin{figure}[tp]
  2446. \begin{minipage}{0.45\textwidth}
  2447. Example $R_1$ program:
  2448. %s0_14.rkt
  2449. \begin{lstlisting}
  2450. (let ([x (read)])
  2451. (let ([y (read)])
  2452. (+ (+ x y) 42)))
  2453. \end{lstlisting}
  2454. \end{minipage}
  2455. \begin{minipage}{0.45\textwidth}
  2456. Generated x86 assembly:
  2457. \begin{lstlisting}
  2458. start:
  2459. callq read_int
  2460. movq %rax, %rbx
  2461. callq read_int
  2462. movq %rax, %rcx
  2463. addq %rcx, %rbx
  2464. movq %rbx, %rax
  2465. addq $42, %rax
  2466. jmp _conclusion
  2467. .globl main
  2468. main:
  2469. pushq %rbp
  2470. movq %rsp, %rbp
  2471. pushq %rbx
  2472. subq $8, %rsp
  2473. jmp start
  2474. conclusion:
  2475. addq $8, %rsp
  2476. popq %rbx
  2477. popq %rbp
  2478. retq
  2479. \end{lstlisting}
  2480. \end{minipage}
  2481. \caption{An example with function calls.}
  2482. \label{fig:example-calling-conventions}
  2483. \end{figure}
  2484. \clearpage
  2485. \section{Liveness Analysis}
  2486. \label{sec:liveness-analysis-r1}
  2487. \index{liveness analysis}
  2488. A variable or register is \emph{live} at a program point if its
  2489. current value is used at some later point in the program. We shall
  2490. refer to variables and registers collectively as \emph{locations}.
  2491. %
  2492. Consider the following code fragment in which there are two writes to
  2493. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2494. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2495. movq $5, a
  2496. movq $30, b
  2497. movq a, c
  2498. movq $10, b
  2499. addq b, c
  2500. \end{lstlisting}
  2501. The answer is no because the integer \code{30} written to \code{b} on
  2502. line 2 is never used. The variable \code{b} is read on line 5 and
  2503. there is an intervening write to \code{b} on line 4, so the read on
  2504. line 5 receives the value written on line 4, not line 2.
  2505. \begin{wrapfigure}[20]{l}[1.0in]{0.6\textwidth}
  2506. \small
  2507. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2508. A \emph{set} is an unordered collection of elements without duplicates.
  2509. \index{set}
  2510. \begin{description}
  2511. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2512. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2513. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2514. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2515. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2516. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2517. \end{description}
  2518. \end{tcolorbox}
  2519. \end{wrapfigure}
  2520. The live locations can be computed by traversing the instruction
  2521. sequence back to front (i.e., backwards in execution order). Let
  2522. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2523. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2524. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2525. locations before instruction $I_k$. The live locations after an
  2526. instruction are always the same as the live locations before the next
  2527. instruction. \index{live-after} \index{live-before}
  2528. \begin{equation} \label{eq:live-after-before-next}
  2529. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2530. \end{equation}
  2531. To start things off, there are no live locations after the last
  2532. instruction\footnote{Technically, the \code{rax} register is live
  2533. but we do not use it for register allocation.}, 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 locations written to by instruction $I_k$ and
  2543. $R(k)$ are the locations 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 $\{\ttm{b},\ttm{c}\}$ because it reads from
  2550. variables \code{b} and \code{c}
  2551. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2552. \[
  2553. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{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) = \{ \ttm{b}, \ttm{c} \}
  2560. \]
  2561. This move instruction writes to \code{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) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2566. \]
  2567. The live-before for instruction \code{movq a, c}
  2568. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2569. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2570. live-before for \code{movq \$30, b} is $\{\ttm{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 \code{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)= \{\ttm{a}\}\\
  2589. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2590. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2591. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2592. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2593. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2594. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2595. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{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 liveness analysis for
  2601. the running example program, with the live-before and live-after sets
  2602. 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. |$\{\ttm{v}\}$|
  2610. movq $42, w
  2611. |$\{\ttm{v},\ttm{w}\}$|
  2612. movq v, x
  2613. |$\{\ttm{w},\ttm{x}\}$|
  2614. addq $7, x
  2615. |$\{\ttm{w},\ttm{x}\}$|
  2616. movq x, y
  2617. |$\{\ttm{w},\ttm{x},\ttm{y}\}$|
  2618. movq x, z
  2619. |$\{\ttm{w},\ttm{y},\ttm{z}\}$|
  2620. addq w, z
  2621. |$\{\ttm{y},\ttm{z}\}$|
  2622. movq y, t
  2623. |$\{\ttm{t},\ttm{z}\}$|
  2624. negq t
  2625. |$\{\ttm{t},\ttm{z}\}$|
  2626. movq z, %rax
  2627. |$\{\ttm{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.
  2642. %
  2643. We recommend organizing your code to use a helper function that takes
  2644. a list of instructions and an initial live-after set (typically empty)
  2645. and returns the list of live-after sets.
  2646. %
  2647. We recommend creating helper functions to 1) compute the set of
  2648. locations that appear in an argument (of an instruction), 2) compute
  2649. the locations read by an instruction which corresponds to the $R$
  2650. function discussed above, and 3) the locations written by an
  2651. instruction which corresponds to $W$. The \key{callq} instruction
  2652. should include all of the caller-saved registers in its $W$ because
  2653. the calling convention says that those registers may be written to
  2654. during the function call.
  2655. \end{exercise}
  2656. \section{Building the Interference Graph}
  2657. \label{sec:build-interference}
  2658. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2659. \small
  2660. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2661. A \emph{graph} is a collection of vertices and edges where each
  2662. edge connects two vertices. A graph is \emph{directed} if each
  2663. edge points from a source to a target. Otherwise the graph is
  2664. \emph{undirected}.
  2665. \index{graph}\index{directed graph}\index{undirected graph}
  2666. \begin{description}
  2667. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2668. directed graph from a list of edges. Each edge is a list
  2669. containing the source and target vertex.
  2670. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2671. undirected graph from a list of edges. Each edge is represented by
  2672. a list containing two vertices.
  2673. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2674. inserts a vertex into the graph.
  2675. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2676. inserts an edge between the two vertices into the graph.
  2677. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2678. returns a sequence of all the neighbors of the given vertex.
  2679. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2680. returns a sequence of all the vertices in the graph.
  2681. \end{description}
  2682. \end{tcolorbox}
  2683. \end{wrapfigure}
  2684. Based on the liveness analysis, we know where each variable is needed.
  2685. However, during register allocation, we need to answer questions of
  2686. the specific form: are variables $u$ and $v$ live at the same time?
  2687. (And therefore cannot be assigned to the same register.) To make this
  2688. question easier to answer, we create an explicit data structure, an
  2689. \emph{interference graph}\index{interference graph}. An interference
  2690. graph is an undirected graph that has an edge between two variables if
  2691. they are live at the same time, that is, if they interfere with each
  2692. other.
  2693. The most obvious way to compute the interference graph is to look at
  2694. the set of live location between each statement in the program and add
  2695. an edge to the graph for every pair of variables in the same set.
  2696. This approach is less than ideal for two reasons. First, it can be
  2697. expensive because it takes $O(n^2)$ time to look at every pair in a
  2698. set of $n$ live locations. Second, there is a special case in which
  2699. two locations that are live at the same time do not actually interfere
  2700. with each other: when they both contain the same value because we have
  2701. assigned one to the other.
  2702. A better way to compute the interference graph is to focus on the
  2703. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2704. instruction to overwrite something in a live location. So for each
  2705. instruction, we create an edge between the locations being written to
  2706. and all the other live locations. (Except that one should not create
  2707. self edges.) Recall that for a \key{callq} instruction, we consider
  2708. all of the caller-saved registers as being written to, so an edge will
  2709. be added between every live variable and every caller-saved
  2710. register. For \key{movq}, we deal with the above-mentioned special
  2711. case by not adding an edge between a live variable $v$ and destination
  2712. $d$ if $v$ matches the source of the move. So we have the following
  2713. two rules.
  2714. \begin{enumerate}
  2715. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2716. $d$, then add the edge $(d,v)$ for every $v \in
  2717. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2718. \item For any other instruction $I_k$, for every $d \in W(k)$
  2719. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2720. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2721. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2722. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2723. %% \item If instruction $I_k$ is of the form \key{callq}
  2724. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2725. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2726. \end{enumerate}
  2727. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2728. the above rules to each instruction. We highlight a few of the
  2729. instructions and then refer the reader to
  2730. Figure~\ref{fig:interference-results} for all the interference
  2731. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2732. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2733. interference edges because the one live variable \code{v} is also the
  2734. destination of this instruction.
  2735. %
  2736. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2737. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2738. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2739. %
  2740. Next we skip forward to the instruction \lstinline{movq x, y}.
  2741. \begin{figure}[tbp]
  2742. \begin{quote}
  2743. \begin{tabular}{ll}
  2744. \lstinline{movq $1, v}& no interference by rule 3,\\
  2745. \lstinline{movq $42, w}& $\ttm{w}$ interferes with $\ttm{v}$ by rule 3,\\
  2746. \lstinline{movq v, x}& $\ttm{x}$ interferes with $\ttm{w}$ by rule 3,\\
  2747. \lstinline{addq $7, x}& $\ttm{x}$ interferes with $\ttm{w}$ by rule 1,\\
  2748. \lstinline{movq x, y}& $\ttm{y}$ interferes with $\ttm{w}$ but not $\ttm{x}$ by rule 3,\\
  2749. \lstinline{movq x, z}& $\ttm{z}$ interferes with $\ttm{w}$ and $\ttm{y}$ by rule 3,\\
  2750. \lstinline{addq w, z}& $\ttm{z}$ interferes with $\ttm{y}$ by rule 1, \\
  2751. \lstinline{movq y, t}& $\ttm{t}$ interferes with $\ttm{z}$ by rule 3, \\
  2752. \lstinline{negq t}& $\ttm{t}$ interferes with $\ttm{z}$ by rule 1, \\
  2753. \lstinline{movq z, %rax} & no interference (ignore rax), \\
  2754. \lstinline{addq t, %rax} & no interference (ignore rax). \\
  2755. \lstinline{jmp conclusion}& no interference.
  2756. \end{tabular}
  2757. \end{quote}
  2758. \caption{Interference results for the running example.}
  2759. \label{fig:interference-results}
  2760. \end{figure}
  2761. The resulting interference graph is shown in
  2762. Figure~\ref{fig:interfere}.
  2763. \begin{figure}[tbp]
  2764. \large
  2765. \[
  2766. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2767. \node (t1) at (0,2) {$\ttm{t}$};
  2768. \node (z) at (3,2) {$\ttm{z}$};
  2769. \node (x) at (6,2) {$\ttm{x}$};
  2770. \node (y) at (3,0) {$\ttm{y}$};
  2771. \node (w) at (6,0) {$\ttm{w}$};
  2772. \node (v) at (9,0) {$\ttm{v}$};
  2773. \draw (t1) to (z);
  2774. \draw (z) to (y);
  2775. \draw (z) to (w);
  2776. \draw (x) to (w);
  2777. \draw (y) to (w);
  2778. \draw (v) to (w);
  2779. \end{tikzpicture}
  2780. \]
  2781. \caption{The interference graph of the example program.}
  2782. \label{fig:interfere}
  2783. \end{figure}
  2784. %% Our next concern is to choose a data structure for representing the
  2785. %% interference graph. There are many choices for how to represent a
  2786. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2787. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2788. %% data structure is to study the algorithm that uses the data structure,
  2789. %% determine what operations need to be performed, and then choose the
  2790. %% data structure that provide the most efficient implementations of
  2791. %% those operations. Often times the choice of data structure can have an
  2792. %% effect on the time complexity of the algorithm, as it does here. If
  2793. %% you skim the next section, you will see that the register allocation
  2794. %% algorithm needs to ask the graph for all of its vertices and, given a
  2795. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2796. %% correct choice of graph representation is that of an adjacency
  2797. %% list. There are helper functions in \code{utilities.rkt} for
  2798. %% representing graphs using the adjacency list representation:
  2799. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2800. %% (Appendix~\ref{appendix:utilities}).
  2801. %% %
  2802. %% \margincomment{\footnotesize To do: change to use the
  2803. %% Racket graph library. \\ --Jeremy}
  2804. %% %
  2805. %% In particular, those functions use a hash table to map each vertex to
  2806. %% the set of adjacent vertices, and the sets are represented using
  2807. %% Racket's \key{set}, which is also a hash table.
  2808. \begin{exercise}\normalfont
  2809. Implement the compiler pass named \code{build-interference} according
  2810. to the algorithm suggested above. We recommend using the \code{graph}
  2811. package to create and inspect the interference graph. The output
  2812. graph of this pass should be stored in the $\itm{info}$ field of the
  2813. program, under the key \code{conflicts}.
  2814. \end{exercise}
  2815. \section{Graph Coloring via Sudoku}
  2816. \label{sec:graph-coloring}
  2817. \index{graph coloring}
  2818. \index{Sudoku}
  2819. \index{color}
  2820. We come to the main event, mapping variables to registers (or to stack
  2821. locations in the event that we run out of registers). We need to make
  2822. sure that two variables do not get mapped to the same register if the
  2823. two variables interfere with each other. Thinking about the
  2824. interference graph, this means that adjacent vertices must be mapped
  2825. to different registers. If we think of registers as colors, the
  2826. register allocation problem becomes the widely-studied graph coloring
  2827. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2828. The reader may be more familiar with the graph coloring problem than he
  2829. or she realizes; the popular game of Sudoku is an instance of the
  2830. graph coloring problem. The following describes how to build a graph
  2831. out of an initial Sudoku board.
  2832. \begin{itemize}
  2833. \item There is one vertex in the graph for each Sudoku square.
  2834. \item There is an edge between two vertices if the corresponding squares
  2835. are in the same row, in the same column, or if the squares are in
  2836. the same $3\times 3$ region.
  2837. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2838. \item Based on the initial assignment of numbers to squares in the
  2839. Sudoku board, assign the corresponding colors to the corresponding
  2840. vertices in the graph.
  2841. \end{itemize}
  2842. If you can color the remaining vertices in the graph with the nine
  2843. colors, then you have also solved the corresponding game of Sudoku.
  2844. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2845. the corresponding graph with colored vertices. We map the Sudoku
  2846. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2847. sampling of the vertices (the colored ones) because showing edges for
  2848. all of the vertices would make the graph unreadable.
  2849. \begin{figure}[tbp]
  2850. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2851. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2852. \caption{A Sudoku game board and the corresponding colored graph.}
  2853. \label{fig:sudoku-graph}
  2854. \end{figure}
  2855. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2856. strategies to come up with an algorithm for allocating registers. For
  2857. example, one of the basic techniques for Sudoku is called Pencil
  2858. Marks. The idea is to use a process of elimination to determine what
  2859. numbers no longer make sense for a square and write down those
  2860. numbers in the square (writing very small). For example, if the number
  2861. $1$ is assigned to a square, then by process of elimination, you can
  2862. write the pencil mark $1$ in all the squares in the same row, column,
  2863. and region. Many Sudoku computer games provide automatic support for
  2864. Pencil Marks.
  2865. %
  2866. The Pencil Marks technique corresponds to the notion of
  2867. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2868. The saturation of a
  2869. vertex, in Sudoku terms, is the set of numbers that are no longer
  2870. available. In graph terminology, we have the following definition:
  2871. \begin{equation*}
  2872. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2873. \text{ and } \mathrm{color}(v) = c \}
  2874. \end{equation*}
  2875. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2876. edge with $u$.
  2877. Using the Pencil Marks technique leads to a simple strategy for
  2878. filling in numbers: if there is a square with only one possible number
  2879. left, then choose that number! But what if there are no squares with
  2880. only one possibility left? One brute-force approach is to try them
  2881. all: choose the first and if it ultimately leads to a solution,
  2882. great. If not, backtrack and choose the next possibility. One good
  2883. thing about Pencil Marks is that it reduces the degree of branching in
  2884. the search tree. Nevertheless, backtracking can be horribly time
  2885. consuming. One way to reduce the amount of backtracking is to use the
  2886. most-constrained-first heuristic. That is, when choosing a square,
  2887. always choose one with the fewest possibilities left (the vertex with
  2888. the highest saturation). The idea is that choosing highly constrained
  2889. squares earlier rather than later is better because later on there may
  2890. not be any possibilities left for those squares.
  2891. However, register allocation is easier than Sudoku because the
  2892. register allocator can map variables to stack locations when the
  2893. registers run out. Thus, it makes sense to drop backtracking in favor
  2894. of greedy search, that is, make the best choice at the time and keep
  2895. going. We still wish to minimize the number of colors needed, so
  2896. keeping the most-constrained-first heuristic is a good idea.
  2897. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2898. algorithm for register allocation based on saturation and the
  2899. most-constrained-first heuristic. It is roughly equivalent to the
  2900. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2901. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2902. Sudoku, the algorithm represents colors with integers. The first $k$
  2903. colors corresponding to the $k$ registers in a given machine and the
  2904. rest of the integers corresponding to stack locations.
  2905. \begin{figure}[btp]
  2906. \centering
  2907. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2908. Algorithm: DSATUR
  2909. Input: a graph |$G$|
  2910. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2911. |$W \gets \mathit{vertices}(G)$|
  2912. while |$W \neq \emptyset$| do
  2913. pick a vertex |$u$| from |$W$| with the highest saturation,
  2914. breaking ties randomly
  2915. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2916. |$\mathrm{color}[u] \gets c$|
  2917. |$W \gets W - \{u\}$|
  2918. \end{lstlisting}
  2919. \caption{The saturation-based greedy graph coloring algorithm.}
  2920. \label{fig:satur-algo}
  2921. \end{figure}
  2922. With this algorithm in hand, let us return to the running example and
  2923. consider how to color the interference graph in
  2924. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2925. colored and they are unsaturated, so we annotate each of them with a
  2926. dash for their color and an empty set for the saturation.
  2927. \[
  2928. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2929. \node (t1) at (0,2) {$\ttm{t}:-,\{\}$};
  2930. \node (z) at (3,2) {$\ttm{z}:-,\{\}$};
  2931. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2932. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2933. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2934. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2935. \draw (t1) to (z);
  2936. \draw (z) to (y);
  2937. \draw (z) to (w);
  2938. \draw (x) to (w);
  2939. \draw (y) to (w);
  2940. \draw (v) to (w);
  2941. \end{tikzpicture}
  2942. \]
  2943. The algorithm says to select a maximally saturated vertex and color it
  2944. $0$. In this case we have a 6-way tie, so we arbitrarily pick
  2945. $\ttm{t}$. We then mark color $0$ as no longer available for $\ttm{z}$
  2946. because it interferes with $\ttm{t}$.
  2947. \[
  2948. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2949. \node (t1) at (0,2) {$\ttm{t}:0,\{\}$};
  2950. \node (z) at (3,2) {$\ttm{z}:-,\{0\}$};
  2951. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2952. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2953. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2954. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2955. \draw (t1) to (z);
  2956. \draw (z) to (y);
  2957. \draw (z) to (w);
  2958. \draw (x) to (w);
  2959. \draw (y) to (w);
  2960. \draw (v) to (w);
  2961. \end{tikzpicture}
  2962. \]
  2963. Next we repeat the process, selecting another maximally saturated
  2964. vertex, which is \code{z}, and color it with the first available number,
  2965. which is $1$.
  2966. \[
  2967. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2968. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  2969. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  2970. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2971. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  2972. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  2973. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2974. \draw (t1) to (z);
  2975. \draw (z) to (y);
  2976. \draw (z) to (w);
  2977. \draw (x) to (w);
  2978. \draw (y) to (w);
  2979. \draw (v) to (w);
  2980. \end{tikzpicture}
  2981. \]
  2982. The most saturated vertices are now \code{w} and \code{y}. We color
  2983. \code{w} with the first available color, which is $0$.
  2984. \[
  2985. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2986. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  2987. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  2988. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  2989. \node (y) at (3,0) {$\ttm{y}:-,\{0,1\}$};
  2990. \node (w) at (6,0) {$\ttm{w}:0,\{1\}$};
  2991. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  2992. \draw (t1) to (z);
  2993. \draw (z) to (y);
  2994. \draw (z) to (w);
  2995. \draw (x) to (w);
  2996. \draw (y) to (w);
  2997. \draw (v) to (w);
  2998. \end{tikzpicture}
  2999. \]
  3000. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3001. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3002. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3003. and \code{z}, whose colors are $0$ and $1$ respectively.
  3004. \[
  3005. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3006. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3007. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3008. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3009. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3010. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3011. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3012. \draw (t1) to (z);
  3013. \draw (z) to (y);
  3014. \draw (z) to (w);
  3015. \draw (x) to (w);
  3016. \draw (y) to (w);
  3017. \draw (v) to (w);
  3018. \end{tikzpicture}
  3019. \]
  3020. Now \code{x} and \code{v} are the most saturated, so we color \code{v} it $1$.
  3021. \[
  3022. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3023. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3024. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3025. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3026. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3027. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3028. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3029. \draw (t1) to (z);
  3030. \draw (z) to (y);
  3031. \draw (z) to (w);
  3032. \draw (x) to (w);
  3033. \draw (y) to (w);
  3034. \draw (v) to (w);
  3035. \end{tikzpicture}
  3036. \]
  3037. In the last step of the algorithm, we color \code{x} with $1$.
  3038. \[
  3039. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3040. \node (t1) at (0,2) {$\ttm{t}:0,\{1,\}$};
  3041. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3042. \node (x) at (6,2) {$\ttm{x}:1,\{0\}$};
  3043. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3044. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3045. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3046. \draw (t1) to (z);
  3047. \draw (z) to (y);
  3048. \draw (z) to (w);
  3049. \draw (x) to (w);
  3050. \draw (y) to (w);
  3051. \draw (v) to (w);
  3052. \end{tikzpicture}
  3053. \]
  3054. With the coloring complete, we finalize the assignment of variables to
  3055. registers and stack locations. Recall that if we have $k$ registers,
  3056. we map the first $k$ colors to registers and the rest to stack
  3057. locations. Suppose for the moment that we have just one register to
  3058. use for register allocation, \key{rcx}. Then the following is the
  3059. mapping of colors to registers and stack allocations.
  3060. \[
  3061. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3062. \]
  3063. Putting this mapping together with the above coloring of the
  3064. variables, we arrive at the following assignment of variables to
  3065. registers and stack locations.
  3066. \begin{gather*}
  3067. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3068. \ttm{w} \mapsto \key{\%rcx}, \,
  3069. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3070. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3071. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3072. \ttm{t} \mapsto \key{\%rcx} \}
  3073. \end{gather*}
  3074. Applying this assignment to our running example, on the left, yields
  3075. the program on the right.
  3076. % why frame size of 32? -JGS
  3077. \begin{center}
  3078. \begin{minipage}{0.3\textwidth}
  3079. \begin{lstlisting}
  3080. movq $1, v
  3081. movq $42, w
  3082. movq v, x
  3083. addq $7, x
  3084. movq x, y
  3085. movq x, z
  3086. addq w, z
  3087. movq y, t
  3088. negq t
  3089. movq z, %rax
  3090. addq t, %rax
  3091. jmp conclusion
  3092. \end{lstlisting}
  3093. \end{minipage}
  3094. $\Rightarrow\qquad$
  3095. \begin{minipage}{0.45\textwidth}
  3096. \begin{lstlisting}
  3097. movq $1, %rcx
  3098. movq $42, %rcx
  3099. movq %rcx, -8(%rbp)
  3100. addq $7, -8(%rbp)
  3101. movq -8(%rbp), -16(%rbp)
  3102. movq -8(%rbp), -8(%rbp)
  3103. addq %rcx, -8(%rbp)
  3104. movq -16(%rbp), %rcx
  3105. negq %rcx
  3106. movq -8(%rbp), %rax
  3107. addq %rcx, %rax
  3108. jmp conclusion
  3109. \end{lstlisting}
  3110. \end{minipage}
  3111. \end{center}
  3112. The resulting program is almost an x86 program. The remaining step is
  3113. the patch instructions pass. In this example, the trivial move of
  3114. \code{-8(\%rbp)} to itself is deleted and the addition of
  3115. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3116. \code{rax} as follows.
  3117. \begin{lstlisting}
  3118. movq -8(%rbp), %rax
  3119. addq %rax, -16(%rbp)
  3120. \end{lstlisting}
  3121. An overview of all of the passes involved in register allocation is
  3122. shown in Figure~\ref{fig:reg-alloc-passes}.
  3123. \begin{figure}[tbp]
  3124. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3125. \node (R1) at (0,2) {\large $R_1$};
  3126. \node (R1-2) at (3,2) {\large $R_1$};
  3127. \node (R1-3) at (6,2) {\large $R_1$};
  3128. \node (C0-1) at (3,0) {\large $C_0$};
  3129. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3130. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3131. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3132. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3133. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3134. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3135. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3136. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3137. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3138. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3139. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3140. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3141. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3142. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3143. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3144. \end{tikzpicture}
  3145. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3146. \label{fig:reg-alloc-passes}
  3147. \end{figure}
  3148. \begin{exercise}\normalfont
  3149. Implement the pass \code{allocate-registers}, which should come
  3150. after the \code{build-interference} pass. The three new passes,
  3151. \code{uncover-live}, \code{build-interference}, and
  3152. \code{allocate-registers} replace the \code{assign-homes} pass of
  3153. Section~\ref{sec:assign-r1}.
  3154. We recommend that you create a helper function named
  3155. \code{color-graph} that takes an interference graph and a list of
  3156. all the variables in the program. This function should return a
  3157. mapping of variables to their colors (represented as natural
  3158. numbers). By creating this helper function, you will be able to
  3159. reuse it in Chapter~\ref{ch:functions} when you add support for
  3160. functions. The support code includes an implementation of the
  3161. priority queue data structure in the file
  3162. \code{priority\_queue.rkt}, which might come in handy for
  3163. prioritizing highly saturated nodes inside your \code{color-graph}
  3164. function.
  3165. Once you have obtained the coloring from \code{color-graph}, you can
  3166. assign the variables to registers or stack locations and then reuse
  3167. code from the \code{assign-homes} pass from
  3168. Section~\ref{sec:assign-r1} to replace the variables with their
  3169. assigned location.
  3170. Test your updated compiler by creating new example programs that
  3171. exercise all of the register allocation algorithm, such as forcing
  3172. variables to be spilled to the stack.
  3173. \end{exercise}
  3174. \section{Print x86 and Conventions for Registers}
  3175. \label{sec:print-x86-reg-alloc}
  3176. \index{calling conventions}
  3177. \index{prelude}\index{conclusion}
  3178. Recall that the \code{print-x86} pass generates the prelude and
  3179. conclusion instructions for the \code{main} function.
  3180. %
  3181. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3182. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3183. reason for this is that our \code{main} function must adhere to the
  3184. x86 calling conventions that we described in
  3185. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3186. allocator assigned variables to other callee-saved registers
  3187. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3188. saved to the stack in the prelude and restored in the conclusion. The
  3189. simplest approach is to save and restore all of the callee-saved
  3190. registers. The more efficient approach is to keep track of which
  3191. callee-saved registers were used and only save and restore
  3192. them. Either way, make sure to take this use of stack space into
  3193. account when you are calculating the size of the frame and adjusting
  3194. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3195. frame needs to be a multiple of 16 bytes!
  3196. \section{Challenge: Move Biasing}
  3197. \label{sec:move-biasing}
  3198. \index{move biasing}
  3199. This section describes an optional enhancement to register allocation
  3200. for those students who are looking for an extra challenge or who have
  3201. a deeper interest in register allocation.
  3202. We return to the running example, but we remove the supposition that
  3203. we only have one register to use. So we have the following mapping of
  3204. color numbers to registers.
  3205. \[
  3206. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3207. \]
  3208. Using the same assignment of variables to color numbers that was
  3209. produced by the register allocator described in the last section, we
  3210. get the following program.
  3211. \begin{minipage}{0.3\textwidth}
  3212. \begin{lstlisting}
  3213. movq $1, v
  3214. movq $42, w
  3215. movq v, x
  3216. addq $7, x
  3217. movq x, y
  3218. movq x, z
  3219. addq w, z
  3220. movq y, t
  3221. negq t
  3222. movq z, %rax
  3223. addq t, %rax
  3224. jmp conclusion
  3225. \end{lstlisting}
  3226. \end{minipage}
  3227. $\Rightarrow\qquad$
  3228. \begin{minipage}{0.45\textwidth}
  3229. \begin{lstlisting}
  3230. movq $1, %rcx
  3231. movq $42, $rbx
  3232. movq %rcx, %rcx
  3233. addq $7, %rcx
  3234. movq %rcx, %rdx
  3235. movq %rcx, %rcx
  3236. addq %rbx, %rcx
  3237. movq %rdx, %rbx
  3238. negq %rbx
  3239. movq %rcx, %rax
  3240. addq %rbx, %rax
  3241. jmp conclusion
  3242. \end{lstlisting}
  3243. \end{minipage}
  3244. In the above output code there are two \key{movq} instructions that
  3245. can be removed because their source and target are the same. However,
  3246. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3247. register, we could instead remove three \key{movq} instructions. We
  3248. can accomplish this by taking into account which variables appear in
  3249. \key{movq} instructions with which other variables.
  3250. We say that two variables $p$ and $q$ are \emph{move
  3251. related}\index{move related} if they participate together in a
  3252. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3253. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3254. for a variable, it should prefer a color that has already been used
  3255. for a move-related variable (assuming that they do not interfere). Of
  3256. course, this preference should not override the preference for
  3257. registers over stack locations. This preference should be used as a
  3258. tie breaker when choosing between registers or when choosing between
  3259. stack locations.
  3260. We recommend representing the move relationships in a graph, similar
  3261. to how we represented interference. The following is the \emph{move
  3262. graph} for our running example.
  3263. \[
  3264. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3265. \node (t) at (0,2) {$\ttm{t}$};
  3266. \node (z) at (3,2) {$\ttm{z}$};
  3267. \node (x) at (6,2) {$\ttm{x}$};
  3268. \node (y) at (3,0) {$\ttm{y}$};
  3269. \node (w) at (6,0) {$\ttm{w}$};
  3270. \node (v) at (9,0) {$\ttm{v}$};
  3271. \draw (v) to (x);
  3272. \draw (x) to (y);
  3273. \draw (x) to (z);
  3274. \draw (y) to (t);
  3275. \end{tikzpicture}
  3276. \]
  3277. Now we replay the graph coloring, pausing to see the coloring of
  3278. \code{y}. Recall the following configuration. The most saturated vertices
  3279. were \code{w} and \code{y}.
  3280. \[
  3281. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3282. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3283. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3284. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3285. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3286. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3287. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3288. \draw (t1) to (z);
  3289. \draw (z) to (y);
  3290. \draw (z) to (w);
  3291. \draw (x) to (w);
  3292. \draw (y) to (w);
  3293. \draw (v) to (w);
  3294. \end{tikzpicture}
  3295. \]
  3296. %
  3297. Last time we chose to color \code{w} with $0$. But this time we note
  3298. that \code{w} is not move related to any vertex, and \code{y} is move
  3299. related to \code{t}. So we choose to color \code{y} the same color,
  3300. $0$.
  3301. \[
  3302. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3303. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3304. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3305. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3306. \node (y) at (3,0) {$\ttm{y}:0,\{1\}$};
  3307. \node (w) at (6,0) {$\ttm{w}:-,\{0,1\}$};
  3308. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3309. \draw (t1) to (z);
  3310. \draw (z) to (y);
  3311. \draw (z) to (w);
  3312. \draw (x) to (w);
  3313. \draw (y) to (w);
  3314. \draw (v) to (w);
  3315. \end{tikzpicture}
  3316. \]
  3317. Now \code{w} is the most saturated, so we color it $2$.
  3318. \[
  3319. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3320. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3321. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3322. \node (x) at (6,2) {$\ttm{x}:-,\{2\}$};
  3323. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3324. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3325. \node (v) at (9,0) {$\ttm{v}:-,\{2\}$};
  3326. \draw (t1) to (z);
  3327. \draw (z) to (y);
  3328. \draw (z) to (w);
  3329. \draw (x) to (w);
  3330. \draw (y) to (w);
  3331. \draw (v) to (w);
  3332. \end{tikzpicture}
  3333. \]
  3334. At this point, vertices \code{x} and \code{v} are most saturated, but
  3335. \code{x} is move related to \code{y} and \code{z}, so we color
  3336. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3337. \[
  3338. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3339. \node (t) at (0,2) {$\ttm{t}:0,\{1\}$};
  3340. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3341. \node (x) at (6,2) {$\ttm{x}:0,\{2\}$};
  3342. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3343. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3344. \node (v) at (9,0) {$\ttm{v}:0,\{2\}$};
  3345. \draw (t) to (z);
  3346. \draw (z) to (y);
  3347. \draw (z) to (w);
  3348. \draw (x) to (w);
  3349. \draw (y) to (w);
  3350. \draw (v) to (w);
  3351. \end{tikzpicture}
  3352. \]
  3353. So we have the following assignment of variables to registers.
  3354. \begin{gather*}
  3355. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3356. \ttm{w} \mapsto \key{\%rdx}, \,
  3357. \ttm{x} \mapsto \key{\%rbx}, \,
  3358. \ttm{y} \mapsto \key{\%rbx}, \,
  3359. \ttm{z} \mapsto \key{\%rcx}, \,
  3360. \ttm{t} \mapsto \key{\%rbx} \}
  3361. \end{gather*}
  3362. We apply this register assignment to the running example, on the left,
  3363. to obtain the code on right.
  3364. \begin{minipage}{0.3\textwidth}
  3365. \begin{lstlisting}
  3366. movq $1, v
  3367. movq $42, w
  3368. movq v, x
  3369. addq $7, x
  3370. movq x, y
  3371. movq x, z
  3372. addq w, z
  3373. movq y, t
  3374. negq t
  3375. movq z, %rax
  3376. addq t, %rax
  3377. jmp conclusion
  3378. \end{lstlisting}
  3379. \end{minipage}
  3380. $\Rightarrow\qquad$
  3381. \begin{minipage}{0.45\textwidth}
  3382. \begin{lstlisting}
  3383. movq $1, %rbx
  3384. movq $42, %rdx
  3385. movq %rbx, %rbx
  3386. addq $7, %rbx
  3387. movq %rbx, %rbx
  3388. movq %rbx, %rcx
  3389. addq %rdx, %rcx
  3390. movq %rbx, %rbx
  3391. negq %rbx
  3392. movq %rcx, %rax
  3393. addq %rbx, %rax
  3394. jmp conclusion
  3395. \end{lstlisting}
  3396. \end{minipage}
  3397. The \code{patch-instructions} then removes the three trivial moves
  3398. from \key{rbx} to \key{rbx} to obtain the following result.
  3399. \begin{minipage}{0.45\textwidth}
  3400. \begin{lstlisting}
  3401. movq $1, %rbx
  3402. movq $42, %rdx
  3403. addq $7, %rbx
  3404. movq %rbx, %rcx
  3405. addq %rdx, %rcx
  3406. negq %rbx
  3407. movq %rcx, %rax
  3408. addq %rbx, %rax
  3409. jmp conclusion
  3410. \end{lstlisting}
  3411. \end{minipage}
  3412. \begin{exercise}\normalfont
  3413. Change your implementation of \code{allocate-registers} to take move
  3414. biasing into account. Make sure that your compiler still passes all of
  3415. the previous tests. Create two new tests that include at least one
  3416. opportunity for move biasing and visually inspect the output x86
  3417. programs to make sure that your move biasing is working properly.
  3418. \end{exercise}
  3419. \margincomment{\footnotesize To do: another neat challenge would be to do
  3420. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3421. \section{Output of the Running Example}
  3422. \label{sec:reg-alloc-output}
  3423. \index{prelude}\index{conclusion}
  3424. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3425. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3426. and move biasing. To demonstrate both the use of registers and the
  3427. stack, we have limited the register allocator to use just two
  3428. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3429. \code{main} function, we push \code{rbx} onto the stack because it is
  3430. a callee-saved register and it was assigned to variable by the
  3431. register allocator. We substract \code{8} from the \code{rsp} at the
  3432. end of the prelude to reserve space for the one spilled variable.
  3433. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3434. Moving on the the \code{start} block, we see how the registers were
  3435. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3436. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3437. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3438. that the prelude saved the callee-save register \code{rbx} onto the
  3439. stack. The spilled variables must be placed lower on the stack than
  3440. the saved callee-save registers, so in this case \code{w} is placed at
  3441. \code{-16(\%rbp)}.
  3442. In the \code{conclusion}, we undo the work that was done in the
  3443. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3444. spilled variables), then we pop the old values of \code{rbx} and
  3445. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3446. return control to the operating system.
  3447. \begin{figure}[tbp]
  3448. % s0_28.rkt
  3449. % (use-minimal-set-of-registers! #t)
  3450. % and only rbx rcx
  3451. % tmp 0 rbx
  3452. % z 1 rcx
  3453. % y 0 rbx
  3454. % w 2 16(%rbp)
  3455. % v 0 rbx
  3456. % x 0 rbx
  3457. \begin{lstlisting}
  3458. start:
  3459. movq $1, %rbx
  3460. movq $42, -16(%rbp)
  3461. addq $7, %rbx
  3462. movq %rbx, %rcx
  3463. addq -16(%rbp), %rcx
  3464. negq %rbx
  3465. movq %rcx, %rax
  3466. addq %rbx, %rax
  3467. jmp conclusion
  3468. .globl main
  3469. main:
  3470. pushq %rbp
  3471. movq %rsp, %rbp
  3472. pushq %rbx
  3473. subq $8, %rsp
  3474. jmp start
  3475. conclusion:
  3476. addq $8, %rsp
  3477. popq %rbx
  3478. popq %rbp
  3479. retq
  3480. \end{lstlisting}
  3481. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3482. \label{fig:running-example-x86}
  3483. \end{figure}
  3484. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3485. \chapter{Booleans and Control Flow}
  3486. \label{ch:bool-types}
  3487. \index{Boolean}
  3488. \index{control flow}
  3489. \index{conditional expression}
  3490. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3491. integers. In this chapter we add a second kind of value, the Booleans,
  3492. to create the $R_2$ language. The Boolean values \emph{true} and
  3493. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3494. Racket. The $R_2$ language includes several operations that involve
  3495. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3496. conditional \key{if} expression. With the addition of \key{if}
  3497. expressions, programs can have non-trivial control flow which which
  3498. significantly impacts the \code{explicate-control} and the liveness
  3499. analysis for register allocation. Also, because we now have two kinds
  3500. of values, we need to handle programs that apply an operation to the
  3501. wrong kind of value, such as \code{(not 1)}.
  3502. There are two language design options for such situations. One option
  3503. is to signal an error and the other is to provide a wider
  3504. interpretation of the operation. The Racket language uses a mixture of
  3505. these two options, depending on the operation and the kind of
  3506. value. For example, the result of \code{(not 1)} in Racket is
  3507. \code{\#f} because Racket treats non-zero integers as if they were
  3508. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3509. error in Racket stating that \code{car} expects a pair.
  3510. The Typed Racket language makes similar design choices as Racket,
  3511. except much of the error detection happens at compile time instead of
  3512. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3513. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3514. reports a compile-time error because Typed Racket expects the type of
  3515. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3516. For the $R_2$ language we choose to be more like Typed Racket in that
  3517. we shall perform type checking during compilation. In
  3518. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3519. is, how to compile a dynamically typed language like Racket. The
  3520. $R_2$ language is a subset of Typed Racket but by no means includes
  3521. all of Typed Racket. For many operations we take a narrower
  3522. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3523. This chapter is organized as follows. We begin by defining the syntax
  3524. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3525. then introduce the idea of type checking and build a type checker for
  3526. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3527. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3528. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3529. how our compiler passes need to change to accommodate Booleans and
  3530. conditional control flow.
  3531. \section{The $R_2$ Language}
  3532. \label{sec:r2-lang}
  3533. The concrete syntax of the $R_2$ language is defined in
  3534. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3535. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3536. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3537. and the conditional \code{if} expression. Also, we expand the
  3538. operators to include
  3539. \begin{enumerate}
  3540. \item subtraction on integers,
  3541. \item the logical operators \key{and}, \key{or} and \key{not},
  3542. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3543. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3544. comparing integers.
  3545. \end{enumerate}
  3546. \begin{figure}[tp]
  3547. \centering
  3548. \fbox{
  3549. \begin{minipage}{0.96\textwidth}
  3550. \[
  3551. \begin{array}{lcl}
  3552. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3553. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3554. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3555. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3556. &\mid& \itm{bool}
  3557. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3558. \mid (\key{not}\;\Exp) \\
  3559. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3560. R_2 &::=& \Exp
  3561. \end{array}
  3562. \]
  3563. \end{minipage}
  3564. }
  3565. \caption{The concrete syntax of $R_2$, extending $R_1$
  3566. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3567. \label{fig:r2-concrete-syntax}
  3568. \end{figure}
  3569. \begin{figure}[tp]
  3570. \centering
  3571. \fbox{
  3572. \begin{minipage}{0.96\textwidth}
  3573. \[
  3574. \begin{array}{lcl}
  3575. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3576. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3577. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3578. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3579. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3580. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3581. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3582. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3583. &\mid& \BINOP{\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3584. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3585. \end{array}
  3586. \]
  3587. \end{minipage}
  3588. }
  3589. \caption{The abstract syntax of $R_2$.}
  3590. \label{fig:r2-syntax}
  3591. \end{figure}
  3592. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3593. the parts that are the same as the interpreter for $R_1$
  3594. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3595. evaluate to the corresponding Boolean values. The conditional
  3596. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3597. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3598. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3599. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3600. you might expect, but note that the \code{and} operation is
  3601. short-circuiting. That is, given the expression
  3602. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3603. $e_1$ evaluates to \code{\#f}.
  3604. With the addition of the comparison operations, there are quite a few
  3605. primitive operations and the interpreter code for them could become
  3606. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3607. out the different parts of the code for primitive operations into the
  3608. \code{interp-op} function and the similar parts of the code into the
  3609. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3610. do not use \code{interp-op} for the \code{and} operation because of
  3611. the short-circuiting behavior in the order of evaluation of its
  3612. arguments.
  3613. \begin{figure}[tbp]
  3614. \begin{lstlisting}
  3615. (define (interp-op op)
  3616. (match op
  3617. ...
  3618. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3619. ['eq? (lambda (v1 v2)
  3620. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3621. (and (boolean? v1) (boolean? v2)))
  3622. (eq? v1 v2)]))]
  3623. ['< (lambda (v1 v2)
  3624. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3625. ['<= (lambda (v1 v2)
  3626. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3627. ['> (lambda (v1 v2)
  3628. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3629. ['>= (lambda (v1 v2)
  3630. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3631. [else (error 'interp-op "unknown operator")]))
  3632. (define (interp-exp env)
  3633. (lambda (e)
  3634. (define recur (interp-exp env))
  3635. (match e
  3636. ...
  3637. [(Bool b) b]
  3638. [(If cnd thn els)
  3639. (define b (recur cnd))
  3640. (match b
  3641. [#t (recur thn)]
  3642. [#f (recur els)])]
  3643. [(Prim 'and (list e1 e2))
  3644. (define v1 (recur e1))
  3645. (match v1
  3646. [#t (match (recur e2) [#t #t] [#f #f])]
  3647. [#f #f])]
  3648. [(Prim op args)
  3649. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3650. )))
  3651. (define (interp-R2 p)
  3652. (match p
  3653. [(Program info e)
  3654. ((interp-exp '()) e)]
  3655. ))
  3656. \end{lstlisting}
  3657. \caption{Interpreter for the $R_2$ language.}
  3658. \label{fig:interp-R2}
  3659. \end{figure}
  3660. \section{Type Checking $R_2$ Programs}
  3661. \label{sec:type-check-r2}
  3662. \index{type checking}
  3663. \index{semantic analysis}
  3664. It is helpful to think about type checking in two complementary
  3665. ways. A type checker predicts the type of value that will be produced
  3666. by each expression in the program. For $R_2$, we have just two types,
  3667. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3668. \begin{lstlisting}
  3669. (+ 10 (- (+ 12 20)))
  3670. \end{lstlisting}
  3671. produces an \key{Integer} while
  3672. \begin{lstlisting}
  3673. (and (not #f) #t)
  3674. \end{lstlisting}
  3675. produces a \key{Boolean}.
  3676. Another way to think about type checking is that it enforces a set of
  3677. rules about which operators can be applied to which kinds of
  3678. values. For example, our type checker for $R_2$ will signal an error
  3679. for the below expression because, as we have seen above, the
  3680. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3681. checker enforces the rule that the argument of \code{not} must be a
  3682. \key{Boolean}.
  3683. \begin{lstlisting}
  3684. (not (+ 10 (- (+ 12 20))))
  3685. \end{lstlisting}
  3686. The type checker for $R_2$ is a structurally recursive function over
  3687. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3688. the \code{type-check-exp} function. Given an input expression
  3689. \code{e}, the type checker either returns a type (\key{Integer} or
  3690. \key{Boolean}) or it signals an error. The type of an integer literal
  3691. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3692. To handle variables, the type checker uses an environment that maps
  3693. variables to types. Consider the clause for \key{let}. We type check
  3694. the initializing expression to obtain its type \key{T} and then
  3695. associate type \code{T} with the variable \code{x} in the
  3696. environment. When the type checker encounters a use of variable
  3697. \code{x} in the body of the \key{let}, it can find its type in the
  3698. environment.
  3699. \begin{figure}[tbp]
  3700. \begin{lstlisting}
  3701. (define (type-check-exp env)
  3702. (lambda (e)
  3703. (match e
  3704. [(Var x) (dict-ref env x)]
  3705. [(Int n) 'Integer]
  3706. [(Bool b) 'Boolean]
  3707. [(Let x e body)
  3708. (define Te ((type-check-exp env) e))
  3709. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3710. Tb]
  3711. ...
  3712. [else
  3713. (error "type-check-exp couldn't match" e)])))
  3714. (define (type-check env)
  3715. (lambda (e)
  3716. (match e
  3717. [(Program info body)
  3718. (define Tb ((type-check-exp '()) body))
  3719. (unless (equal? Tb 'Integer)
  3720. (error "result of the program must be an integer, not " Tb))
  3721. (Program info body)]
  3722. )))
  3723. \end{lstlisting}
  3724. \caption{Skeleton of a type checker for the $R_2$ language.}
  3725. \label{fig:type-check-R2}
  3726. \end{figure}
  3727. \begin{exercise}\normalfont
  3728. Complete the implementation of \code{type-check}. Test your type
  3729. checker using \code{interp-tests} and \code{compiler-tests} by passing
  3730. the \code{type-check} function as the second argument. Create 10 new
  3731. example programs in $R_2$ that you choose based on how thoroughly they
  3732. test you type checking function. Half of the example programs should
  3733. have a type error to make sure that your type checker properly rejects
  3734. them. For those programs, to signal that a type error is expected,
  3735. create an empty file with the same base name but with file extension
  3736. \code{.tyerr}. For example, if the test \code{r2\_14.rkt} is expected
  3737. to error, then create an empty file named \code{r2\_14.tyerr}. The
  3738. other half of the example programs should not have type errors. Note
  3739. that if your type checker does not signal an error for a program, then
  3740. interpreting that program should not encounter an error. If it does,
  3741. there is something wrong with your type checker.
  3742. \end{exercise}
  3743. \section{Shrink the $R_2$ Language}
  3744. \label{sec:shrink-r2}
  3745. The $R_2$ language includes several operators that are easily
  3746. expressible in terms of other operators. For example, subtraction is
  3747. expressible in terms of addition and negation.
  3748. \[
  3749. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3750. \]
  3751. Several of the comparison operations are expressible in terms of
  3752. less-than and logical negation.
  3753. \[
  3754. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3755. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3756. \]
  3757. The \key{let} is needed in the above translation to ensure that
  3758. expression $e_1$ is evaluated before $e_2$.
  3759. By performing these translations near the front-end of the compiler,
  3760. the later passes of the compiler do not need to deal with these
  3761. constructs, making those passes shorter. On the other hand, sometimes
  3762. these translations make it more difficult to generate the most
  3763. efficient code with respect to the number of instructions. However,
  3764. these differences typically do not affect the number of accesses to
  3765. memory, which is the primary factor that determines execution time on
  3766. modern computer architectures.
  3767. \begin{exercise}\normalfont
  3768. Implement the pass \code{shrink} that removes subtraction,
  3769. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3770. by translating them to other constructs in $R_2$. Create tests to
  3771. make sure that the behavior of all of these constructs stays the
  3772. same after translation.
  3773. \end{exercise}
  3774. \section{The x86$_1$ Language}
  3775. \label{sec:x86-1}
  3776. \index{x86}
  3777. To implement the new logical operations, the comparison operations,
  3778. and the \key{if} expression, we need to delve further into the x86
  3779. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3780. the concrete and abstract syntax for a larger subset of x86 that
  3781. includes instructions for logical operations, comparisons, and
  3782. conditional jumps.
  3783. One small challenge is that x86 does not provide an instruction that
  3784. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3785. However, the \code{xorq} instruction can be used to encode \code{not}.
  3786. The \key{xorq} instruction takes two arguments, performs a pairwise
  3787. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3788. and writes the results into its second argument. Recall the truth
  3789. table for exclusive-or:
  3790. \begin{center}
  3791. \begin{tabular}{l|cc}
  3792. & 0 & 1 \\ \hline
  3793. 0 & 0 & 1 \\
  3794. 1 & 1 & 0
  3795. \end{tabular}
  3796. \end{center}
  3797. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3798. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3799. for the bit $1$, the result is the opposite of the second bit. Thus,
  3800. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3801. the first argument:
  3802. \[
  3803. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3804. \qquad\Rightarrow\qquad
  3805. \begin{array}{l}
  3806. \key{movq}~ \Arg\key{,} \Var\\
  3807. \key{xorq}~ \key{\$1,} \Var
  3808. \end{array}
  3809. \]
  3810. \begin{figure}[tp]
  3811. \fbox{
  3812. \begin{minipage}{0.96\textwidth}
  3813. \[
  3814. \begin{array}{lcl}
  3815. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3816. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3817. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3818. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3819. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3820. \key{subq} \; \Arg\key{,} \Arg \mid
  3821. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3822. && \gray{ \key{callq} \; \itm{label} \mid
  3823. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3824. && \gray{ \itm{label}\key{:}\; \Instr }
  3825. \mid \key{xorq}~\Arg\key{,}~\Arg
  3826. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3827. && \key{set}cc~\Arg
  3828. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3829. \mid \key{j}cc~\itm{label}
  3830. \\
  3831. x86_1 &::= & \gray{ \key{.globl main} }\\
  3832. & & \gray{ \key{main:} \; \Instr\ldots }
  3833. \end{array}
  3834. \]
  3835. \end{minipage}
  3836. }
  3837. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3838. \label{fig:x86-1-concrete}
  3839. \end{figure}
  3840. \begin{figure}[tp]
  3841. \fbox{
  3842. \begin{minipage}{0.96\textwidth}
  3843. \small
  3844. \[
  3845. \begin{array}{lcl}
  3846. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3847. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3848. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3849. \mid \BYTEREG{\itm{bytereg}} \\
  3850. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3851. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3852. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3853. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3854. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3855. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3856. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3857. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3858. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3859. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3860. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3861. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3862. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3863. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3864. \end{array}
  3865. \]
  3866. \end{minipage}
  3867. }
  3868. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3869. \label{fig:x86-1}
  3870. \end{figure}
  3871. Next we consider the x86 instructions that are relevant for compiling
  3872. the comparison operations. The \key{cmpq} instruction compares its two
  3873. arguments to determine whether one argument is less than, equal, or
  3874. greater than the other argument. The \key{cmpq} instruction is unusual
  3875. regarding the order of its arguments and where the result is
  3876. placed. The argument order is backwards: if you want to test whether
  3877. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3878. \key{cmpq} is placed in the special EFLAGS register. This register
  3879. cannot be accessed directly but it can be queried by a number of
  3880. instructions, including the \key{set} instruction. The \key{set}
  3881. instruction puts a \key{1} or \key{0} into its destination depending
  3882. on whether the comparison came out according to the condition code
  3883. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3884. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3885. The \key{set} instruction has an annoying quirk in that its
  3886. destination argument must be single byte register, such as \code{al}
  3887. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  3888. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  3889. then be used to move from a single byte register to a normal 64-bit
  3890. register.
  3891. The x86 instruction for conditional jump are relevant to the
  3892. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3893. updates the program counter to point to the instruction after the
  3894. indicated label depending on whether the result in the EFLAGS register
  3895. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3896. instruction falls through to the next instruction. The abstract
  3897. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3898. that it separates the instruction name from the condition code. For
  3899. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3900. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3901. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3902. instruction to set the EFLAGS register.
  3903. \section{The $C_1$ Intermediate Language}
  3904. \label{sec:c1}
  3905. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3906. we need to grow that intermediate language to handle the new features
  3907. in $R_2$: Booleans and conditional expressions.
  3908. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3909. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3910. particular, we add logical and comparison operators to the $\Exp$
  3911. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3912. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3913. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3914. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3915. sequence of statements may now end with a \code{goto} or a conditional
  3916. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3917. depending on the outcome of the comparison. In
  3918. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3919. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3920. and \key{goto}'s.
  3921. \begin{figure}[tbp]
  3922. \fbox{
  3923. \begin{minipage}{0.96\textwidth}
  3924. \small
  3925. \[
  3926. \begin{array}{lcl}
  3927. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3928. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3929. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3930. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3931. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3932. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3933. \mid \key{goto}~\itm{label}\key{;}\\
  3934. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3935. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  3936. \end{array}
  3937. \]
  3938. \end{minipage}
  3939. }
  3940. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3941. \label{fig:c1-concrete-syntax}
  3942. \end{figure}
  3943. \begin{figure}[tp]
  3944. \fbox{
  3945. \begin{minipage}{0.96\textwidth}
  3946. \small
  3947. \[
  3948. \begin{array}{lcl}
  3949. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3950. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3951. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3952. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3953. &\mid& \UNIOP{\key{'not}}{\Atm}
  3954. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3955. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3956. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3957. \mid \GOTO{\itm{label}} \\
  3958. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3959. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  3960. \end{array}
  3961. \]
  3962. \end{minipage}
  3963. }
  3964. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  3965. (Figure~\ref{fig:c0-syntax}).}
  3966. \label{fig:c1-syntax}
  3967. \end{figure}
  3968. \clearpage
  3969. \section{Remove Complex Operands}
  3970. \label{sec:remove-complex-opera-R2}
  3971. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  3972. \code{rco-atom} functions according to the definition of the output
  3973. language for this pass, $R_2^{\dagger}$, the administrative normal
  3974. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  3975. \code{Bool} form is an atomic expressions but \code{If} is not. All
  3976. three sub-expressions of an \code{If} are allowed to be complex
  3977. expressions in the output of \code{remove-complex-opera*}, but the
  3978. operands of \code{not} and the comparisons must be atoms. Regarding
  3979. the \code{If} form, it is particularly important to \textbf{not}
  3980. replace its condition with a temporary variable because that would
  3981. interfere with the generation of high-quality output in the
  3982. \code{explicate-control} pass.
  3983. \begin{figure}[tp]
  3984. \centering
  3985. \fbox{
  3986. \begin{minipage}{0.96\textwidth}
  3987. \[
  3988. \begin{array}{rcl}
  3989. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  3990. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  3991. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3992. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  3993. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  3994. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3995. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3996. \end{array}
  3997. \]
  3998. \end{minipage}
  3999. }
  4000. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4001. \label{fig:r2-anf-syntax}
  4002. \end{figure}
  4003. \section{Explicate Control}
  4004. \label{sec:explicate-control-r2}
  4005. Recall that the purpose of \code{explicate-control} is to make the
  4006. order of evaluation explicit in the syntax of the program. With the
  4007. addition of \key{if} in $R_2$ this get more interesting.
  4008. As a motivating example, consider the following program that has an
  4009. \key{if} expression nested in the predicate of another \key{if}.
  4010. % s1_41.rkt
  4011. \begin{center}
  4012. \begin{minipage}{0.96\textwidth}
  4013. \begin{lstlisting}
  4014. (let ([x (read)])
  4015. (let ([y (read)])
  4016. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4017. (+ y 2)
  4018. (+ y 10))))
  4019. \end{lstlisting}
  4020. \end{minipage}
  4021. \end{center}
  4022. %
  4023. The naive way to compile \key{if} and the comparison would be to
  4024. handle each of them in isolation, regardless of their context. Each
  4025. comparison would be translated into a \key{cmpq} instruction followed
  4026. by a couple instructions to move the result from the EFLAGS register
  4027. into a general purpose register or stack location. Each \key{if} would
  4028. be translated into the combination of a \key{cmpq} and a conditional
  4029. jump. The generated code for the inner \key{if} in the above example
  4030. would be as follows.
  4031. \begin{center}
  4032. \begin{minipage}{0.96\textwidth}
  4033. \begin{lstlisting}
  4034. ...
  4035. cmpq $1, x ;; (< x 1)
  4036. setl %al
  4037. movzbq %al, tmp
  4038. cmpq $1, tmp ;; (if (< x 1) ...)
  4039. je then_branch_1
  4040. jmp else_branch_1
  4041. ...
  4042. \end{lstlisting}
  4043. \end{minipage}
  4044. \end{center}
  4045. However, if we take context into account we can do better and reduce
  4046. the use of \key{cmpq} and EFLAG-accessing instructions.
  4047. One idea is to try and reorganize the code at the level of $R_2$,
  4048. pushing the outer \key{if} inside the inner one. This would yield the
  4049. following code.
  4050. \begin{center}
  4051. \begin{minipage}{0.96\textwidth}
  4052. \begin{lstlisting}
  4053. (let ([x (read)])
  4054. (let ([y (read)])
  4055. (if (< x 1)
  4056. (if (eq? x 0)
  4057. (+ y 2)
  4058. (+ y 10))
  4059. (if (eq? x 2)
  4060. (+ y 2)
  4061. (+ y 10)))))
  4062. \end{lstlisting}
  4063. \end{minipage}
  4064. \end{center}
  4065. Unfortunately, this approach duplicates the two branches, and a
  4066. compiler must never duplicate code!
  4067. We need a way to perform the above transformation, but without
  4068. duplicating code. The solution is straightforward if we think at the
  4069. level of x86 assembly: we can label the code for each of the branches
  4070. and insert jumps in all the places that need to execute the
  4071. branches. Put another way, we need to move away from abstract syntax
  4072. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  4073. use a standard program representation called a \emph{control flow
  4074. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4075. \index{control-flow graph}
  4076. Each vertex is a labeled sequence of code, called a \emph{basic block}, and
  4077. each edge represents a jump to another block. The \key{Program}
  4078. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4079. as an alist mapping labels to basic blocks. Each basic block is
  4080. represented by the $\Tail$ non-terminal.
  4081. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4082. \code{remove-complex-opera*} pass and then the
  4083. \code{explicate-control} pass on the example program. We walk through
  4084. the output program and then discuss the algorithm.
  4085. %
  4086. Following the order of evaluation in the output of
  4087. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4088. and then the less-than-comparison to \code{1} in the predicate of the
  4089. inner \key{if}. In the output of \code{explicate-control}, in the
  4090. block labeled \code{start}, this becomes two assignment statements
  4091. followed by a conditional \key{goto} to label \code{block96} or
  4092. \code{block97}. The blocks associated with those labels contain the
  4093. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4094. respectively. Regarding the block labeled with \code{block96}, we
  4095. start with the comparison to \code{0} and then have a conditional
  4096. goto, either to label \code{block92} or label \code{block93}, which
  4097. indirectly take us to labels \code{block90} and \code{block91}, the
  4098. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4099. y 10)}. The story for the block labeled \code{block97} is similar.
  4100. \begin{figure}[tbp]
  4101. \begin{tabular}{lll}
  4102. \begin{minipage}{0.4\textwidth}
  4103. % s1_41.rkt
  4104. \begin{lstlisting}
  4105. (let ([x (read)])
  4106. (let ([y (read)])
  4107. (if (if (< x 1)
  4108. (eq? x 0)
  4109. (eq? x 2))
  4110. (+ y 2)
  4111. (+ y 10))))
  4112. \end{lstlisting}
  4113. \hspace{40pt}$\Downarrow$
  4114. \begin{lstlisting}
  4115. (let ([x (read)])
  4116. (let ([y (read)])
  4117. (if (if (< x 1)
  4118. (eq? x 0)
  4119. (eq? x 2))
  4120. (+ y 2)
  4121. (+ y 10))))
  4122. \end{lstlisting}
  4123. \end{minipage}
  4124. &
  4125. $\Rightarrow$
  4126. &
  4127. \begin{minipage}{0.55\textwidth}
  4128. \begin{lstlisting}
  4129. start:
  4130. x = (read);
  4131. y = (read);
  4132. if (< x 1)
  4133. goto block96;
  4134. else
  4135. goto block97;
  4136. block96:
  4137. if (eq? x 0)
  4138. goto block92;
  4139. else
  4140. goto block93;
  4141. block97:
  4142. if (eq? x 2)
  4143. goto block94;
  4144. else
  4145. goto block95;
  4146. block92:
  4147. goto block90;
  4148. block93:
  4149. goto block91;
  4150. block94:
  4151. goto block90;
  4152. block95:
  4153. goto block91;
  4154. block90:
  4155. return (+ y 2);
  4156. block91:
  4157. return (+ y 10);
  4158. \end{lstlisting}
  4159. \end{minipage}
  4160. \end{tabular}
  4161. \caption{Example translation from $R_2$ to $C_1$
  4162. via the \code{explicate-control}.}
  4163. \label{fig:explicate-control-s1-38}
  4164. \end{figure}
  4165. The nice thing about the output of \code{explicate-control} is that
  4166. there are no unnecessary comparisons and every comparison is part of a
  4167. conditional jump. The down-side of this output is that it includes
  4168. trivial blocks, such as the blocks labeled \code{block92} through
  4169. \code{block95}, that only jump to another block. We discuss a solution
  4170. to this problem in Section~\ref{sec:opt-jumps}.
  4171. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4172. \code{explicate-control} for $R_1$ using two mutually recursive
  4173. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4174. former function translates expressions in tail position whereas the
  4175. later function translates expressions on the right-hand-side of a
  4176. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4177. new kind of context to deal with: the predicate position of the
  4178. \key{if}. We need another function, \code{explicate-pred}, that takes
  4179. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4180. the then-branch and else-branch. The output of \code{explicate-pred}
  4181. is a block and a list of formerly \key{let}-bound variables.
  4182. Note that the three explicate functions need to construct a
  4183. control-flow graph, which we recommend they do via updates to a global
  4184. variable.
  4185. In the following paragraphs we consider the specific additions to the
  4186. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4187. of cases for the \code{explicate-pred} function.
  4188. The \code{explicate-tail} function needs an additional case for
  4189. \key{if}. The branches of the \key{if} inherit the current context, so
  4190. they are in tail position. Let $B_1$ be the result of
  4191. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4192. is a $\Tail$ AST node. Let $B_2$ be the result of apply
  4193. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4194. the $\Tail$ that results fromapplying \code{explicate-pred} to the
  4195. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4196. \key{if} as a whole translates to block $B_3$.
  4197. \[
  4198. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4199. \]
  4200. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4201. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4202. should not be confused with the labels for the blocks that appear in
  4203. the generated code. We initially construct unlabeled blocks; we only
  4204. attach labels to blocks when we add them to the control-flow graph, as
  4205. we shall see in the next case.
  4206. Next consider the case for \key{if} in the \code{explicate-assign}
  4207. function. The context of the \key{if} is an assignment to some
  4208. variable $x$ and then the control continues to some block $B_1$. The
  4209. code that we generate for both the ``then'' and ``else'' branches
  4210. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4211. add it to the control flow graph with a fresh label $\ell_1$. The
  4212. branches of the \key{if} inherit the current context, so that are in
  4213. assignment positions. Let $B_2$ be the result of applying
  4214. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4215. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4216. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4217. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4218. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4219. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4220. $B_4$.
  4221. \[
  4222. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4223. \]
  4224. The function \code{explicate-pred} will need a case for every
  4225. expression that can have type \code{Boolean}. We detail a few cases
  4226. here and leave the rest for the reader. The input to this function is
  4227. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4228. the enclosing \key{if}. Suppose the expression is the Boolean
  4229. \code{\#t}. Then we can perform a kind of partial evaluation
  4230. \index{partial evaluation} and translate it to the ``then'' branch
  4231. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4232. \[
  4233. \key{\#t} \quad\Rightarrow\quad B_1,
  4234. \qquad\qquad\qquad
  4235. \key{\#f} \quad\Rightarrow\quad B_2
  4236. \]
  4237. Next, suppose the expression is a less-than comparison. We translate
  4238. it to a conditional \code{goto}. We need labels for the two branches
  4239. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4240. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4241. less-than comparison is as follows.
  4242. \[
  4243. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4244. \begin{array}{l}
  4245. \key{if}~(\key{<}~e_1~e_2) \\
  4246. \qquad\key{goto}~\ell_1\key{;}\\
  4247. \key{else}\\
  4248. \qquad\key{goto}~\ell_2\key{;}
  4249. \end{array}
  4250. \]
  4251. The case for \key{if} in \code{explicate-pred} is particularly
  4252. illuminating as it deals with the challenges that we discussed above
  4253. regarding the example of the nested \key{if} expressions. Again, we
  4254. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4255. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4256. branches of the current \key{if} inherit their context from the
  4257. current one, that is, predicate context. So we apply
  4258. \code{explicate-pred} to the ``then'' branch with the two blocks
  4259. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4260. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4261. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4262. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4263. \[
  4264. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4265. \quad\Rightarrow\quad
  4266. B_5
  4267. \]
  4268. Finally, note that the way in which the \code{shrink} pass transforms
  4269. logical operations such as \code{and} and \code{or} can impact the
  4270. quality of code generated by \code{explicate-control}. For example,
  4271. consider the following program.
  4272. \begin{lstlisting}
  4273. (if (and (eq? (read) 0) (eq? (read) 1))
  4274. 0
  4275. 42)
  4276. \end{lstlisting}
  4277. The \code{and} operation should transform into something that the
  4278. \code{explicat-pred} function can still analyze and descend through to
  4279. reach the underlying \code{eq?} conditions. Ideally, your
  4280. \code{explicate-control} pass should generate code similar to the
  4281. following for the above program.\footnote{If the trivial blocks 17,
  4282. 18, and 20 bother you, take a look at the challenge problem in
  4283. Section~\ref{sec:opt-jumps}.}
  4284. \begin{center}
  4285. \begin{minipage}{0.45\textwidth}
  4286. \begin{lstlisting}
  4287. start:
  4288. tmp13 = (read);
  4289. if (eq? tmp13 0)
  4290. goto block19;
  4291. else
  4292. goto block20;
  4293. block19:
  4294. tmp14 = (read);
  4295. if (eq? tmp14 1)
  4296. goto block17;
  4297. else
  4298. goto block18;
  4299. \end{lstlisting}
  4300. \end{minipage}
  4301. \begin{minipage}{0.45\textwidth}
  4302. \begin{lstlisting}
  4303. block20:
  4304. goto block16;
  4305. block17:
  4306. goto block15;
  4307. block18:
  4308. goto block16;
  4309. block15:
  4310. return 0;
  4311. block16:
  4312. return 42;
  4313. \end{lstlisting}
  4314. \end{minipage}
  4315. \end{center}
  4316. \begin{exercise}\normalfont
  4317. Implement the pass \code{explicate-control} by adding the cases for
  4318. \key{if} to the functions for tail and assignment contexts, and
  4319. implement \code{explicate-pred} for predicate contexts. Create test
  4320. cases that exercise all of the new cases in the code for this pass.
  4321. \end{exercise}
  4322. \section{Select Instructions}
  4323. \label{sec:select-r2}
  4324. \index{instruction selection}
  4325. Recall that the \code{select-instructions} pass lowers from our
  4326. $C$-like intermediate representation to the pseudo-x86 language, which
  4327. is suitable for conducting register allocation. The pass is
  4328. implemented using three auxiliary functions, one for each of the
  4329. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4330. For $\Atm$, we have new cases for the Booleans. We take the usual
  4331. approach of encoding them as integers, with true as 1 and false as 0.
  4332. \[
  4333. \key{\#t} \Rightarrow \key{1}
  4334. \qquad
  4335. \key{\#f} \Rightarrow \key{0}
  4336. \]
  4337. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4338. be implemented in terms of \code{xorq} as we discussed at the
  4339. beginning of this section. Given an assignment
  4340. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4341. if the left-hand side $\itm{var}$ is
  4342. the same as $\Atm$, then just the \code{xorq} suffices.
  4343. \[
  4344. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4345. \quad\Rightarrow\quad
  4346. \key{xorq}~\key{\$}1\key{,}~\Var
  4347. \]
  4348. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4349. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4350. x86. Then we have
  4351. \[
  4352. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4353. \quad\Rightarrow\quad
  4354. \begin{array}{l}
  4355. \key{movq}~\Arg\key{,}~\Var\\
  4356. \key{xorq}~\key{\$}1\key{,}~\Var
  4357. \end{array}
  4358. \]
  4359. Next consider the cases for \code{eq?} and less-than comparison.
  4360. Translating these operations to x86 is slightly involved due to the
  4361. unusual nature of the \key{cmpq} instruction discussed above. We
  4362. recommend translating an assignment from \code{eq?} into the following
  4363. sequence of three instructions. \\
  4364. \begin{tabular}{lll}
  4365. \begin{minipage}{0.4\textwidth}
  4366. \begin{lstlisting}
  4367. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4368. \end{lstlisting}
  4369. \end{minipage}
  4370. &
  4371. $\Rightarrow$
  4372. &
  4373. \begin{minipage}{0.4\textwidth}
  4374. \begin{lstlisting}
  4375. cmpq |$\Arg_2$|, |$\Arg_1$|
  4376. sete %al
  4377. movzbq %al, |$\Var$|
  4378. \end{lstlisting}
  4379. \end{minipage}
  4380. \end{tabular} \\
  4381. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4382. and conditional \key{goto}. Both are straightforward to handle. A
  4383. \key{goto} becomes a jump instruction.
  4384. \[
  4385. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4386. \]
  4387. A conditional \key{goto} becomes a compare instruction followed
  4388. by a conditional jump (for ``then'') and the fall-through is
  4389. to a regular jump (for ``else'').\\
  4390. \begin{tabular}{lll}
  4391. \begin{minipage}{0.4\textwidth}
  4392. \begin{lstlisting}
  4393. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4394. goto |$\ell_1$|;
  4395. else
  4396. goto |$\ell_2$|;
  4397. \end{lstlisting}
  4398. \end{minipage}
  4399. &
  4400. $\Rightarrow$
  4401. &
  4402. \begin{minipage}{0.4\textwidth}
  4403. \begin{lstlisting}
  4404. cmpq |$\Arg_2$|, |$\Arg_1$|
  4405. je |$\ell_1$|
  4406. jmp |$\ell_2$|
  4407. \end{lstlisting}
  4408. \end{minipage}
  4409. \end{tabular} \\
  4410. \begin{exercise}\normalfont
  4411. Expand your \code{select-instructions} pass to handle the new features
  4412. of the $R_2$ language. Test the pass on all the examples you have
  4413. created and make sure that you have some test programs that use the
  4414. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4415. the output using the \code{interp-x86} interpreter
  4416. (Appendix~\ref{appendix:interp}).
  4417. \end{exercise}
  4418. \section{Register Allocation}
  4419. \label{sec:register-allocation-r2}
  4420. \index{register allocation}
  4421. The changes required for $R_2$ affect liveness analysis, building the
  4422. interference graph, and assigning homes, but the graph coloring
  4423. algorithm itself does not change.
  4424. \subsection{Liveness Analysis}
  4425. \label{sec:liveness-analysis-r2}
  4426. \index{liveness analysis}
  4427. Recall that for $R_1$ we implemented liveness analysis for a single
  4428. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4429. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4430. produces many basic blocks arranged in a control-flow graph. The first
  4431. question we need to consider is: what order should we process the
  4432. basic blocks? Recall that to perform liveness analysis, we need to
  4433. know the live-after set. If a basic block has no successor blocks
  4434. (i.e. no out-edges in the control flow graph), then it has an empty
  4435. live-after set and we can immediately apply liveness analysis to
  4436. it. If a basic block has some successors, then we need to complete
  4437. liveness analysis on those blocks first. Furthermore, we know that
  4438. the control flow graph does not contain any cycles because $R_2$ does
  4439. not include loops
  4440. %
  4441. \footnote{If we were to add loops to the language, then the CFG could
  4442. contain cycles and we would instead need to use the classic worklist
  4443. algorithm for computing the fixed point of the liveness
  4444. analysis~\citep{Aho:1986qf}.}.
  4445. %
  4446. Returning to the question of what order should we process the basic
  4447. blocks, the answer is reverse topological order. We recommend using
  4448. the \code{tsort} (topological sort) and \code{transpose} functions of
  4449. the Racket \code{graph} package to obtain this ordering.
  4450. \index{topological order}
  4451. \index{topological sort}
  4452. The next question is how to compute the live-after set of a block
  4453. given the live-before sets of all its successor blocks. (There can be
  4454. more than one because of conditional jumps.) During compilation we do
  4455. not know which way a conditional jump will go, so we do not know which
  4456. of the successor's live-before set to use. The solution to this
  4457. challenge is based on the observation that there is no harm to the
  4458. correctness of the compiler if we classify more variables as live than
  4459. the ones that are truly live during a particular execution of the
  4460. block. Thus, we can take the union of the live-before sets from all
  4461. the successors to be the live-after set for the block. Once we have
  4462. computed the live-after set, we can proceed to perform liveness
  4463. analysis on the block just as we did in
  4464. Section~\ref{sec:liveness-analysis-r1}.
  4465. The helper functions for computing the variables in an instruction's
  4466. argument and for computing the variables read-from ($R$) or written-to
  4467. ($W$) by an instruction need to be updated to handle the new kinds of
  4468. arguments and instructions in x86$_1$.
  4469. \subsection{Build Interference}
  4470. \label{sec:build-interference-r2}
  4471. Many of the new instructions in x86$_1$ can be handled in the same way
  4472. as the instructions in x86$_0$. Thus, if your code was already quite
  4473. general, it will not need to be changed to handle the new
  4474. instructions. If you code is not general enough, I recommend that you
  4475. change your code to be more general. For example, you can factor out
  4476. the computing of the the read and write sets for each kind of
  4477. instruction into two auxiliary functions.
  4478. Note that the \key{movzbq} instruction requires some special care,
  4479. just like the \key{movq} instruction. See rule number 3 in
  4480. Section~\ref{sec:build-interference}.
  4481. %% \subsection{Assign Homes}
  4482. %% \label{sec:assign-homes-r2}
  4483. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4484. %% to be updated to handle the \key{if} statement, simply by recursively
  4485. %% processing the child nodes. Hopefully your code already handles the
  4486. %% other new instructions, but if not, you can generalize your code.
  4487. \begin{exercise}\normalfont
  4488. Update the \code{register-allocation} pass so that it works for $R_2$
  4489. and test your compiler using your previously created programs on the
  4490. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4491. \end{exercise}
  4492. \section{Patch Instructions}
  4493. The second argument of the \key{cmpq} instruction must not be an
  4494. immediate value (such as an integer). So if you are comparing two
  4495. immediates, we recommend inserting a \key{movq} instruction to put the
  4496. second argument in \key{rax}.
  4497. %
  4498. The second argument of the \key{movzbq} must be a register.
  4499. %
  4500. There are no special restrictions on the x86 instructions \key{JmpIf}
  4501. and \key{Jmp}.
  4502. \begin{exercise}\normalfont
  4503. Update \code{patch-instructions} to handle the new x86 instructions.
  4504. Test your compiler using your previously created programs on the
  4505. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4506. \end{exercise}
  4507. \section{An Example Translation}
  4508. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4509. $R_2$ translated to x86, showing the results of
  4510. \code{explicate-control}, \code{select-instructions}, and the final
  4511. x86 assembly code.
  4512. \begin{figure}[tbp]
  4513. \begin{tabular}{lll}
  4514. \begin{minipage}{0.5\textwidth}
  4515. % s1_20.rkt
  4516. \begin{lstlisting}
  4517. (if (eq? (read) 1) 42 0)
  4518. \end{lstlisting}
  4519. $\Downarrow$
  4520. \begin{lstlisting}
  4521. start:
  4522. tmp7951 = (read);
  4523. if (eq? tmp7951 1) then
  4524. goto block7952;
  4525. else
  4526. goto block7953;
  4527. block7952:
  4528. return 42;
  4529. block7953:
  4530. return 0;
  4531. \end{lstlisting}
  4532. $\Downarrow$
  4533. \begin{lstlisting}
  4534. start:
  4535. callq read_int
  4536. movq %rax, tmp7951
  4537. cmpq $1, tmp7951
  4538. je block7952
  4539. jmp block7953
  4540. block7953:
  4541. movq $0, %rax
  4542. jmp conclusion
  4543. block7952:
  4544. movq $42, %rax
  4545. jmp conclusion
  4546. \end{lstlisting}
  4547. \end{minipage}
  4548. &
  4549. $\Rightarrow\qquad$
  4550. \begin{minipage}{0.4\textwidth}
  4551. \begin{lstlisting}
  4552. start:
  4553. callq read_int
  4554. movq %rax, %rcx
  4555. cmpq $1, %rcx
  4556. je block7952
  4557. jmp block7953
  4558. block7953:
  4559. movq $0, %rax
  4560. jmp conclusion
  4561. block7952:
  4562. movq $42, %rax
  4563. jmp conclusion
  4564. .globl main
  4565. main:
  4566. pushq %rbp
  4567. movq %rsp, %rbp
  4568. pushq %r13
  4569. pushq %r12
  4570. pushq %rbx
  4571. pushq %r14
  4572. subq $0, %rsp
  4573. jmp start
  4574. conclusion:
  4575. addq $0, %rsp
  4576. popq %r14
  4577. popq %rbx
  4578. popq %r12
  4579. popq %r13
  4580. popq %rbp
  4581. retq
  4582. \end{lstlisting}
  4583. \end{minipage}
  4584. \end{tabular}
  4585. \caption{Example compilation of an \key{if} expression to x86.}
  4586. \label{fig:if-example-x86}
  4587. \end{figure}
  4588. \begin{figure}[p]
  4589. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4590. \node (R2) at (0,2) {\large $R_2$};
  4591. \node (R2-2) at (3,2) {\large $R_2$};
  4592. \node (R2-3) at (6,2) {\large $R_2$};
  4593. \node (R2-4) at (9,2) {\large $R_2$};
  4594. \node (R2-5) at (9,0) {\large $R_2$};
  4595. \node (C1-1) at (3,-2) {\large $C_1$};
  4596. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4597. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4598. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4599. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4600. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4601. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4602. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4603. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4604. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4605. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4606. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4607. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4608. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4609. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4610. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4611. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4612. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4613. \end{tikzpicture}
  4614. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4615. \label{fig:R2-passes}
  4616. \end{figure}
  4617. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4618. compilation of $R_2$.
  4619. \section{Challenge: Optimize and Remove Jumps}
  4620. \label{sec:opt-jumps}
  4621. Recall that in the example output of \code{explicate-control} in
  4622. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4623. \code{block60} are trivial blocks, they do nothing but jump to another
  4624. block. The first goal of this challenge assignment is to remove those
  4625. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4626. \code{explicate-control} on the left and shows the result of bypassing
  4627. the trivial blocks on the right. Let us focus on \code{block61}. The
  4628. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4629. \code{block55}. The optimized code on the right of
  4630. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4631. \code{then} branch jumping directly to \code{block55}. The story is
  4632. similar for the \code{else} branch, as well as for the two branches in
  4633. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4634. have been optimized in this way, there are no longer any jumps to
  4635. blocks \code{block57} through \code{block60}, so they can be removed.
  4636. \begin{figure}[tbp]
  4637. \begin{tabular}{lll}
  4638. \begin{minipage}{0.4\textwidth}
  4639. \begin{lstlisting}
  4640. block62:
  4641. tmp54 = (read);
  4642. if (eq? tmp54 2) then
  4643. goto block59;
  4644. else
  4645. goto block60;
  4646. block61:
  4647. tmp53 = (read);
  4648. if (eq? tmp53 0) then
  4649. goto block57;
  4650. else
  4651. goto block58;
  4652. block60:
  4653. goto block56;
  4654. block59:
  4655. goto block55;
  4656. block58:
  4657. goto block56;
  4658. block57:
  4659. goto block55;
  4660. block56:
  4661. return (+ 700 77);
  4662. block55:
  4663. return (+ 10 32);
  4664. start:
  4665. tmp52 = (read);
  4666. if (eq? tmp52 1) then
  4667. goto block61;
  4668. else
  4669. goto block62;
  4670. \end{lstlisting}
  4671. \end{minipage}
  4672. &
  4673. $\Rightarrow$
  4674. &
  4675. \begin{minipage}{0.55\textwidth}
  4676. \begin{lstlisting}
  4677. block62:
  4678. tmp54 = (read);
  4679. if (eq? tmp54 2) then
  4680. goto block55;
  4681. else
  4682. goto block56;
  4683. block61:
  4684. tmp53 = (read);
  4685. if (eq? tmp53 0) then
  4686. goto block55;
  4687. else
  4688. goto block56;
  4689. block56:
  4690. return (+ 700 77);
  4691. block55:
  4692. return (+ 10 32);
  4693. start:
  4694. tmp52 = (read);
  4695. if (eq? tmp52 1) then
  4696. goto block61;
  4697. else
  4698. goto block62;
  4699. \end{lstlisting}
  4700. \end{minipage}
  4701. \end{tabular}
  4702. \caption{Optimize jumps by removing trivial blocks.}
  4703. \label{fig:optimize-jumps}
  4704. \end{figure}
  4705. The name of this pass is \code{optimize-jumps}. We recommend
  4706. implementing this pass in two phases. The first phrase builds a hash
  4707. table that maps labels to possibly improved labels. The second phase
  4708. changes the target of each \code{goto} to use the improved label. If
  4709. the label is for a trivial block, then the hash table should map the
  4710. label to the first non-trivial block that can be reached from this
  4711. label by jumping through trivial blocks. If the label is for a
  4712. non-trivial block, then the hash table should map the label to itself;
  4713. we do not want to change jumps to non-trivial blocks.
  4714. The first phase can be accomplished by constructing an empty hash
  4715. table, call it \code{short-cut}, and then iterating over the control
  4716. flow graph. Each time you encouter a block that is just a \code{goto},
  4717. then update the hash table, mapping the block's source to the target
  4718. of the \code{goto}. Also, the hash table may already have mapped some
  4719. labels to the block's source, to you must iterate through the hash
  4720. table and update all of those so that they instead map to the target
  4721. of the \code{goto}.
  4722. For the second phase, we recommend iterating through the $\Tail$ of
  4723. each block in the program, updating the target of every \code{goto}
  4724. according to the mapping in \code{short-cut}.
  4725. \begin{exercise}\normalfont
  4726. Implement the \code{optimize-jumps} pass as a transformation from
  4727. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4728. Check that \code{optimize-jumps} removes trivial blocks in a few
  4729. example programs. Then check that your compiler still passes all of
  4730. your tests.
  4731. \end{exercise}
  4732. There is another opportunity for optimizing jumps that is apparent in
  4733. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4734. end with a jump to \code{block7953} and there are no other jumps to
  4735. \code{block7953} in the rest of the program. In this situation we can
  4736. avoid the runtime overhead of this jump by merging \code{block7953}
  4737. into the preceeding block, in this case the \code{start} block.
  4738. Figure~\ref{fig:remove-jumps} shows the output of
  4739. \code{select-instructions} on the left and the result of this
  4740. optimization on the right.
  4741. \begin{figure}[tbp]
  4742. \begin{tabular}{lll}
  4743. \begin{minipage}{0.5\textwidth}
  4744. % s1_20.rkt
  4745. \begin{lstlisting}
  4746. start:
  4747. callq read_int
  4748. movq %rax, tmp7951
  4749. cmpq $1, tmp7951
  4750. je block7952
  4751. jmp block7953
  4752. block7953:
  4753. movq $0, %rax
  4754. jmp conclusion
  4755. block7952:
  4756. movq $42, %rax
  4757. jmp conclusion
  4758. \end{lstlisting}
  4759. \end{minipage}
  4760. &
  4761. $\Rightarrow\qquad$
  4762. \begin{minipage}{0.4\textwidth}
  4763. \begin{lstlisting}
  4764. start:
  4765. callq read_int
  4766. movq %rax, tmp7951
  4767. cmpq $1, tmp7951
  4768. je block7952
  4769. movq $0, %rax
  4770. jmp conclusion
  4771. block7952:
  4772. movq $42, %rax
  4773. jmp conclusion
  4774. \end{lstlisting}
  4775. \end{minipage}
  4776. \end{tabular}
  4777. \caption{Merging basic blocks by removing unnecessary jumps.}
  4778. \label{fig:remove-jumps}
  4779. \end{figure}
  4780. \begin{exercise}\normalfont
  4781. Implement a pass named \code{remove-jumps} that merges basic blocks
  4782. into their preceeding basic block, when there is only one preceeding
  4783. block. The pass should translate from psuedo $x86_1$ to pseudo
  4784. $x86_1$ and it should come immediately after
  4785. \code{select-instructions}. Check that \code{remove-jumps}
  4786. accomplishes the goal of merging basic blocks on several test
  4787. programs and check that your compiler passes all of your tests.
  4788. \end{exercise}
  4789. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4790. \chapter{Tuples and Garbage Collection}
  4791. \label{ch:tuples}
  4792. \index{tuple}
  4793. \index{vector}
  4794. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4795. add simple structures. \\ --Jeremy}
  4796. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4797. things to discuss in this chapter. \\ --Jeremy}
  4798. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4799. all the IR grammars are spelled out! \\ --Jeremy}
  4800. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4801. but keep type annotations on vector creation and local variables, function
  4802. parameters, etc. \\ --Jeremy}
  4803. \margincomment{\scriptsize Be more explicit about how to deal with
  4804. the root stack. \\ --Jeremy}
  4805. In this chapter we study the implementation of mutable tuples (called
  4806. ``vectors'' in Racket). This language feature is the first to use the
  4807. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  4808. indefinite, that is, a tuple lives forever from the programmer's
  4809. viewpoint. Of course, from an implementer's viewpoint, it is important
  4810. to reclaim the space associated with a tuple when it is no longer
  4811. needed, which is why we also study \emph{garbage collection}
  4812. \emph{garbage collection}
  4813. techniques in this chapter.
  4814. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4815. interpreter and type checker. The $R_3$ language extends the $R_2$
  4816. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4817. \code{void} value. The reason for including the later is that the
  4818. \code{vector-set!} operation returns a value of type
  4819. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4820. called the \code{Unit} type in the programming languages
  4821. literature. Racket's \code{Void} type is inhabited by a single value
  4822. \code{void} which corresponds to \code{unit} or \code{()} in the
  4823. literature~\citep{Pierce:2002hj}.}.
  4824. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4825. copying live objects back and forth between two halves of the
  4826. heap. The garbage collector requires coordination with the compiler so
  4827. that it can see all of the \emph{root} pointers, that is, pointers in
  4828. registers or on the procedure call stack.
  4829. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4830. discuss all the necessary changes and additions to the compiler
  4831. passes, including a new compiler pass named \code{expose-allocation}.
  4832. \section{The $R_3$ Language}
  4833. \label{sec:r3}
  4834. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4835. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4836. $R_3$ language includes three new forms: \code{vector} for creating a
  4837. tuple, \code{vector-ref} for reading an element of a tuple, and
  4838. \code{vector-set!} for writing to an element of a tuple. The program
  4839. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4840. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4841. the 3-tuple, demonstrating that tuples are first-class values. The
  4842. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4843. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4844. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4845. 1-tuple. So the result of the program is \code{42}.
  4846. \begin{figure}[tbp]
  4847. \centering
  4848. \fbox{
  4849. \begin{minipage}{0.96\textwidth}
  4850. \[
  4851. \begin{array}{lcl}
  4852. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4853. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4854. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4855. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4856. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4857. \mid (\key{and}\;\Exp\;\Exp)
  4858. \mid (\key{or}\;\Exp\;\Exp)
  4859. \mid (\key{not}\;\Exp) } \\
  4860. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4861. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4862. &\mid& (\key{vector}\;\Exp\ldots)
  4863. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4864. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4865. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4866. R_3 &::=& \Exp
  4867. \end{array}
  4868. \]
  4869. \end{minipage}
  4870. }
  4871. \caption{The concrete syntax of $R_3$, extending $R_2$
  4872. (Figure~\ref{fig:r2-concrete-syntax}).}
  4873. \label{fig:r3-concrete-syntax}
  4874. \end{figure}
  4875. \begin{figure}[tbp]
  4876. \begin{lstlisting}
  4877. (let ([t (vector 40 #t (vector 2))])
  4878. (if (vector-ref t 1)
  4879. (+ (vector-ref t 0)
  4880. (vector-ref (vector-ref t 2) 0))
  4881. 44))
  4882. \end{lstlisting}
  4883. \caption{Example program that creates tuples and reads from them.}
  4884. \label{fig:vector-eg}
  4885. \end{figure}
  4886. \begin{figure}[tp]
  4887. \centering
  4888. \fbox{
  4889. \begin{minipage}{0.96\textwidth}
  4890. \[
  4891. \begin{array}{lcl}
  4892. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4893. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4894. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4895. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4896. &\mid& \gray{ \BOOL{\itm{bool}}
  4897. \mid \AND{\Exp}{\Exp} }\\
  4898. &\mid& \gray{ \OR{\Exp}{\Exp}
  4899. \mid \NOT{\Exp} } \\
  4900. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  4901. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4902. &\mid& \VECTOR{\Exp} \\
  4903. &\mid& \VECREF{\Exp}{\Int}\\
  4904. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4905. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  4906. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4907. \end{array}
  4908. \]
  4909. \end{minipage}
  4910. }
  4911. \caption{The abstract syntax of $R_3$.}
  4912. \label{fig:r3-syntax}
  4913. \end{figure}
  4914. \index{allocate}
  4915. \index{heap allocate}
  4916. Tuples are our first encounter with heap-allocated data, which raises
  4917. several interesting issues. First, variable binding performs a
  4918. shallow-copy when dealing with tuples, which means that different
  4919. variables can refer to the same tuple, that is, different variables
  4920. can be \emph{aliases} for the same entity. Consider the following
  4921. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4922. Thus, the mutation through \code{t2} is visible when referencing the
  4923. tuple from \code{t1}, so the result of this program is \code{42}.
  4924. \index{alias}\index{mutation}
  4925. \begin{center}
  4926. \begin{minipage}{0.96\textwidth}
  4927. \begin{lstlisting}
  4928. (let ([t1 (vector 3 7)])
  4929. (let ([t2 t1])
  4930. (let ([_ (vector-set! t2 0 42)])
  4931. (vector-ref t1 0))))
  4932. \end{lstlisting}
  4933. \end{minipage}
  4934. \end{center}
  4935. The next issue concerns the lifetime of tuples. Of course, they are
  4936. created by the \code{vector} form, but when does their lifetime end?
  4937. Notice that $R_3$ does not include an operation for deleting
  4938. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  4939. of static scoping. For example, the following program returns
  4940. \code{42} even though the variable \code{w} goes out of scope prior to
  4941. the \code{vector-ref} that reads from the vector it was bound to.
  4942. \begin{center}
  4943. \begin{minipage}{0.96\textwidth}
  4944. \begin{lstlisting}
  4945. (let ([v (vector (vector 44))])
  4946. (let ([x (let ([w (vector 42)])
  4947. (let ([_ (vector-set! v 0 w)])
  4948. 0))])
  4949. (+ x (vector-ref (vector-ref v 0) 0))))
  4950. \end{lstlisting}
  4951. \end{minipage}
  4952. \end{center}
  4953. From the perspective of programmer-observable behavior, tuples live
  4954. forever. Of course, if they really lived forever, then many programs
  4955. would run out of memory.\footnote{The $R_3$ language does not have
  4956. looping or recursive functions, so it is nigh impossible to write a
  4957. program in $R_3$ that will run out of memory. However, we add
  4958. recursive functions in the next Chapter!} A Racket implementation
  4959. must therefore perform automatic garbage collection.
  4960. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4961. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4962. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4963. operations in Racket. One subtle point is that the \code{vector-set!}
  4964. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4965. can be passed around just like other values inside an $R_3$ program
  4966. and a \code{\#<void>} value can be compared for equality with another
  4967. \code{\#<void>} value. However, there are no other operations specific
  4968. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  4969. the \code{void?} predicate that returns \code{\#t} when applied to
  4970. \code{\#<void>} and \code{\#f} otherwise.
  4971. \begin{figure}[tbp]
  4972. \begin{lstlisting}
  4973. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4974. (define (interp-op op)
  4975. (match op
  4976. ...
  4977. ['vector vector]
  4978. ['vector-ref vector-ref]
  4979. ['vector-set! vector-set!]
  4980. [else (error 'interp-op "unknown operator")]))
  4981. (define (interp-exp env)
  4982. (lambda (e)
  4983. (define recur (interp-exp env))
  4984. (match e
  4985. ...
  4986. )))
  4987. (define (interp-R3 p)
  4988. (match p
  4989. [(Program '() e)
  4990. ((interp-exp '()) e)]
  4991. ))
  4992. \end{lstlisting}
  4993. \caption{Interpreter for the $R_3$ language.}
  4994. \label{fig:interp-R3}
  4995. \end{figure}
  4996. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4997. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4998. need to know which variables contain pointers into the heap, that is,
  4999. which variables contain vectors. Also, when allocating a vector, we
  5000. need to know which elements of the vector are pointers. We can obtain
  5001. this information during type checking. The type checker in
  5002. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  5003. expression, it also wraps every sub-expression $e$ with the form
  5004. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  5005. Subsequently, in the \code{uncover-locals} pass
  5006. (Section~\ref{sec:uncover-locals-r3}) this type information is
  5007. propagated to all variables (including the temporaries generated by
  5008. \code{remove-complex-opera*}).
  5009. \begin{figure}[tp]
  5010. \begin{lstlisting}
  5011. (define (type-check-exp env)
  5012. (lambda (e)
  5013. (define recur (type-check-exp env))
  5014. (match e
  5015. ...
  5016. [(Void) (values (HasType (Void) 'Void) 'Void)]
  5017. [(Prim 'vector es)
  5018. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5019. (let ([t `(Vector ,@t*)])
  5020. (values (HasType (Prim 'vector e*) t) t))]
  5021. [(Prim 'vector-ref (list e (Int i)))
  5022. (define-values (e^ t) (recur e))
  5023. (match t
  5024. [`(Vector ,ts ...)
  5025. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5026. (error 'type-check-exp "invalid index ~a" i))
  5027. (let ([t (list-ref ts i)])
  5028. (values
  5029. (HasType (Prim 'vector-ref
  5030. (list e^ (HasType (Int i) 'Integer)))
  5031. t)
  5032. t))]
  5033. [else (error "expected a vector in vector-ref, not" t)])]
  5034. [(Prim 'eq? (list e1 e2))
  5035. (define-values (e1^ T1) (recur e1))
  5036. (define-values (e2^ T2) (recur e2))
  5037. (unless (equal? T1 T2)
  5038. (error "arguments of eq? must have the same type, but are not"
  5039. (list T1 T2)))
  5040. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  5041. ...
  5042. )))
  5043. \end{lstlisting}
  5044. \caption{Type checker for the $R_3$ language.}
  5045. \label{fig:typecheck-R3}
  5046. \end{figure}
  5047. \section{Garbage Collection}
  5048. \label{sec:GC}
  5049. Here we study a relatively simple algorithm for garbage collection
  5050. that is the basis of state-of-the-art garbage
  5051. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5052. particular, we describe a two-space copying
  5053. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5054. perform the
  5055. copy~\citep{Cheney:1970aa}.
  5056. \index{copying collector}
  5057. \index{two-space copying collector}
  5058. Figure~\ref{fig:copying-collector} gives a
  5059. coarse-grained depiction of what happens in a two-space collector,
  5060. showing two time steps, prior to garbage collection (on the top) and
  5061. after garbage collection (on the bottom). In a two-space collector,
  5062. the heap is divided into two parts named the FromSpace and the
  5063. ToSpace. Initially, all allocations go to the FromSpace until there is
  5064. not enough room for the next allocation request. At that point, the
  5065. garbage collector goes to work to make more room.
  5066. \index{ToSpace}
  5067. \index{FromSpace}
  5068. The garbage collector must be careful not to reclaim tuples that will
  5069. be used by the program in the future. Of course, it is impossible in
  5070. general to predict what a program will do, but we can over approximate
  5071. the will-be-used tuples by preserving all tuples that could be
  5072. accessed by \emph{any} program given the current computer state. A
  5073. program could access any tuple whose address is in a register or on
  5074. the procedure call stack. These addresses are called the \emph{root
  5075. set}\index{root set}. In addition, a program could access any tuple that is
  5076. transitively reachable from the root set. Thus, it is safe for the
  5077. garbage collector to reclaim the tuples that are not reachable in this
  5078. way.
  5079. So the goal of the garbage collector is twofold:
  5080. \begin{enumerate}
  5081. \item preserve all tuple that are reachable from the root set via a
  5082. path of pointers, that is, the \emph{live} tuples, and
  5083. \item reclaim the memory of everything else, that is, the
  5084. \emph{garbage}.
  5085. \end{enumerate}
  5086. A copying collector accomplishes this by copying all of the live
  5087. objects from the FromSpace into the ToSpace and then performs a slight
  5088. of hand, treating the ToSpace as the new FromSpace and the old
  5089. FromSpace as the new ToSpace. In the example of
  5090. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5091. root set, one in a register and two on the stack. All of the live
  5092. objects have been copied to the ToSpace (the right-hand side of
  5093. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5094. pointer relationships. For example, the pointer in the register still
  5095. points to a 2-tuple whose first element is a 3-tuple and whose second
  5096. element is a 2-tuple. There are four tuples that are not reachable
  5097. from the root set and therefore do not get copied into the ToSpace.
  5098. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5099. created by a well-typed program in $R_3$ because it contains a
  5100. cycle. However, creating cycles will be possible once we get to $R_6$.
  5101. We design the garbage collector to deal with cycles to begin with so
  5102. we will not need to revisit this issue.
  5103. \begin{figure}[tbp]
  5104. \centering
  5105. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5106. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5107. \caption{A copying collector in action.}
  5108. \label{fig:copying-collector}
  5109. \end{figure}
  5110. There are many alternatives to copying collectors (and their bigger
  5111. siblings, the generational collectors) when its comes to garbage
  5112. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5113. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5114. collectors are that allocation is fast (just a comparison and pointer
  5115. increment), there is no fragmentation, cyclic garbage is collected,
  5116. and the time complexity of collection only depends on the amount of
  5117. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5118. main disadvantages of a two-space copying collector is that it uses a
  5119. lot of space and takes a long time to perform the copy, though these
  5120. problems are ameliorated in generational collectors. Racket and
  5121. Scheme programs tend to allocate many small objects and generate a lot
  5122. of garbage, so copying and generational collectors are a good fit.
  5123. Garbage collection is an active research topic, especially concurrent
  5124. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5125. developing new techniques and revisiting old
  5126. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5127. meet every year at the International Symposium on Memory Management to
  5128. present these findings.
  5129. \subsection{Graph Copying via Cheney's Algorithm}
  5130. \label{sec:cheney}
  5131. \index{Cheney's algorithm}
  5132. Let us take a closer look at the copying of the live objects. The
  5133. allocated objects and pointers can be viewed as a graph and we need to
  5134. copy the part of the graph that is reachable from the root set. To
  5135. make sure we copy all of the reachable vertices in the graph, we need
  5136. an exhaustive graph traversal algorithm, such as depth-first search or
  5137. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5138. such algorithms take into account the possibility of cycles by marking
  5139. which vertices have already been visited, so as to ensure termination
  5140. of the algorithm. These search algorithms also use a data structure
  5141. such as a stack or queue as a to-do list to keep track of the vertices
  5142. that need to be visited. We shall use breadth-first search and a trick
  5143. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5144. and copying tuples into the ToSpace.
  5145. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5146. copy progresses. The queue is represented by a chunk of contiguous
  5147. memory at the beginning of the ToSpace, using two pointers to track
  5148. the front and the back of the queue. The algorithm starts by copying
  5149. all tuples that are immediately reachable from the root set into the
  5150. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5151. old tuple to indicate that it has been visited. We discuss how this
  5152. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5153. pointers inside the copied tuples in the queue still point back to the
  5154. FromSpace. Once the initial queue has been created, the algorithm
  5155. enters a loop in which it repeatedly processes the tuple at the front
  5156. of the queue and pops it off the queue. To process a tuple, the
  5157. algorithm copies all the tuple that are directly reachable from it to
  5158. the ToSpace, placing them at the back of the queue. The algorithm then
  5159. updates the pointers in the popped tuple so they point to the newly
  5160. copied tuples.
  5161. \begin{figure}[tbp]
  5162. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5163. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5164. \label{fig:cheney}
  5165. \end{figure}
  5166. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5167. tuple whose second element is $42$ to the back of the queue. The other
  5168. pointer goes to a tuple that has already been copied, so we do not
  5169. need to copy it again, but we do need to update the pointer to the new
  5170. location. This can be accomplished by storing a \emph{forwarding
  5171. pointer} to the new location in the old tuple, back when we initially
  5172. copied the tuple into the ToSpace. This completes one step of the
  5173. algorithm. The algorithm continues in this way until the front of the
  5174. queue is empty, that is, until the front catches up with the back.
  5175. \subsection{Data Representation}
  5176. \label{sec:data-rep-gc}
  5177. The garbage collector places some requirements on the data
  5178. representations used by our compiler. First, the garbage collector
  5179. needs to distinguish between pointers and other kinds of data. There
  5180. are several ways to accomplish this.
  5181. \begin{enumerate}
  5182. \item Attached a tag to each object that identifies what type of
  5183. object it is~\citep{McCarthy:1960dz}.
  5184. \item Store different types of objects in different
  5185. regions~\citep{Steele:1977ab}.
  5186. \item Use type information from the program to either generate
  5187. type-specific code for collecting or to generate tables that can
  5188. guide the
  5189. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5190. \end{enumerate}
  5191. Dynamically typed languages, such as Lisp, need to tag objects
  5192. anyways, so option 1 is a natural choice for those languages.
  5193. However, $R_3$ is a statically typed language, so it would be
  5194. unfortunate to require tags on every object, especially small and
  5195. pervasive objects like integers and Booleans. Option 3 is the
  5196. best-performing choice for statically typed languages, but comes with
  5197. a relatively high implementation complexity. To keep this chapter
  5198. within a 2-week time budget, we recommend a combination of options 1
  5199. and 2, using separate strategies for the stack and the heap.
  5200. Regarding the stack, we recommend using a separate stack for pointers,
  5201. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5202. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5203. is, when a local variable needs to be spilled and is of type
  5204. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5205. stack instead of the normal procedure call stack. Furthermore, we
  5206. always spill vector-typed variables if they are live during a call to
  5207. the collector, thereby ensuring that no pointers are in registers
  5208. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5209. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5210. the data layout using a root stack. The root stack contains the two
  5211. pointers from the regular stack and also the pointer in the second
  5212. register.
  5213. \begin{figure}[tbp]
  5214. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5215. \caption{Maintaining a root stack to facilitate garbage collection.}
  5216. \label{fig:shadow-stack}
  5217. \end{figure}
  5218. The problem of distinguishing between pointers and other kinds of data
  5219. also arises inside of each tuple on the heap. We solve this problem by
  5220. attaching a tag, an extra 64-bits, to each
  5221. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5222. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5223. that we have drawn the bits in a big-endian way, from right-to-left,
  5224. with bit location 0 (the least significant bit) on the far right,
  5225. which corresponds to the direction of the x86 shifting instructions
  5226. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5227. is dedicated to specifying which elements of the tuple are pointers,
  5228. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5229. indicates there is a pointer and a 0 bit indicates some other kind of
  5230. data. The pointer mask starts at bit location 7. We have limited
  5231. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5232. the pointer mask. The tag also contains two other pieces of
  5233. information. The length of the tuple (number of elements) is stored in
  5234. bits location 1 through 6. Finally, the bit at location 0 indicates
  5235. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5236. value 1, then this tuple has not yet been copied. If the bit has
  5237. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5238. of a pointer are always zero anyways because our tuples are 8-byte
  5239. aligned.)
  5240. \begin{figure}[tbp]
  5241. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5242. \caption{Representation of tuples in the heap.}
  5243. \label{fig:tuple-rep}
  5244. \end{figure}
  5245. \subsection{Implementation of the Garbage Collector}
  5246. \label{sec:organize-gz}
  5247. \index{prelude}
  5248. An implementation of the copying collector is provided in the
  5249. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5250. interface to the garbage collector that is used by the compiler. The
  5251. \code{initialize} function creates the FromSpace, ToSpace, and root
  5252. stack and should be called in the prelude of the \code{main}
  5253. function. The \code{initialize} function puts the address of the
  5254. beginning of the FromSpace into the global variable
  5255. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5256. the address that is 1-past the last element of the FromSpace. (We use
  5257. half-open intervals to represent chunks of
  5258. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5259. points to the first element of the root stack.
  5260. As long as there is room left in the FromSpace, your generated code
  5261. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5262. %
  5263. The amount of room left in FromSpace is the difference between the
  5264. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5265. function should be called when there is not enough room left in the
  5266. FromSpace for the next allocation. The \code{collect} function takes
  5267. a pointer to the current top of the root stack (one past the last item
  5268. that was pushed) and the number of bytes that need to be
  5269. allocated. The \code{collect} function performs the copying collection
  5270. and leaves the heap in a state such that the next allocation will
  5271. succeed.
  5272. \begin{figure}[tbp]
  5273. \begin{lstlisting}
  5274. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5275. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5276. int64_t* free_ptr;
  5277. int64_t* fromspace_begin;
  5278. int64_t* fromspace_end;
  5279. int64_t** rootstack_begin;
  5280. \end{lstlisting}
  5281. \caption{The compiler's interface to the garbage collector.}
  5282. \label{fig:gc-header}
  5283. \end{figure}
  5284. %% \begin{exercise}
  5285. %% In the file \code{runtime.c} you will find the implementation of
  5286. %% \code{initialize} and a partial implementation of \code{collect}.
  5287. %% The \code{collect} function calls another function, \code{cheney},
  5288. %% to perform the actual copy, and that function is left to the reader
  5289. %% to implement. The following is the prototype for \code{cheney}.
  5290. %% \begin{lstlisting}
  5291. %% static void cheney(int64_t** rootstack_ptr);
  5292. %% \end{lstlisting}
  5293. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5294. %% rootstack (which is an array of pointers). The \code{cheney} function
  5295. %% also communicates with \code{collect} through the global
  5296. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5297. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5298. %% the ToSpace:
  5299. %% \begin{lstlisting}
  5300. %% static int64_t* tospace_begin;
  5301. %% static int64_t* tospace_end;
  5302. %% \end{lstlisting}
  5303. %% The job of the \code{cheney} function is to copy all the live
  5304. %% objects (reachable from the root stack) into the ToSpace, update
  5305. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5306. %% update the root stack so that it points to the objects in the
  5307. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5308. %% and ToSpace.
  5309. %% \end{exercise}
  5310. %% \section{Compiler Passes}
  5311. %% \label{sec:code-generation-gc}
  5312. The introduction of garbage collection has a non-trivial impact on our
  5313. compiler passes. We introduce two new compiler passes named
  5314. \code{expose-allocation} and \code{uncover-locals}. We make
  5315. significant changes to \code{select-instructions},
  5316. \code{build-interference}, \code{allocate-registers}, and
  5317. \code{print-x86} and make minor changes in severl more passes. The
  5318. following program will serve as our running example. It creates two
  5319. tuples, one nested inside the other. Both tuples have length one. The
  5320. program accesses the element in the inner tuple tuple via two vector
  5321. references.
  5322. % tests/s2_17.rkt
  5323. \begin{lstlisting}
  5324. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5325. \end{lstlisting}
  5326. \section{Shrink}
  5327. \label{sec:shrink-R3}
  5328. Recall that the \code{shrink} pass translates the primitives operators
  5329. into a smaller set of primitives. Because this pass comes after type
  5330. checking, but before the passes that require the type information in
  5331. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5332. to wrap \code{HasType} around each AST node that it generates.
  5333. \section{Expose Allocation}
  5334. \label{sec:expose-allocation}
  5335. The pass \code{expose-allocation} lowers the \code{vector} creation
  5336. form into a conditional call to the collector followed by the
  5337. allocation. We choose to place the \code{expose-allocation} pass
  5338. before \code{remove-complex-opera*} because the code generated by
  5339. \code{expose-allocation} contains complex operands. We also place
  5340. \code{expose-allocation} before \code{explicate-control} because
  5341. \code{expose-allocation} introduces new variables using \code{let},
  5342. but \code{let} is gone after \code{explicate-control}.
  5343. The output of \code{expose-allocation} is a language $R'_3$ that
  5344. extends $R_3$ with the three new forms that we use in the translation
  5345. of the \code{vector} form.
  5346. \[
  5347. \begin{array}{lcl}
  5348. \Exp &::=& \cdots
  5349. \mid (\key{collect} \,\itm{int})
  5350. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5351. \mid (\key{global-value} \,\itm{name})
  5352. \end{array}
  5353. \]
  5354. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5355. $n$ bytes. It will become a call to the \code{collect} function in
  5356. \code{runtime.c} in \code{select-instructions}. The
  5357. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5358. \index{allocate}
  5359. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5360. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5361. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5362. a global variable, such as \code{free\_ptr}.
  5363. In the following, we show the transformation for the \code{vector}
  5364. form into 1) a sequence of let-bindings for the initializing
  5365. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5366. \code{allocate}, and 4) the initialization of the vector. In the
  5367. following, \itm{len} refers to the length of the vector and
  5368. \itm{bytes} is how many total bytes need to be allocated for the
  5369. vector, which is 8 for the tag plus \itm{len} times 8.
  5370. \begin{lstlisting}
  5371. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5372. |$\Longrightarrow$|
  5373. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5374. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5375. (global-value fromspace_end))
  5376. (void)
  5377. (collect |\itm{bytes}|))])
  5378. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5379. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5380. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5381. |$v$|) ... )))) ...)
  5382. \end{lstlisting}
  5383. In the above, we suppressed all of the \code{has-type} forms in the
  5384. output for the sake of readability. The placement of the initializing
  5385. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5386. sequence of \code{vector-set!} is important, as those expressions may
  5387. trigger garbage collection and we cannot have an allocated but
  5388. uninitialized tuple on the heap during a collection.
  5389. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5390. \code{expose-allocation} pass on our running example.
  5391. \begin{figure}[tbp]
  5392. % tests/s2_17.rkt
  5393. \begin{lstlisting}
  5394. (vector-ref
  5395. (vector-ref
  5396. (let ([vecinit7976
  5397. (let ([vecinit7972 42])
  5398. (let ([collectret7974
  5399. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5400. (void)
  5401. (collect 16)
  5402. )])
  5403. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5404. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5405. alloc7971)
  5406. )
  5407. )
  5408. )
  5409. ])
  5410. (let ([collectret7978
  5411. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5412. (void)
  5413. (collect 16)
  5414. )])
  5415. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5416. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5417. alloc7975)
  5418. )
  5419. )
  5420. )
  5421. 0)
  5422. 0)
  5423. \end{lstlisting}
  5424. \caption{Output of the \code{expose-allocation} pass, minus
  5425. all of the \code{has-type} forms.}
  5426. \label{fig:expose-alloc-output}
  5427. \end{figure}
  5428. \section{Remove Complex Operands}
  5429. \label{sec:remove-complex-opera-R3}
  5430. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5431. should all be treated as complex operands. A new case for
  5432. \code{HasType} is needed and the case for \code{Prim} needs to be
  5433. handled carefully to prevent the \code{Prim} node from being separated
  5434. from its enclosing \code{HasType}.
  5435. \section{Explicate Control and the $C_2$ language}
  5436. \label{sec:explicate-control-r3}
  5437. \begin{figure}[tbp]
  5438. \fbox{
  5439. \begin{minipage}{0.96\textwidth}
  5440. \small
  5441. \[
  5442. \begin{array}{lcl}
  5443. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5444. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5445. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5446. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5447. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5448. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5449. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5450. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5451. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5452. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5453. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5454. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5455. \end{array}
  5456. \]
  5457. \end{minipage}
  5458. }
  5459. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5460. \label{fig:c2-concrete-syntax}
  5461. \end{figure}
  5462. \begin{figure}[tp]
  5463. \fbox{
  5464. \begin{minipage}{0.96\textwidth}
  5465. \small
  5466. \[
  5467. \begin{array}{lcl}
  5468. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5469. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5470. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5471. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5472. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5473. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5474. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  5475. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  5476. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5477. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5478. \mid (\key{Collect} \,\itm{int}) \\
  5479. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5480. \mid \GOTO{\itm{label}} } \\
  5481. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5482. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5483. \end{array}
  5484. \]
  5485. \end{minipage}
  5486. }
  5487. \caption{The abstract syntax of $C_2$, extending $C_1$
  5488. (Figure~\ref{fig:c1-syntax}).}
  5489. \label{fig:c2-syntax}
  5490. \end{figure}
  5491. The output of \code{explicate-control} is a program in the
  5492. intermediate language $C_2$, whose concrete syntax is defined in
  5493. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5494. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5495. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5496. \key{global-value} expressions and the \code{collect} statement. The
  5497. \code{explicate-control} pass can treat these new forms much like the
  5498. other forms.
  5499. \section{Uncover Locals}
  5500. \label{sec:uncover-locals-r3}
  5501. Recall that the \code{explicate-control} function collects all of the
  5502. local variables so that it can store them in the $\itm{info}$ field of
  5503. the \code{Program} structure. Also recall that we need to know the
  5504. types of all the local variables for purposes of identifying the root
  5505. set for the garbage collector. Thus, we create a pass named
  5506. \code{uncover-locals} to collect not just the variables but the
  5507. variables and their types in the form of an alist. Thanks to the
  5508. \code{HasType} nodes, the types are readily available at every
  5509. assignment to a variable. We recommend storing the resulting alist in
  5510. the $\itm{info}$ field of the program, associated with the
  5511. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5512. of the \code{uncover-locals} pass on the running example.
  5513. \begin{figure}[tbp]
  5514. % tests/s2_17.rkt
  5515. \begin{lstlisting}
  5516. locals:
  5517. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5518. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5519. collectret7974 : 'Void, initret7977 : 'Void,
  5520. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5521. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5522. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5523. vecinit7972 : 'Integer, initret7973 : 'Void,
  5524. block91:
  5525. (collect 16)
  5526. goto block89;
  5527. block90:
  5528. collectret7974 = (void);
  5529. goto block89;
  5530. block89:
  5531. alloc7971 = (allocate 1 (Vector Integer));
  5532. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5533. vecinit7976 = alloc7971;
  5534. tmp7982 = (global-value free_ptr);
  5535. tmp7983 = (+ tmp7982 16);
  5536. tmp7984 = (global-value fromspace_end);
  5537. if (< tmp7983 tmp7984) then
  5538. goto block87;
  5539. else
  5540. goto block88;
  5541. block88:
  5542. (collect 16)
  5543. goto block86;
  5544. block87:
  5545. collectret7978 = (void);
  5546. goto block86;
  5547. block86:
  5548. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5549. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5550. tmp7985 = (vector-ref alloc7975 0);
  5551. return (vector-ref tmp7985 0);
  5552. start:
  5553. vecinit7972 = 42;
  5554. tmp7979 = (global-value free_ptr);
  5555. tmp7980 = (+ tmp7979 16);
  5556. tmp7981 = (global-value fromspace_end);
  5557. if (< tmp7980 tmp7981) then
  5558. goto block90;
  5559. else
  5560. goto block91;
  5561. \end{lstlisting}
  5562. \caption{Output of \code{uncover-locals} for the running example.}
  5563. \label{fig:uncover-locals-r3}
  5564. \end{figure}
  5565. \clearpage
  5566. \section{Select Instructions and the x86$_2$ Language}
  5567. \label{sec:select-instructions-gc}
  5568. \index{instruction selection}
  5569. %% void (rep as zero)
  5570. %% allocate
  5571. %% collect (callq collect)
  5572. %% vector-ref
  5573. %% vector-set!
  5574. %% global (postpone)
  5575. In this pass we generate x86 code for most of the new operations that
  5576. were needed to compile tuples, including \code{Allocate},
  5577. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5578. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5579. the later has a different concrete syntax (see
  5580. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5581. \index{x86}
  5582. The \code{vector-ref} and \code{vector-set!} forms translate into
  5583. \code{movq} instructions. (The plus one in the offset is to get past
  5584. the tag at the beginning of the tuple representation.)
  5585. \begin{lstlisting}
  5586. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5587. |$\Longrightarrow$|
  5588. movq |$\itm{vec}'$|, %r11
  5589. movq |$-8(n+1)$|(%r11), |$\itm{lhs'}$|
  5590. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5591. |$\Longrightarrow$|
  5592. movq |$\itm{vec}'$|, %r11
  5593. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5594. movq $0, |$\itm{lhs'}$|
  5595. \end{lstlisting}
  5596. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5597. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5598. register \code{r11} ensures that offset expression
  5599. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5600. removing \code{r11} from consideration by the register allocating.
  5601. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5602. \code{rax}. Then the generated code for \code{vector-set!} would be
  5603. \begin{lstlisting}
  5604. movq |$\itm{vec}'$|, %rax
  5605. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5606. movq $0, |$\itm{lhs}'$|
  5607. \end{lstlisting}
  5608. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5609. \code{patch-instructions} would insert a move through \code{rax}
  5610. as follows.
  5611. \begin{lstlisting}
  5612. movq |$\itm{vec}'$|, %rax
  5613. movq |$\itm{arg}'$|, %rax
  5614. movq %rax, |$8(n+1)$|(%rax)
  5615. movq $0, |$\itm{lhs}'$|
  5616. \end{lstlisting}
  5617. But the above sequence of instructions does not work because we're
  5618. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5619. $\itm{arg}'$) at the same time!
  5620. We compile the \code{allocate} form to operations on the
  5621. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5622. is the next free address in the FromSpace, so we move it into the
  5623. \itm{lhs} and then move it forward by enough space for the tuple being
  5624. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5625. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5626. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5627. how the tag is organized. We recommend using the Racket operations
  5628. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5629. during compilation. The type annotation in the \code{vector} form is
  5630. used to determine the pointer mask region of the tag.
  5631. \begin{lstlisting}
  5632. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5633. |$\Longrightarrow$|
  5634. movq free_ptr(%rip), |$\itm{lhs}'$|
  5635. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5636. movq |$\itm{lhs}'$|, %r11
  5637. movq $|$\itm{tag}$|, 0(%r11)
  5638. \end{lstlisting}
  5639. The \code{collect} form is compiled to a call to the \code{collect}
  5640. function in the runtime. The arguments to \code{collect} are 1) the
  5641. top of the root stack and 2) the number of bytes that need to be
  5642. allocated. We shall use another dedicated register, \code{r15}, to
  5643. store the pointer to the top of the root stack. So \code{r15} is not
  5644. available for use by the register allocator.
  5645. \begin{lstlisting}
  5646. (collect |$\itm{bytes}$|)
  5647. |$\Longrightarrow$|
  5648. movq %r15, %rdi
  5649. movq $|\itm{bytes}|, %rsi
  5650. callq collect
  5651. \end{lstlisting}
  5652. \begin{figure}[tp]
  5653. \fbox{
  5654. \begin{minipage}{0.96\textwidth}
  5655. \[
  5656. \begin{array}{lcl}
  5657. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5658. x86_1 &::= & \gray{ \key{.globl main} }\\
  5659. & & \gray{ \key{main:} \; \Instr\ldots }
  5660. \end{array}
  5661. \]
  5662. \end{minipage}
  5663. }
  5664. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5665. \label{fig:x86-2-concrete}
  5666. \end{figure}
  5667. \begin{figure}[tp]
  5668. \fbox{
  5669. \begin{minipage}{0.96\textwidth}
  5670. \small
  5671. \[
  5672. \begin{array}{lcl}
  5673. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5674. \mid \BYTEREG{\Reg}} \\
  5675. &\mid& (\key{Global}~\Var) \\
  5676. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5677. \end{array}
  5678. \]
  5679. \end{minipage}
  5680. }
  5681. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5682. \label{fig:x86-2}
  5683. \end{figure}
  5684. The concrete and abstract syntax of the $x86_2$ language is defined in
  5685. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5686. x86$_1$ just in the addition of the form for global variables.
  5687. %
  5688. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5689. \code{select-instructions} pass on the running example.
  5690. \begin{figure}[tbp]
  5691. \centering
  5692. % tests/s2_17.rkt
  5693. \begin{minipage}[t]{0.5\textwidth}
  5694. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5695. block35:
  5696. movq free_ptr(%rip), alloc9024
  5697. addq $16, free_ptr(%rip)
  5698. movq alloc9024, %r11
  5699. movq $131, 0(%r11)
  5700. movq alloc9024, %r11
  5701. movq vecinit9025, 8(%r11)
  5702. movq $0, initret9026
  5703. movq alloc9024, %r11
  5704. movq 8(%r11), tmp9034
  5705. movq tmp9034, %r11
  5706. movq 8(%r11), %rax
  5707. jmp conclusion
  5708. block36:
  5709. movq $0, collectret9027
  5710. jmp block35
  5711. block38:
  5712. movq free_ptr(%rip), alloc9020
  5713. addq $16, free_ptr(%rip)
  5714. movq alloc9020, %r11
  5715. movq $3, 0(%r11)
  5716. movq alloc9020, %r11
  5717. movq vecinit9021, 8(%r11)
  5718. movq $0, initret9022
  5719. movq alloc9020, vecinit9025
  5720. movq free_ptr(%rip), tmp9031
  5721. movq tmp9031, tmp9032
  5722. addq $16, tmp9032
  5723. movq fromspace_end(%rip), tmp9033
  5724. cmpq tmp9033, tmp9032
  5725. jl block36
  5726. jmp block37
  5727. block37:
  5728. movq %r15, %rdi
  5729. movq $16, %rsi
  5730. callq 'collect
  5731. jmp block35
  5732. block39:
  5733. movq $0, collectret9023
  5734. jmp block38
  5735. \end{lstlisting}
  5736. \end{minipage}
  5737. \begin{minipage}[t]{0.45\textwidth}
  5738. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5739. start:
  5740. movq $42, vecinit9021
  5741. movq free_ptr(%rip), tmp9028
  5742. movq tmp9028, tmp9029
  5743. addq $16, tmp9029
  5744. movq fromspace_end(%rip), tmp9030
  5745. cmpq tmp9030, tmp9029
  5746. jl block39
  5747. jmp block40
  5748. block40:
  5749. movq %r15, %rdi
  5750. movq $16, %rsi
  5751. callq 'collect
  5752. jmp block38
  5753. \end{lstlisting}
  5754. \end{minipage}
  5755. \caption{Output of the \code{select-instructions} pass.}
  5756. \label{fig:select-instr-output-gc}
  5757. \end{figure}
  5758. \clearpage
  5759. \section{Register Allocation}
  5760. \label{sec:reg-alloc-gc}
  5761. \index{register allocation}
  5762. As discussed earlier in this chapter, the garbage collector needs to
  5763. access all the pointers in the root set, that is, all variables that
  5764. are vectors. It will be the responsibility of the register allocator
  5765. to make sure that:
  5766. \begin{enumerate}
  5767. \item the root stack is used for spilling vector-typed variables, and
  5768. \item if a vector-typed variable is live during a call to the
  5769. collector, it must be spilled to ensure it is visible to the
  5770. collector.
  5771. \end{enumerate}
  5772. The later responsibility can be handled during construction of the
  5773. inference graph, by adding interference edges between the call-live
  5774. vector-typed variables and all the callee-saved registers. (They
  5775. already interfere with the caller-saved registers.) The type
  5776. information for variables is in the \code{Program} form, so we
  5777. recommend adding another parameter to the \code{build-interference}
  5778. function to communicate this alist.
  5779. The spilling of vector-typed variables to the root stack can be
  5780. handled after graph coloring, when choosing how to assign the colors
  5781. (integers) to registers and stack locations. The \code{Program} output
  5782. of this pass changes to also record the number of spills to the root
  5783. stack.
  5784. % build-interference
  5785. %
  5786. % callq
  5787. % extra parameter for var->type assoc. list
  5788. % update 'program' and 'if'
  5789. % allocate-registers
  5790. % allocate spilled vectors to the rootstack
  5791. % don't change color-graph
  5792. \section{Print x86}
  5793. \label{sec:print-x86-gc}
  5794. \index{prelude}\index{conclusion}
  5795. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5796. \code{print-x86} pass on the running example. In the prelude and
  5797. conclusion of the \code{main} function, we treat the root stack very
  5798. much like the regular stack in that we move the root stack pointer
  5799. (\code{r15}) to make room for the spills to the root stack, except
  5800. that the root stack grows up instead of down. For the running
  5801. example, there was just one spill so we increment \code{r15} by 8
  5802. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5803. One issue that deserves special care is that there may be a call to
  5804. \code{collect} prior to the initializing assignments for all the
  5805. variables in the root stack. We do not want the garbage collector to
  5806. accidentally think that some uninitialized variable is a pointer that
  5807. needs to be followed. Thus, we zero-out all locations on the root
  5808. stack in the prelude of \code{main}. In
  5809. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5810. %
  5811. \lstinline{movq $0, (%r15)}
  5812. %
  5813. accomplishes this task. The garbage collector tests each root to see
  5814. if it is null prior to dereferencing it.
  5815. \begin{figure}[htbp]
  5816. \begin{minipage}[t]{0.5\textwidth}
  5817. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5818. block35:
  5819. movq free_ptr(%rip), %rcx
  5820. addq $16, free_ptr(%rip)
  5821. movq %rcx, %r11
  5822. movq $131, 0(%r11)
  5823. movq %rcx, %r11
  5824. movq -8(%r15), %rax
  5825. movq %rax, 8(%r11)
  5826. movq $0, %rdx
  5827. movq %rcx, %r11
  5828. movq 8(%r11), %rcx
  5829. movq %rcx, %r11
  5830. movq 8(%r11), %rax
  5831. jmp conclusion
  5832. block36:
  5833. movq $0, %rcx
  5834. jmp block35
  5835. block38:
  5836. movq free_ptr(%rip), %rcx
  5837. addq $16, free_ptr(%rip)
  5838. movq %rcx, %r11
  5839. movq $3, 0(%r11)
  5840. movq %rcx, %r11
  5841. movq %rbx, 8(%r11)
  5842. movq $0, %rdx
  5843. movq %rcx, -8(%r15)
  5844. movq free_ptr(%rip), %rcx
  5845. addq $16, %rcx
  5846. movq fromspace_end(%rip), %rdx
  5847. cmpq %rdx, %rcx
  5848. jl block36
  5849. movq %r15, %rdi
  5850. movq $16, %rsi
  5851. callq collect
  5852. jmp block35
  5853. block39:
  5854. movq $0, %rcx
  5855. jmp block38
  5856. \end{lstlisting}
  5857. \end{minipage}
  5858. \begin{minipage}[t]{0.45\textwidth}
  5859. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5860. start:
  5861. movq $42, %rbx
  5862. movq free_ptr(%rip), %rdx
  5863. addq $16, %rdx
  5864. movq fromspace_end(%rip), %rcx
  5865. cmpq %rcx, %rdx
  5866. jl block39
  5867. movq %r15, %rdi
  5868. movq $16, %rsi
  5869. callq collect
  5870. jmp block38
  5871. .globl main
  5872. main:
  5873. pushq %rbp
  5874. movq %rsp, %rbp
  5875. pushq %r13
  5876. pushq %r12
  5877. pushq %rbx
  5878. pushq %r14
  5879. subq $0, %rsp
  5880. movq $16384, %rdi
  5881. movq $16, %rsi
  5882. callq initialize
  5883. movq rootstack_begin(%rip), %r15
  5884. movq $0, (%r15)
  5885. addq $8, %r15
  5886. jmp start
  5887. conclusion:
  5888. subq $8, %r15
  5889. addq $0, %rsp
  5890. popq %r14
  5891. popq %rbx
  5892. popq %r12
  5893. popq %r13
  5894. popq %rbp
  5895. retq
  5896. \end{lstlisting}
  5897. \end{minipage}
  5898. \caption{Output of the \code{print-x86} pass.}
  5899. \label{fig:print-x86-output-gc}
  5900. \end{figure}
  5901. \begin{figure}[p]
  5902. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5903. \node (R3) at (0,2) {\large $R_3$};
  5904. \node (R3-2) at (3,2) {\large $R_3$};
  5905. \node (R3-3) at (6,2) {\large $R_3$};
  5906. \node (R3-4) at (9,2) {\large $R_3$};
  5907. \node (R3-5) at (9,0) {\large $R'_3$};
  5908. \node (R3-6) at (6,0) {\large $R'_3$};
  5909. \node (C2-4) at (3,-2) {\large $C_2$};
  5910. \node (C2-3) at (0,-2) {\large $C_2$};
  5911. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5912. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5913. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5914. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5915. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5916. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5917. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5918. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5919. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5920. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5921. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5922. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5923. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5924. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5925. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5926. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5927. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5928. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5929. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5930. \end{tikzpicture}
  5931. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5932. \label{fig:R3-passes}
  5933. \end{figure}
  5934. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5935. for the compilation of $R_3$.
  5936. \section{Challenge: Simple Structures}
  5937. \label{sec:simple-structures}
  5938. \index{struct}
  5939. \index{structure}
  5940. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  5941. $R^s_3$, which extends $R^3$ with support for simple structures.
  5942. Recall that a \code{struct} in Typed Racket is a user-defined data
  5943. type that contains named fields and that is heap allocated, similar to
  5944. a vector. The following is an example of a structure definition, in
  5945. this case the definition of a \code{point} type.
  5946. \begin{lstlisting}
  5947. (struct point ([x : Integer] [y : Integer]) #:mutable)
  5948. \end{lstlisting}
  5949. \begin{figure}[tbp]
  5950. \centering
  5951. \fbox{
  5952. \begin{minipage}{0.96\textwidth}
  5953. \[
  5954. \begin{array}{lcl}
  5955. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5956. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  5957. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5958. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  5959. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  5960. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5961. \mid (\key{and}\;\Exp\;\Exp)
  5962. \mid (\key{or}\;\Exp\;\Exp)
  5963. \mid (\key{not}\;\Exp) } \\
  5964. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5965. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  5966. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  5967. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  5968. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  5969. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  5970. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  5971. R_3 &::=& \Def \ldots \; \Exp
  5972. \end{array}
  5973. \]
  5974. \end{minipage}
  5975. }
  5976. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  5977. (Figure~\ref{fig:r3-concrete-syntax}).}
  5978. \label{fig:r3s-concrete-syntax}
  5979. \end{figure}
  5980. An instance of a structure is created using function call syntax, with
  5981. the name of the structure in the function position:
  5982. \begin{lstlisting}
  5983. (point 7 12)
  5984. \end{lstlisting}
  5985. Function-call syntax is also used to read the value in a field of a
  5986. structure. The function name is formed by the structure name, a dash,
  5987. and the field name. The following example uses \code{point-x} and
  5988. \code{point-y} to access the \code{x} and \code{y} fields of two point
  5989. instances.
  5990. \begin{center}
  5991. \begin{lstlisting}
  5992. (let ([pt1 (point 7 12)])
  5993. (let ([pt2 (point 4 3)])
  5994. (+ (- (point-x pt1) (point-x pt2))
  5995. (- (point-y pt1) (point-y pt2)))))
  5996. \end{lstlisting}
  5997. \end{center}
  5998. Similarly, to write to a field of a structure, use its set function,
  5999. whose name starts with \code{set-}, followed by the structure name,
  6000. then a dash, then the field name, and conclused with an exclamation
  6001. mark. The folowing example uses \code{set-point-x!} to change the
  6002. \code{x} field from \code{7} to \code{42}.
  6003. \begin{center}
  6004. \begin{lstlisting}
  6005. (let ([pt (point 7 12)])
  6006. (let ([_ (set-point-x! pt 42)])
  6007. (point-x pt)))
  6008. \end{lstlisting}
  6009. \end{center}
  6010. \begin{exercise}\normalfont
  6011. Extend your compiler with support for simple structures, compiling
  6012. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6013. structures and test your compiler.
  6014. \end{exercise}
  6015. \section{Challenge: Generational Collection}
  6016. The copying collector described in Section~\ref{sec:GC} can incur
  6017. significant runtime overhead because the call to \code{collect} takes
  6018. time proportional to all of the live data. One way to reduce this
  6019. overhead is to reduce how much data is inspected in each call to
  6020. \code{collect}. In particular, researchers have observed that recently
  6021. allocated data is more likely to become garbage then data that has
  6022. survived one or more previous calls to \code{collect}. This insight
  6023. motivated the creation of \emph{generational garbage collectors}
  6024. \index{generational garbage collector} that
  6025. 1) segragates data according to its age into two or more generations,
  6026. 2) allocates less space for younger generations, so collecting them is
  6027. faster, and more space for the older generations, and 3) performs
  6028. collection on the younger generations more frequently then for older
  6029. generations~\citep{Wilson:1992fk}.
  6030. For this challenge assignment, the goal is to adapt the copying
  6031. collector implemented in \code{runtime.c} to use two generations, one
  6032. for young data and one for old data. Each generation consists of a
  6033. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6034. \code{collect} function to use the two generations.
  6035. \begin{enumerate}
  6036. \item Copy the young generation's FromSpace to its ToSpace then switch
  6037. the role of the ToSpace and FromSpace
  6038. \item If there is enough space for the requested number of bytes in
  6039. the young FromSpace, then return from \code{collect}.
  6040. \item If there is not enough space in the young FromSpace for the
  6041. requested bytes, then move the data from the young generation to the
  6042. old one with the following steps:
  6043. \begin{enumerate}
  6044. \item If there is enough room in the old FromSpace, copy the young
  6045. FromSpace to the old FromSpace and then return.
  6046. \item If there is not enough room in the old FromSpace, then collect
  6047. the old generation by copying the old FromSpace to the old ToSpace
  6048. and swap the roles of the old FromSpace and ToSpace.
  6049. \item If there is enough room now, copy the young FromSpace to the
  6050. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6051. and ToSpace for the old generation. Copy the young FromSpace and
  6052. the old FromSpace into the larger FromSpace for the old
  6053. generation and then return.
  6054. \end{enumerate}
  6055. \end{enumerate}
  6056. We recommend that you generalize the \code{cheney} function so that it
  6057. can be used for all the copies mentioned above: between the young
  6058. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6059. between the young FromSpace and old FromSpace. This can be
  6060. accomplished by adding parameters to \code{cheney} that replace its
  6061. use of the global variables \code{fromspace\_begin},
  6062. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6063. Note that the collection of the young generation does not traverse the
  6064. old generation. This introduces a potential problem: there may be
  6065. young data that is only reachable through pointers in the old
  6066. generation. If these pointers are not taken into account, the
  6067. collector could throw away young data that is live! One solution,
  6068. called \emph{pointer recording}, is to maintain a set of all the
  6069. pointers from the old generation into the new generation and consider
  6070. this set as part of the root set. To maintain this set, the compiler
  6071. must insert extra instructions around every \code{vector-set!}. If the
  6072. vector being modified is in the old generation, and if the value being
  6073. written is a pointer into the new generation, than that pointer must
  6074. be added to the set. Also, if the value being overwritten was a
  6075. pointer into the new generation, then that pointer should be removed
  6076. from the set.
  6077. \begin{exercise}\normalfont
  6078. Adapt the \code{collect} function in \code{runtime.c} to implement
  6079. generational garbage collection, as outlined in this section.
  6080. Update the code generation for \code{vector-set!} to implement
  6081. pointer recording. Make sure that your new compiler and runtime
  6082. passes your test suite.
  6083. \end{exercise}
  6084. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6085. \chapter{Functions}
  6086. \label{ch:functions}
  6087. \index{function}
  6088. This chapter studies the compilation of functions similar to those
  6089. found in the C language. This corresponds to a subset of Typed Racket
  6090. in which only top-level function definitions are allowed. This kind of
  6091. function is an important stepping stone to implementing
  6092. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6093. is the topic of Chapter~\ref{ch:lambdas}.
  6094. \section{The $R_4$ Language}
  6095. The concrete and abstract syntax for function definitions and function
  6096. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6097. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6098. $R_4$ begin with zero or more function definitions. The function
  6099. names from these definitions are in-scope for the entire program,
  6100. including all other function definitions (so the ordering of function
  6101. definitions does not matter). The concrete syntax for function
  6102. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6103. where the first expression must
  6104. evaluate to a function and the rest are the arguments.
  6105. The abstract syntax for function application is
  6106. $\APPLY{\Exp}{\Exp\ldots}$.
  6107. %% The syntax for function application does not include an explicit
  6108. %% keyword, which is error prone when using \code{match}. To alleviate
  6109. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6110. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6111. Functions are first-class in the sense that a function pointer
  6112. \index{function pointer} is data and can be stored in memory or passed
  6113. as a parameter to another function. Thus, we introduce a function
  6114. type, written
  6115. \begin{lstlisting}
  6116. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6117. \end{lstlisting}
  6118. for a function whose $n$ parameters have the types $\Type_1$ through
  6119. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6120. these functions (with respect to Racket functions) is that they are
  6121. not lexically scoped. That is, the only external entities that can be
  6122. referenced from inside a function body are other globally-defined
  6123. functions. The syntax of $R_4$ prevents functions from being nested
  6124. inside each other.
  6125. \begin{figure}[tp]
  6126. \centering
  6127. \fbox{
  6128. \begin{minipage}{0.96\textwidth}
  6129. \small
  6130. \[
  6131. \begin{array}{lcl}
  6132. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6133. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6134. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6135. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  6136. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  6137. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6138. \mid (\key{and}\;\Exp\;\Exp)
  6139. \mid (\key{or}\;\Exp\;\Exp)
  6140. \mid (\key{not}\;\Exp)} \\
  6141. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6142. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6143. (\key{vector-ref}\;\Exp\;\Int)} \\
  6144. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6145. \mid (\key{has-type}~\Exp~\Type)} \\
  6146. &\mid& (\Exp \; \Exp \ldots) \\
  6147. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp) \\
  6148. R_4 &::=& \Def \ldots \; \Exp
  6149. \end{array}
  6150. \]
  6151. \end{minipage}
  6152. }
  6153. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6154. \label{fig:r4-concrete-syntax}
  6155. \end{figure}
  6156. \begin{figure}[tp]
  6157. \centering
  6158. \fbox{
  6159. \begin{minipage}{0.96\textwidth}
  6160. \small
  6161. \[
  6162. \begin{array}{lcl}
  6163. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6164. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6165. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6166. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6167. &\mid& \gray{ \BOOL{\itm{bool}}
  6168. \mid \AND{\Exp}{\Exp} }\\
  6169. &\mid& \gray{ \OR{\Exp}{\Exp}
  6170. \mid \NOT{\Exp} } \\
  6171. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6172. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6173. &\mid& \gray{ \VECTOR{\Exp} } \\
  6174. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  6175. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  6176. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6177. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6178. \Def &::=& \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp}\\
  6179. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp}
  6180. \end{array}
  6181. \]
  6182. \end{minipage}
  6183. }
  6184. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6185. \label{fig:r4-syntax}
  6186. \end{figure}
  6187. The program in Figure~\ref{fig:r4-function-example} is a
  6188. representative example of defining and using functions in $R_4$. We
  6189. define a function \code{map-vec} that applies some other function
  6190. \code{f} to both elements of a vector and returns a new
  6191. vector containing the results. We also define a function \code{add1}.
  6192. The program applies
  6193. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6194. \code{(vector 1 42)}, from which we return the \code{42}.
  6195. \begin{figure}[tbp]
  6196. \begin{lstlisting}
  6197. (define (map-vec [f : (Integer -> Integer)]
  6198. [v : (Vector Integer Integer)])
  6199. : (Vector Integer Integer)
  6200. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6201. (define (add1 [x : Integer]) : Integer
  6202. (+ x 1))
  6203. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6204. \end{lstlisting}
  6205. \caption{Example of using functions in $R_4$.}
  6206. \label{fig:r4-function-example}
  6207. \end{figure}
  6208. The definitional interpreter for $R_4$ is in
  6209. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6210. responsible for setting up the mutual recursion between the top-level
  6211. function definitions. We use the classic back-patching \index{back-patching}
  6212. approach that uses mutable variables and makes two passes over the function
  6213. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6214. top-level environment using a mutable cons cell for each function
  6215. definition. Note that the \code{lambda} value for each function is
  6216. incomplete; it does not yet include the environment. Once the
  6217. top-level environment is constructed, we then iterate over it and
  6218. update the \code{lambda} values to use the top-level environment.
  6219. \begin{figure}[tp]
  6220. \begin{lstlisting}
  6221. (define (interp-exp env)
  6222. (lambda (e)
  6223. (define recur (interp-exp env))
  6224. (match e
  6225. ...
  6226. [(Apply fun args)
  6227. (define fun-val (recur fun))
  6228. (define arg-vals (for/list ([e args]) (recur e)))
  6229. (match fun-val
  6230. [`(lambda (,xs ...) ,body ,fun-env)
  6231. (define new-env (append (map cons xs arg-vals) fun-env))
  6232. ((interp-exp new-env) body)])]
  6233. ...
  6234. )))
  6235. (define (interp-def d)
  6236. (match d
  6237. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6238. (mcons f `(lambda ,xs ,body ()))]
  6239. ))
  6240. (define (interp-R4 p)
  6241. (match p
  6242. [(ProgramDefsExp info ds body)
  6243. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6244. (for/list ([b top-level])
  6245. (set-mcdr! b (match (mcdr b)
  6246. [`(lambda ,xs ,body ())
  6247. `(lambda ,xs ,body ,top-level)])))
  6248. ((interp-exp top-level) body))]
  6249. ))
  6250. \end{lstlisting}
  6251. \caption{Interpreter for the $R_4$ language.}
  6252. \label{fig:interp-R4}
  6253. \end{figure}
  6254. \margincomment{TODO: explain type checker}
  6255. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6256. \begin{figure}[tp]
  6257. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6258. (define (fun-def-name d)
  6259. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6260. (define (fun-def-type d)
  6261. (match d
  6262. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6263. (define (type-check-exp env)
  6264. (lambda (e)
  6265. (match e
  6266. ...
  6267. [(Apply e es)
  6268. (define-values (e^ ty) ((type-check-exp env) e))
  6269. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6270. ((type-check-exp env) e)))
  6271. (match ty
  6272. [`(,ty^* ... -> ,rt)
  6273. (for ([arg-ty ty*] [prm-ty ty^*])
  6274. (unless (equal? arg-ty prm-ty)
  6275. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6276. (values (HasType (Apply e^ e*) rt) rt)]
  6277. [else (error "expected a function, not" ty)])])))
  6278. (define (type-check-def env)
  6279. (lambda (e)
  6280. (match e
  6281. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6282. (define new-env (append (map cons xs ps) env))
  6283. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6284. (unless (equal? ty^ rt)
  6285. (error "body type ~a not equal to return type ~a" ty^ rt))
  6286. (Def f p:t* rt info body^)])))
  6287. (define (type-check env)
  6288. (lambda (e)
  6289. (match e
  6290. [(ProgramDefsExp info ds body)
  6291. (define new-env (for/list ([d ds])
  6292. (cons (fun-def-name d) (fun-def-type d))))
  6293. (define ds^ (for/list ([d ds])
  6294. ((type-check-def new-env) d)))
  6295. (define-values (body^ ty) ((type-check-exp new-env) body))
  6296. (unless (equal? ty 'Integer)
  6297. (error "result of the program must be an integer, not " ty))
  6298. (ProgramDefsExp info ds^ body^)]
  6299. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6300. \end{lstlisting}
  6301. \caption{Type checker for the $R_4$ language.}
  6302. \label{fig:type-check-R4}
  6303. \end{figure}
  6304. \section{Functions in x86}
  6305. \label{sec:fun-x86}
  6306. \margincomment{\tiny Make sure callee-saved registers are discussed
  6307. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6308. \margincomment{\tiny Talk about the return address on the
  6309. stack and what callq and retq does.\\ --Jeremy }
  6310. The x86 architecture provides a few features to support the
  6311. implementation of functions. We have already seen that x86 provides
  6312. labels so that one can refer to the location of an instruction, as is
  6313. needed for jump instructions. Labels can also be used to mark the
  6314. beginning of the instructions for a function. Going further, we can
  6315. obtain the address of a label by using the \key{leaq} instruction and
  6316. PC-relative addressing. For example, the following puts the
  6317. address of the \code{add1} label into the \code{rbx} register.
  6318. \begin{lstlisting}
  6319. leaq add1(%rip), %rbx
  6320. \end{lstlisting}
  6321. The instruction pointer register \key{rip} (aka. the program counter
  6322. \index{program counter}) always points to the next instruction to be
  6323. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6324. linker computes the distance $d$ between the address of \code{add1}
  6325. and where the \code{rip} would be at that moment and then changes
  6326. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6327. the address of \code{add1}.
  6328. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6329. jump to a function whose location is given by a label. To support
  6330. function calls in this chapter we instead will be jumping to a
  6331. function whose location is given by an address in a register, that is,
  6332. we need to make an \emph{indirect function call}. The x86 syntax for
  6333. this is a \code{callq} instruction but with an asterisk before the
  6334. register name.\index{indirect function call}
  6335. \begin{lstlisting}
  6336. callq *%rbx
  6337. \end{lstlisting}
  6338. \subsection{Calling Conventions}
  6339. \index{calling conventions}
  6340. The \code{callq} instruction provides partial support for implementing
  6341. functions: it pushes the return address on the stack and it jumps to
  6342. the target. However, \code{callq} does not handle
  6343. \begin{enumerate}
  6344. \item parameter passing,
  6345. \item pushing frames on the procedure call stack and popping them off,
  6346. or
  6347. \item determining how registers are shared by different functions.
  6348. \end{enumerate}
  6349. These issues require coordination between the caller and the callee,
  6350. which is often assembly code written by different programmers or
  6351. generated by different compilers. As a result, people have developed
  6352. \emph{conventions} that govern how functions calls are performed.
  6353. Here we use conventions that are compatible with those of the
  6354. \code{gcc} compiler~\citep{Matz:2013aa}.
  6355. Regarding (1) parameter passing, the convention is to use the
  6356. following six registers:
  6357. \begin{lstlisting}
  6358. rdi rsi rdx rcx r8 r9
  6359. \end{lstlisting}
  6360. in that order, to pass arguments to a function. If there are more than
  6361. six arguments, then the convention is to use space on the frame of the
  6362. caller for the rest of the arguments. However, to ease the
  6363. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  6364. we arrange to never need more than six arguments.
  6365. %
  6366. The register \code{rax} is for the return value of the function.
  6367. \index{prelude}\index{conclusion}
  6368. Regarding (2) frames \index{frame} and the procedure call stack
  6369. \index{procedure call stack}, recall from Section~\ref{sec:x86} that
  6370. the stack grows down, with each function call using a chunk of space
  6371. called a frame. The caller sets the stack pointer, register
  6372. \code{rsp}, to the last data item in its frame. The callee must not
  6373. change anything in the caller's frame, that is, anything that is at or
  6374. above the stack pointer. The callee is free to use locations that are
  6375. below the stack pointer.
  6376. Recall that we are storing variables of vector type on the root stack.
  6377. So the prelude needs to move the root stack pointer \code{r15} up and
  6378. the conclusion needs to move the root stack pointer back down. Also,
  6379. the prelude must initialize to \code{0} this frame's slots in the root
  6380. stack to signal to the garbage collector that those slots do not yet
  6381. contain a pointer to a vector. Otherwise the garbage collector will
  6382. interpret the garbage bits in those slots as memory addresses and try
  6383. to traverse them, causing serious mayhem!
  6384. Regarding (3) the sharing of registers between different functions,
  6385. recall from Section~\ref{sec:calling-conventions} that the registers
  6386. are divided into two groups, the caller-saved registers and the
  6387. callee-saved registers. The caller should assume that all the
  6388. caller-saved registers get overwritten with arbitrary values by the
  6389. callee. That is why we recommend in
  6390. Section~\ref{sec:calling-conventions} that variables that are live
  6391. during a function call should not be assigned to caller-saved
  6392. registers.
  6393. On the flip side, if the callee wants to use a callee-saved register,
  6394. the callee must save the contents of those registers on their stack
  6395. frame and then put them back prior to returning to the caller. That
  6396. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6397. the register allocator assigns a variable to a callee-saved register,
  6398. then the prelude of the \code{main} function must save that register
  6399. to the stack and the conclusion of \code{main} must restore it. This
  6400. recommendation now generalizes to all functions.
  6401. Also recall that the base pointer, register \code{rbp}, is used as a
  6402. point-of-reference within a frame, so that each local variable can be
  6403. accessed at a fixed offset from the base pointer
  6404. (Section~\ref{sec:x86}).
  6405. %
  6406. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6407. and callee frames.
  6408. \begin{figure}[tbp]
  6409. \centering
  6410. \begin{tabular}{r|r|l|l} \hline
  6411. Caller View & Callee View & Contents & Frame \\ \hline
  6412. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6413. 0(\key{\%rbp}) & & old \key{rbp} \\
  6414. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6415. \ldots & & \ldots \\
  6416. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6417. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6418. \ldots & & \ldots \\
  6419. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6420. %% & & \\
  6421. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6422. %% & \ldots & \ldots \\
  6423. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6424. \hline
  6425. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6426. & 0(\key{\%rbp}) & old \key{rbp} \\
  6427. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6428. & \ldots & \ldots \\
  6429. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6430. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6431. & \ldots & \ldots \\
  6432. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6433. \end{tabular}
  6434. \caption{Memory layout of caller and callee frames.}
  6435. \label{fig:call-frames}
  6436. \end{figure}
  6437. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6438. %% local variables and for storing the values of callee-saved registers
  6439. %% (we shall refer to all of these collectively as ``locals''), and that
  6440. %% at the beginning of a function we move the stack pointer \code{rsp}
  6441. %% down to make room for them.
  6442. %% We recommend storing the local variables
  6443. %% first and then the callee-saved registers, so that the local variables
  6444. %% can be accessed using \code{rbp} the same as before the addition of
  6445. %% functions.
  6446. %% To make additional room for passing arguments, we shall
  6447. %% move the stack pointer even further down. We count how many stack
  6448. %% arguments are needed for each function call that occurs inside the
  6449. %% body of the function and find their maximum. Adding this number to the
  6450. %% number of locals gives us how much the \code{rsp} should be moved at
  6451. %% the beginning of the function. In preparation for a function call, we
  6452. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6453. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6454. %% so on.
  6455. %% Upon calling the function, the stack arguments are retrieved by the
  6456. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6457. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6458. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6459. %% the layout of the caller and callee frames. Notice how important it is
  6460. %% that we correctly compute the maximum number of arguments needed for
  6461. %% function calls; if that number is too small then the arguments and
  6462. %% local variables will smash into each other!
  6463. \subsection{Efficient Tail Calls}
  6464. \label{sec:tail-call}
  6465. In general, the amount of stack space used by a program is determined
  6466. by the longest chain of nested function calls. That is, if function
  6467. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6468. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6469. $n$ can grow quite large in the case of recursive or mutually
  6470. recursive functions. However, in some cases we can arrange to use only
  6471. constant space, i.e. $O(1)$, instead of $O(n)$.
  6472. If a function call is the last action in a function body, then that
  6473. call is said to be a \emph{tail call}\index{tail call}.
  6474. For example, in the following
  6475. program, the recursive call to \code{tail-sum} is a tail call.
  6476. \begin{center}
  6477. \begin{lstlisting}
  6478. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6479. (if (eq? n 0)
  6480. r
  6481. (tail-sum (- n 1) (+ n r))))
  6482. (+ (tail-sum 5 0) 27)
  6483. \end{lstlisting}
  6484. \end{center}
  6485. At a tail call, the frame of the caller is no longer needed, so we
  6486. can pop the caller's frame before making the tail call. With this
  6487. approach, a recursive function that only makes tail calls will only
  6488. use $O(1)$ stack space. Functional languages like Racket typically
  6489. rely heavily on recursive functions, so they typically guarantee that
  6490. all tail calls will be optimized in this way.
  6491. \index{frame}
  6492. However, some care is needed with regards to argument passing in tail
  6493. calls. As mentioned above, for arguments beyond the sixth, the
  6494. convention is to use space in the caller's frame for passing
  6495. arguments. But for a tail call we pop the caller's frame and can no
  6496. longer use it. Another alternative is to use space in the callee's
  6497. frame for passing arguments. However, this option is also problematic
  6498. because the caller and callee's frame overlap in memory. As we begin
  6499. to copy the arguments from their sources in the caller's frame, the
  6500. target locations in the callee's frame might overlap with the sources
  6501. for later arguments! We solve this problem by not using the stack for
  6502. passing more than six arguments but instead using the heap, as we
  6503. describe in the Section~\ref{sec:limit-functions-r4}.
  6504. As mentioned above, for a tail call we pop the caller's frame prior to
  6505. making the tail call. The instructions for popping a frame are the
  6506. instructions that we usually place in the conclusion of a
  6507. function. Thus, we also need to place such code immediately before
  6508. each tail call. These instructions include restoring the callee-saved
  6509. registers, so it is good that the argument passing registers are all
  6510. caller-saved registers.
  6511. One last note regarding which instruction to use to make the tail
  6512. call. When the callee is finished, it should not return to the current
  6513. function, but it should return to the function that called the current
  6514. one. Thus, the return address that is already on the stack is the
  6515. right one, and we should not use \key{callq} to make the tail call, as
  6516. that would unnecessarily overwrite the return address. Instead we can
  6517. simply use the \key{jmp} instruction. Like the indirect function call,
  6518. we write an \emph{indirect jump}\index{indirect jump} with a register
  6519. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6520. jump target because the preceding conclusion overwrites just about
  6521. everything else.
  6522. \begin{lstlisting}
  6523. jmp *%rax
  6524. \end{lstlisting}
  6525. \section{Shrink $R_4$}
  6526. \label{sec:shrink-r4}
  6527. The \code{shrink} pass performs a minor modification to ease the
  6528. later passes. This pass introduces an explicit \code{main} function
  6529. and changes the top \code{ProgramDefsExp} form to
  6530. \code{ProgramDefs} as follows.
  6531. \begin{lstlisting}
  6532. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6533. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6534. \end{lstlisting}
  6535. where $\itm{mainDef}$ is
  6536. \begin{lstlisting}
  6537. (Def 'main '() 'Integer '() |$\Exp'$|)
  6538. \end{lstlisting}
  6539. \section{Reveal Functions and the $F_1$ language}
  6540. \label{sec:reveal-functions-r4}
  6541. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6542. respect: it conflates the use of function names and local
  6543. variables. This is a problem because we need to compile the use of a
  6544. function name differently than the use of a local variable; we need to
  6545. use \code{leaq} to convert the function name (a label in x86) to an
  6546. address in a register. Thus, it is a good idea to create a new pass
  6547. that changes function references from just a symbol $f$ to
  6548. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6549. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6550. \begin{figure}[tp]
  6551. \centering
  6552. \fbox{
  6553. \begin{minipage}{0.96\textwidth}
  6554. \[
  6555. \begin{array}{lcl}
  6556. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6557. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6558. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6559. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6560. &\mid& \gray{ \BOOL{\itm{bool}}
  6561. \mid \AND{\Exp}{\Exp} }\\
  6562. &\mid& \gray{ \OR{\Exp}{\Exp}
  6563. \mid \NOT{\Exp} } \\
  6564. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6565. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6566. &\mid& \gray{ \VECTOR{\Exp} } \\
  6567. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  6568. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  6569. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6570. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6571. &\mid& \FUNREF{\Var}\\
  6572. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6573. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6574. \end{array}
  6575. \]
  6576. \end{minipage}
  6577. }
  6578. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6579. (Figure~\ref{fig:r4-syntax}).}
  6580. \label{fig:f1-syntax}
  6581. \end{figure}
  6582. %% Distinguishing between calls in tail position and non-tail position
  6583. %% requires the pass to have some notion of context. We recommend using
  6584. %% two mutually recursive functions, one for processing expressions in
  6585. %% tail position and another for the rest.
  6586. Placing this pass after \code{uniquify} will make sure that there are
  6587. no local variables and functions that share the same name. On the
  6588. other hand, \code{reveal-functions} needs to come before the
  6589. \code{explicate-control} pass because that pass helps us compile
  6590. \code{FunRef} forms into assignment statements.
  6591. \section{Limit Functions}
  6592. \label{sec:limit-functions-r4}
  6593. Recall that we wish to limit the number of function parameters to six
  6594. so that we do not need to use the stack for argument passing, which
  6595. makes it easier to implement efficient tail calls. However, because
  6596. the input language $R_4$ supports arbitrary numbers of function
  6597. arguments, we have some work to do!
  6598. This pass transforms functions and function calls that involve more
  6599. than six arguments to pass the first five arguments as usual, but it
  6600. packs the rest of the arguments into a vector and passes it as the
  6601. sixth argument.
  6602. Each function definition with too many parameters is transformed as
  6603. follows.
  6604. \begin{lstlisting}
  6605. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6606. |$\Rightarrow$|
  6607. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6608. \end{lstlisting}
  6609. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6610. the occurences of the later parameters with vector references.
  6611. \begin{lstlisting}
  6612. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6613. \end{lstlisting}
  6614. For function calls with too many arguments, the \code{limit-functions}
  6615. pass transforms them in the following way.
  6616. \begin{tabular}{lll}
  6617. \begin{minipage}{0.2\textwidth}
  6618. \begin{lstlisting}
  6619. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6620. \end{lstlisting}
  6621. \end{minipage}
  6622. &
  6623. $\Rightarrow$
  6624. &
  6625. \begin{minipage}{0.4\textwidth}
  6626. \begin{lstlisting}
  6627. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6628. \end{lstlisting}
  6629. \end{minipage}
  6630. \end{tabular}
  6631. \section{Remove Complex Operators and Operands}
  6632. \label{sec:rco-r4}
  6633. The primary decisions to make for this pass is whether to classify
  6634. \code{FunRef} and \code{Apply} as either simple or complex
  6635. expressions. Recall that a simple expression will eventually end up as
  6636. just an ``immediate'' argument of an x86 instruction. Function
  6637. application will be translated to a sequence of instructions, so
  6638. \code{Apply} must be classified as complex expression. Regarding
  6639. \code{FunRef}, as discussed above, the function label needs to
  6640. be converted to an address using the \code{leaq} instruction. Thus,
  6641. even though \code{FunRef} seems rather simple, it needs to be
  6642. classified as a complex expression so that we generate an assignment
  6643. statement with a left-hand side that can serve as the target of the
  6644. \code{leaq}.
  6645. \section{Explicate Control and the $C_3$ language}
  6646. \label{sec:explicate-control-r4}
  6647. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6648. the concrete and abstract syntax for $C_3$, the output of
  6649. \key{explicate-control}. The three mutually recursive functions for
  6650. this pass, for assignment, tail, and predicate contexts, must all be
  6651. updated with cases for \code{FunRef} and \code{Apply}. In assignment
  6652. and predicate contexts, \code{Apply} becomes \code{Call} in $C_3$,
  6653. whereas in tail position \code{Apply} becomes \code{TailCall} in
  6654. $C_3$. We recommend defining a new function for processing function
  6655. definitions. This code is similar to the case for \code{Program} in
  6656. $R_3$. The top-level \code{explicate-control} function that handles
  6657. the \code{ProgramDefs} form of $R_4$ can then apply this new function
  6658. to all the function definitions.
  6659. \begin{figure}[tp]
  6660. \fbox{
  6661. \begin{minipage}{0.96\textwidth}
  6662. \[
  6663. \begin{array}{lcl}
  6664. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6665. \\
  6666. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6667. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  6668. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  6669. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6670. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  6671. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6672. &\mid& \itm{label} \mid (\key{call} \,\Arg\,\Arg\ldots) \\
  6673. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6674. \mid (\key{collect} \,\itm{int}) }\\
  6675. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6676. &\mid& \gray{(\key{goto}\,\itm{label})
  6677. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6678. &\mid& (\Arg\,\Arg\ldots) \\
  6679. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6680. C_3 & ::= & \Def\ldots
  6681. \end{array}
  6682. \]
  6683. \end{minipage}
  6684. }
  6685. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  6686. \label{fig:c3-concrete-syntax}
  6687. \end{figure}
  6688. \begin{figure}[tp]
  6689. \fbox{
  6690. \begin{minipage}{0.96\textwidth}
  6691. UNDER CONSTRUCTION
  6692. \end{minipage}
  6693. }
  6694. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  6695. \label{fig:c3-syntax}
  6696. \end{figure}
  6697. \section{Uncover Locals}
  6698. \label{sec:uncover-locals-r4}
  6699. The function for processing $\Tail$ should be updated with a case for
  6700. \code{TailCall}. We also recommend creating a new function for
  6701. processing function definitions. Each function definition in $C_3$ has
  6702. its own set of local variables, so the code for function definitions
  6703. should be similar to the case for the \code{Program} form in $C_2$.
  6704. \section{Select Instructions and the x86$_3$ Language}
  6705. \label{sec:select-r4}
  6706. \index{instruction selection}
  6707. The output of select instructions is a program in the x86$_3$
  6708. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6709. \index{x86}
  6710. \begin{figure}[tp]
  6711. \fbox{
  6712. \begin{minipage}{0.96\textwidth}
  6713. \[
  6714. \begin{array}{lcl}
  6715. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6716. \mid (\key{deref}\,\Reg\,\Int) } \\
  6717. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6718. \mid (\key{global}\; \itm{name}) } \\
  6719. &\mid& (\key{fun-ref}\; \itm{label})\\
  6720. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6721. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6722. (\key{subq} \; \Arg\; \Arg) \mid
  6723. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6724. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6725. (\key{pushq}\;\Arg) \mid
  6726. (\key{popq}\;\Arg) \mid
  6727. (\key{retq}) } \\
  6728. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6729. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6730. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6731. \mid (\key{jmp} \; \itm{label})
  6732. \mid (\key{j}\itm{cc} \; \itm{label})
  6733. \mid (\key{label} \; \itm{label}) } \\
  6734. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6735. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  6736. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6737. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6738. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6739. \end{array}
  6740. \]
  6741. \end{minipage}
  6742. }
  6743. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6744. \label{fig:x86-3-concrete}
  6745. \end{figure}
  6746. \begin{figure}[tp]
  6747. UNDER CONSTRUCTION
  6748. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6749. \label{fig:x86-3}
  6750. \end{figure}
  6751. \margincomment{TODO: abstract syntax for $x86_3$.}
  6752. An assignment of \code{FunRef} becomes a \code{leaq} instruction
  6753. as follows: \\
  6754. \begin{tabular}{lll}
  6755. \begin{minipage}{0.35\textwidth}
  6756. \begin{lstlisting}
  6757. (Assign |$\itm{lhs}$| (FunRef |$f$|))
  6758. \end{lstlisting}
  6759. \end{minipage}
  6760. &
  6761. $\Rightarrow$
  6762. &
  6763. \begin{minipage}{0.4\textwidth}
  6764. \begin{lstlisting}
  6765. (Instr 'leaq (list (FunRef |$f$|) |$\itm{lhs}'$|))
  6766. \end{lstlisting}
  6767. \end{minipage}
  6768. \end{tabular} \\
  6769. \margincomment{TODO: show AST transformation for function definitions.}
  6770. Regarding function definitions, we need to remove their parameters and
  6771. instead perform parameter passing in terms of the conventions
  6772. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  6773. in the argument passing registers, and inside the function we should
  6774. generate a \code{movq} instruction for each parameter, to move the
  6775. argument value from the appropriate register to a new local variable
  6776. with the same name as the old parameter.
  6777. Next, consider the compilation of function calls, which have the
  6778. following form upon input to \code{select-instructions}.
  6779. \begin{lstlisting}
  6780. (Assign |\itm{lhs}| (Call |\itm{fun}| |\itm{args}| |$\ldots$|))
  6781. \end{lstlisting}
  6782. In the mirror image of handling the parameters of function
  6783. definitions, the arguments \itm{args} need to be moved to the argument
  6784. passing registers.
  6785. %
  6786. Once the instructions for parameter passing have been generated, the
  6787. function call itself can be performed with an indirect function call,
  6788. for which I recommend creating the new instruction
  6789. \code{indirect-callq}. Of course, the return value from the function
  6790. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  6791. \begin{lstlisting}
  6792. (IndirectCallq |\itm{fun}|)
  6793. (Instr 'movq (Reg rax) |\itm{lhs}|)
  6794. \end{lstlisting}
  6795. Regarding tail calls, the parameter passing is the same as non-tail
  6796. calls: generate instructions to move the arguments into to the
  6797. argument passing registers. After that we need to pop the frame from
  6798. the procedure call stack. However, we do not yet know how big the
  6799. frame is; that gets determined during register allocation. So instead
  6800. of generating those instructions here, we invent a new instruction
  6801. that means ``pop the frame and then do an indirect jump'', which we
  6802. name \code{TailJmp}.
  6803. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6804. using the label \code{start} for the initial block of a program, and
  6805. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6806. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  6807. can be compiled to an assignment to \code{rax} followed by a jump to
  6808. \code{conclusion}. With the addition of function definitions, we will
  6809. have a starting block and conclusion for each function, but their
  6810. labels need to be unique. We recommend prepending the function's name
  6811. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6812. labels. (Alternatively, one could \code{gensym} labels for the start
  6813. and conclusion and store them in the $\itm{info}$ field of the
  6814. function definition.)
  6815. \section{Uncover Live}
  6816. %% The rest of the passes need only minor modifications to handle the new
  6817. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6818. %% \code{leaq}.
  6819. The \code{IndirectCallq} instruction should be treated like
  6820. \code{Callq} regarding its written locations $W$, in that they should
  6821. include all the caller-saved registers. Recall that the reason for
  6822. that is to force call-live variables to be assigned to callee-saved
  6823. registers or to be spilled to the stack.
  6824. \section{Build Interference Graph}
  6825. With the addition of function definitions, we compute an interference
  6826. graph for each function (not just one for the whole program).
  6827. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6828. spill vector-typed variables that are live during a call to the
  6829. \code{collect}. With the addition of functions to our language, we
  6830. need to revisit this issue. Many functions will perform allocation and
  6831. therefore have calls to the collector inside of them. Thus, we should
  6832. not only spill a vector-typed variable when it is live during a call
  6833. to \code{collect}, but we should spill the variable if it is live
  6834. during any function call. Thus, in the \code{build-interference} pass,
  6835. we recommend adding interference edges between call-live vector-typed
  6836. variables and the callee-saved registers (in addition to the usual
  6837. addition of edges between call-live variables and the caller-saved
  6838. registers).
  6839. \section{Patch Instructions}
  6840. In \code{patch-instructions}, you should deal with the x86
  6841. idiosyncrasy that the destination argument of \code{leaq} must be a
  6842. register. Additionally, you should ensure that the argument of
  6843. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  6844. code generation more convenient, because we will be trampling many
  6845. registers before the tail call (as explained below).
  6846. \section{Print x86}
  6847. For the \code{print-x86} pass, we recommend the following translations:
  6848. \begin{lstlisting}
  6849. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6850. (IndirectCallq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6851. \end{lstlisting}
  6852. Handling \code{TailJmp} requires a bit more care. A straightforward
  6853. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, which
  6854. is what we will want to do, but before the jump we need to pop the
  6855. current frame. So we need to restore the state of the registers to the
  6856. point they were at when the current function was called. This
  6857. sequence of instructions is the same as the code for the conclusion of
  6858. a function.
  6859. Note that your \code{print-x86} pass needs to add the code for saving
  6860. and restoring callee-saved registers, if you have not already
  6861. implemented that. This is necessary when generating code for function
  6862. definitions.
  6863. \section{An Example Translation}
  6864. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6865. function in $R_4$ to x86. The figure also includes the results of the
  6866. \code{explicate-control} and \code{select-instructions} passes. We
  6867. have omitted the \code{has-type} AST nodes for readability. Can you
  6868. see any ways to improve the translation?
  6869. \begin{figure}[tbp]
  6870. \begin{tabular}{ll}
  6871. \begin{minipage}{0.45\textwidth}
  6872. % s3_2.rkt
  6873. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6874. (define (add [x : Integer]
  6875. [y : Integer]) : Integer (+ x y))
  6876. (add 40 2)
  6877. \end{lstlisting}
  6878. $\Downarrow$
  6879. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6880. (define (add86 [x87 : Integer]
  6881. [y88 : Integer]) : Integer ()
  6882. ((add86start . (return (+ x87 y88)))))
  6883. (define (main) : Integer ()
  6884. ((mainstart .
  6885. (seq (assign tmp89 (fun-ref add86))
  6886. (tailcall tmp89 40 2)))))
  6887. \end{lstlisting}
  6888. \end{minipage}
  6889. &
  6890. $\Rightarrow$
  6891. \begin{minipage}{0.5\textwidth}
  6892. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6893. (program ()
  6894. (define (add86)
  6895. ((locals (x87 . Integer) (y88 . Integer))
  6896. (num-params . 2))
  6897. ((add86start .
  6898. (block ()
  6899. (movq (reg rcx) (var x87))
  6900. (movq (reg rdx) (var y88))
  6901. (movq (var x87) (reg rax))
  6902. (addq (var y88) (reg rax))
  6903. (jmp add86conclusion)))))
  6904. (define (main)
  6905. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6906. (num-params . 0))
  6907. ((mainstart .
  6908. (block ()
  6909. (leaq (fun-ref add86) (var tmp89))
  6910. (movq (int 40) (reg rcx))
  6911. (movq (int 2) (reg rdx))
  6912. (tail-jmp (var tmp89))))))
  6913. \end{lstlisting}
  6914. $\Downarrow$
  6915. \end{minipage}
  6916. \end{tabular}
  6917. \begin{tabular}{lll}
  6918. \begin{minipage}{0.3\textwidth}
  6919. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6920. _add90start:
  6921. movq %rcx, %rsi
  6922. movq %rdx, %rcx
  6923. movq %rsi, %rax
  6924. addq %rcx, %rax
  6925. jmp _add90conclusion
  6926. .globl _add90
  6927. .align 16
  6928. _add90:
  6929. pushq %rbp
  6930. movq %rsp, %rbp
  6931. pushq %r12
  6932. pushq %rbx
  6933. pushq %r13
  6934. pushq %r14
  6935. subq $0, %rsp
  6936. jmp _add90start
  6937. _add90conclusion:
  6938. addq $0, %rsp
  6939. popq %r14
  6940. popq %r13
  6941. popq %rbx
  6942. popq %r12
  6943. subq $0, %r15
  6944. popq %rbp
  6945. retq
  6946. \end{lstlisting}
  6947. \end{minipage}
  6948. &
  6949. \begin{minipage}{0.3\textwidth}
  6950. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6951. _mainstart:
  6952. leaq _add90(%rip), %rsi
  6953. movq $40, %rcx
  6954. movq $2, %rdx
  6955. movq %rsi, %rax
  6956. addq $0, %rsp
  6957. popq %r14
  6958. popq %r13
  6959. popq %rbx
  6960. popq %r12
  6961. subq $0, %r15
  6962. popq %rbp
  6963. jmp *%rax
  6964. .globl _main
  6965. .align 16
  6966. _main:
  6967. pushq %rbp
  6968. movq %rsp, %rbp
  6969. pushq %r12
  6970. pushq %rbx
  6971. pushq %r13
  6972. pushq %r14
  6973. subq $0, %rsp
  6974. movq $16384, %rdi
  6975. movq $16, %rsi
  6976. callq _initialize
  6977. movq _rootstack_begin(%rip), %r15
  6978. jmp _mainstart
  6979. \end{lstlisting}
  6980. \end{minipage}
  6981. &
  6982. \begin{minipage}{0.3\textwidth}
  6983. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6984. _mainconclusion:
  6985. addq $0, %rsp
  6986. popq %r14
  6987. popq %r13
  6988. popq %rbx
  6989. popq %r12
  6990. subq $0, %r15
  6991. popq %rbp
  6992. retq
  6993. \end{lstlisting}
  6994. \end{minipage}
  6995. \end{tabular}
  6996. \caption{Example compilation of a simple function to x86.}
  6997. \label{fig:add-fun}
  6998. \end{figure}
  6999. \begin{exercise}\normalfont
  7000. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7001. Create 5 new programs that use functions, including examples that pass
  7002. functions and return functions from other functions and including
  7003. recursive functions. Test your compiler on these new programs and all
  7004. of your previously created test programs.
  7005. \end{exercise}
  7006. \begin{figure}[p]
  7007. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7008. \node (R4) at (0,2) {\large $R_4$};
  7009. \node (R4-2) at (3,2) {\large $R_4$};
  7010. \node (R4-3) at (6,2) {\large $R_4$};
  7011. \node (F1-1) at (12,0) {\large $F_1$};
  7012. \node (F1-2) at (9,0) {\large $F_1$};
  7013. \node (F1-3) at (6,0) {\large $F_1$};
  7014. \node (F1-4) at (3,0) {\large $F_1$};
  7015. \node (C3-1) at (6,-2) {\large $C_3$};
  7016. \node (C3-2) at (3,-2) {\large $C_3$};
  7017. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7018. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7019. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7020. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7021. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7022. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7023. \path[->,bend left=15] (R4) edge [above] node
  7024. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7025. \path[->,bend left=15] (R4-2) edge [above] node
  7026. {\ttfamily\footnotesize uniquify} (R4-3);
  7027. \path[->,bend left=15] (R4-3) edge [right] node
  7028. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7029. \path[->,bend left=15] (F1-1) edge [below] node
  7030. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7031. \path[->,bend right=15] (F1-2) edge [above] node
  7032. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7033. \path[->,bend right=15] (F1-3) edge [above] node
  7034. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7035. \path[->,bend left=15] (F1-4) edge [right] node
  7036. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  7037. \path[->,bend left=15] (C3-1) edge [below] node
  7038. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  7039. \path[->,bend right=15] (C3-2) edge [left] node
  7040. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7041. \path[->,bend left=15] (x86-2) edge [left] node
  7042. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7043. \path[->,bend right=15] (x86-2-1) edge [below] node
  7044. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7045. \path[->,bend right=15] (x86-2-2) edge [left] node
  7046. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7047. \path[->,bend left=15] (x86-3) edge [above] node
  7048. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7049. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7050. \end{tikzpicture}
  7051. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7052. \label{fig:R4-passes}
  7053. \end{figure}
  7054. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  7055. the compilation of $R_4$.
  7056. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7057. \chapter{Lexically Scoped Functions}
  7058. \label{ch:lambdas}
  7059. \index{lambda}
  7060. \index{lexical scoping}
  7061. This chapter studies lexically scoped functions as they appear in
  7062. functional languages such as Racket. By lexical scoping we mean that a
  7063. function's body may refer to variables whose binding site is outside
  7064. of the function, in an enclosing scope.
  7065. %
  7066. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  7067. anonymous function defined using the \key{lambda} form. The body of
  7068. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  7069. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  7070. the \key{lambda}. Variable \code{y} is bound by the enclosing
  7071. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  7072. returned from the function \code{f}. Below the definition of \code{f},
  7073. we have two calls to \code{f} with different arguments for \code{x},
  7074. first \code{5} then \code{3}. The functions returned from \code{f} are
  7075. bound to variables \code{g} and \code{h}. Even though these two
  7076. functions were created by the same \code{lambda}, they are really
  7077. different functions because they use different values for
  7078. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  7079. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  7080. the result of this program is \code{42}.
  7081. \begin{figure}[btp]
  7082. % s4_6.rkt
  7083. \begin{lstlisting}
  7084. (define (f [x : Integer]) : (Integer -> Integer)
  7085. (let ([y 4])
  7086. (lambda: ([z : Integer]) : Integer
  7087. (+ x (+ y z)))))
  7088. (let ([g (f 5)])
  7089. (let ([h (f 3)])
  7090. (+ (g 11) (h 15))))
  7091. \end{lstlisting}
  7092. \caption{Example of a lexically scoped function.}
  7093. \label{fig:lexical-scoping}
  7094. \end{figure}
  7095. \section{The $R_5$ Language}
  7096. The syntax for this language with anonymous functions and lexical
  7097. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  7098. \key{lambda} form to the grammar for $R_4$, which already has syntax
  7099. for function application. In this chapter we shall describe how to
  7100. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  7101. into a combination of functions (as in $R_4$) and tuples (as in
  7102. $R_3$).
  7103. \begin{figure}[tp]
  7104. \centering
  7105. \fbox{
  7106. \begin{minipage}{0.96\textwidth}
  7107. \[
  7108. \begin{array}{lcl}
  7109. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7110. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7111. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7112. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7113. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7114. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  7115. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7116. \mid (\key{and}\;\Exp\;\Exp)
  7117. \mid (\key{or}\;\Exp\;\Exp)
  7118. \mid (\key{not}\;\Exp) } \\
  7119. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7120. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7121. (\key{vector-ref}\;\Exp\;\Int)} \\
  7122. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7123. &\mid& \gray{(\Exp \; \Exp\ldots)} \\
  7124. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp) \\
  7125. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7126. R_5 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7127. \end{array}
  7128. \]
  7129. \end{minipage}
  7130. }
  7131. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7132. with \key{lambda}.}
  7133. \label{fig:r5-syntax}
  7134. \end{figure}
  7135. To compile lexically-scoped functions to top-level function
  7136. definitions, the compiler will need to provide special treatment to
  7137. variable occurrences such as \code{x} and \code{y} in the body of the
  7138. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  7139. of $R_4$ may not refer to variables defined outside the function. To
  7140. identify such variable occurrences, we review the standard notion of
  7141. free variable.
  7142. \begin{definition}
  7143. A variable is \emph{free with respect to an expression} $e$ if the
  7144. variable occurs inside $e$ but does not have an enclosing binding in
  7145. $e$.\index{free variable}
  7146. \end{definition}
  7147. For example, the variables \code{x}, \code{y}, and \code{z} are all
  7148. free with respect to the expression \code{(+ x (+ y z))}. On the
  7149. other hand, only \code{x} and \code{y} are free with respect to the
  7150. following expression because \code{z} is bound by the \code{lambda}.
  7151. \begin{lstlisting}
  7152. (lambda: ([z : Integer]) : Integer
  7153. (+ x (+ y z)))
  7154. \end{lstlisting}
  7155. Once we have identified the free variables of a \code{lambda}, we need
  7156. to arrange for some way to transport, at runtime, the values of those
  7157. variables from the point where the \code{lambda} was created to the
  7158. point where the \code{lambda} is applied. Referring again to
  7159. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  7160. needs to be used in the application of \code{g} to \code{11}, but the
  7161. binding of \code{x} to \code{3} needs to be used in the application of
  7162. \code{h} to \code{15}. An efficient solution to the problem, due to
  7163. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7164. free variables together with the function pointer for the lambda's
  7165. code, an arrangement called a \emph{flat closure} (which we shorten to
  7166. just ``closure'').
  7167. \index{closure}\index{flat closure}
  7168. Fortunately, we have all the ingredients to make
  7169. closures, Chapter~\ref{ch:tuples} gave us vectors and
  7170. Chapter~\ref{ch:functions} gave us function pointers. The function
  7171. pointer shall reside at index $0$ and the values for free variables
  7172. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  7173. the two closures created by the two calls to \code{f} in
  7174. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  7175. the same \key{lambda}, they share the same function pointer but differ
  7176. in the values for the free variable \code{x}.
  7177. \begin{figure}[tbp]
  7178. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7179. \caption{Example closure representation for the \key{lambda}'s
  7180. in Figure~\ref{fig:lexical-scoping}.}
  7181. \label{fig:closures}
  7182. \end{figure}
  7183. \section{Interpreting $R_5$}
  7184. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7185. $R_5$. The clause for \key{lambda} saves the current environment
  7186. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7187. the environment from the \key{lambda}, the \code{lam-env}, when
  7188. interpreting the body of the \key{lambda}. The \code{lam-env}
  7189. environment is extended with the mapping of parameters to argument
  7190. values.
  7191. \begin{figure}[tbp]
  7192. \begin{lstlisting}
  7193. (define (interp-exp env)
  7194. (lambda (e)
  7195. (define recur (interp-exp env))
  7196. (match e
  7197. ...
  7198. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  7199. `(lambda ,xs ,body ,env)]
  7200. [`(app ,fun ,args ...)
  7201. (define fun-val ((interp-exp env) fun))
  7202. (define arg-vals (map (interp-exp env) args))
  7203. (match fun-val
  7204. [`(lambda (,xs ...) ,body ,lam-env)
  7205. (define new-env (append (map cons xs arg-vals) lam-env))
  7206. ((interp-exp new-env) body)]
  7207. [else (error "interp-exp, expected function, not" fun-val)])]
  7208. [else (error 'interp-exp "unrecognized expression")]
  7209. )))
  7210. \end{lstlisting}
  7211. \caption{Interpreter for $R_5$.}
  7212. \label{fig:interp-R5}
  7213. \end{figure}
  7214. \section{Type Checking $R_5$}
  7215. \label{sec:type-check-r5}
  7216. \index{type checking}
  7217. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  7218. \key{lambda} form. The body of the \key{lambda} is checked in an
  7219. environment that includes the current environment (because it is
  7220. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7221. require the body's type to match the declared return type.
  7222. \begin{figure}[tbp]
  7223. \begin{lstlisting}
  7224. (define (typecheck-R5 env)
  7225. (lambda (e)
  7226. (match e
  7227. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  7228. (define new-env (append (map cons xs Ts) env))
  7229. (define bodyT ((typecheck-R5 new-env) body))
  7230. (cond [(equal? rT bodyT)
  7231. `(,@Ts -> ,rT)]
  7232. [else
  7233. (error "mismatch in return type" bodyT rT)])]
  7234. ...
  7235. )))
  7236. \end{lstlisting}
  7237. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7238. \label{fig:typecheck-R5}
  7239. \end{figure}
  7240. \section{Closure Conversion}
  7241. \label{sec:closure-conversion}
  7242. \index{closure conversion}
  7243. The compiling of lexically-scoped functions into top-level function
  7244. definitions is accomplished in the pass \code{convert-to-closures}
  7245. that comes after \code{reveal-functions} and before
  7246. \code{limit-functions}.
  7247. As usual, we shall implement the pass as a recursive function over the
  7248. AST. All of the action is in the clauses for \key{lambda} and
  7249. \key{Apply}. We transform a \key{lambda} expression into an expression
  7250. that creates a closure, that is, creates a vector whose first element
  7251. is a function pointer and the rest of the elements are the free
  7252. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7253. generated to identify the function.
  7254. \begin{tabular}{lll}
  7255. \begin{minipage}{0.4\textwidth}
  7256. \begin{lstlisting}
  7257. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7258. \end{lstlisting}
  7259. \end{minipage}
  7260. &
  7261. $\Rightarrow$
  7262. &
  7263. \begin{minipage}{0.4\textwidth}
  7264. \begin{lstlisting}
  7265. (vector |\itm{name}| |\itm{fvs}| ...)
  7266. \end{lstlisting}
  7267. \end{minipage}
  7268. \end{tabular} \\
  7269. %
  7270. In addition to transforming each \key{lambda} into a \key{vector}, we
  7271. must create a top-level function definition for each \key{lambda}, as
  7272. shown below.\\
  7273. \begin{minipage}{0.8\textwidth}
  7274. \begin{lstlisting}
  7275. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7276. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7277. ...
  7278. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7279. |\itm{body'}|)...))
  7280. \end{lstlisting}
  7281. \end{minipage}\\
  7282. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7283. parameters are the normal parameters of the \key{lambda}. The types
  7284. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7285. underscore is a dummy type because it is rather difficult to give a
  7286. type to the function in the closure's type, and it does not matter.
  7287. The sequence of \key{let} forms bind the free variables to their
  7288. values obtained from the closure.
  7289. We transform function application into code that retrieves the
  7290. function pointer from the closure and then calls the function, passing
  7291. in the closure as the first argument. We bind $e'$ to a temporary
  7292. variable to avoid code duplication.
  7293. \begin{tabular}{lll}
  7294. \begin{minipage}{0.3\textwidth}
  7295. \begin{lstlisting}
  7296. (app |$e$| |\itm{es}| ...)
  7297. \end{lstlisting}
  7298. \end{minipage}
  7299. &
  7300. $\Rightarrow$
  7301. &
  7302. \begin{minipage}{0.5\textwidth}
  7303. \begin{lstlisting}
  7304. (let ([|\itm{tmp}| |$e'$|])
  7305. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7306. \end{lstlisting}
  7307. \end{minipage}
  7308. \end{tabular} \\
  7309. There is also the question of what to do with top-level function
  7310. definitions. To maintain a uniform translation of function
  7311. application, we turn function references into closures.
  7312. \begin{tabular}{lll}
  7313. \begin{minipage}{0.3\textwidth}
  7314. \begin{lstlisting}
  7315. (fun-ref |$f$|)
  7316. \end{lstlisting}
  7317. \end{minipage}
  7318. &
  7319. $\Rightarrow$
  7320. &
  7321. \begin{minipage}{0.5\textwidth}
  7322. \begin{lstlisting}
  7323. (vector (fun-ref |$f$|))
  7324. \end{lstlisting}
  7325. \end{minipage}
  7326. \end{tabular} \\
  7327. %
  7328. The top-level function definitions need to be updated as well to take
  7329. an extra closure parameter.
  7330. \section{An Example Translation}
  7331. \label{sec:example-lambda}
  7332. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  7333. conversion for the example program demonstrating lexical scoping that
  7334. we discussed at the beginning of this chapter.
  7335. \begin{figure}[h]
  7336. \begin{minipage}{0.8\textwidth}
  7337. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7338. (program
  7339. (define (f [x : Integer]) : (Integer -> Integer)
  7340. (let ([y 4])
  7341. (lambda: ([z : Integer]) : Integer
  7342. (+ x (+ y z)))))
  7343. (let ([g (f 5)])
  7344. (let ([h (f 3)])
  7345. (+ (g 11) (h 15)))))
  7346. \end{lstlisting}
  7347. $\Downarrow$
  7348. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7349. (program (type Integer)
  7350. (define (f (x : Integer)) : (Integer -> Integer)
  7351. (let ((y 4))
  7352. (lambda: ((z : Integer)) : Integer
  7353. (+ x (+ y z)))))
  7354. (let ((g (app (fun-ref f) 5)))
  7355. (let ((h (app (fun-ref f) 3)))
  7356. (+ (app g 11) (app h 15)))))
  7357. \end{lstlisting}
  7358. $\Downarrow$
  7359. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7360. (program (type Integer)
  7361. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  7362. (let ((y 4))
  7363. (vector (fun-ref lam.1) x y)))
  7364. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  7365. (let ((x (vector-ref clos.2 1)))
  7366. (let ((y (vector-ref clos.2 2)))
  7367. (+ x (+ y z)))))
  7368. (let ((g (let ((t.1 (vector (fun-ref f))))
  7369. (app (vector-ref t.1 0) t.1 5))))
  7370. (let ((h (let ((t.2 (vector (fun-ref f))))
  7371. (app (vector-ref t.2 0) t.2 3))))
  7372. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  7373. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  7374. \end{lstlisting}
  7375. \end{minipage}
  7376. \caption{Example of closure conversion.}
  7377. \label{fig:lexical-functions-example}
  7378. \end{figure}
  7379. \begin{figure}[p]
  7380. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7381. \node (R4) at (0,2) {\large $R_4$};
  7382. \node (R4-2) at (3,2) {\large $R_4$};
  7383. \node (R4-3) at (6,2) {\large $R_4$};
  7384. \node (F1-1) at (12,0) {\large $F_1$};
  7385. \node (F1-2) at (9,0) {\large $F_1$};
  7386. \node (F1-3) at (6,0) {\large $F_1$};
  7387. \node (F1-4) at (3,0) {\large $F_1$};
  7388. \node (F1-5) at (0,0) {\large $F_1$};
  7389. \node (C3-1) at (6,-2) {\large $C_3$};
  7390. \node (C3-2) at (3,-2) {\large $C_3$};
  7391. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7392. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7393. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7394. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7395. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7396. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7397. \path[->,bend left=15] (R4) edge [above] node
  7398. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7399. \path[->,bend left=15] (R4-2) edge [above] node
  7400. {\ttfamily\footnotesize uniquify} (R4-3);
  7401. \path[->] (R4-3) edge [right] node
  7402. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7403. \path[->,bend left=15] (F1-1) edge [below] node
  7404. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7405. \path[->,bend right=15] (F1-2) edge [above] node
  7406. {\ttfamily\footnotesize limit-functions} (F1-3);
  7407. \path[->,bend right=15] (F1-3) edge [above] node
  7408. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7409. \path[->,bend right=15] (F1-4) edge [above] node
  7410. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7411. \path[->] (F1-5) edge [left] node
  7412. {\ttfamily\footnotesize explicate-control} (C3-1);
  7413. \path[->,bend left=15] (C3-1) edge [below] node
  7414. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7415. \path[->,bend right=15] (C3-2) edge [left] node
  7416. {\ttfamily\footnotesize select-instr.} (x86-2);
  7417. \path[->,bend left=15] (x86-2) edge [left] node
  7418. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7419. \path[->,bend right=15] (x86-2-1) edge [below] node
  7420. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7421. \path[->,bend right=15] (x86-2-2) edge [left] node
  7422. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7423. \path[->,bend left=15] (x86-3) edge [above] node
  7424. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7425. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7426. \end{tikzpicture}
  7427. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7428. functions.}
  7429. \label{fig:R5-passes}
  7430. \end{figure}
  7431. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7432. for the compilation of $R_5$.
  7433. \begin{exercise}\normalfont
  7434. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7435. Create 5 new programs that use \key{lambda} functions and make use of
  7436. lexical scoping. Test your compiler on these new programs and all of
  7437. your previously created test programs.
  7438. \end{exercise}
  7439. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7440. \chapter{Dynamic Typing}
  7441. \label{ch:type-dynamic}
  7442. \index{dynamic typing}
  7443. In this chapter we discuss the compilation of a dynamically typed
  7444. language, named $R_7$, that is a subset of the Racket
  7445. language. (Recall that in the previous chapters we have studied
  7446. subsets of the \emph{Typed} Racket language.) In dynamically typed
  7447. languages, an expression may produce values of differing
  7448. type. Consider the following example with a conditional expression
  7449. that may return a Boolean or an integer depending on the input to the
  7450. program.
  7451. \begin{lstlisting}
  7452. (not (if (eq? (read) 1) #f 0))
  7453. \end{lstlisting}
  7454. Languages that allow expressions to produce different kinds of values
  7455. are called \emph{polymorphic}. There are many kinds of polymorphism,
  7456. such as subtype polymorphism and parametric
  7457. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we are
  7458. talking about here does not have a special name, but it is the usual
  7459. kind that arises in dynamically typed languages.
  7460. Another characteristic of dynamically typed languages is that
  7461. primitive operations, such as \code{not}, are often defined to operate
  7462. on many different types of values. In fact, in Racket, the \code{not}
  7463. operator produces a result for any kind of value: given \code{\#f} it
  7464. returns \code{\#t} and given anything else it returns \code{\#f}.
  7465. Furthermore, even when primitive operations restrict their inputs to
  7466. values of a certain type, this restriction is enforced at runtime
  7467. instead of during compilation. For example, the following vector
  7468. reference results in a run-time contract violation.
  7469. \begin{lstlisting}
  7470. (vector-ref (vector 42) #t)
  7471. \end{lstlisting}
  7472. \begin{figure}[tp]
  7473. \centering
  7474. \fbox{
  7475. \begin{minipage}{0.97\textwidth}
  7476. \[
  7477. \begin{array}{rcl}
  7478. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7479. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7480. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  7481. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  7482. &\mid& \key{\#t} \mid \key{\#f}
  7483. \mid (\key{and}\;\Exp\;\Exp)
  7484. \mid (\key{or}\;\Exp\;\Exp)
  7485. \mid (\key{not}\;\Exp) \\
  7486. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  7487. &\mid& (\key{vector}\;\Exp\ldots) \mid
  7488. (\key{vector-ref}\;\Exp\;\Exp) \\
  7489. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  7490. &\mid& (\Exp \; \Exp\ldots) \mid (\key{lambda}\; (\Var\ldots) \; \Exp) \\
  7491. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7492. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7493. \Def &::=& (\key{define}\; (\Var \; \Var\ldots) \; \Exp) \\
  7494. R_7 &::=& (\key{program} \; \Def\ldots\; \Exp)
  7495. \end{array}
  7496. \]
  7497. \end{minipage}
  7498. }
  7499. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7500. \label{fig:r7-syntax}
  7501. \end{figure}
  7502. The syntax of $R_7$, our subset of Racket, is defined in
  7503. Figure~\ref{fig:r7-syntax}.
  7504. %
  7505. The definitional interpreter for $R_7$ is given in
  7506. Figure~\ref{fig:interp-R7}.
  7507. \begin{figure}[tbp]
  7508. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7509. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  7510. (define (valid-op? op) (member op '(+ - and or not)))
  7511. (define (interp-r7 env)
  7512. (lambda (ast)
  7513. (define recur (interp-r7 env))
  7514. (match ast
  7515. [(? symbol?) (lookup ast env)]
  7516. [(? integer?) `(inject ,ast Integer)]
  7517. [#t `(inject #t Boolean)]
  7518. [#f `(inject #f Boolean)]
  7519. [`(read) `(inject ,(read-fixnum) Integer)]
  7520. [`(lambda (,xs ...) ,body)
  7521. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  7522. [`(define (,f ,xs ...) ,body)
  7523. (mcons f `(lambda ,xs ,body))]
  7524. [`(program ,ds ... ,body)
  7525. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  7526. (for/list ([b top-level])
  7527. (set-mcdr! b (match (mcdr b)
  7528. [`(lambda ,xs ,body)
  7529. `(inject (lambda ,xs ,body ,top-level)
  7530. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  7531. ((interp-r7 top-level) body))]
  7532. [`(vector ,(app recur elts) ...)
  7533. (define tys (map get-tagged-type elts))
  7534. `(inject ,(apply vector elts) (Vector ,@tys))]
  7535. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  7536. (match v1
  7537. [`(inject ,vec ,ty)
  7538. (vector-set! vec n v2)
  7539. `(inject (void) Void)])]
  7540. [`(vector-ref ,(app recur v) ,n)
  7541. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  7542. [`(let ([,x ,(app recur v)]) ,body)
  7543. ((interp-r7 (cons (cons x v) env)) body)]
  7544. [`(,op ,es ...) #:when (valid-op? op)
  7545. (interp-r7-op op (for/list ([e es]) (recur e)))]
  7546. [`(eq? ,(app recur l) ,(app recur r))
  7547. `(inject ,(equal? l r) Boolean)]
  7548. [`(if ,(app recur q) ,t ,f)
  7549. (match q
  7550. [`(inject #f Boolean) (recur f)]
  7551. [else (recur t)])]
  7552. [`(,(app recur f-val) ,(app recur vs) ...)
  7553. (match f-val
  7554. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  7555. (define new-env (append (map cons xs vs) lam-env))
  7556. ((interp-r7 new-env) body)]
  7557. [else (error "interp-r7, expected function, not" f-val)])])))
  7558. \end{lstlisting}
  7559. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  7560. \label{fig:interp-R7}
  7561. \end{figure}
  7562. Let us consider how we might compile $R_7$ to x86, thinking about the
  7563. first example above. Our bit-level representation of the Boolean
  7564. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7565. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7566. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7567. general, cannot be determined at compile time, but depends on the
  7568. runtime type of its input, as in the example above that depends on the
  7569. result of \code{(read)}.
  7570. The way around this problem is to include information about a value's
  7571. runtime type in the value itself, so that this information can be
  7572. inspected by operators such as \code{not}. In particular, we shall
  7573. steal the 3 right-most bits from our 64-bit values to encode the
  7574. runtime type. We shall use $001$ to identify integers, $100$ for
  7575. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7576. void value. We shall refer to these 3 bits as the \emph{tag} and we
  7577. define the following auxiliary function.
  7578. \begin{align*}
  7579. \itm{tagof}(\key{Integer}) &= 001 \\
  7580. \itm{tagof}(\key{Boolean}) &= 100 \\
  7581. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7582. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7583. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7584. \itm{tagof}(\key{Void}) &= 101
  7585. \end{align*}
  7586. (We shall say more about the new \key{Vectorof} type shortly.)
  7587. This stealing of 3 bits comes at some
  7588. price: our integers are reduced to ranging from $-2^{60}$ to
  7589. $2^{60}$. The stealing does not adversely affect vectors and
  7590. procedures because those values are addresses, and our addresses are
  7591. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7592. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7593. bits with the tag and we can simply zero-out the tag to recover the
  7594. original address.
  7595. In some sense, these tagged values are a new kind of value. Indeed,
  7596. we can extend our \emph{typed} language with tagged values by adding a
  7597. new type to classify them, called \key{Any}, and with operations for
  7598. creating and using tagged values, yielding the $R_6$ language that we
  7599. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7600. fundamental support for polymorphism and runtime types that we need to
  7601. support dynamic typing.
  7602. There is an interesting interaction between tagged values and garbage
  7603. collection. A variable of type \code{Any} might refer to a vector and
  7604. therefore it might be a root that needs to be inspected and copied
  7605. during garbage collection. Thus, we need to treat variables of type
  7606. \code{Any} in a similar way to variables of type \code{Vector} for
  7607. purposes of register allocation, which we discuss in
  7608. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7609. variable of type \code{Any} is spilled, it must be spilled to the root
  7610. stack. But this means that the garbage collector needs to be able to
  7611. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7612. value that points to a tuple, and (3) a tagged value that is not a
  7613. tuple. We enable this differentiation by choosing not to use the tag
  7614. $000$. Instead, that bit pattern is reserved for identifying plain old
  7615. pointers to tuples. On the other hand, if one of the first three bits
  7616. is set, then we have a tagged value, and inspecting the tag can
  7617. differentiation between vectors ($010$) and the other kinds of values.
  7618. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  7619. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7620. extend our compiler to handle the new features of $R_6$
  7621. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7622. \ref{sec:register-allocation-r6}).
  7623. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7624. \label{sec:r6-lang}
  7625. \begin{figure}[tp]
  7626. \centering
  7627. \fbox{
  7628. \begin{minipage}{0.97\textwidth}
  7629. \[
  7630. \begin{array}{lcl}
  7631. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7632. \mid (\key{Vector}\;\Type\ldots) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7633. &\mid& \gray{(\Type\ldots \; \key{->}\; \Type)} \mid \key{Any} \\
  7634. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}\ldots) \\
  7635. &\mid& (\key{Any}\ldots \; \key{->}\; \key{Any})\\
  7636. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7637. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7638. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7639. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7640. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7641. \mid (\key{and}\;\Exp\;\Exp)
  7642. \mid (\key{or}\;\Exp\;\Exp)
  7643. \mid (\key{not}\;\Exp)} \\
  7644. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7645. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7646. (\key{vector-ref}\;\Exp\;\Int)} \\
  7647. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7648. &\mid& \gray{(\Exp \; \Exp\ldots)
  7649. \mid (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7650. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7651. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7652. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7653. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7654. R_6 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7655. \end{array}
  7656. \]
  7657. \end{minipage}
  7658. }
  7659. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7660. with \key{Any}.}
  7661. \label{fig:r6-syntax}
  7662. \end{figure}
  7663. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7664. $(\key{inject}\; e\; T)$ form converts the value produced by
  7665. expression $e$ of type $T$ into a tagged value. The
  7666. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7667. expression $e$ into a value of type $T$ or else halts the program if
  7668. the type tag is equivalent to $T$. We treat
  7669. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7670. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7671. Note that in both \key{inject} and
  7672. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7673. which simplifies the implementation and corresponds with what is
  7674. needed for compiling untyped Racket. The type predicates,
  7675. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7676. if the tag corresponds to the predicate, and return \key{\#t}
  7677. otherwise.
  7678. %
  7679. Selections from the type checker for $R_6$ are shown in
  7680. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7681. Figure~\ref{fig:interp-R6}.
  7682. \begin{figure}[btp]
  7683. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7684. (define (flat-ty? ty) ...)
  7685. (define (typecheck-R6 env)
  7686. (lambda (e)
  7687. (define recur (typecheck-R6 env))
  7688. (match e
  7689. [`(inject ,e ,ty)
  7690. (unless (flat-ty? ty)
  7691. (error "may only inject a value of flat type, not ~a" ty))
  7692. (define-values (new-e e-ty) (recur e))
  7693. (cond
  7694. [(equal? e-ty ty)
  7695. (values `(inject ,new-e ,ty) 'Any)]
  7696. [else
  7697. (error "inject expected ~a to have type ~a" e ty)])]
  7698. [`(project ,e ,ty)
  7699. (unless (flat-ty? ty)
  7700. (error "may only project to a flat type, not ~a" ty))
  7701. (define-values (new-e e-ty) (recur e))
  7702. (cond
  7703. [(equal? e-ty 'Any)
  7704. (values `(project ,new-e ,ty) ty)]
  7705. [else
  7706. (error "project expected ~a to have type Any" e)])]
  7707. [`(vector-ref ,e ,i)
  7708. (define-values (new-e e-ty) (recur e))
  7709. (match e-ty
  7710. [`(Vector ,ts ...) ...]
  7711. [`(Vectorof ,ty)
  7712. (unless (exact-nonnegative-integer? i)
  7713. (error 'type-check "invalid index ~a" i))
  7714. (values `(vector-ref ,new-e ,i) ty)]
  7715. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7716. ...
  7717. )))
  7718. \end{lstlisting}
  7719. \caption{Type checker for parts of the $R_6$ language.}
  7720. \label{fig:typecheck-R6}
  7721. \end{figure}
  7722. % to do: add rules for vector-ref, etc. for Vectorof
  7723. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7724. \begin{figure}[btp]
  7725. \begin{lstlisting}
  7726. (define primitives (set 'boolean? ...))
  7727. (define (interp-op op)
  7728. (match op
  7729. ['boolean? (lambda (v)
  7730. (match v
  7731. [`(tagged ,v1 Boolean) #t]
  7732. [else #f]))]
  7733. ...))
  7734. ;; Equivalence of flat types
  7735. (define (tyeq? t1 t2)
  7736. (match `(,t1 ,t2)
  7737. [`((Vectorof Any) (Vector ,t2s ...))
  7738. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7739. [`((Vector ,t1s ...) (Vectorof Any))
  7740. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7741. [else (equal? t1 t2)]))
  7742. (define (interp-R6 env)
  7743. (lambda (ast)
  7744. (match ast
  7745. [`(inject ,e ,t)
  7746. `(tagged ,((interp-R6 env) e) ,t)]
  7747. [`(project ,e ,t2)
  7748. (define v ((interp-R6 env) e))
  7749. (match v
  7750. [`(tagged ,v1 ,t1)
  7751. (cond [(tyeq? t1 t2)
  7752. v1]
  7753. [else
  7754. (error "in project, type mismatch" t1 t2)])]
  7755. [else
  7756. (error "in project, expected tagged value" v)])]
  7757. ...)))
  7758. \end{lstlisting}
  7759. \caption{Interpreter for $R_6$.}
  7760. \label{fig:interp-R6}
  7761. \end{figure}
  7762. %\clearpage
  7763. \section{Shrinking $R_6$}
  7764. \label{sec:shrink-r6}
  7765. In the \code{shrink} pass we recommend compiling \code{project} into
  7766. an explicit \code{if} expression that uses three new operations:
  7767. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7768. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7769. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7770. value from a tagged value. Finally, the \code{exit} operation ends the
  7771. execution of the program by invoking the operating system's
  7772. \code{exit} function. So the translation for \code{project} is as
  7773. follows. (We have omitted the \code{has-type} AST nodes to make this
  7774. output more readable.)
  7775. \begin{tabular}{lll}
  7776. \begin{minipage}{0.3\textwidth}
  7777. \begin{lstlisting}
  7778. (project |$e$| |$\Type$|)
  7779. \end{lstlisting}
  7780. \end{minipage}
  7781. &
  7782. $\Rightarrow$
  7783. &
  7784. \begin{minipage}{0.5\textwidth}
  7785. \begin{lstlisting}
  7786. (let ([|$\itm{tmp}$| |$e'$|])
  7787. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7788. (value-of-any |$\itm{tmp}$|)
  7789. (exit)))
  7790. \end{lstlisting}
  7791. \end{minipage}
  7792. \end{tabular} \\
  7793. Similarly, we recommend translating the type predicates
  7794. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7795. \section{Instruction Selection for $R_6$}
  7796. \label{sec:select-r6}
  7797. \paragraph{Inject}
  7798. We recommend compiling an \key{inject} as follows if the type is
  7799. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7800. destination to the left by the number of bits specified its source
  7801. argument (in this case $3$, the length of the tag) and it preserves
  7802. the sign of the integer. We use the \key{orq} instruction to combine
  7803. the tag and the value to form the tagged value. \\
  7804. \begin{tabular}{lll}
  7805. \begin{minipage}{0.4\textwidth}
  7806. \begin{lstlisting}
  7807. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7808. \end{lstlisting}
  7809. \end{minipage}
  7810. &
  7811. $\Rightarrow$
  7812. &
  7813. \begin{minipage}{0.5\textwidth}
  7814. \begin{lstlisting}
  7815. (movq |$e'$| |\itm{lhs}'|)
  7816. (salq (int 3) |\itm{lhs}'|)
  7817. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7818. \end{lstlisting}
  7819. \end{minipage}
  7820. \end{tabular} \\
  7821. The instruction selection for vectors and procedures is different
  7822. because their is no need to shift them to the left. The rightmost 3
  7823. bits are already zeros as described above. So we just combine the
  7824. value and the tag using \key{orq}. \\
  7825. \begin{tabular}{lll}
  7826. \begin{minipage}{0.4\textwidth}
  7827. \begin{lstlisting}
  7828. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7829. \end{lstlisting}
  7830. \end{minipage}
  7831. &
  7832. $\Rightarrow$
  7833. &
  7834. \begin{minipage}{0.5\textwidth}
  7835. \begin{lstlisting}
  7836. (movq |$e'$| |\itm{lhs}'|)
  7837. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7838. \end{lstlisting}
  7839. \end{minipage}
  7840. \end{tabular}
  7841. \paragraph{Tag of Any}
  7842. Recall that the \code{tag-of-any} operation extracts the type tag from
  7843. a value of type \code{Any}. The type tag is the bottom three bits, so
  7844. we obtain the tag by taking the bitwise-and of the value with $111$
  7845. ($7$ in decimal).
  7846. \begin{tabular}{lll}
  7847. \begin{minipage}{0.4\textwidth}
  7848. \begin{lstlisting}
  7849. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7850. \end{lstlisting}
  7851. \end{minipage}
  7852. &
  7853. $\Rightarrow$
  7854. &
  7855. \begin{minipage}{0.5\textwidth}
  7856. \begin{lstlisting}
  7857. (movq |$e'$| |\itm{lhs}'|)
  7858. (andq (int 7) |\itm{lhs}'|)
  7859. \end{lstlisting}
  7860. \end{minipage}
  7861. \end{tabular}
  7862. \paragraph{Value of Any}
  7863. Like \key{inject}, the instructions for \key{value-of-any} are
  7864. different depending on whether the type $T$ is a pointer (vector or
  7865. procedure) or not (Integer or Boolean). The following shows the
  7866. instruction selection for Integer and Boolean. We produce an untagged
  7867. value by shifting it to the right by 3 bits.
  7868. %
  7869. \\
  7870. \begin{tabular}{lll}
  7871. \begin{minipage}{0.4\textwidth}
  7872. \begin{lstlisting}
  7873. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7874. \end{lstlisting}
  7875. \end{minipage}
  7876. &
  7877. $\Rightarrow$
  7878. &
  7879. \begin{minipage}{0.5\textwidth}
  7880. \begin{lstlisting}
  7881. (movq |$e'$| |\itm{lhs}'|)
  7882. (sarq (int 3) |\itm{lhs}'|)
  7883. \end{lstlisting}
  7884. \end{minipage}
  7885. \end{tabular} \\
  7886. %
  7887. In the case for vectors and procedures, there is no need to
  7888. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7889. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7890. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7891. \code{movq} into the destination $\itm{lhs}$. We then generate
  7892. \code{andq} with the tagged value to get the desired result. \\
  7893. %
  7894. \begin{tabular}{lll}
  7895. \begin{minipage}{0.4\textwidth}
  7896. \begin{lstlisting}
  7897. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7898. \end{lstlisting}
  7899. \end{minipage}
  7900. &
  7901. $\Rightarrow$
  7902. &
  7903. \begin{minipage}{0.5\textwidth}
  7904. \begin{lstlisting}
  7905. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7906. (andq |$e'$| |\itm{lhs}'|)
  7907. \end{lstlisting}
  7908. \end{minipage}
  7909. \end{tabular}
  7910. %% \paragraph{Type Predicates} We leave it to the reader to
  7911. %% devise a sequence of instructions to implement the type predicates
  7912. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7913. \section{Register Allocation for $R_6$}
  7914. \label{sec:register-allocation-r6}
  7915. \index{register allocation}
  7916. As mentioned above, a variable of type \code{Any} might refer to a
  7917. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7918. of type \code{Any} in the same way that it treats variables of type
  7919. \code{Vector} for purposes of garbage collection. In particular,
  7920. \begin{itemize}
  7921. \item If a variable of type \code{Any} is live during a function call,
  7922. then it must be spilled. One way to accomplish this is to augment
  7923. the pass \code{build-interference} to mark all variables that are
  7924. live after a \code{callq} as interfering with all the registers.
  7925. \item If a variable of type \code{Any} is spilled, it must be spilled
  7926. to the root stack instead of the normal procedure call stack.
  7927. \end{itemize}
  7928. \begin{exercise}\normalfont
  7929. Expand your compiler to handle $R_6$ as discussed in the last few
  7930. sections. Create 5 new programs that use the \code{Any} type and the
  7931. new operations (\code{inject}, \code{project}, \code{boolean?},
  7932. etc.). Test your compiler on these new programs and all of your
  7933. previously created test programs.
  7934. \end{exercise}
  7935. \section{Compiling $R_7$ to $R_6$}
  7936. \label{sec:compile-r7}
  7937. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7938. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7939. given a subexpression $e$ of $R_7$, the pass will produce an
  7940. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7941. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7942. the Boolean \code{\#t}, which must be injected to produce an
  7943. expression of type \key{Any}.
  7944. %
  7945. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7946. addition, is representative of compilation for many operations: the
  7947. arguments have type \key{Any} and must be projected to \key{Integer}
  7948. before the addition can be performed.
  7949. The compilation of \key{lambda} (third row of
  7950. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7951. produce type annotations: we simply use \key{Any}.
  7952. %
  7953. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7954. has to account for some differences in behavior between $R_7$ and
  7955. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7956. kind of values can be used in various places. For example, the
  7957. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7958. the arguments need not be of the same type (but in that case, the
  7959. result will be \code{\#f}).
  7960. \begin{figure}[btp]
  7961. \centering
  7962. \begin{tabular}{|lll|} \hline
  7963. \begin{minipage}{0.25\textwidth}
  7964. \begin{lstlisting}
  7965. #t
  7966. \end{lstlisting}
  7967. \end{minipage}
  7968. &
  7969. $\Rightarrow$
  7970. &
  7971. \begin{minipage}{0.6\textwidth}
  7972. \begin{lstlisting}
  7973. (inject #t Boolean)
  7974. \end{lstlisting}
  7975. \end{minipage}
  7976. \\[2ex]\hline
  7977. \begin{minipage}{0.25\textwidth}
  7978. \begin{lstlisting}
  7979. (+ |$e_1$| |$e_2$|)
  7980. \end{lstlisting}
  7981. \end{minipage}
  7982. &
  7983. $\Rightarrow$
  7984. &
  7985. \begin{minipage}{0.6\textwidth}
  7986. \begin{lstlisting}
  7987. (inject
  7988. (+ (project |$e'_1$| Integer)
  7989. (project |$e'_2$| Integer))
  7990. Integer)
  7991. \end{lstlisting}
  7992. \end{minipage}
  7993. \\[2ex]\hline
  7994. \begin{minipage}{0.25\textwidth}
  7995. \begin{lstlisting}
  7996. (lambda (|$x_1 \ldots$|) |$e$|)
  7997. \end{lstlisting}
  7998. \end{minipage}
  7999. &
  8000. $\Rightarrow$
  8001. &
  8002. \begin{minipage}{0.6\textwidth}
  8003. \begin{lstlisting}
  8004. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  8005. (Any|$\ldots$|Any -> Any))
  8006. \end{lstlisting}
  8007. \end{minipage}
  8008. \\[2ex]\hline
  8009. \begin{minipage}{0.25\textwidth}
  8010. \begin{lstlisting}
  8011. (app |$e_0$| |$e_1 \ldots e_n$|)
  8012. \end{lstlisting}
  8013. \end{minipage}
  8014. &
  8015. $\Rightarrow$
  8016. &
  8017. \begin{minipage}{0.6\textwidth}
  8018. \begin{lstlisting}
  8019. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  8020. |$e'_1 \ldots e'_n$|)
  8021. \end{lstlisting}
  8022. \end{minipage}
  8023. \\[2ex]\hline
  8024. \begin{minipage}{0.25\textwidth}
  8025. \begin{lstlisting}
  8026. (vector-ref |$e_1$| |$e_2$|)
  8027. \end{lstlisting}
  8028. \end{minipage}
  8029. &
  8030. $\Rightarrow$
  8031. &
  8032. \begin{minipage}{0.6\textwidth}
  8033. \begin{lstlisting}
  8034. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  8035. (let ([tmp2 (project |$e'_2$| Integer)])
  8036. (vector-ref tmp1 tmp2)))
  8037. \end{lstlisting}
  8038. \end{minipage}
  8039. \\[2ex]\hline
  8040. \begin{minipage}{0.25\textwidth}
  8041. \begin{lstlisting}
  8042. (if |$e_1$| |$e_2$| |$e_3$|)
  8043. \end{lstlisting}
  8044. \end{minipage}
  8045. &
  8046. $\Rightarrow$
  8047. &
  8048. \begin{minipage}{0.6\textwidth}
  8049. \begin{lstlisting}
  8050. (if (eq? |$e'_1$| (inject #f Boolean))
  8051. |$e'_3$|
  8052. |$e'_2$|)
  8053. \end{lstlisting}
  8054. \end{minipage}
  8055. \\[2ex]\hline
  8056. \begin{minipage}{0.25\textwidth}
  8057. \begin{lstlisting}
  8058. (eq? |$e_1$| |$e_2$|)
  8059. \end{lstlisting}
  8060. \end{minipage}
  8061. &
  8062. $\Rightarrow$
  8063. &
  8064. \begin{minipage}{0.6\textwidth}
  8065. \begin{lstlisting}
  8066. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8067. \end{lstlisting}
  8068. \end{minipage}
  8069. \\[2ex]\hline
  8070. \end{tabular}
  8071. \caption{Compiling $R_7$ to $R_6$.}
  8072. \label{fig:compile-r7-r6}
  8073. \end{figure}
  8074. \begin{exercise}\normalfont
  8075. Expand your compiler to handle $R_7$ as outlined in this chapter.
  8076. Create tests for $R_7$ by adapting all of your previous test programs
  8077. by removing type annotations. Add 5 more tests programs that
  8078. specifically rely on the language being dynamically typed. That is,
  8079. they should not be legal programs in a statically typed language, but
  8080. nevertheless, they should be valid $R_7$ programs that run to
  8081. completion without error.
  8082. \end{exercise}
  8083. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8084. \chapter{Gradual Typing}
  8085. \label{ch:gradual-typing}
  8086. \index{gradual typing}
  8087. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  8088. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8089. \chapter{Parametric Polymorphism}
  8090. \label{ch:parametric-polymorphism}
  8091. \index{parametric polymorphism}
  8092. \index{generics}
  8093. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  8094. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  8095. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8096. \chapter{High-level Optimization}
  8097. \label{ch:high-level-optimization}
  8098. This chapter will present a procedure inlining pass based on the
  8099. algorithm of \citet{Waddell:1997fk}.
  8100. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8101. \chapter{Appendix}
  8102. \section{Interpreters}
  8103. \label{appendix:interp}
  8104. \index{interpreter}
  8105. We provide interpreters for each of the source languages $R_0$, $R_1$,
  8106. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  8107. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  8108. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  8109. the rest of the intermediate languages, including pseudo-x86 and x86
  8110. are in the \key{interp.rkt} file.
  8111. \section{Utility Functions}
  8112. \label{appendix:utilities}
  8113. The utility functions described here are in the \key{utilities.rkt}
  8114. file.
  8115. \paragraph{\code{interp-tests}}
  8116. The \key{interp-tests} function runs the compiler passes and the
  8117. interpreters on each of the specified tests to check whether each pass
  8118. is correct. The \key{interp-tests} function has the following
  8119. parameters:
  8120. \begin{description}
  8121. \item[name (a string)] a name to identify the compiler,
  8122. \item[typechecker] a function of exactly one argument that either
  8123. raises an error using the \code{error} function when it encounters a
  8124. type error, or returns \code{\#f} when it encounters a type
  8125. error. If there is no type error, the type checker returns the
  8126. program.
  8127. \item[passes] a list with one entry per pass. An entry is a list with
  8128. three things: a string giving the name of the pass, the function
  8129. that implements the pass (a translator from AST to AST), and a
  8130. function that implements the interpreter (a function from AST to
  8131. result value) for the language of the output of the pass.
  8132. \item[source-interp] an interpreter for the source language. The
  8133. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8134. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8135. \item[tests] a list of test numbers that specifies which tests to
  8136. run. (see below)
  8137. \end{description}
  8138. %
  8139. The \key{interp-tests} function assumes that the subdirectory
  8140. \key{tests} has a collection of Racket programs whose names all start
  8141. with the family name, followed by an underscore and then the test
  8142. number, ending with the file extension \key{.rkt}. Also, for each test
  8143. program that calls \code{read} one or more times, there is a file with
  8144. the same name except that the file extension is \key{.in} that
  8145. provides the input for the Racket program. If the test program is
  8146. expected to fail type checking, then there should be an empty file of
  8147. the same name but with extension \key{.tyerr}.
  8148. \paragraph{\code{compiler-tests}}
  8149. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8150. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8151. machine code and checks that the output is $42$. The parameters to the
  8152. \code{compiler-tests} function are similar to those of the
  8153. \code{interp-tests} function, and consist of
  8154. \begin{itemize}
  8155. \item a compiler name (a string),
  8156. \item a type checker,
  8157. \item description of the passes,
  8158. \item name of a test-family, and
  8159. \item a list of test numbers.
  8160. \end{itemize}
  8161. \paragraph{\code{compile-file}}
  8162. takes a description of the compiler passes (see the comment for
  8163. \key{interp-tests}) and returns a function that, given a program file
  8164. name (a string ending in \key{.rkt}), applies all of the passes and
  8165. writes the output to a file whose name is the same as the program file
  8166. name but with \key{.rkt} replaced with \key{.s}.
  8167. \paragraph{\code{read-program}}
  8168. takes a file path and parses that file (it must be a Racket program)
  8169. into an abstract syntax tree.
  8170. \paragraph{\code{parse-program}}
  8171. takes an S-expression representation of an abstract syntax tree and converts it into
  8172. the struct-based representation.
  8173. \paragraph{\code{assert}}
  8174. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8175. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8176. \paragraph{\code{lookup}}
  8177. % remove discussion of lookup? -Jeremy
  8178. takes a key and an alist, and returns the first value that is
  8179. associated with the given key, if there is one. If not, an error is
  8180. triggered. The alist may contain both immutable pairs (built with
  8181. \key{cons}) and mutable pairs (built with \key{mcons}).
  8182. %The \key{map2} function ...
  8183. \section{x86 Instruction Set Quick-Reference}
  8184. \label{sec:x86-quick-reference}
  8185. \index{x86}
  8186. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8187. do. We write $A \to B$ to mean that the value of $A$ is written into
  8188. location $B$. Address offsets are given in bytes. The instruction
  8189. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8190. registers (such as \code{\%rax}), or memory references (such as
  8191. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8192. reference per instruction. Other operands must be immediates or
  8193. registers.
  8194. \begin{table}[tbp]
  8195. \centering
  8196. \begin{tabular}{l|l}
  8197. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8198. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8199. \texttt{negq} $A$ & $- A \to A$ \\
  8200. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8201. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8202. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8203. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8204. \texttt{retq} & Pops the return address and jumps to it \\
  8205. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8206. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8207. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8208. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8209. be an immediate) \\
  8210. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8211. matches the condition code of the instruction, otherwise go to the
  8212. next instructions. The condition codes are \key{e} for ``equal'',
  8213. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8214. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8215. \texttt{jl} $L$ & \\
  8216. \texttt{jle} $L$ & \\
  8217. \texttt{jg} $L$ & \\
  8218. \texttt{jge} $L$ & \\
  8219. \texttt{jmp} $L$ & Jump to label $L$ \\
  8220. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8221. \texttt{movzbq} $A$, $B$ &
  8222. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8223. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8224. and the extra bytes of $B$ are set to zero.} \\
  8225. & \\
  8226. & \\
  8227. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8228. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8229. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8230. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8231. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8232. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8233. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8234. description of the condition codes. $A$ must be a single byte register
  8235. (e.g., \texttt{al} or \texttt{cl}).} \\
  8236. \texttt{setl} $A$ & \\
  8237. \texttt{setle} $A$ & \\
  8238. \texttt{setg} $A$ & \\
  8239. \texttt{setge} $A$ &
  8240. \end{tabular}
  8241. \vspace{5pt}
  8242. \caption{Quick-reference for the x86 instructions used in this book.}
  8243. \label{tab:x86-instr}
  8244. \end{table}
  8245. \cleardoublepage
  8246. \addcontentsline{toc}{chapter}{Index}
  8247. \printindex
  8248. \cleardoublepage
  8249. \bibliographystyle{plainnat}
  8250. \bibliography{all}
  8251. \addcontentsline{toc}{chapter}{Bibliography}
  8252. \end{document}
  8253. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8254. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8255. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8256. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8257. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8258. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8259. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8260. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8261. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8262. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8263. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8264. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8265. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  8266. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8267. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8268. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8269. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8270. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8271. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8272. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8273. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8274. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8275. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8276. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8277. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8278. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8279. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8280. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8281. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8282. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8283. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8284. % LocalWords: struct symtab