book.tex 583 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \definecolor{lightgray}{gray}{1}
  17. \newcommand{\black}[1]{{\color{black} #1}}
  18. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  19. \newcommand{\gray}[1]{{\color{gray} #1}}
  20. \def\racketEd{0}
  21. \def\pythonEd{1}
  22. \def\edition{1}
  23. % material that is specific to the Racket edition of the book
  24. \newcommand{\racket}[1]{{\if\edition\racketEd\color{olive}{#1}\fi}}
  25. % would like a command for: \if\edition\racketEd\color{olive}
  26. % and : \fi\color{black}
  27. % material that is specific to the Python edition of the book
  28. \newcommand{\python}[1]{{\if\edition\pythonEd\color{purple}{#1}\fi}}
  29. %% For multiple indices:
  30. \usepackage{multind}
  31. \makeindex{subject}
  32. \makeindex{authors}
  33. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  34. \lstset{%
  35. language=Lisp,
  36. basicstyle=\ttfamily\small,
  37. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  38. deletekeywords={read,mapping,vector},
  39. escapechar=|,
  40. columns=flexible,
  41. moredelim=[is][\color{red}]{~}{~},
  42. showstringspaces=false
  43. }
  44. %%% Any shortcut own defined macros place here
  45. %% sample of author macro:
  46. \input{defs}
  47. \newtheorem{exercise}[theorem]{Exercise}
  48. % Adjusted settings
  49. \setlength{\columnsep}{4pt}
  50. %% \begingroup
  51. %% \setlength{\intextsep}{0pt}%
  52. %% \setlength{\columnsep}{0pt}%
  53. %% \begin{wrapfigure}{r}{0.5\textwidth}
  54. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  55. %% \caption{Basic layout}
  56. %% \end{wrapfigure}
  57. %% \lipsum[1]
  58. %% \endgroup
  59. \newbox\oiintbox
  60. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  61. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  62. \def\oiint{\copy\oiintbox}
  63. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  64. %\usepackage{showframe}
  65. \def\ShowFrameLinethickness{0.125pt}
  66. \addbibresource{book.bib}
  67. \begin{document}
  68. \frontmatter
  69. \HalfTitle{Essentials of Compilation}
  70. \halftitlepage
  71. %% \begin{seriespage}
  72. %% \seriestitle{Industrial Economics}
  73. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  74. %% \title{Engineering and Economics}
  75. %% \author{Samuel Endgrove}
  76. %% \title{Structural Economics: From Beginning to End}
  77. %% \author{Guang Xi}
  78. %% \end{seriespage}
  79. \Title{Essentials of Compilation}
  80. \Booksubtitle{The Incremental, Nano-Pass Approach}
  81. \edition{First Edition}
  82. \BookAuthor{Jeremy G. Siek}
  83. \imprint{The MIT Press\\
  84. Cambridge, Massachusetts\\
  85. London, England}
  86. \begin{copyrightpage}
  87. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  88. or personal downloading under the
  89. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  90. license.
  91. Copyright in this monograph has been licensed exclusively to The MIT
  92. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  93. version to the public in 2022. All inquiries regarding rights should
  94. be addressed to The MIT Press, Rights and Permissions Department.
  95. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  96. %% All rights reserved. No part of this book may be reproduced in any
  97. %% form by any electronic or mechanical means (including photocopying,
  98. %% recording, or information storage and retrieval) without permission in
  99. %% writing from the publisher.
  100. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  101. %% United States of America.
  102. %% Library of Congress Cataloging-in-Publication Data is available.
  103. %% ISBN:
  104. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  105. \end{copyrightpage}
  106. \dedication{This book is dedicated to the programming language wonks
  107. at Indiana University.}
  108. %% \begin{epigraphpage}
  109. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  110. %% \textit{Book Name if any}}
  111. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  112. %% \end{epigraphpage}
  113. \tableofcontents
  114. \listoffigures
  115. \listoftables
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \chapter*{Preface}
  118. \addcontentsline{toc}{fmbm}{Preface}
  119. There is a magical moment when a programmer presses the ``run'' button
  120. and the software begins to execute. Somehow a program written in a
  121. high-level language is running on a computer that is only capable of
  122. shuffling bits. Here we reveal the wizardry that makes that moment
  123. possible. Beginning with the groundbreaking work of Backus and
  124. colleagues in the 1950s, computer scientists discovered techniques for
  125. constructing programs, called \emph{compilers}, that automatically
  126. translate high-level programs into machine code.
  127. We take you on a journey by constructing your own compiler for a small
  128. but powerful language. Along the way we explain the essential
  129. concepts, algorithms, and data structures that underlie compilers. We
  130. develop your understanding of how programs are mapped onto computer
  131. hardware, which is helpful when reasoning about properties at the
  132. junction between hardware and software such as execution time,
  133. software errors, and security vulnerabilities. For those interested
  134. in pursuing compiler construction, our goal is to provide a
  135. stepping-stone to advanced topics such as just-in-time compilation,
  136. program analysis, and program optimization. For those interested in
  137. designing and implementing programming languages, we connect
  138. language design choices to their impact on the compiler and the generated
  139. code.
  140. A compiler is typically organized as a sequence of stages that
  141. progressively translates a program to code that runs on hardware. We
  142. take this approach to the extreme by partitioning our compiler into a
  143. large number of \emph{nanopasses}, each of which performs a single
  144. task. This allows us to test the output of each pass in isolation, and
  145. furthermore, allows us to focus our attention making the compiler far
  146. easier to understand.
  147. %% [TODO: easier to understand/debug for those maintaining the compiler,
  148. %% proving correctness]
  149. The most familiar approach to describing compilers is with one pass
  150. per chapter. The problem with that is it obfuscates how language
  151. features motivate design choices in a compiler. We take an
  152. \emph{incremental} approach in which we build a complete compiler in
  153. each chapter, starting with arithmetic and variables and add new
  154. features in subsequent chapters.
  155. Our choice of language features is designed to elicit the fundamental
  156. concepts and algorithms used in compilers.
  157. \begin{itemize}
  158. \item We begin with integer arithmetic and local variables in
  159. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  160. the fundamental tools of compiler construction: \emph{abstract
  161. syntax trees} and \emph{recursive functions}.
  162. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  163. \emph{graph coloring} to assign variables to machine registers.
  164. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  165. an elegant recursive algorithm for mapping expressions to
  166. \emph{control-flow graphs}.
  167. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  168. \emph{garbage collection}.
  169. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  170. but lack lexical scoping, similar to the C programming
  171. language~\citep{Kernighan:1988nx} except that we generate efficient
  172. tail calls. The reader learns about the procedure call stack,
  173. \emph{calling conventions}, and their interaction with register
  174. allocation and garbage collection.
  175. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  176. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  177. \emph{closure conversion}, in which lambdas are translated into a
  178. combination of functions and tuples.
  179. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  180. point the input languages are statically typed. The reader extends
  181. the statically typed language with an \code{Any} type which serves
  182. as a target for compiling the dynamically typed language.
  183. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  184. programming languages with the addition of loops and mutable
  185. variables. These additions elicit the need for \emph{dataflow
  186. analysis} in the register allocator.
  187. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  188. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  189. in which different regions of a program may be static or dynamically
  190. typed. The reader implements runtime support for \emph{proxies} that
  191. allow values to safely move between regions.
  192. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  193. leveraging the \code{Any} type and type casts developed in Chapters
  194. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  195. \end{itemize}
  196. There are many language features that we do not include. Our choices
  197. weigh the incidental complexity of a feature against the fundamental
  198. concepts that it exposes. For example, we include tuples and not
  199. records because they both elicit the study of heap allocation and
  200. garbage collection but records come with more incidental complexity.
  201. Since 2016 this book has served as the textbook for the compiler
  202. course at Indiana University, a 16-week course for upper-level
  203. undergraduates and first-year graduate students.
  204. %
  205. Prior to this course, students learn to program in both imperative and
  206. functional languages, study data structures and algorithms, and take
  207. discrete mathematics.
  208. %
  209. At the beginning of the course, students form groups of 2-4 people.
  210. The groups complete one chapter every two weeks, starting with
  211. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  212. chapters include a challenge problem that we assign to the graduate
  213. students. The last two weeks of the course involve a final project in
  214. which students design and implement a compiler extension of their
  215. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  216. \ref{ch:Rpoly} can be used in support of these projects or they can
  217. replace some of the earlier chapters. For example, a course with an
  218. emphasis on statically-typed imperative languages would skip
  219. Chapter~\ref{ch:Rdyn} in favor of
  220. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  221. the dependencies between chapters.
  222. This book has also been used in compiler courses at California
  223. Polytechnic State University, Portland State University, Rose–Hulman
  224. Institute of Technology, University of Massachusetts Lowell, and the
  225. University of Vermont.
  226. \begin{figure}[tp]
  227. \begin{tikzpicture}[baseline=(current bounding box.center)]
  228. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  229. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  230. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  231. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  232. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  233. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  234. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  235. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  236. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  237. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  238. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  239. \path[->] (C1) edge [above] node {} (C2);
  240. \path[->] (C2) edge [above] node {} (C3);
  241. \path[->] (C3) edge [above] node {} (C4);
  242. \path[->] (C4) edge [above] node {} (C5);
  243. \path[->] (C5) edge [above] node {} (C6);
  244. \path[->] (C6) edge [above] node {} (C7);
  245. \path[->] (C4) edge [above] node {} (C8);
  246. \path[->] (C4) edge [above] node {} (C9);
  247. \path[->] (C8) edge [above] node {} (C10);
  248. \path[->] (C10) edge [above] node {} (C11);
  249. \end{tikzpicture}
  250. \caption{Diagram of chapter dependencies.}
  251. \label{fig:chapter-dependences}
  252. \end{figure}
  253. \racket{
  254. We use the \href{https://racket-lang.org/}{Racket} language both for
  255. the implementation of the compiler and for the input language, so the
  256. reader should be proficient with Racket or Scheme. There are many
  257. excellent resources for learning Scheme and
  258. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  259. }
  260. \python{
  261. This edition of the book uses the \href{https://www.python.org/}{Python}
  262. both for the implementation of the compiler and for the input language, so the
  263. reader should be proficient with Python. There are many
  264. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  265. }
  266. The support code for this book is in the \code{github} repository at
  267. the following URL:
  268. \begin{center}\small
  269. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  270. \end{center}
  271. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  272. is helpful but not necessary for the reader to have taken a computer
  273. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  274. of x86-64 assembly language that are needed.
  275. %
  276. We follow the System V calling
  277. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  278. that we generate works with the runtime system (written in C) when it
  279. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  280. operating systems.
  281. %
  282. On the Windows operating system, \code{gcc} uses the Microsoft x64
  283. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  284. assembly code that we generate does \emph{not} work with the runtime
  285. system on Windows. One workaround is to use a virtual machine with
  286. Linux as the guest operating system.
  287. \section*{Acknowledgments}
  288. The tradition of compiler construction at Indiana University goes back
  289. to research and courses on programming languages by Daniel Friedman in
  290. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  291. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  292. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  293. the compiler course and continued the development of Chez Scheme.
  294. %
  295. The compiler course evolved to incorporate novel pedagogical ideas
  296. while also including elements of efficient real-world compilers. One
  297. of Friedman's ideas was to split the compiler into many small
  298. passes. Another idea, called ``the game'', was to test the code
  299. generated by each pass using interpreters.
  300. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  301. developed infrastructure to support this approach and evolved the
  302. course to use even smaller
  303. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  304. design decisions in this book are inspired by the assignment
  305. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  306. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  307. organization of the course made it difficult for students to
  308. understand the rationale for the compiler design. Ghuloum proposed the
  309. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  310. on.
  311. We thank the many students who served as teaching assistants for the
  312. compiler course at IU and made suggestions for improving the book
  313. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  314. thank Andre Kuhlenschmidt for his work on the garbage collector,
  315. Michael Vollmer for his work on efficient tail calls, and Michael
  316. Vitousek for his help running the first offering of the incremental
  317. compiler course at IU.
  318. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  319. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  320. for teaching courses based on drafts of this book and for their
  321. invaluable feedback.
  322. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  323. course in the early 2000's and especially for finding the bug that
  324. sent our garbage collector on a wild goose chase!
  325. \mbox{}\\
  326. \noindent Jeremy G. Siek \\
  327. Bloomington, Indiana
  328. \mainmatter
  329. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  330. \chapter{Preliminaries}
  331. \label{ch:trees-recur}
  332. In this chapter we review the basic tools that are needed to implement
  333. a compiler. Programs are typically input by a programmer as text,
  334. i.e., a sequence of characters. The program-as-text representation is
  335. called \emph{concrete syntax}. We use concrete syntax to concisely
  336. write down and talk about programs. Inside the compiler, we use
  337. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  338. that efficiently supports the operations that the compiler needs to
  339. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  340. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  341. from concrete syntax to abstract syntax is a process called
  342. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  343. implementation of parsing in this book.
  344. %
  345. \racket{A parser is provided in the support code for translating from
  346. concrete to abstract syntax.}
  347. %
  348. \python{We use Python's \code{ast} module to translate from concrete
  349. to abstract syntax.}
  350. ASTs can be represented in many different ways inside the compiler,
  351. depending on the programming language used to write the compiler.
  352. %
  353. \racket{We use Racket's
  354. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  355. feature to represent ASTs (Section~\ref{sec:ast}).}
  356. %
  357. \python{We use Python classes and objects to represent ASTs, especially the
  358. classes defined in the standard \code{ast} module for the Python
  359. source language.}
  360. %
  361. We use grammars to define the abstract syntax of programming languages
  362. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  363. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  364. recursive functions to construct and deconstruct ASTs
  365. (Section~\ref{sec:recursion}). This chapter provides an brief
  366. introduction to these ideas.
  367. \racket{\index{subject}{struct}}
  368. \python{\index{subject}{class}\index{subject}{object}}
  369. \section{Abstract Syntax Trees}
  370. \label{sec:ast}
  371. Compilers use abstract syntax trees to represent programs because they
  372. often need to ask questions like: for a given part of a program, what
  373. kind of language feature is it? What are its sub-parts? Consider the
  374. program on the left and its AST on the right. This program is an
  375. addition operation and it has two sub-parts, a read operation and a
  376. negation. The negation has another sub-part, the integer constant
  377. \code{8}. By using a tree to represent the program, we can easily
  378. follow the links to go from one part of a program to its sub-parts.
  379. \begin{center}
  380. \begin{minipage}{0.4\textwidth}
  381. \if\edition\racketEd
  382. \begin{lstlisting}
  383. (+ (read) (- 8))
  384. \end{lstlisting}
  385. \fi
  386. \if\edition\pythonEd
  387. \begin{lstlisting}
  388. input_int() + -8
  389. \end{lstlisting}
  390. \fi
  391. \end{minipage}
  392. \begin{minipage}{0.4\textwidth}
  393. \begin{equation}
  394. \begin{tikzpicture}
  395. \node[draw] (plus) at (0 , 0) {\key{+}};
  396. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  397. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  398. \node[draw] (8) at (1 , -3) {\key{8}};
  399. \draw[->] (plus) to (read);
  400. \draw[->] (plus) to (minus);
  401. \draw[->] (minus) to (8);
  402. \end{tikzpicture}
  403. \label{eq:arith-prog}
  404. \end{equation}
  405. \end{minipage}
  406. \end{center}
  407. We use the standard terminology for trees to describe ASTs: each
  408. rectangle above is called a \emph{node}. The arrows connect a node to its
  409. \emph{children} (which are also nodes). The top-most node is the
  410. \emph{root}. Every node except for the root has a \emph{parent} (the
  411. node it is the child of). If a node has no children, it is a
  412. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  413. \index{subject}{node}
  414. \index{subject}{children}
  415. \index{subject}{root}
  416. \index{subject}{parent}
  417. \index{subject}{leaf}
  418. \index{subject}{internal node}
  419. %% Recall that an \emph{symbolic expression} (S-expression) is either
  420. %% \begin{enumerate}
  421. %% \item an atom, or
  422. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  423. %% where $e_1$ and $e_2$ are each an S-expression.
  424. %% \end{enumerate}
  425. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  426. %% null value \code{'()}, etc. We can create an S-expression in Racket
  427. %% simply by writing a backquote (called a quasi-quote in Racket)
  428. %% followed by the textual representation of the S-expression. It is
  429. %% quite common to use S-expressions to represent a list, such as $a, b
  430. %% ,c$ in the following way:
  431. %% \begin{lstlisting}
  432. %% `(a . (b . (c . ())))
  433. %% \end{lstlisting}
  434. %% Each element of the list is in the first slot of a pair, and the
  435. %% second slot is either the rest of the list or the null value, to mark
  436. %% the end of the list. Such lists are so common that Racket provides
  437. %% special notation for them that removes the need for the periods
  438. %% and so many parenthesis:
  439. %% \begin{lstlisting}
  440. %% `(a b c)
  441. %% \end{lstlisting}
  442. %% The following expression creates an S-expression that represents AST
  443. %% \eqref{eq:arith-prog}.
  444. %% \begin{lstlisting}
  445. %% `(+ (read) (- 8))
  446. %% \end{lstlisting}
  447. %% When using S-expressions to represent ASTs, the convention is to
  448. %% represent each AST node as a list and to put the operation symbol at
  449. %% the front of the list. The rest of the list contains the children. So
  450. %% in the above case, the root AST node has operation \code{`+} and its
  451. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  452. %% diagram \eqref{eq:arith-prog}.
  453. %% To build larger S-expressions one often needs to splice together
  454. %% several smaller S-expressions. Racket provides the comma operator to
  455. %% splice an S-expression into a larger one. For example, instead of
  456. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  457. %% we could have first created an S-expression for AST
  458. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  459. %% S-expression.
  460. %% \begin{lstlisting}
  461. %% (define ast1.4 `(- 8))
  462. %% (define ast1_1 `(+ (read) ,ast1.4))
  463. %% \end{lstlisting}
  464. %% In general, the Racket expression that follows the comma (splice)
  465. %% can be any expression that produces an S-expression.
  466. {\if\edition\racketEd\color{olive}
  467. We define a Racket \code{struct} for each kind of node. For this
  468. chapter we require just two kinds of nodes: one for integer constants
  469. and one for primitive operations. The following is the \code{struct}
  470. definition for integer constants.
  471. \begin{lstlisting}
  472. (struct Int (value))
  473. \end{lstlisting}
  474. An integer node includes just one thing: the integer value.
  475. To create an AST node for the integer $8$, we write \INT{8}.
  476. \begin{lstlisting}
  477. (define eight (Int 8))
  478. \end{lstlisting}
  479. We say that the value created by \INT{8} is an
  480. \emph{instance} of the
  481. \code{Int} structure.
  482. The following is the \code{struct} definition for primitive operations.
  483. \begin{lstlisting}
  484. (struct Prim (op args))
  485. \end{lstlisting}
  486. A primitive operation node includes an operator symbol \code{op} and a
  487. list of child \code{args}. For example, to create an AST that negates
  488. the number $8$, we write \code{(Prim '- (list eight))}.
  489. \begin{lstlisting}
  490. (define neg-eight (Prim '- (list eight)))
  491. \end{lstlisting}
  492. Primitive operations may have zero or more children. The \code{read}
  493. operator has zero children:
  494. \begin{lstlisting}
  495. (define rd (Prim 'read '()))
  496. \end{lstlisting}
  497. whereas the addition operator has two children:
  498. \begin{lstlisting}
  499. (define ast1_1 (Prim '+ (list rd neg-eight)))
  500. \end{lstlisting}
  501. We have made a design choice regarding the \code{Prim} structure.
  502. Instead of using one structure for many different operations
  503. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  504. structure for each operation, as follows.
  505. \begin{lstlisting}
  506. (struct Read ())
  507. (struct Add (left right))
  508. (struct Neg (value))
  509. \end{lstlisting}
  510. The reason we choose to use just one structure is that in many parts
  511. of the compiler the code for the different primitive operators is the
  512. same, so we might as well just write that code once, which is enabled
  513. by using a single structure.
  514. \fi}
  515. {\if\edition\pythonEd\color{purple}
  516. We use a Python \code{class} for each kind of node.
  517. The following is the class definition for constants.
  518. \begin{lstlisting}
  519. class Constant:
  520. def __init__(self, value):
  521. self.value = value
  522. \end{lstlisting}
  523. An integer constant node includes just one thing: the integer value.
  524. To create an AST node for the integer $8$, we write \INT{8}.
  525. \begin{lstlisting}
  526. eight = Constant(8)
  527. \end{lstlisting}
  528. We say that the value created by \INT{8} is an
  529. \emph{instance} of the \code{Constant} class.
  530. The following is class definition for unary operators.
  531. \begin{lstlisting}
  532. class UnaryOp:
  533. def __init__(self, op, operand):
  534. self.op = op
  535. self.operand = operand
  536. \end{lstlisting}
  537. The specific operation is specified by the \code{op} parameter. For
  538. example, the class \code{USub} is for unary subtraction. (More unary
  539. operators are introduced in later chapters.) To create an AST that
  540. negates the number $8$, we write \NEG{\code{eight}}.
  541. \begin{lstlisting}
  542. neg_eight = UnaryOp(USub(), eight)
  543. \end{lstlisting}
  544. The call to the \code{input\_int} function is represented by the
  545. \code{Call} and \code{Name} classes.
  546. \begin{lstlisting}
  547. class Call:
  548. def __init__(self, func, args):
  549. self.func = func
  550. self.args = args
  551. class Name:
  552. def __init__(self, id):
  553. self.id = id
  554. \end{lstlisting}
  555. To create an AST node that calls \code{input\_int}, we write
  556. \begin{lstlisting}
  557. read = Call(Name('input_int'), [])
  558. \end{lstlisting}
  559. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  560. the \code{BinOp} class for binary operators.
  561. \begin{lstlisting}
  562. class BinOp:
  563. def __init__(self, left, op, right):
  564. self.op = op
  565. self.left = left
  566. self.right = right
  567. \end{lstlisting}
  568. Similar to \code{UnaryOp}, the specific operation is specified by the
  569. \code{op} parameter, which for now is just an instance of the
  570. \code{Add} class. So to create the AST node that adds negative eight
  571. to some user input, we write the following.
  572. \begin{lstlisting}
  573. ast1_1 = BinOp(read, Add(), neg_eight)
  574. \end{lstlisting}
  575. \fi}
  576. When compiling a program such as \eqref{eq:arith-prog}, we need to
  577. know that the operation associated with the root node is addition and
  578. we need to be able to access its two children. \racket{Racket}\python{Python}
  579. provides pattern matching to support these kinds of queries, as we see in
  580. Section~\ref{sec:pattern-matching}.
  581. In this book, we often write down the concrete syntax of a program
  582. even when we really have in mind the AST because the concrete syntax
  583. is more concise. We recommend that, in your mind, you always think of
  584. programs as abstract syntax trees.
  585. \section{Grammars}
  586. \label{sec:grammar}
  587. \index{subject}{integer}
  588. \index{subject}{literal}
  589. \index{subject}{constant}
  590. A programming language can be thought of as a \emph{set} of programs.
  591. The set is typically infinite (one can always create larger and larger
  592. programs), so one cannot simply describe a language by listing all of
  593. the programs in the language. Instead we write down a set of rules, a
  594. \emph{grammar}, for building programs. Grammars are often used to
  595. define the concrete syntax of a language, but they can also be used to
  596. describe the abstract syntax. We write our rules in a variant of
  597. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  598. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  599. As an example, we describe a small language, named \LangInt{}, that consists of
  600. integers and arithmetic operations.
  601. \index{subject}{grammar}
  602. The first grammar rule for the abstract syntax of \LangInt{} says that an
  603. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  604. \begin{equation}
  605. \Exp ::= \INT{\Int} \label{eq:arith-int}
  606. \end{equation}
  607. %
  608. Each rule has a left-hand-side and a right-hand-side.
  609. If you have an AST node that matches the
  610. right-hand-side, then you can categorize it according to the
  611. left-hand-side.
  612. %
  613. A name such as $\Exp$ that is defined by the grammar rules is a
  614. \emph{non-terminal}. \index{subject}{non-terminal}
  615. %
  616. The name $\Int$ is also a non-terminal, but instead of defining it
  617. with a grammar rule, we define it with the following explanation. An
  618. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  619. $-$ (for negative integers), such that the sequence of decimals
  620. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  621. the representation of integers using 63 bits, which simplifies several
  622. aspects of compilation. \racket{Thus, these integers corresponds to
  623. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  624. \python{In contrast, integers in Python have unlimited precision, but
  625. the techniques need to handle unlimited precision fall outside the
  626. scope of this book.}
  627. The second grammar rule is the \READOP{} operation that receives an
  628. input integer from the user of the program.
  629. \begin{equation}
  630. \Exp ::= \READ{} \label{eq:arith-read}
  631. \end{equation}
  632. The third rule says that, given an $\Exp$ node, the negation of that
  633. node is also an $\Exp$.
  634. \begin{equation}
  635. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  636. \end{equation}
  637. Symbols in typewriter font are \emph{terminal} symbols and must
  638. literally appear in the program for the rule to be applicable.
  639. \index{subject}{terminal}
  640. We can apply these rules to categorize the ASTs that are in the
  641. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  642. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  643. following AST is an $\Exp$.
  644. \begin{center}
  645. \begin{minipage}{0.5\textwidth}
  646. \NEG{\INT{\code{8}}}
  647. \end{minipage}
  648. \begin{minipage}{0.25\textwidth}
  649. \begin{equation}
  650. \begin{tikzpicture}
  651. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  652. \node[draw, circle] (8) at (0, -1.2) {$8$};
  653. \draw[->] (minus) to (8);
  654. \end{tikzpicture}
  655. \label{eq:arith-neg8}
  656. \end{equation}
  657. \end{minipage}
  658. \end{center}
  659. The next grammar rule is for addition expressions:
  660. \begin{equation}
  661. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  662. \end{equation}
  663. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  664. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  665. \eqref{eq:arith-read} and we have already categorized
  666. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  667. to show that
  668. \[
  669. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  670. \]
  671. is an $\Exp$ in the \LangInt{} language.
  672. If you have an AST for which the above rules do not apply, then the
  673. AST is not in \LangInt{}. For example, the program \racket{\code{(-
  674. (read) 8)}} \python{\code{input\_int() - 8}} is not in \LangInt{}
  675. because there are no rules for the \key{-} operator with two
  676. arguments. Whenever we define a language with a grammar, the language
  677. only includes those programs that are justified by the rules.
  678. {\if\edition\pythonEd\color{purple}
  679. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  680. There is a statement for printing the value of an expression
  681. \[
  682. \Stmt{} ::= \PRINT{\Exp}
  683. \]
  684. and a statement that evaluates an expression but ignores the result.
  685. \[
  686. \Stmt{} ::= \EXPR{\Exp}
  687. \]
  688. \fi}
  689. {\if\edition\racketEd\color{olive}
  690. The last grammar rule for \LangInt{} states that there is a
  691. \code{Program} node to mark the top of the whole program:
  692. \[
  693. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  694. \]
  695. The \code{Program} structure is defined as follows
  696. \begin{lstlisting}
  697. (struct Program (info body))
  698. \end{lstlisting}
  699. where \code{body} is an expression. In later chapters, the \code{info}
  700. part will be used to store auxiliary information but for now it is
  701. just the empty list.
  702. \fi}
  703. {\if\edition\pythonEd\color{purple}
  704. The last grammar rule for \LangInt{} states that there is a
  705. \code{Module} node to mark the top of the whole program:
  706. \[
  707. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  708. \]
  709. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  710. this case, a list of statements.
  711. %
  712. The \code{Module} class is defined as follows
  713. \begin{lstlisting}
  714. class Module:
  715. def __init__(self, body):
  716. self.body = body
  717. \end{lstlisting}
  718. where \code{body} is a list of statements.
  719. \fi}
  720. It is common to have many grammar rules with the same left-hand side
  721. but different right-hand sides, such as the rules for $\Exp$ in the
  722. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  723. combine several right-hand-sides into a single rule.
  724. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  725. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  726. defined in Figure~\ref{fig:r0-concrete-syntax}.
  727. \racket{The \code{read-program} function provided in
  728. \code{utilities.rkt} of the support code reads a program in from a
  729. file (the sequence of characters in the concrete syntax of Racket)
  730. and parses it into an abstract syntax tree. See the description of
  731. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  732. details.}
  733. \python{The \code{parse} function in Python's \code{ast} module
  734. converts the concrete syntax (represented as a string) into an
  735. abstract syntax tree.}
  736. \begin{figure}[tp]
  737. \fbox{
  738. \begin{minipage}{0.96\textwidth}
  739. {\if\edition\racketEd\color{olive}
  740. \[
  741. \begin{array}{rcl}
  742. \Exp &::=& \Int \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp\;\Exp\RP\\
  743. \LangInt{} &::=& \Exp
  744. \end{array}
  745. \]
  746. \fi}
  747. {\if\edition\pythonEd\color{purple}
  748. \[
  749. \begin{array}{rcl}
  750. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp\\
  751. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp\\
  752. \LangInt{} &::=& \Stmt^{*}
  753. \end{array}
  754. \]
  755. \fi}
  756. \end{minipage}
  757. }
  758. \caption{The concrete syntax of \LangInt{}.}
  759. \label{fig:r0-concrete-syntax}
  760. \end{figure}
  761. \begin{figure}[tp]
  762. \fbox{
  763. \begin{minipage}{0.96\textwidth}
  764. {\if\edition\racketEd\color{olive}
  765. \[
  766. \begin{array}{rcl}
  767. \Exp &::=& \INT{\Int} \MID \READ{} \MID \NEG{\Exp} \\
  768. &\MID& \ADD{\Exp}{\Exp} \\
  769. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  770. \end{array}
  771. \]
  772. \fi}
  773. {\if\edition\pythonEd\color{purple}
  774. \[
  775. \begin{array}{rcl}
  776. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  777. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  778. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  779. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  780. \end{array}
  781. \]
  782. \fi}
  783. \end{minipage}
  784. }
  785. \caption{The abstract syntax of \LangInt{}.}
  786. \label{fig:r0-syntax}
  787. \end{figure}
  788. \section{Pattern Matching}
  789. \label{sec:pattern-matching}
  790. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  791. the parts of an AST node. \racket{Racket}\python{Python} provides the
  792. \texttt{match} feature to access the parts of a value.
  793. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  794. \begin{center}
  795. \begin{minipage}{0.5\textwidth}
  796. {\if\edition\racketEd\color{olive}
  797. \begin{lstlisting}
  798. (match ast1_1
  799. [(Prim op (list child1 child2))
  800. (print op)])
  801. \end{lstlisting}
  802. \fi}
  803. {\if\edition\pythonEd\color{purple}
  804. \begin{lstlisting}
  805. match ast1_1:
  806. case BinOp(child1, op, child2):
  807. print(op)
  808. \end{lstlisting}
  809. \fi}
  810. \end{minipage}
  811. \end{center}
  812. {\if\edition\racketEd\color{olive}
  813. %
  814. In the above example, the \texttt{match} form checks whether the AST
  815. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  816. three pattern variables \texttt{op}, \texttt{child1}, and
  817. \texttt{child2}, and then prints out the operator. In general, a match
  818. clause consists of a \emph{pattern} and a
  819. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  820. to be either a pattern variable, a structure name followed by a
  821. pattern for each of the structure's arguments, or an S-expression
  822. (symbols, lists, etc.). (See Chapter 12 of The Racket
  823. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  824. and Chapter 9 of The Racket
  825. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  826. for a complete description of \code{match}.)
  827. %
  828. The body of a match clause may contain arbitrary Racket code. The
  829. pattern variables can be used in the scope of the body, such as
  830. \code{op} in \code{(print op)}.
  831. %
  832. \fi}
  833. %
  834. %
  835. {\if\edition\pythonEd\color{purple}
  836. %
  837. In the above example, the \texttt{match} form checks whether the AST
  838. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  839. three pattern variables \texttt{child1}, \texttt{op}, and
  840. \texttt{child2}, and then prints out the operator. In general, each
  841. \code{case} consists of a \emph{pattern} and a
  842. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  843. to be either a pattern variable, a class name followed by a pattern
  844. for each of its constructor's arguments, or other literals such as
  845. strings, lists, etc.
  846. %
  847. The body of each \code{case} may contain arbitrary Python code. The
  848. pattern variables can be used in the body, such as \code{op} in
  849. \code{print(op)}.
  850. %
  851. \fi}
  852. A \code{match} form may contain several clauses, as in the following
  853. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  854. the AST. The \code{match} proceeds through the clauses in order,
  855. checking whether the pattern can match the input AST. The body of the
  856. first clause that matches is executed. The output of \code{leaf} for
  857. several ASTs is shown on the right.
  858. \begin{center}
  859. \begin{minipage}{0.6\textwidth}
  860. {\if\edition\racketEd\color{olive}
  861. \begin{lstlisting}
  862. (define (leaf arith)
  863. (match arith
  864. [(Int n) #t]
  865. [(Prim 'read '()) #t]
  866. [(Prim '- (list e1)) #f]
  867. [(Prim '+ (list e1 e2)) #f]))
  868. (leaf (Prim 'read '()))
  869. (leaf (Prim '- (list (Int 8))))
  870. (leaf (Int 8))
  871. \end{lstlisting}
  872. \fi}
  873. {\if\edition\pythonEd\color{purple}
  874. \begin{lstlisting}
  875. def leaf(arith):
  876. match arith:
  877. case Constant(n):
  878. return True
  879. case Call(Name('input_int'), []):
  880. return True
  881. case UnaryOp(USub(), e1):
  882. return False
  883. case BinOp(e1, Add(), e2):
  884. return False
  885. case _:
  886. return False
  887. print(leaf(Call(Name('input_int'), [])))
  888. print(leaf(UnaryOp(USub(), eight)))
  889. print(leaf(Constant(8)))
  890. \end{lstlisting}
  891. \fi}
  892. \end{minipage}
  893. \vrule
  894. \begin{minipage}{0.25\textwidth}
  895. {\if\edition\racketEd\color{olive}
  896. \begin{lstlisting}
  897. #t
  898. #f
  899. #t
  900. \end{lstlisting}
  901. \fi}
  902. {\if\edition\pythonEd\color{purple}
  903. \begin{lstlisting}
  904. True
  905. False
  906. True
  907. \end{lstlisting}
  908. \fi}
  909. \end{minipage}
  910. \end{center}
  911. When writing a \code{match}, we refer to the grammar definition to
  912. identify which non-terminal we are expecting to match against, then we
  913. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  914. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  915. corresponding right-hand side of a grammar rule. For the \code{match}
  916. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  917. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  918. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  919. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  920. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  921. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  922. patterns, replace non-terminals such as $\Exp$ with pattern variables
  923. of your choice (e.g. \code{e1} and \code{e2}).
  924. \section{Recursive Functions}
  925. \label{sec:recursion}
  926. \index{subject}{recursive function}
  927. Programs are inherently recursive. For example, an \LangInt{}
  928. expression is often made of smaller expressions. Thus, the natural way
  929. to process an entire program is with a recursive function. As a first
  930. example of such a recursive function, we define the function
  931. \code{exp} in Figure~\ref{fig:exp-predicate}, which takes an
  932. arbitrary value and determines whether or not it is an \LangInt{}
  933. expression.
  934. %
  935. We say that a function is defined by \emph{structural recursion} when
  936. it is defined using a sequence of match \racket{clauses}\python{cases}
  937. that correspond to a grammar, and the body of each \racket{clause}\python{case}
  938. makes a recursive call on each
  939. child node.\footnote{This principle of structuring code according to
  940. the data definition is advocated in the book \emph{How to Design
  941. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  942. \python{We define a second function, named \code{stmt}, that recognizes
  943. whether a value is a \LangInt{} statement.}
  944. \python{Finally, }
  945. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{Rint}, which
  946. determines whether an AST is a program in \LangInt{}. In general we can
  947. expect to write one recursive function to handle each non-terminal in
  948. a grammar.\index{subject}{structural recursion}
  949. \begin{figure}[tp]
  950. {\if\edition\racketEd\color{olive}
  951. \begin{minipage}{0.7\textwidth}
  952. \begin{lstlisting}
  953. (define (exp ast)
  954. (match ast
  955. [(Int n) #t]
  956. [(Prim 'read '()) #t]
  957. [(Prim '- (list e)) (exp e)]
  958. [(Prim '+ (list e1 e2))
  959. (and (exp e1) (exp e2))]
  960. [else #f]))
  961. (define (Rint ast)
  962. (match ast
  963. [(Program '() e) (exp e)]
  964. [else #f]))
  965. (Rint (Program '() ast1_1)
  966. (Rint (Program '()
  967. (Prim '- (list (Prim 'read '())
  968. (Prim '+ (list (Num 8)))))))
  969. \end{lstlisting}
  970. \end{minipage}
  971. \vrule
  972. \begin{minipage}{0.25\textwidth}
  973. \begin{lstlisting}
  974. #t
  975. #f
  976. \end{lstlisting}
  977. \end{minipage}
  978. \fi}
  979. {\if\edition\pythonEd\color{purple}
  980. \begin{minipage}{0.7\textwidth}
  981. \begin{lstlisting}
  982. def exp(e):
  983. match e:
  984. case Constant(n):
  985. return True
  986. case Call(Name('input_int'), []):
  987. return True
  988. case UnaryOp(USub(), e1):
  989. return exp(e1)
  990. case BinOp(e1, Add(), e2):
  991. return exp(e1) and exp(e2)
  992. case _:
  993. return False
  994. def stmt(s):
  995. match s:
  996. case Call(Name('print'), [e]):
  997. return exp(e)
  998. case Expr(e):
  999. return exp(e)
  1000. case _:
  1001. return False
  1002. def Rint(p):
  1003. match p:
  1004. case Module(body):
  1005. return all([stmt(s) for s in body])
  1006. case _:
  1007. return False
  1008. print(Rint(Module([Expr(ast1_1)])))
  1009. print(Rint(Module([Expr(BinOp(read, Sub(),
  1010. UnaryOp(Add(), Constant(8))))])))
  1011. \end{lstlisting}
  1012. \end{minipage}
  1013. \vrule
  1014. \begin{minipage}{0.25\textwidth}
  1015. \begin{lstlisting}
  1016. True
  1017. False
  1018. \end{lstlisting}
  1019. \end{minipage}
  1020. \fi}
  1021. \caption{Example of recursive functions for \LangInt{}. These functions
  1022. recognize whether an AST is in \LangInt{}.}
  1023. \label{fig:exp-predicate}
  1024. \end{figure}
  1025. %% You may be tempted to merge the two functions into one, like this:
  1026. %% \begin{center}
  1027. %% \begin{minipage}{0.5\textwidth}
  1028. %% \begin{lstlisting}
  1029. %% (define (Rint ast)
  1030. %% (match ast
  1031. %% [(Int n) #t]
  1032. %% [(Prim 'read '()) #t]
  1033. %% [(Prim '- (list e)) (Rint e)]
  1034. %% [(Prim '+ (list e1 e2)) (and (Rint e1) (Rint e2))]
  1035. %% [(Program '() e) (Rint e)]
  1036. %% [else #f]))
  1037. %% \end{lstlisting}
  1038. %% \end{minipage}
  1039. %% \end{center}
  1040. %% %
  1041. %% Sometimes such a trick will save a few lines of code, especially when
  1042. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1043. %% \emph{not} recommended because it can get you into trouble.
  1044. %% %
  1045. %% For example, the above function is subtly wrong:
  1046. %% \lstinline{(Rint (Program '() (Program '() (Int 3))))}
  1047. %% returns true when it should return false.
  1048. \section{Interpreters}
  1049. \label{sec:interp_Rint}
  1050. \index{subject}{interpreter}
  1051. The behavior of a program is defined by the specification of the
  1052. programming language.
  1053. %
  1054. \racket{For example, the Scheme language is defined in the report by
  1055. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1056. reference manual~\citep{plt-tr}.}
  1057. %
  1058. \python{For example, the Python language is defined in the Python
  1059. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1060. %
  1061. In this book we use interpreters
  1062. to specify each language that we consider. An interpreter that is
  1063. designated as the definition of a language is called a
  1064. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1065. \index{subject}{definitional interpreter} We warm up by creating a
  1066. definitional interpreter for the \LangInt{} language, which serves as
  1067. a second example of structural recursion. The \texttt{interp\_Rint}
  1068. function is defined in Figure~\ref{fig:interp_Rint}. The body of the
  1069. function is a match on the input program followed by a call to the
  1070. \lstinline{interp_exp} helper function, which in turn has one match
  1071. clause per grammar rule for \LangInt{} expressions.
  1072. \begin{figure}[tp]
  1073. {\if\edition\racketEd\color{olive}
  1074. \begin{lstlisting}
  1075. (define (interp_exp e)
  1076. (match e
  1077. [(Int n) n]
  1078. [(Prim 'read '())
  1079. (define r (read))
  1080. (cond [(fixnum? r) r]
  1081. [else (error 'interp_exp "read expected an integer" r)])]
  1082. [(Prim '- (list e))
  1083. (define v (interp_exp e))
  1084. (fx- 0 v)]
  1085. [(Prim '+ (list e1 e2))
  1086. (define v1 (interp_exp e1))
  1087. (define v2 (interp_exp e2))
  1088. (fx+ v1 v2)]))
  1089. (define (interp_Rint p)
  1090. (match p
  1091. [(Program '() e) (interp_exp e)]))
  1092. \end{lstlisting}
  1093. \fi}
  1094. {\if\edition\pythonEd\color{purple}
  1095. \begin{lstlisting}
  1096. def interp_exp(e):
  1097. match e:
  1098. case BinOp(left, Add(), right):
  1099. l = interp_exp(left)
  1100. r = interp_exp(right)
  1101. return l + r
  1102. case UnaryOp(USub(), v):
  1103. return - interp_exp(v)
  1104. case Constant(value):
  1105. return value
  1106. case Call(Name('input_int'), []):
  1107. return int(input())
  1108. def interp_stmt(s):
  1109. match s:
  1110. case Expr(Call(Name('print'), [arg])):
  1111. print(interp_exp(arg))
  1112. case Expr(value):
  1113. interp_exp(value)
  1114. def interp_Pint(p):
  1115. match p:
  1116. case Module(body):
  1117. for s in body:
  1118. interp_stmt(s)
  1119. \end{lstlisting}
  1120. \fi}
  1121. \caption{Interpreter for the \LangInt{} language.}
  1122. \label{fig:interp_Rint}
  1123. \end{figure}
  1124. Let us consider the result of interpreting a few \LangInt{} programs. The
  1125. following program adds two integers.
  1126. {\if\edition\racketEd\color{olive}
  1127. \begin{lstlisting}
  1128. (+ 10 32)
  1129. \end{lstlisting}
  1130. \fi}
  1131. {\if\edition\pythonEd\color{purple}
  1132. \begin{lstlisting}
  1133. print(10 + 32)
  1134. \end{lstlisting}
  1135. \fi}
  1136. The result is \key{42}, the answer to life, the universe, and
  1137. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1138. Galaxy} by Douglas Adams.}.
  1139. %
  1140. We wrote the above program in concrete syntax whereas the parsed
  1141. abstract syntax is:
  1142. {\if\edition\racketEd\color{olive}
  1143. \begin{lstlisting}
  1144. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1145. \end{lstlisting}
  1146. \fi}
  1147. {\if\edition\pythonEd\color{purple}
  1148. \begin{lstlisting}
  1149. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1150. \end{lstlisting}
  1151. \fi}
  1152. The next example demonstrates that expressions may be nested within
  1153. each other, in this case nesting several additions and negations.
  1154. {\if\edition\racketEd\color{olive}
  1155. \begin{lstlisting}
  1156. (+ 10 (- (+ 12 20)))
  1157. \end{lstlisting}
  1158. \fi}
  1159. {\if\edition\pythonEd\color{purple}
  1160. \begin{lstlisting}
  1161. print(10 + -(12 + 20))
  1162. \end{lstlisting}
  1163. \fi}
  1164. What is the result of the above program?
  1165. {\if\edition\racketEd\color{olive}
  1166. As mentioned previously, the \LangInt{} language does not support
  1167. arbitrarily-large integers, but only $63$-bit integers, so we
  1168. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1169. in Racket.
  1170. Suppose
  1171. \[
  1172. n = 999999999999999999
  1173. \]
  1174. which indeed fits in $63$-bits. What happens when we run the
  1175. following program in our interpreter?
  1176. \begin{lstlisting}
  1177. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1178. \end{lstlisting}
  1179. It produces an error:
  1180. \begin{lstlisting}
  1181. fx+: result is not a fixnum
  1182. \end{lstlisting}
  1183. We establish the convention that if running the definitional
  1184. interpreter on a program produces an error then the meaning of that
  1185. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1186. error is a \code{trapped-error}. A compiler for the language is under
  1187. no obligations regarding programs with unspecified behavior; it does
  1188. not have to produce an executable, and if it does, that executable can
  1189. do anything. On the other hand, if the error is a
  1190. \code{trapped-error}, then the compiler must produce an executable and
  1191. it is required to report that an error occurred. To signal an error,
  1192. exit with a return code of \code{255}. The interpreters in chapters
  1193. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1194. \code{trapped-error}.
  1195. \fi}
  1196. % TODO: how to deal with too-large integers in the Python interpreter?
  1197. %% This convention applies to the languages defined in this
  1198. %% book, as a way to simplify the student's task of implementing them,
  1199. %% but this convention is not applicable to all programming languages.
  1200. %%
  1201. Moving on to the last feature of the \LangInt{} language, the
  1202. \READOP{} operation prompts the user of the program for an integer.
  1203. Recall that program \eqref{eq:arith-prog} requests an integer input
  1204. and then subtracts \code{8}. So if we run
  1205. {\if\edition\racketEd\color{olive}
  1206. \begin{lstlisting}
  1207. (interp_Rint (Program '() ast1_1))
  1208. \end{lstlisting}
  1209. \fi}
  1210. {\if\edition\pythonEd\color{purple}
  1211. \begin{lstlisting}
  1212. interp_Pint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1213. \end{lstlisting}
  1214. \fi}
  1215. \noindent and if the input is \code{50}, the result is \code{42}.
  1216. We include the \READOP{} operation in \LangInt{} so a clever student
  1217. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1218. during compilation to obtain the output and then generates the trivial
  1219. code to produce the output.\footnote{Yes, a clever student did this in the
  1220. first instance of this course!}
  1221. The job of a compiler is to translate a program in one language into a
  1222. program in another language so that the output program behaves the
  1223. same way as the input program does. This idea is depicted in the
  1224. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1225. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1226. Given a compiler that translates from language $\mathcal{L}_1$ to
  1227. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1228. compiler must translate it into some program $P_2$ such that
  1229. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1230. same input $i$ yields the same output $o$.
  1231. \begin{equation} \label{eq:compile-correct}
  1232. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1233. \node (p1) at (0, 0) {$P_1$};
  1234. \node (p2) at (3, 0) {$P_2$};
  1235. \node (o) at (3, -2.5) {$o$};
  1236. \path[->] (p1) edge [above] node {compile} (p2);
  1237. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  1238. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  1239. \end{tikzpicture}
  1240. \end{equation}
  1241. In the next section we see our first example of a compiler.
  1242. \section{Example Compiler: a Partial Evaluator}
  1243. \label{sec:partial-evaluation}
  1244. In this section we consider a compiler that translates \LangInt{} programs
  1245. into \LangInt{} programs that may be more efficient, that is, this compiler
  1246. is an optimizer. This optimizer eagerly computes the parts of the
  1247. program that do not depend on any inputs, a process known as
  1248. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1249. \index{subject}{partial evaluation}
  1250. For example, given the following program
  1251. {\if\edition\racketEd\color{olive}
  1252. \begin{lstlisting}
  1253. (+ (read) (- (+ 5 3)))
  1254. \end{lstlisting}
  1255. \fi}
  1256. {\if\edition\pythonEd\color{purple}
  1257. \begin{lstlisting}
  1258. print input_int() + -(5 + 3)
  1259. \end{lstlisting}
  1260. \fi}
  1261. \noindent our compiler translates it into the program
  1262. {\if\edition\racketEd\color{olive}
  1263. \begin{lstlisting}
  1264. (+ (read) -8)
  1265. \end{lstlisting}
  1266. \fi}
  1267. {\if\edition\pythonEd\color{purple}
  1268. \begin{lstlisting}
  1269. print input_int() + -8
  1270. \end{lstlisting}
  1271. \fi}
  1272. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1273. evaluator for the \LangInt{} language. The output of the partial evaluator
  1274. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1275. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1276. whereas the code for partially evaluating the negation and addition
  1277. operations is factored into two separate helper functions:
  1278. \code{pe\_neg} and \code{pe\_add}. The input to these helper
  1279. functions is the output of partially evaluating the children.
  1280. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1281. arguments are integers and if they are, perform the appropriate
  1282. arithmetic. Otherwise, they create an AST node for the arithmetic
  1283. operation.
  1284. \begin{figure}[tp]
  1285. {\if\edition\racketEd\color{olive}
  1286. \begin{lstlisting}
  1287. (define (pe_neg r)
  1288. (match r
  1289. [(Int n) (Int (fx- 0 n))]
  1290. [else (Prim '- (list r))]))
  1291. (define (pe_add r1 r2)
  1292. (match* (r1 r2)
  1293. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1294. [(_ _) (Prim '+ (list r1 r2))]))
  1295. (define (pe_exp e)
  1296. (match e
  1297. [(Int n) (Int n)]
  1298. [(Prim 'read '()) (Prim 'read '())]
  1299. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1300. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1301. (define (pe_Rint p)
  1302. (match p
  1303. [(Program '() e) (Program '() (pe_exp e))]))
  1304. \end{lstlisting}
  1305. \fi}
  1306. {\if\edition\pythonEd\color{purple}
  1307. \begin{lstlisting}
  1308. def pe_neg(r):
  1309. match r:
  1310. case Constant(n):
  1311. return Constant(-n)
  1312. case _:
  1313. return UnaryOp(USub(), r)
  1314. def pe_add(r1, r2):
  1315. match (r1, r2):
  1316. case (Constant(n1), Constant(n2)):
  1317. return Constant(n1 + n2)
  1318. case _:
  1319. return BinOp(r1, Add(), r2)
  1320. def pe_exp(e):
  1321. match e:
  1322. case BinOp(left, Add(), right):
  1323. return pe_add(pe_exp(left), pe_exp(right))
  1324. case UnaryOp(USub(), v):
  1325. return pe_neg(pe_exp(v))
  1326. case Constant(value):
  1327. return e
  1328. case Call(Name('input_int'), []):
  1329. return e
  1330. def pe_stmt(s):
  1331. match s:
  1332. case Expr(Call(Name('print'), [arg])):
  1333. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1334. case Expr(value):
  1335. return Expr(pe_exp(value))
  1336. def pe_Pint(p):
  1337. match p:
  1338. case Module(body):
  1339. new_body = [pe_stmt(s) for s in body]
  1340. return Module(new_body)
  1341. \end{lstlisting}
  1342. \fi}
  1343. \caption{A partial evaluator for \LangInt{}.}
  1344. \label{fig:pe-arith}
  1345. \end{figure}
  1346. To gain some confidence that the partial evaluator is correct, we can
  1347. test whether it produces programs that get the same result as the
  1348. input programs. That is, we can test whether it satisfies Diagram
  1349. \ref{eq:compile-correct}.
  1350. %
  1351. {\if\edition\racketEd\color{olive}
  1352. The following code runs the partial evaluator on several examples and
  1353. tests the output program. The \texttt{parse-program} and
  1354. \texttt{assert} functions are defined in
  1355. Appendix~\ref{appendix:utilities}.\\
  1356. \begin{minipage}{1.0\textwidth}
  1357. \begin{lstlisting}
  1358. (define (test_pe p)
  1359. (assert "testing pe_Rint"
  1360. (equal? (interp_Rint p) (interp_Rint (pe_Rint p)))))
  1361. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1362. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1363. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1364. \end{lstlisting}
  1365. \end{minipage}
  1366. \fi}
  1367. % TODO: python version of testing the PE
  1368. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1369. \chapter{Integers and Variables}
  1370. \label{ch:Rvar}
  1371. This chapter is about compiling a subset of \racket{Racket}\python{Python}
  1372. to x86-64 assembly
  1373. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1374. integer arithmetic and local variable binding. We often refer to
  1375. x86-64 simply as x86. The chapter begins with a description of the
  1376. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1377. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1378. is large so we discuss only the instructions needed for compiling
  1379. \LangVar{}. We introduce more x86 instructions in later chapters.
  1380. After introducing \LangVar{} and x86, we reflect on their differences
  1381. and come up with a plan to break down the translation from \LangVar{}
  1382. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1383. rest of the sections in this chapter give detailed hints regarding
  1384. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1385. We hope to give enough hints that the well-prepared reader, together
  1386. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1387. a couple weeks. To give the reader a feeling for the scale of this
  1388. first compiler, the instructor solution for the \LangVar{} compiler is
  1389. approximately \racket{500}\python{300} lines of code.
  1390. \section{The \LangVar{} Language}
  1391. \label{sec:s0}
  1392. \index{subject}{variable}
  1393. The \LangVar{} language extends the \LangInt{} language with
  1394. variables. The concrete syntax of the \LangVar{} language is defined
  1395. by the grammar in Figure~\ref{fig:Rvar-concrete-syntax} and the
  1396. abstract syntax is defined in Figure~\ref{fig:Rvar-syntax}. The
  1397. non-terminal \Var{} may be any Racket identifier. As in \LangInt{},
  1398. \key{read} is a nullary operator, \key{-} is a unary operator, and
  1399. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1400. syntax of \LangVar{} includes the \racket{\key{Program}
  1401. struct}\python{\key{Module} instance} to mark the top of the
  1402. program.
  1403. %% The $\itm{info}$
  1404. %% field of the \key{Program} structure contains an \emph{association
  1405. %% list} (a list of key-value pairs) that is used to communicate
  1406. %% auxiliary data from one compiler pass the next.
  1407. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1408. exhibit several compilation techniques.
  1409. \begin{figure}[tp]
  1410. \centering
  1411. \fbox{
  1412. \begin{minipage}{0.96\textwidth}
  1413. {\if\edition\racketEd\color{olive}
  1414. \[
  1415. \begin{array}{rcl}
  1416. \Exp &::=& \Int{} \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}\\
  1417. &\MID& \Var{} \MID \CLET{\Var}{\Exp}{\Exp} \\
  1418. \LangVarM{} &::=& \Exp
  1419. \end{array}
  1420. \]
  1421. \fi}
  1422. {\if\edition\pythonEd\color{purple}
  1423. \[
  1424. \begin{array}{rcl}
  1425. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Var{} \\
  1426. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp\\
  1427. \LangVarM{} &::=& \Stmt^{*}
  1428. \end{array}
  1429. \]
  1430. \fi}
  1431. \end{minipage}
  1432. }
  1433. \caption{The concrete syntax of \LangVar{}.}
  1434. \label{fig:Rvar-concrete-syntax}
  1435. \end{figure}
  1436. \begin{figure}[tp]
  1437. \centering
  1438. \fbox{
  1439. \begin{minipage}{0.96\textwidth}
  1440. {\if\edition\racketEd\color{olive}
  1441. \[
  1442. \begin{array}{rcl}
  1443. \Exp &::=& \INT{\Int} \MID \READ{} \\
  1444. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  1445. &\MID& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  1446. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1447. \end{array}
  1448. \]
  1449. \fi}
  1450. {\if\edition\pythonEd\color{purple}
  1451. \[
  1452. \begin{array}{rcl}
  1453. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  1454. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \VAR{\Var{}} \\
  1455. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  1456. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  1457. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1458. \end{array}
  1459. \]
  1460. \fi}
  1461. \end{minipage}
  1462. }
  1463. \caption{The abstract syntax of \LangVar{}.}
  1464. \label{fig:Rvar-syntax}
  1465. \end{figure}
  1466. {\if\edition\racketEd\color{olive}
  1467. Let us dive further into the syntax and semantics of the \LangVar{}
  1468. language. The \key{let} feature defines a variable for use within its
  1469. body and initializes the variable with the value of an expression.
  1470. The abstract syntax for \key{let} is defined in
  1471. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for \key{let} is
  1472. \begin{lstlisting}
  1473. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1474. \end{lstlisting}
  1475. For example, the following program initializes \code{x} to $32$ and then
  1476. evaluates the body \code{(+ 10 x)}, producing $42$.
  1477. \begin{lstlisting}
  1478. (let ([x (+ 12 20)]) (+ 10 x))
  1479. \end{lstlisting}
  1480. \fi}
  1481. %
  1482. {\if\edition\pythonEd\color{purple}
  1483. The \LangVar{} language adds variables and the assignment statement
  1484. to \LangInt{}. The assignment statement defines a variable for use by
  1485. later statements and initializes the variable with the value of an expression.
  1486. The abstract syntax for assignment is defined in
  1487. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for assignment is
  1488. \begin{lstlisting}
  1489. |$\itm{var}$| = |$\itm{exp}$|
  1490. \end{lstlisting}
  1491. For example, the following program initializes \code{x} to $32$ and then
  1492. prints the result of \code{10 + x}, producing $42$.
  1493. \begin{lstlisting}
  1494. x = 12 + 20
  1495. print(10 + x)
  1496. \end{lstlisting}
  1497. \fi}
  1498. {\if\edition\racketEd\color{olive}
  1499. When there are multiple \key{let}'s for the same variable, the closest
  1500. enclosing \key{let} is used. That is, variable definitions overshadow
  1501. prior definitions. Consider the following program with two \key{let}'s
  1502. that define variables named \code{x}. Can you figure out the result?
  1503. \begin{lstlisting}
  1504. (let ([x 32]) (+ (let ([x 10]) x) x))
  1505. \end{lstlisting}
  1506. For the purposes of depicting which variable uses correspond to which
  1507. definitions, the following shows the \code{x}'s annotated with
  1508. subscripts to distinguish them. Double check that your answer for the
  1509. above is the same as your answer for this annotated version of the
  1510. program.
  1511. \begin{lstlisting}
  1512. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1513. \end{lstlisting}
  1514. The initializing expression is always evaluated before the body of the
  1515. \key{let}, so in the following, the \key{read} for \code{x} is
  1516. performed before the \key{read} for \code{y}. Given the input
  1517. $52$ then $10$, the following produces $42$ (not $-42$).
  1518. \begin{lstlisting}
  1519. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1520. \end{lstlisting}
  1521. \fi}
  1522. \subsection{Extensible Interpreters via Method Overriding}
  1523. \label{sec:extensible-interp}
  1524. To prepare for discussing the interpreter for \LangVar{}, we
  1525. explain why we to implement the interpreter using
  1526. object-oriented programming, that is, as a collection of methods
  1527. inside of a class. Throughout this book we define many interpreters,
  1528. one for each of the languages that we study. Because each language
  1529. builds on the prior one, there is a lot of commonality between these
  1530. interpreters. We want to write down the common parts just once
  1531. instead of many times. A naive approach would be to have, for example,
  1532. the interpreter for \LangIf{} handle all of the new features in that
  1533. language and then have a default case that dispatches to the
  1534. interpreter for \LangVar{}. The following code sketches this idea.
  1535. \begin{center}
  1536. {\if\edition\racketEd\color{olive}
  1537. \begin{minipage}{0.45\textwidth}
  1538. \begin{lstlisting}
  1539. (define (interp_Rvar_exp e)
  1540. (match e
  1541. [(Prim '- (list e1))
  1542. (fx- 0 (interp_Rvar_exp e1))]
  1543. ...))
  1544. \end{lstlisting}
  1545. \end{minipage}
  1546. \begin{minipage}{0.45\textwidth}
  1547. \begin{lstlisting}
  1548. (define (interp_Rif_exp e)
  1549. (match e
  1550. [(If cnd thn els)
  1551. (match (interp_Rif_exp cnd)
  1552. [#t (interp_Rif_exp thn)]
  1553. [#f (interp_Rif_exp els)])]
  1554. ...
  1555. [else (interp_Rvar_exp e)]))
  1556. \end{lstlisting}
  1557. \end{minipage}
  1558. \fi}
  1559. {\if\edition\pythonEd\color{purple}
  1560. \begin{minipage}{0.45\textwidth}
  1561. \begin{lstlisting}
  1562. def interp_Rvar_exp(e):
  1563. match e:
  1564. case UnaryOp(USub(), e1):
  1565. return - interp_Rvar_exp(e1)
  1566. ...
  1567. \end{lstlisting}
  1568. \end{minipage}
  1569. \begin{minipage}{0.45\textwidth}
  1570. \begin{lstlisting}
  1571. def interp_Rif_exp(e):
  1572. match e:
  1573. case IfExp(cnd, thn, els):
  1574. match interp_Rif_exp(cnd):
  1575. case True:
  1576. return interp_Rif_exp(thn)
  1577. case False:
  1578. return interp_Rif_exp(els)
  1579. ...
  1580. case _:
  1581. return interp_Rvar_exp(e)
  1582. \end{lstlisting}
  1583. \end{minipage}
  1584. \fi}
  1585. \end{center}
  1586. The problem with this approach is that it does not handle situations
  1587. in which an \LangIf{} feature, such as a conditional expression, is
  1588. nested inside an \LangVar{} feature, like the \code{-} operator, as in
  1589. the following program.
  1590. {\if\edition\racketEd\color{olive}
  1591. \begin{lstlisting}
  1592. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1593. \end{lstlisting}
  1594. \fi}
  1595. {\if\edition\pythonEd\color{purple}
  1596. \begin{lstlisting}
  1597. print(-(42 if True else 0))
  1598. \end{lstlisting}
  1599. \fi}
  1600. If we invoke \code{interp\_Rif\_exp} on this program, it dispatches to
  1601. \code{interp\_Rvar\_exp} to handle the \code{-} operator, but then it
  1602. recurisvely calls \code{interp\_Rvar\_exp} again on the argument of \code{-},
  1603. which is an \code{If}. But there is no case for \code{If} in
  1604. \code{interp\_Rvar\_exp}, so we get an error!
  1605. To make our interpreters extensible we need something called
  1606. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1607. recursive knot is delayed to when the functions are
  1608. composed. Object-oriented languages provide open recursion with the
  1609. late-binding of overridden methods\index{subject}{method overriding}. The
  1610. following code sketches this idea for interpreting \LangVar{} and
  1611. \LangIf{} using
  1612. \racket{the
  1613. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1614. \index{subject}{class} feature of Racket}
  1615. \python{a Python \code{class} definition}. We define one class for each
  1616. language and define a method for interpreting expressions inside each
  1617. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1618. and the method \code{interp\_exp} in \LangIf{} overrides the
  1619. \code{interp\_exp} in \LangVar{}. Note that the default case of
  1620. \code{interp\_exp} in \LangIf{} uses \code{super} to invoke
  1621. \code{interp\_exp}, and because \LangIf{} inherits from \LangVar{},
  1622. that dispatches to the \code{interp\_exp} in \LangVar{}.
  1623. \begin{center}
  1624. {\if\edition\racketEd\color{olive}
  1625. \begin{minipage}{0.45\textwidth}
  1626. \begin{lstlisting}
  1627. (define interp-Rvar-class
  1628. (class object%
  1629. (define/public (interp-exp e)
  1630. (match e
  1631. [(Prim '- (list e))
  1632. (fx- 0 (interp-exp e))]
  1633. ...))
  1634. ...))
  1635. \end{lstlisting}
  1636. \end{minipage}
  1637. \begin{minipage}{0.45\textwidth}
  1638. \begin{lstlisting}
  1639. (define interp-Rif-class
  1640. (class interp-Rvar-class
  1641. (define/override (interp-exp e)
  1642. (match e
  1643. [(If cnd thn els)
  1644. (match (interp-exp cnd)
  1645. [#t (interp-exp thn)]
  1646. [#f (interp-exp els)])]
  1647. ...
  1648. [else (super interp-exp e)]))
  1649. ...
  1650. ))
  1651. \end{lstlisting}
  1652. \end{minipage}
  1653. \fi}
  1654. {\if\edition\pythonEd\color{purple}
  1655. \begin{minipage}{0.45\textwidth}
  1656. \begin{lstlisting}
  1657. class InterpRvar:
  1658. def interp_exp(e):
  1659. match e:
  1660. case UnaryOp(USub(), e1):
  1661. return -self.interp_exp(e1)
  1662. ...
  1663. ...
  1664. \end{lstlisting}
  1665. \end{minipage}
  1666. \begin{minipage}{0.45\textwidth}
  1667. \begin{lstlisting}
  1668. def InterpRif(InterpRVar):
  1669. def interp_exp(e):
  1670. match e:
  1671. case IfExp(cnd, thn, els):
  1672. match self.interp_exp(cnd):
  1673. case True:
  1674. return self.interp_exp(thn)
  1675. case False:
  1676. return self.interp_exp(els)
  1677. ...
  1678. case _:
  1679. return super().interp_exp(e)
  1680. ...
  1681. \end{lstlisting}
  1682. \end{minipage}
  1683. \fi}
  1684. \end{center}
  1685. Getting back to the troublesome example, repeated here:
  1686. {\if\edition\racketEd\color{olive}
  1687. \begin{lstlisting}
  1688. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1689. \end{lstlisting}
  1690. \fi}
  1691. {\if\edition\pythonEd\color{purple}
  1692. \begin{lstlisting}
  1693. -(42 if True else 0)
  1694. \end{lstlisting}
  1695. \fi}
  1696. \noindent We can invoke the \code{interp\_exp} method for \LangIf{} on this
  1697. expression, call it \code{e0}, by creating an object of the \LangIf{} class
  1698. and calling the \code{interp\_exp} method.
  1699. {\if\edition\racketEd\color{olive}
  1700. \begin{lstlisting}
  1701. (send (new interp-Rif-class) interp-exp e0)
  1702. \end{lstlisting}
  1703. \fi}
  1704. {\if\edition\pythonEd\color{purple}
  1705. \begin{lstlisting}
  1706. InterpRif().interp_exp(e0)
  1707. \end{lstlisting}
  1708. \fi}
  1709. \noindent The default case of \code{interp\_exp} in \LangIf{} handles it by
  1710. dispatching to the \code{interp\_exp} method in \LangVar{}, which
  1711. handles the \code{-} operator. But then for the recursive method call,
  1712. it dispatches back to \code{interp\_exp} in \LangIf{}, where the
  1713. \code{If} is handled correctly. Thus, method overriding gives us the
  1714. open recursion that we need to implement our interpreters in an
  1715. extensible way.
  1716. \subsection{Definitional Interpreter for \LangVar{}}
  1717. {\if\edition\racketEd\color{olive}
  1718. \begin{figure}[tp]
  1719. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1720. \small
  1721. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1722. An \emph{association list} (alist) is a list of key-value pairs.
  1723. For example, we can map people to their ages with an alist.
  1724. \index{subject}{alist}\index{subject}{association list}
  1725. \begin{lstlisting}[basicstyle=\ttfamily]
  1726. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1727. \end{lstlisting}
  1728. The \emph{dictionary} interface is for mapping keys to values.
  1729. Every alist implements this interface. \index{subject}{dictionary} The package
  1730. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1731. provides many functions for working with dictionaries. Here
  1732. are a few of them:
  1733. \begin{description}
  1734. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1735. returns the value associated with the given $\itm{key}$.
  1736. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1737. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1738. but otherwise is the same as $\itm{dict}$.
  1739. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1740. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1741. of keys and values in $\itm{dict}$. For example, the following
  1742. creates a new alist in which the ages are incremented.
  1743. \end{description}
  1744. \vspace{-10pt}
  1745. \begin{lstlisting}[basicstyle=\ttfamily]
  1746. (for/list ([(k v) (in-dict ages)])
  1747. (cons k (add1 v)))
  1748. \end{lstlisting}
  1749. \end{tcolorbox}
  1750. %\end{wrapfigure}
  1751. \caption{Association lists implement the dictionary interface.}
  1752. \label{fig:alist}
  1753. \end{figure}
  1754. \fi}
  1755. Having justified the use of classes and methods to implement
  1756. interpreters, we turn to the definitional interpreter for \LangVar{}
  1757. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1758. \LangInt{} but adds two new \key{match} cases for variables and
  1759. \racket{\key{let}}\python{assignment}. For
  1760. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1761. value bound to a variable to all the uses of the variable. To
  1762. accomplish this, we maintain a mapping from variables to
  1763. values. Throughout the compiler we often need to map variables to
  1764. information about them. We refer to these mappings as
  1765. \emph{environments}\index{subject}{environment}.\footnote{Another
  1766. common term for environment in the compiler literature is \emph{symbol
  1767. table}\index{subject}{symbol table}.}
  1768. %
  1769. We use \racket{an association list
  1770. (alist)}\python{\href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}} to represent the
  1771. environment. \racket{Figure~\ref{fig:alist} gives a brief introduction
  1772. to alists and the \code{racket/dict} package.} The
  1773. \code{interp\_exp} function takes the current environment, \code{env},
  1774. as an extra parameter. When the interpreter encounters a variable, it
  1775. looks up the corresponding value in the dictionary.
  1776. %
  1777. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1778. initializing expression, extends the environment with the result
  1779. value bound to the variable, using \code{dict-set}, then evaluates
  1780. the body of the \key{Let}.}
  1781. %
  1782. \python{When the interpreter encounters an assignment, it evaluates
  1783. the initializing expression and then associates the resulting value
  1784. with the variable in the environment.}
  1785. \begin{figure}[tp]
  1786. {\if\edition\racketEd\color{olive}
  1787. \begin{lstlisting}
  1788. (define interp-Rvar-class
  1789. (class object%
  1790. (super-new)
  1791. (define/public ((interp_exp env) e)
  1792. (match e
  1793. [(Int n) n]
  1794. [(Prim 'read '())
  1795. (define r (read))
  1796. (cond [(fixnum? r) r]
  1797. [else (error 'interp_exp "expected an integer" r)])]
  1798. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1799. [(Prim '+ (list e1 e2))
  1800. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1801. [(Var x) (dict-ref env x)]
  1802. [(Let x e body)
  1803. (define new-env (dict-set env x ((interp_exp env) e)))
  1804. ((interp_exp new-env) body)]))
  1805. (define/public (interp-program p)
  1806. (match p
  1807. [(Program '() e) ((interp_exp '()) e)]))
  1808. ))
  1809. (define (interp-Rvar p)
  1810. (send (new interp-Rvar-class) interp-program p))
  1811. \end{lstlisting}
  1812. \fi}
  1813. {\if\edition\pythonEd\color{purple}
  1814. \begin{lstlisting}
  1815. class InterpPvar:
  1816. def interp_exp(self, e, env):
  1817. match e:
  1818. case BinOp(left, Add(), right):
  1819. l = self.interp_exp(left, env)
  1820. r = self.interp_exp(right, env)
  1821. return l + r
  1822. case UnaryOp(USub(), v):
  1823. return - self.interp_exp(v, env)
  1824. case Name(id):
  1825. return env[id]
  1826. case Constant(value):
  1827. return value
  1828. case Call(Name('input_int'), []):
  1829. return int(input())
  1830. def interp_stmt(self, s, env):
  1831. match s:
  1832. case Assign([lhs], value):
  1833. env[lhs.id] = self.interp_exp(value, env)
  1834. case Expr(Call(Name('print'), [arg])):
  1835. print(self.interp_exp(arg, env))
  1836. case Expr(value):
  1837. self.interp_exp(value, env)
  1838. def interp_Pvar(self, p):
  1839. match p:
  1840. case Module(body):
  1841. env = {}
  1842. for s in body:
  1843. self.interp_stmt(s, env)
  1844. \end{lstlisting}
  1845. \fi}
  1846. \caption{Interpreter for the \LangVar{} language.}
  1847. \label{fig:interp-Rvar}
  1848. \end{figure}
  1849. The goal for this chapter is to implement a compiler that translates
  1850. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1851. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1852. computer as the $P_1$ program interpreted by \code{interp\_Rvar}. That
  1853. is, they output the same integer $n$. We depict this correctness
  1854. criteria in the following diagram.
  1855. \[
  1856. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1857. \node (p1) at (0, 0) {$P_1$};
  1858. \node (p2) at (4, 0) {$P_2$};
  1859. \node (o) at (4, -2) {$n$};
  1860. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1861. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Rvar}} (o);
  1862. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  1863. \end{tikzpicture}
  1864. \]
  1865. In the next section we introduce the \LangXInt{} subset of x86 that
  1866. suffices for compiling \LangVar{}.
  1867. \section{The \LangXInt{} Assembly Language}
  1868. \label{sec:x86}
  1869. \index{subject}{x86}
  1870. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1871. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1872. assembler.
  1873. %
  1874. A program begins with a \code{main} label followed by a sequence of
  1875. instructions. The \key{globl} directive says that the \key{main}
  1876. procedure is externally visible, which is necessary so that the
  1877. operating system can call it. In the grammar, ellipses such as
  1878. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1879. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1880. %
  1881. An x86 program is stored in the computer's memory. For our purposes,
  1882. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1883. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1884. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1885. the address of the next instruction to be executed. For most
  1886. instructions, the program counter is incremented after the instruction
  1887. is executed, so it points to the next instruction in memory. Most x86
  1888. instructions take two operands, where each operand is either an
  1889. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1890. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1891. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  1892. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  1893. && \key{r8} \MID \key{r9} \MID \key{r10}
  1894. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  1895. \MID \key{r14} \MID \key{r15}}
  1896. \begin{figure}[tp]
  1897. \fbox{
  1898. \begin{minipage}{0.96\textwidth}
  1899. \[
  1900. \begin{array}{lcl}
  1901. \Reg &::=& \allregisters{} \\
  1902. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  1903. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  1904. \key{subq} \; \Arg\key{,} \Arg \MID
  1905. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  1906. && \key{callq} \; \mathit{label} \MID
  1907. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  1908. && \itm{label}\key{:}\; \Instr \\
  1909. \LangXIntM{} &::= & \key{.globl main}\\
  1910. & & \key{main:} \; \Instr\ldots
  1911. \end{array}
  1912. \]
  1913. \end{minipage}
  1914. }
  1915. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1916. \label{fig:x86-int-concrete}
  1917. \end{figure}
  1918. A register is a special kind of variable. Each one holds a 64-bit
  1919. value; there are 16 general-purpose registers in the computer and
  1920. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1921. is written with a \key{\%} followed by the register name, such as
  1922. \key{\%rax}.
  1923. An immediate value is written using the notation \key{\$}$n$ where $n$
  1924. is an integer.
  1925. %
  1926. %
  1927. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1928. which obtains the address stored in register $r$ and then adds $n$
  1929. bytes to the address. The resulting address is used to load or store
  1930. to memory depending on whether it occurs as a source or destination
  1931. argument of an instruction.
  1932. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1933. source $s$ and destination $d$, applies the arithmetic operation, then
  1934. writes the result back to the destination $d$.
  1935. %
  1936. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1937. stores the result in $d$.
  1938. %
  1939. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1940. specified by the label and $\key{retq}$ returns from a procedure to
  1941. its caller.
  1942. %
  1943. We discuss procedure calls in more detail later in this chapter and in
  1944. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1945. updates the program counter to the address of the instruction after
  1946. the specified label.
  1947. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1948. all of the x86 instructions used in this book.
  1949. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  1950. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  1951. \lstinline{movq $10, %rax}
  1952. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1953. adds $32$ to the $10$ in \key{rax} and
  1954. puts the result, $42$, back into \key{rax}.
  1955. %
  1956. The last instruction, \key{retq}, finishes the \key{main} function by
  1957. returning the integer in \key{rax} to the operating system. The
  1958. operating system interprets this integer as the program's exit
  1959. code. By convention, an exit code of 0 indicates that a program
  1960. completed successfully, and all other exit codes indicate various
  1961. errors. Nevertheless, in this book we return the result of the program
  1962. as the exit code.
  1963. \begin{figure}[tbp]
  1964. \begin{lstlisting}
  1965. .globl main
  1966. main:
  1967. movq $10, %rax
  1968. addq $32, %rax
  1969. retq
  1970. \end{lstlisting}
  1971. \caption{An x86 program that computes
  1972. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  1973. \label{fig:p0-x86}
  1974. \end{figure}
  1975. The x86 assembly language varies in a couple of ways depending on what
  1976. operating system it is assembled in. The code examples shown here are
  1977. correct on Linux and most Unix-like platforms, but when assembled on
  1978. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1979. as in \key{\_main}.
  1980. We exhibit the use of memory for storing intermediate results in the
  1981. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  1982. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  1983. uses a region of memory called the \emph{procedure call stack} (or
  1984. \emph{stack} for
  1985. short). \index{subject}{stack}\index{subject}{procedure call stack}
  1986. The stack consists of a separate \emph{frame}\index{subject}{frame}
  1987. for each procedure call. The memory layout for an individual frame is
  1988. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1989. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  1990. item at the top of the stack. The stack grows downward in memory, so
  1991. we increase the size of the stack by subtracting from the stack
  1992. pointer. In the context of a procedure call, the \emph{return
  1993. address}\index{subject}{return address} is the instruction after the
  1994. call instruction on the caller side. The function call instruction,
  1995. \code{callq}, pushes the return address onto the stack prior to
  1996. jumping to the procedure. The register \key{rbp} is the \emph{base
  1997. pointer}\index{subject}{base pointer} and is used to access variables
  1998. that are stored in the frame of the current procedure call. The base
  1999. pointer of the caller is pushed onto the stack after the return
  2000. address and then the base pointer is set to the location of the old
  2001. base pointer. In Figure~\ref{fig:frame} we number the variables from
  2002. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  2003. variable $2$ at $-16\key{(\%rbp)}$, etc.
  2004. \begin{figure}[tbp]
  2005. \begin{lstlisting}
  2006. start:
  2007. movq $10, -8(%rbp)
  2008. negq -8(%rbp)
  2009. movq -8(%rbp), %rax
  2010. addq $52, %rax
  2011. jmp conclusion
  2012. .globl main
  2013. main:
  2014. pushq %rbp
  2015. movq %rsp, %rbp
  2016. subq $16, %rsp
  2017. jmp start
  2018. conclusion:
  2019. addq $16, %rsp
  2020. popq %rbp
  2021. retq
  2022. \end{lstlisting}
  2023. \caption{An x86 program that computes
  2024. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2025. \label{fig:p1-x86}
  2026. \end{figure}
  2027. \begin{figure}[tbp]
  2028. \centering
  2029. \begin{tabular}{|r|l|} \hline
  2030. Position & Contents \\ \hline
  2031. 8(\key{\%rbp}) & return address \\
  2032. 0(\key{\%rbp}) & old \key{rbp} \\
  2033. -8(\key{\%rbp}) & variable $1$ \\
  2034. -16(\key{\%rbp}) & variable $2$ \\
  2035. \ldots & \ldots \\
  2036. 0(\key{\%rsp}) & variable $n$\\ \hline
  2037. \end{tabular}
  2038. \caption{Memory layout of a frame.}
  2039. \label{fig:frame}
  2040. \end{figure}
  2041. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2042. control is transferred from the operating system to the \code{main}
  2043. function. The operating system issues a \code{callq main} instruction
  2044. which pushes its return address on the stack and then jumps to
  2045. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2046. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2047. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2048. alignment (because the \code{callq} pushed the return address). The
  2049. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2050. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2051. pointer for the caller onto the stack and subtracts $8$ from the stack
  2052. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  2053. base pointer so that it points the location of the old base
  2054. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2055. pointer down to make enough room for storing variables. This program
  2056. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2057. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2058. functions. The last instruction of the prelude is \code{jmp start},
  2059. which transfers control to the instructions that were generated from
  2060. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.
  2061. The first instruction under the \code{start} label is
  2062. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2063. %
  2064. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2065. %
  2066. The next instruction moves the $-10$ from variable $1$ into the
  2067. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2068. the value in \code{rax}, updating its contents to $42$.
  2069. The three instructions under the label \code{conclusion} are the
  2070. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  2071. two instructions restore the \code{rsp} and \code{rbp} registers to
  2072. the state they were in at the beginning of the procedure. The
  2073. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  2074. point at the old base pointer. Then \key{popq \%rbp} returns the old
  2075. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  2076. instruction, \key{retq}, jumps back to the procedure that called this
  2077. one and adds $8$ to the stack pointer.
  2078. The compiler needs a convenient representation for manipulating x86
  2079. programs, so we define an abstract syntax for x86 in
  2080. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2081. \LangXInt{}.
  2082. %
  2083. {\if\edition\racketEd\color{olive}
  2084. The main difference compared to the concrete syntax of \LangXInt{}
  2085. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2086. front of every instruction. Instead instructions are grouped into
  2087. \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  2088. label associated with every block, which is why the \key{X86Program}
  2089. struct includes an alist mapping labels to blocks. The reason for this
  2090. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  2091. introduce conditional branching. The \code{Block} structure includes
  2092. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2093. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  2094. $\itm{info}$ field should contain an empty list.
  2095. \fi}
  2096. %
  2097. {\if\edition\pythonEd\color{purple}
  2098. %
  2099. The main difference compared to the concrete syntax of \LangXInt{}
  2100. (Figure~\ref{fig:x86-int-concrete}) is that we do not yet include a
  2101. way to label instructions but instead recommend inserting the
  2102. \key{main}, \key{start}, and \key{conclusion} labels when printing the
  2103. final x86 program.
  2104. %
  2105. \fi}
  2106. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2107. node includes an integer for representing the arity of the function,
  2108. i.e., the number of arguments, which is helpful to know during
  2109. register allocation (Chapter~\ref{ch:register-allocation-Rvar}).
  2110. \begin{figure}[tp]
  2111. \fbox{
  2112. \begin{minipage}{0.98\textwidth}
  2113. \small
  2114. {\if\edition\racketEd\color{olive}
  2115. \[
  2116. \begin{array}{lcl}
  2117. \Reg &::=& \allregisters{} \\
  2118. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2119. \MID \DEREF{\Reg}{\Int} \\
  2120. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2121. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2122. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2123. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2124. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2125. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2126. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2127. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2128. \end{array}
  2129. \]
  2130. \fi}
  2131. {\if\edition\pythonEd\color{purple}
  2132. \[
  2133. \begin{array}{lcl}
  2134. \Reg &::=& \allregisters{} \\
  2135. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2136. \MID \DEREF{\Reg}{\Int} \\
  2137. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2138. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2139. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2140. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2141. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2142. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2143. \LangXIntM{} &::= & \XPROGRAM{\Instr^{*}}{}
  2144. \end{array}
  2145. \]
  2146. \fi}
  2147. \end{minipage}
  2148. }
  2149. \caption{The abstract syntax of \LangXInt{} assembly.}
  2150. \label{fig:x86-int-ast}
  2151. \end{figure}
  2152. \section{Planning the trip to x86 via the \LangCVar{} language}
  2153. \label{sec:plan-s0-x86}
  2154. To compile one language to another it helps to focus on the
  2155. differences between the two languages because the compiler will need
  2156. to bridge those differences. What are the differences between \LangVar{}
  2157. and x86 assembly? Here are some of the most important ones:
  2158. \begin{enumerate}
  2159. \item[(a)] x86 arithmetic instructions typically have two arguments
  2160. and update the second argument in place. In contrast, \LangVar{}
  2161. arithmetic operations take two arguments and produce a new value.
  2162. An x86 instruction may have at most one memory-accessing argument.
  2163. Furthermore, some instructions place special restrictions on their
  2164. arguments.
  2165. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  2166. expression, whereas x86 instructions restrict their arguments to be
  2167. integer constants, registers, and memory locations.
  2168. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  2169. sequence of instructions and jumps to labeled positions, whereas in
  2170. \LangVar{} the order of evaluation is a left-to-right depth-first
  2171. traversal of the abstract syntax tree.
  2172. \item[(d)] A program in \LangVar{} can have any number of variables
  2173. whereas x86 has 16 registers and the procedure calls stack.
  2174. {\if\edition\racketEd\color{olive}
  2175. \item[(e)] Variables in \LangVar{} can shadow other variables with the
  2176. same name. In x86, registers have unique names and memory locations
  2177. have unique addresses.
  2178. \fi}
  2179. \end{enumerate}
  2180. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2181. the problem into several steps, dealing with the above differences one
  2182. at a time. Each of these steps is called a \emph{pass} of the
  2183. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2184. %
  2185. This terminology comes from the way each step passes over the AST of
  2186. the program.
  2187. %
  2188. We begin by sketching how we might implement each pass, and give them
  2189. names. We then figure out an ordering of the passes and the
  2190. input/output language for each pass. The very first pass has
  2191. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2192. its output language. In between we can choose whichever language is
  2193. most convenient for expressing the output of each pass, whether that
  2194. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2195. our own design. Finally, to implement each pass we write one
  2196. recursive function per non-terminal in the grammar of the input
  2197. language of the pass. \index{subject}{intermediate language}
  2198. \begin{description}
  2199. \item[\key{select\_instructions}] handles the difference between
  2200. \LangVar{} operations and x86 instructions. This pass converts each
  2201. \LangVar{} operation to a short sequence of instructions that
  2202. accomplishes the same task.
  2203. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2204. of a primitive operation or function call is a variable or integer,
  2205. that is, an \emph{atomic} expression. We refer to non-atomic
  2206. expressions as \emph{complex}. This pass introduces temporary
  2207. variables to hold the results of complex
  2208. subexpressions.\index{subject}{atomic
  2209. expression}\index{subject}{complex expression}%
  2210. \footnote{The subexpressions of an operation are often called
  2211. operators and operands which explains the presence of
  2212. \code{opera*} in the name of this pass.}
  2213. {\if\edition\racketEd\color{olive}
  2214. \item[\key{explicate\_control}] makes the execution order of the
  2215. program explicit. It convert the abstract syntax tree representation
  2216. into a control-flow graph in which each node contains a sequence of
  2217. statements and the edges between nodes say which nodes contain jumps
  2218. to other nodes.
  2219. \fi}
  2220. \item[\key{assign\_homes}] replaces the variables in \LangVar{} with
  2221. registers or stack locations in x86.
  2222. {\if\edition\racketEd\color{olive}
  2223. \item[\key{uniquify}] deals with the shadowing of variables by
  2224. renaming every variable to a unique name.
  2225. \fi}
  2226. \end{description}
  2227. The next question is: in what order should we apply these passes? This
  2228. question can be challenging because it is difficult to know ahead of
  2229. time which orderings will be better (easier to implement, produce more
  2230. efficient code, etc.) so oftentimes trial-and-error is
  2231. involved. Nevertheless, we can try to plan ahead and make educated
  2232. choices regarding the ordering.
  2233. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2234. \key{uniquify}? The \key{uniquify} pass should come first because
  2235. \key{explicate\_control} changes all the \key{let}-bound variables to
  2236. become local variables whose scope is the entire program, which would
  2237. confuse variables with the same name.}
  2238. %
  2239. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2240. because the later removes the \key{let} form, but it is convenient to
  2241. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2242. %
  2243. \racket{The ordering of \key{uniquify} with respect to
  2244. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2245. \key{uniquify} to come first.}
  2246. The \key{select\_instructions} and \key{assign\_homes}. passes are
  2247. intertwined. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers
  2248. are used for passing arguments to functions and it is preferable to
  2249. assign parameters to their corresponding registers. On the other hand,
  2250. by selecting instructions first we may run into a dead end in
  2251. \key{assign\_homes}. Recall that only one argument of an x86
  2252. instruction may be a memory access but \key{assign\_homes} might fail
  2253. to assign even one of them to a register.
  2254. %
  2255. A sophisticated approach is to iteratively repeat the two passes until
  2256. a solution is found. However, to reduce implementation complexity we
  2257. recommend a simpler approach in which \key{select\_instructions} comes
  2258. first, followed by the \key{assign\_homes}, then a third pass named
  2259. \key{patch\_instructions} that uses a reserved register to fix
  2260. outstanding problems.
  2261. \begin{figure}[tbp]
  2262. {\if\edition\racketEd\color{olive}
  2263. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2264. \node (Rvar) at (0,2) {\large \LangVar{}};
  2265. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2266. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  2267. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2268. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2269. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2270. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2271. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2272. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2273. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  2274. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-3);
  2275. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2276. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2277. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2278. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2279. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print\_x86} (x86-5);
  2280. \end{tikzpicture}
  2281. \fi}
  2282. {\if\edition\pythonEd\color{purple}
  2283. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2284. \node (Rvar) at (0,2) {\large \LangVar{}};
  2285. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2286. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2287. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2288. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2289. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2290. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-2);
  2291. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2292. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2293. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2294. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  2295. \end{tikzpicture}
  2296. \fi}
  2297. \caption{Diagram of the passes for compiling \LangVar{}. }
  2298. \label{fig:Rvar-passes}
  2299. \end{figure}
  2300. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  2301. passes and identifies the input and output language of each pass. The
  2302. last pass, \key{print\_x86}, converts from the abstract syntax of
  2303. \LangXInt{} to the concrete syntax.
  2304. %
  2305. \racket{In the following two sections we discuss the \LangCVar{}
  2306. intermediate language and the \LangXVar{} dialect of x86.}
  2307. %
  2308. \python{In the following section we discuss the \LangXVar{} dialect of
  2309. x86.}
  2310. %
  2311. The remainder of this chapter gives hints regarding the implementation
  2312. of each of the compiler passes in Figure~\ref{fig:Rvar-passes}.
  2313. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2314. %% are programs that are still in the \LangVar{} language, though the
  2315. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2316. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  2317. %% %
  2318. %% The output of \key{explicate-control} is in an intermediate language
  2319. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2320. %% syntax, which we introduce in the next section. The
  2321. %% \key{select-instruction} pass translates from \LangCVar{} to
  2322. %% \LangXVar{}. The \key{assign-homes} and
  2323. %% \key{patch-instructions}
  2324. %% passes input and output variants of x86 assembly.
  2325. {\if\edition\racketEd\color{olive}
  2326. \subsection{The \LangCVar{} Intermediate Language}
  2327. The output of \key{explicate-control} is similar to the $C$
  2328. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2329. categories for expressions and statements, so we name it \LangCVar{}. The
  2330. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2331. (The concrete syntax for \LangCVar{} is in the Appendix,
  2332. Figure~\ref{fig:c0-concrete-syntax}.)
  2333. %
  2334. The \LangCVar{} language supports the same operators as \LangVar{} but
  2335. the arguments of operators are restricted to atomic
  2336. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2337. assignment statements which can be executed in sequence using the
  2338. \key{Seq} form. A sequence of statements always ends with
  2339. \key{Return}, a guarantee that is baked into the grammar rules for
  2340. \itm{tail}. The naming of this non-terminal comes from the term
  2341. \emph{tail position}\index{subject}{tail position}, which refers to an
  2342. expression that is the last one to execute within a function.
  2343. A \LangCVar{} program consists of a control-flow graph represented as
  2344. an alist mapping labels to tails. This is more general than necessary
  2345. for the present chapter, as we do not yet introduce \key{goto} for
  2346. jumping to labels, but it saves us from having to change the syntax in
  2347. Chapter~\ref{ch:Rif}. For now there will be just one label,
  2348. \key{start}, and the whole program is its tail.
  2349. %
  2350. The $\itm{info}$ field of the \key{CProgram} form, after the
  2351. \key{explicate-control} pass, contains a mapping from the symbol
  2352. \key{locals} to a list of variables, that is, a list of all the
  2353. variables used in the program. At the start of the program, these
  2354. variables are uninitialized; they become initialized on their first
  2355. assignment.
  2356. \begin{figure}[tbp]
  2357. \fbox{
  2358. \begin{minipage}{0.96\textwidth}
  2359. \[
  2360. \begin{array}{lcl}
  2361. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2362. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2363. &\MID& \ADD{\Atm}{\Atm}\\
  2364. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2365. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2366. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2367. \end{array}
  2368. \]
  2369. \end{minipage}
  2370. }
  2371. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2372. \label{fig:c0-syntax}
  2373. \end{figure}
  2374. The definitional interpreter for \LangCVar{} is in the support code,
  2375. in the file \code{interp-Cvar.rkt}.
  2376. \fi}
  2377. \section{The \LangXVar{} dialect}
  2378. The \LangXVar{} language is the output of the pass
  2379. \key{select\_instructions}. It extends \LangXInt{} with an unbounded
  2380. number of program-scope variables and removes the restrictions
  2381. regarding instruction arguments.
  2382. {\if\edition\racketEd\color{olive}
  2383. \section{Uniquify Variables}
  2384. \label{sec:uniquify-Rvar}
  2385. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2386. programs in which every \key{let} binds a unique variable name. For
  2387. example, the \code{uniquify} pass should translate the program on the
  2388. left into the program on the right.
  2389. \begin{transformation}
  2390. \begin{lstlisting}
  2391. (let ([x 32])
  2392. (+ (let ([x 10]) x) x))
  2393. \end{lstlisting}
  2394. \compilesto
  2395. \begin{lstlisting}
  2396. (let ([x.1 32])
  2397. (+ (let ([x.2 10]) x.2) x.1))
  2398. \end{lstlisting}
  2399. \end{transformation}
  2400. The following is another example translation, this time of a program
  2401. with a \key{let} nested inside the initializing expression of another
  2402. \key{let}.
  2403. \begin{transformation}
  2404. \begin{lstlisting}
  2405. (let ([x (let ([x 4])
  2406. (+ x 1))])
  2407. (+ x 2))
  2408. \end{lstlisting}
  2409. \compilesto
  2410. \begin{lstlisting}
  2411. (let ([x.2 (let ([x.1 4])
  2412. (+ x.1 1))])
  2413. (+ x.2 2))
  2414. \end{lstlisting}
  2415. \end{transformation}
  2416. We recommend implementing \code{uniquify} by creating a structurally
  2417. recursive function named \code{uniquify-exp} that mostly just copies
  2418. an expression. However, when encountering a \key{let}, it should
  2419. generate a unique name for the variable and associate the old name
  2420. with the new name in an alist.\footnote{The Racket function
  2421. \code{gensym} is handy for generating unique variable names.} The
  2422. \code{uniquify-exp} function needs to access this alist when it gets
  2423. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2424. for the alist.
  2425. The skeleton of the \code{uniquify-exp} function is shown in
  2426. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  2427. convenient to partially apply it to an alist and then apply it to
  2428. different expressions, as in the last case for primitive operations in
  2429. Figure~\ref{fig:uniquify-Rvar}. The
  2430. %
  2431. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2432. %
  2433. form of Racket is useful for transforming each element of a list to
  2434. produce a new list.\index{subject}{for/list}
  2435. \begin{figure}[tbp]
  2436. \begin{lstlisting}
  2437. (define (uniquify-exp env)
  2438. (lambda (e)
  2439. (match e
  2440. [(Var x) ___]
  2441. [(Int n) (Int n)]
  2442. [(Let x e body) ___]
  2443. [(Prim op es)
  2444. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2445. (define (uniquify p)
  2446. (match p
  2447. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2448. \end{lstlisting}
  2449. \caption{Skeleton for the \key{uniquify} pass.}
  2450. \label{fig:uniquify-Rvar}
  2451. \end{figure}
  2452. \begin{exercise}
  2453. \normalfont % I don't like the italics for exercises. -Jeremy
  2454. Complete the \code{uniquify} pass by filling in the blanks in
  2455. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  2456. variables and for the \key{let} form in the file \code{compiler.rkt}
  2457. in the support code.
  2458. \end{exercise}
  2459. \begin{exercise}
  2460. \normalfont % I don't like the italics for exercises. -Jeremy
  2461. \label{ex:Rvar}
  2462. Create five \LangVar{} programs that exercise the most interesting
  2463. parts of the \key{uniquify} pass, that is, the programs should include
  2464. \key{let} forms, variables, and variables that shadow each other.
  2465. The five programs should be placed in the subdirectory named
  2466. \key{tests} and the file names should start with \code{var\_test\_}
  2467. followed by a unique integer and end with the file extension
  2468. \key{.rkt}.
  2469. %
  2470. The \key{run-tests.rkt} script in the support code checks whether the
  2471. output programs produce the same result as the input programs. The
  2472. script uses the \key{interp-tests} function
  2473. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2474. your \key{uniquify} pass on the example programs. The \code{passes}
  2475. parameter of \key{interp-tests} is a list that should have one entry
  2476. for each pass in your compiler. For now, define \code{passes} to
  2477. contain just one entry for \code{uniquify} as shown below.
  2478. \begin{lstlisting}
  2479. (define passes
  2480. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  2481. \end{lstlisting}
  2482. Run the \key{run-tests.rkt} script in the support code to check
  2483. whether the output programs produce the same result as the input
  2484. programs.
  2485. \end{exercise}
  2486. \fi}
  2487. \section{Remove Complex Operands}
  2488. \label{sec:remove-complex-opera-Rvar}
  2489. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2490. into a restricted form in which the arguments of operations are atomic
  2491. expressions. Put another way, this pass removes complex
  2492. operands\index{subject}{complex operand}, such as the expression
  2493. \racket{\code{(- 10)}}\python{\code{-10}}
  2494. in the program below. This is accomplished by introducing a new
  2495. temporary variable, assigning the complex operand to the new
  2496. variable, and then using the new variable in place of the complex
  2497. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2498. right.
  2499. {\if\edition\racketEd\color{olive}
  2500. \begin{transformation}
  2501. % var_test_19.rkt
  2502. \begin{lstlisting}
  2503. (let ([x (+ 42 (- 10))])
  2504. (+ x 10))
  2505. \end{lstlisting}
  2506. \compilesto
  2507. \begin{lstlisting}
  2508. (let ([x (let ([tmp.1 (- 10)])
  2509. (+ 42 tmp.1))])
  2510. (+ x 10))
  2511. \end{lstlisting}
  2512. \end{transformation}
  2513. \fi}
  2514. {\if\edition\pythonEd\color{purple}
  2515. \begin{transformation}
  2516. \begin{lstlisting}
  2517. x = 42 + -10
  2518. print(x + 10)
  2519. \end{lstlisting}
  2520. \compilesto
  2521. \begin{lstlisting}
  2522. tmp_0 = -10
  2523. x = 42 + tmp_0
  2524. tmp_1 = x + 10
  2525. print(tmp_1)
  2526. \end{lstlisting}
  2527. \end{transformation}
  2528. \fi}
  2529. \begin{figure}[tp]
  2530. \centering
  2531. \fbox{
  2532. \begin{minipage}{0.96\textwidth}
  2533. {\if\edition\racketEd\color{olive}
  2534. \[
  2535. \begin{array}{rcl}
  2536. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2537. \Exp &::=& \Atm \MID \READ{} \\
  2538. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2539. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2540. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2541. \end{array}
  2542. \]
  2543. \fi}
  2544. {\if\edition\pythonEd\color{purple}
  2545. \[
  2546. \begin{array}{rcl}
  2547. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2548. \Exp{} &::=& \Atm \MID \READ{} \\
  2549. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  2550. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2551. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2552. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2553. \end{array}
  2554. \]
  2555. \fi}
  2556. \end{minipage}
  2557. }
  2558. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2559. atomic expressions, like administrative normal form (ANF).}
  2560. \label{fig:Rvar-anf-syntax}
  2561. \end{figure}
  2562. Figure~\ref{fig:Rvar-anf-syntax} presents the grammar for the output of
  2563. this pass, the language \LangVarANF{}. The only difference is that
  2564. operator arguments are restricted to be atomic expressions that are
  2565. defined by the \Atm{} non-terminal. In particular, integer constants
  2566. and variables are atomic. In the literature, restricting arguments to
  2567. be atomic expressions is one of the ideas in \emph{administrative
  2568. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2569. \index{subject}{administrative normal form} \index{subject}{ANF}
  2570. {\if\edition\racketEd\color{olive}
  2571. We recommend implementing this pass with two mutually recursive
  2572. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2573. \code{rco\_atom} to subexpressions that need to become atomic and to
  2574. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2575. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2576. returns an expression. The \code{rco\_atom} function returns two
  2577. things: an atomic expression and an alist mapping temporary variables to
  2578. complex subexpressions. You can return multiple things from a function
  2579. using Racket's \key{values} form and you can receive multiple things
  2580. from a function call using the \key{define-values} form.
  2581. Also, the
  2582. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2583. form is useful for applying a function to each element of a list, in
  2584. the case where the function returns multiple values.
  2585. \index{subject}{for/lists}
  2586. \fi}
  2587. %
  2588. {\if\edition\pythonEd\color{purple}
  2589. %
  2590. We recommend implementing this pass with an auxiliary method named
  2591. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2592. Boolean that specifies whether the expression needs to become atomic
  2593. or not. The \code{rco\_exp} method should return a pair consisting of
  2594. the new expression and a list of pairs, associating new temporary
  2595. variables with their initializing expressions.
  2596. %
  2597. \fi}
  2598. {\if\edition\racketEd\color{olive}
  2599. Returning to the example program with the expression \code{(+ 42 (-
  2600. 10))}, the subexpression \code{(- 10)} should be processed using the
  2601. \code{rco\_atom} function because it is an argument of the \code{+} and
  2602. therefore needs to become atomic. The output of \code{rco\_atom}
  2603. applied to \code{(- 10)} is as follows.
  2604. \begin{transformation}
  2605. \begin{lstlisting}
  2606. (- 10)
  2607. \end{lstlisting}
  2608. \compilesto
  2609. \begin{lstlisting}
  2610. tmp.1
  2611. ((tmp.1 . (- 10)))
  2612. \end{lstlisting}
  2613. \end{transformation}
  2614. \fi}
  2615. %
  2616. {\if\edition\pythonEd\color{purple}
  2617. %
  2618. Returning to the example program with the expression \code{42 + -10},
  2619. the subexpression \code{-10} should be processed using the
  2620. \code{rco\_exp} function with \code{True} as the second argument
  2621. because \code{-10} is an argument of the \code{+} operator and
  2622. therefore needs to become atomic. The output of \code{rco\_exp}
  2623. applied to \code{-10} is as follows.
  2624. \begin{transformation}
  2625. \begin{lstlisting}
  2626. -10
  2627. \end{lstlisting}
  2628. \compilesto
  2629. \begin{lstlisting}
  2630. tmp_1
  2631. [(tmp_1, -10)]
  2632. \end{lstlisting}
  2633. \end{transformation}
  2634. %
  2635. \fi}
  2636. Take special care of programs such as the following that \racket{bind
  2637. a variable to an atomic expression}\python{assign an atomic
  2638. expression to a variable}. You should leave such \racket{variable
  2639. bindings}\python{assignments} unchanged, as shown in the program on
  2640. the right\\
  2641. %
  2642. {\if\edition\racketEd\color{olive}
  2643. \begin{transformation}
  2644. % var_test_20.rkt
  2645. \begin{lstlisting}
  2646. (let ([a 42])
  2647. (let ([b a])
  2648. b))
  2649. \end{lstlisting}
  2650. \compilesto
  2651. \begin{lstlisting}
  2652. (let ([a 42])
  2653. (let ([b a])
  2654. b))
  2655. \end{lstlisting}
  2656. \end{transformation}
  2657. \fi}
  2658. {\if\edition\pythonEd\color{purple}
  2659. \begin{transformation}
  2660. \begin{lstlisting}
  2661. a = 42
  2662. b = a
  2663. print(b)
  2664. \end{lstlisting}
  2665. \compilesto
  2666. \begin{lstlisting}
  2667. a = 42
  2668. b = a
  2669. print(b)
  2670. \end{lstlisting}
  2671. \end{transformation}
  2672. \fi}
  2673. A careless implementation might produce the following output with
  2674. unnecessary temporary variables.
  2675. \begin{center}
  2676. \begin{minipage}{0.4\textwidth}
  2677. {\if\edition\racketEd\color{olive}
  2678. \begin{lstlisting}
  2679. (let ([tmp.1 42])
  2680. (let ([a tmp.1])
  2681. (let ([tmp.2 a])
  2682. (let ([b tmp.2])
  2683. b))))
  2684. \end{lstlisting}
  2685. \fi}
  2686. {\if\edition\pythonEd\color{purple}
  2687. \begin{lstlisting}
  2688. tmp_1 = 42
  2689. a = tmp_1
  2690. tmp_2 = a
  2691. b = tmp_2
  2692. print(b)
  2693. \end{lstlisting}
  2694. \fi}
  2695. \end{minipage}
  2696. \end{center}
  2697. \begin{exercise}
  2698. \normalfont
  2699. {\if\edition\racketEd\color{olive}
  2700. Implement the \code{remove-complex-opera*} function in
  2701. \code{compiler.rkt}.
  2702. %
  2703. Create three new \LangVar{} programs that exercise the interesting
  2704. code in the \code{remove-complex-opera*} pass. Follow the guidelines
  2705. regarding file names described in Exercise~\ref{ex:Rvar}.
  2706. %
  2707. In the \code{run-tests.rkt} script, add the following entry to the
  2708. list of \code{passes} and then run the script to test your compiler.
  2709. \begin{lstlisting}
  2710. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2711. \end{lstlisting}
  2712. While debugging your compiler, it is often useful to see the
  2713. intermediate programs that are output from each pass. To print the
  2714. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2715. \code{interp-tests} in \code{run-tests.rkt}.
  2716. \fi}
  2717. %
  2718. {\if\edition\pythonEd\color{purple}
  2719. Implement the \code{remove\_complex\_operands} function in
  2720. \code{compiler.py}, creating auxiliary functions for each
  2721. non-terminal in the grammar, i.e., \code{rco\_exp}
  2722. and \code{rco\_stmt}.
  2723. \fi}
  2724. \end{exercise}
  2725. {\if\edition\pythonEd\color{purple}
  2726. \begin{exercise}
  2727. \normalfont % I don't like the italics for exercises. -Jeremy
  2728. \label{ex:Rvar}
  2729. Create five \LangVar{} programs that exercise the most interesting
  2730. parts of the Remove Complex Operands pass. The five programs should
  2731. be placed in the subdirectory named \key{tests} and the file names
  2732. should start with \code{var\_test\_} followed by a unique integer and
  2733. end with the file extension \key{.py}.
  2734. % TODO: come up with passes infrastructure for Python -Jeremy
  2735. %% The \key{run-tests.rkt} script in the support code checks whether the
  2736. %% output programs produce the same result as the input programs. The
  2737. %% script uses the \key{interp-tests} function
  2738. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2739. %% your \key{uniquify} pass on the example programs. The \code{passes}
  2740. %% parameter of \key{interp-tests} is a list that should have one entry
  2741. %% for each pass in your compiler. For now, define \code{passes} to
  2742. %% contain just one entry for \code{uniquify} as shown below.
  2743. %% \begin{lstlisting}
  2744. %% (define passes
  2745. %% (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  2746. %% \end{lstlisting}
  2747. Run the \key{run-tests.py} script in the support code to check
  2748. whether the output programs produce the same result as the input
  2749. programs.
  2750. \end{exercise}
  2751. \fi}
  2752. {\if\edition\racketEd\color{olive}
  2753. \section{Explicate Control}
  2754. \label{sec:explicate-control-Rvar}
  2755. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2756. programs that make the order of execution explicit in their
  2757. syntax. For now this amounts to flattening \key{let} constructs into a
  2758. sequence of assignment statements. For example, consider the following
  2759. \LangVar{} program.\\
  2760. % var_test_11.rkt
  2761. \begin{minipage}{0.96\textwidth}
  2762. \begin{lstlisting}
  2763. (let ([y (let ([x 20])
  2764. (+ x (let ([x 22]) x)))])
  2765. y)
  2766. \end{lstlisting}
  2767. \end{minipage}\\
  2768. %
  2769. The output of the previous pass and of \code{explicate-control} is
  2770. shown below. Recall that the right-hand-side of a \key{let} executes
  2771. before its body, so the order of evaluation for this program is to
  2772. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2773. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2774. output of \code{explicate-control} makes this ordering explicit.
  2775. \begin{transformation}
  2776. \begin{lstlisting}
  2777. (let ([y (let ([x.1 20])
  2778. (let ([x.2 22])
  2779. (+ x.1 x.2)))])
  2780. y)
  2781. \end{lstlisting}
  2782. \compilesto
  2783. \begin{lstlisting}[language=C]
  2784. start:
  2785. x.1 = 20;
  2786. x.2 = 22;
  2787. y = (+ x.1 x.2);
  2788. return y;
  2789. \end{lstlisting}
  2790. \end{transformation}
  2791. \begin{figure}[tbp]
  2792. \begin{lstlisting}
  2793. (define (explicate-tail e)
  2794. (match e
  2795. [(Var x) ___]
  2796. [(Int n) (Return (Int n))]
  2797. [(Let x rhs body) ___]
  2798. [(Prim op es) ___]
  2799. [else (error "explicate-tail unhandled case" e)]))
  2800. (define (explicate-assign e x cont)
  2801. (match e
  2802. [(Var x) ___]
  2803. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2804. [(Let y rhs body) ___]
  2805. [(Prim op es) ___]
  2806. [else (error "explicate-assign unhandled case" e)]))
  2807. (define (explicate-control p)
  2808. (match p
  2809. [(Program info body) ___]))
  2810. \end{lstlisting}
  2811. \caption{Skeleton for the \key{explicate-control} pass.}
  2812. \label{fig:explicate-control-Rvar}
  2813. \end{figure}
  2814. The organization of this pass depends on the notion of tail position
  2815. that we have alluded to earlier.
  2816. \begin{definition}
  2817. The following rules define when an expression is in \textbf{\emph{tail
  2818. position}}\index{subject}{tail position} for the language \LangVar{}.
  2819. \begin{enumerate}
  2820. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2821. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2822. \end{enumerate}
  2823. \end{definition}
  2824. We recommend implementing \code{explicate-control} using two mutually
  2825. recursive functions, \code{explicate-tail} and
  2826. \code{explicate-assign}, as suggested in the skeleton code in
  2827. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2828. function should be applied to expressions in tail position whereas the
  2829. \code{explicate-assign} should be applied to expressions that occur on
  2830. the right-hand-side of a \key{let}.
  2831. %
  2832. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2833. input and produces a \Tail{} in \LangCVar{} (see
  2834. Figure~\ref{fig:c0-syntax}).
  2835. %
  2836. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2837. the variable that it is to be assigned to, and a \Tail{} in
  2838. \LangCVar{} for the code that comes after the assignment. The
  2839. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2840. The \code{explicate-assign} function is in accumulator-passing style:
  2841. the \code{cont} parameter is used for accumulating the output. This
  2842. accumulator-passing style plays an important role in how we generate
  2843. high-quality code for conditional expressions in Chapter~\ref{ch:Rif}.
  2844. \begin{exercise}\normalfont
  2845. %
  2846. Implement the \code{explicate-control} function in
  2847. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2848. exercise the code in \code{explicate-control}.
  2849. %
  2850. In the \code{run-tests.rkt} script, add the following entry to the
  2851. list of \code{passes} and then run the script to test your compiler.
  2852. \begin{lstlisting}
  2853. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2854. \end{lstlisting}
  2855. \end{exercise}
  2856. \fi}
  2857. \section{Select Instructions}
  2858. \label{sec:select-Rvar}
  2859. \index{subject}{instruction selection}
  2860. In the \code{select\_instructions} pass we begin the work of
  2861. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  2862. language of this pass is a variant of x86 that still uses variables,
  2863. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  2864. non-terminal of the \LangXInt{} abstract syntax
  2865. (Figure~\ref{fig:x86-int-ast}).
  2866. \racket{We recommend implementing the
  2867. \code{select\_instructions} with three auxiliary functions, one for
  2868. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  2869. $\Tail$.}
  2870. \python{We recommend implementing an auxiliary function
  2871. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  2872. \racket{
  2873. The cases for $\Atm$ are straightforward; variables stay
  2874. the same and integer constants change to immediates:
  2875. $\INT{n}$ changes to $\IMM{n}$.}
  2876. We consider the cases for the $\Stmt$ non-terminal, starting with
  2877. arithmetic operations. For example, consider the addition
  2878. operation. We can use the \key{addq} instruction, but it performs an
  2879. in-place update. So we could move $\itm{arg}_1$ into the left-hand
  2880. side \itm{var} and then add $\itm{arg}_2$ to \itm{var}.
  2881. \begin{transformation}
  2882. {\if\edition\racketEd\color{olive}
  2883. \begin{lstlisting}
  2884. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2885. \end{lstlisting}
  2886. \fi}
  2887. {\if\edition\pythonEd\color{purple}
  2888. \begin{lstlisting}
  2889. |$\itm{var}$| = |$\itm{arg}_1$| + |$\itm{arg}_2$|
  2890. \end{lstlisting}
  2891. \fi}
  2892. \compilesto
  2893. \begin{lstlisting}
  2894. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2895. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2896. \end{lstlisting}
  2897. \end{transformation}
  2898. There are also cases that require special care to avoid generating
  2899. needlessly complicated code. For example, if one of the arguments of
  2900. the addition is the same variable as the left-hand side of the
  2901. assignment, then there is no need for the extra move instruction. The
  2902. assignment statement can be translated into a single \key{addq}
  2903. instruction as follows.
  2904. \begin{transformation}
  2905. {\if\edition\racketEd\color{olive}
  2906. \begin{lstlisting}
  2907. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2908. \end{lstlisting}
  2909. \fi}
  2910. {\if\edition\pythonEd\color{purple}
  2911. \begin{lstlisting}
  2912. |$\itm{var}$| = |$\itm{arg}_1$| + |$\itm{var}$|
  2913. \end{lstlisting}
  2914. \fi}
  2915. \compilesto
  2916. \begin{lstlisting}
  2917. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2918. \end{lstlisting}
  2919. \end{transformation}
  2920. The \key{read} operation does not have a direct counterpart in x86
  2921. assembly, so we provide this functionality with the function
  2922. \code{read\_int} in the file \code{runtime.c}, written in
  2923. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2924. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  2925. system}, or simply the \emph{runtime} for short. When compiling your
  2926. generated x86 assembly code, you need to compile \code{runtime.c} to
  2927. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2928. \code{-c}) and link it into the executable. For our purposes of code
  2929. generation, all you need to do is translate an assignment of
  2930. \key{read} into a call to the \code{read\_int} function followed by a
  2931. move from \code{rax} to the left-hand-side variable. (Recall that the
  2932. return value of a function goes into \code{rax}.)
  2933. \begin{transformation}
  2934. {\if\edition\racketEd\color{olive}
  2935. \begin{lstlisting}
  2936. |$\itm{var}$| = (read);
  2937. \end{lstlisting}
  2938. \fi}
  2939. {\if\edition\pythonEd\color{purple}
  2940. \begin{lstlisting}
  2941. |$\itm{var}$| = input_int();
  2942. \end{lstlisting}
  2943. \fi}
  2944. \compilesto
  2945. \begin{lstlisting}
  2946. callq read_int
  2947. movq %rax, |$\itm{var}$|
  2948. \end{lstlisting}
  2949. \end{transformation}
  2950. {\if\edition\racketEd\color{olive}
  2951. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2952. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2953. assignment to the \key{rax} register followed by a jump to the
  2954. conclusion of the program (so the conclusion needs to be labeled).
  2955. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2956. recursively and then append the resulting instructions.
  2957. \fi}
  2958. \begin{exercise}
  2959. \normalfont
  2960. {\if\edition\racketEd\color{olive}
  2961. Implement the \key{select-instructions} pass in
  2962. \code{compiler.rkt}. Create three new example programs that are
  2963. designed to exercise all of the interesting cases in this pass.
  2964. %
  2965. In the \code{run-tests.rkt} script, add the following entry to the
  2966. list of \code{passes} and then run the script to test your compiler.
  2967. \begin{lstlisting}
  2968. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2969. \end{lstlisting}
  2970. \fi}
  2971. {\if\edition\pythonEd\color{purple}
  2972. Implement the \key{select\_instructions} pass in
  2973. \code{compiler.py}. Create three new example programs that are
  2974. designed to exercise all of the interesting cases in this pass.
  2975. Run the \code{run-tests.py} script to to check
  2976. whether the output programs produce the same result as the input
  2977. programs.
  2978. \fi}
  2979. \end{exercise}
  2980. \section{Assign Homes}
  2981. \label{sec:assign-Rvar}
  2982. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  2983. \LangXVar{} programs that no longer use program variables.
  2984. Thus, the \key{assign-homes} pass is responsible for placing all of
  2985. the program variables in registers or on the stack. For runtime
  2986. efficiency, it is better to place variables in registers, but as there
  2987. are only 16 registers, some programs must necessarily resort to
  2988. placing some variables on the stack. In this chapter we focus on the
  2989. mechanics of placing variables on the stack. We study an algorithm for
  2990. placing variables in registers in
  2991. Chapter~\ref{ch:register-allocation-Rvar}.
  2992. Consider again the following \LangVar{} program from
  2993. Section~\ref{sec:remove-complex-opera-Rvar}.
  2994. % var_test_20.rkt
  2995. {\if\edition\racketEd\color{olive}
  2996. \begin{lstlisting}
  2997. (let ([a 42])
  2998. (let ([b a])
  2999. b))
  3000. \end{lstlisting}
  3001. \fi}
  3002. {\if\edition\pythonEd\color{purple}
  3003. \begin{lstlisting}
  3004. a = 42
  3005. b = a
  3006. print(b)
  3007. \end{lstlisting}
  3008. \fi}
  3009. The output of \code{select\_instructions} is shown on the left and the
  3010. output of \code{assign\_homes} on the right. In this example, we
  3011. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  3012. variable \code{b} to location \code{-16(\%rbp)}.
  3013. \begin{transformation}
  3014. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3015. start:
  3016. movq $42, a
  3017. movq a, b
  3018. movq b, %rax
  3019. jmp conclusion
  3020. \end{lstlisting}
  3021. \compilesto
  3022. %stack-space: 16
  3023. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3024. start:
  3025. movq $42, -8(%rbp)
  3026. movq -8(%rbp), -16(%rbp)
  3027. movq -16(%rbp), %rax
  3028. jmp conclusion
  3029. \end{lstlisting}
  3030. \end{transformation}
  3031. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3032. \code{X86Program} node is an alist mapping all the variables in the
  3033. program to their types (for now just \code{Integer}). The
  3034. \code{assign\_homes} pass should replace all uses of those variables
  3035. with stack locations. As an aside, the \code{locals-types} entry is
  3036. computed by \code{type-check-Cvar} in the support code, which installs
  3037. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  3038. be propagated to the \code{X86Program} node.}
  3039. %
  3040. \python{The \code{assign\_homes} pass should replace all uses of
  3041. variables with stack locations.}
  3042. In the process of assigning variables to stack locations, it is
  3043. convenient for you to compute and store the size of the frame (in
  3044. bytes) in%
  3045. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3046. %
  3047. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3048. which is needed later to generate the conclusion of the \code{main}
  3049. procedure. The x86-64 standard requires the frame size to be a
  3050. multiple of 16 bytes.\index{subject}{frame}
  3051. % TODO: store the number of variables instead? -Jeremy
  3052. \begin{exercise}\normalfont
  3053. Implement the \key{assign\_homes} pass in
  3054. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3055. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  3056. \Block{}. We recommend that the auxiliary functions take an extra
  3057. parameter that maps variable names to homes (stack locations for now).
  3058. %
  3059. {\if\edition\racketEd\color{olive}
  3060. In the \code{run-tests.rkt} script, add the following entry to the
  3061. list of \code{passes} and then run the script to test your compiler.
  3062. \begin{lstlisting}
  3063. (list "assign homes" assign-homes interp-x86-0)
  3064. \end{lstlisting}
  3065. \fi}
  3066. {\if\edition\pythonEd\color{purple}
  3067. Run the \code{run-tests.py} script to to check
  3068. whether the output programs produce the same result as the input
  3069. programs.
  3070. \fi}
  3071. \end{exercise}
  3072. \section{Patch Instructions}
  3073. \label{sec:patch-s0}
  3074. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3075. \LangXInt{} by making sure that each instruction adheres to the
  3076. restriction that at most one argument of an instruction may be a
  3077. memory reference.
  3078. We return to the following example.\\
  3079. \begin{minipage}{0.5\textwidth}
  3080. % var_test_20.rkt
  3081. {\if\edition\racketEd\color{olive}
  3082. \begin{lstlisting}
  3083. (let ([a 42])
  3084. (let ([b a])
  3085. b))
  3086. \end{lstlisting}
  3087. \fi}
  3088. {\if\edition\pythonEd\color{purple}
  3089. \begin{lstlisting}
  3090. a = 42
  3091. b = a
  3092. print(b)
  3093. \end{lstlisting}
  3094. \fi}
  3095. \end{minipage}\\
  3096. The \key{assign\_homes} pass produces the following translation. \\
  3097. \begin{minipage}{0.5\textwidth}
  3098. {\if\edition\racketEd\color{olive}
  3099. \begin{lstlisting}
  3100. movq $42, -8(%rbp)
  3101. movq -8(%rbp), -16(%rbp)
  3102. movq -16(%rbp), %rax
  3103. \end{lstlisting}
  3104. \fi}
  3105. {\if\edition\pythonEd\color{purple}
  3106. \begin{lstlisting}
  3107. movq 42, -8(%rbp)
  3108. movq -8(%rbp), -16(%rbp)
  3109. movq -16(%rbp), %rdi
  3110. callq print_int
  3111. \end{lstlisting}
  3112. \fi}
  3113. \end{minipage}\\
  3114. The second \key{movq} instruction is problematic because both
  3115. arguments are stack locations. We suggest fixing this problem by
  3116. moving from the source location to the register \key{rax} and then
  3117. from \key{rax} to the destination location, as follows.
  3118. \begin{lstlisting}
  3119. movq -8(%rbp), %rax
  3120. movq %rax, -16(%rbp)
  3121. \end{lstlisting}
  3122. \begin{exercise}
  3123. \normalfont Implement the \key{patch\_instructions} pass in
  3124. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3125. Create three new example programs that are
  3126. designed to exercise all of the interesting cases in this pass.
  3127. %
  3128. {\if\edition\racketEd\color{olive}
  3129. In the \code{run-tests.rkt} script, add the following entry to the
  3130. list of \code{passes} and then run the script to test your compiler.
  3131. \begin{lstlisting}
  3132. (list "patch instructions" patch-instructions interp-x86-0)
  3133. \end{lstlisting}
  3134. \fi}
  3135. {\if\edition\pythonEd\color{purple}
  3136. Run the \code{run-tests.py} script to to check
  3137. whether the output programs produce the same result as the input
  3138. programs.
  3139. \fi}
  3140. \end{exercise}
  3141. \section{Print x86}
  3142. \label{sec:print-x86}
  3143. The last step of the compiler from \LangVar{} to x86 is to convert the
  3144. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  3145. string representation (defined in
  3146. Figure~\ref{fig:x86-int-concrete}). \racket{The Racket \key{format} and
  3147. \key{string-append} functions are useful in this regard.} The main work
  3148. that this step needs to perform is to create the \key{main} function
  3149. and the standard instructions for its prelude and conclusion, as shown
  3150. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  3151. know the amount of space needed for the stack frame, which you can
  3152. obtain from the \racket{\code{stack-space} entry in the $\itm{info}$ field}
  3153. \python{\code{stack\_space} field}
  3154. of the \key{X86Program} node.
  3155. When running on Mac OS X, your compiler should prefix an underscore to
  3156. labels like \key{main}. \racket{The Racket call \code{(system-type 'os)} is
  3157. useful for determining which operating system the compiler is running
  3158. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3159. \python{The Python \code{platform} library includes a \code{system()} function
  3160. that returns \code{'Linux'}, \code{'Windows'}, or \code{'Darwin'} (for Mac).}
  3161. \begin{exercise}\normalfont
  3162. %
  3163. Implement the \key{print\_x86} pass in \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3164. %
  3165. {\if\edition\racketEd\color{olive}
  3166. In the \code{run-tests.rkt} script, add the following entry to the
  3167. list of \code{passes} and then run the script to test your compiler.
  3168. \begin{lstlisting}
  3169. (list "print x86" print-x86 #f)
  3170. \end{lstlisting}
  3171. %
  3172. Uncomment the call to the \key{compiler-tests} function
  3173. (Appendix~\ref{appendix:utilities}), which tests your complete
  3174. compiler by executing the generated x86 code. Compile the provided
  3175. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  3176. script to test your compiler.
  3177. \fi}
  3178. {\if\edition\pythonEd\color{purple}
  3179. Run the \code{run-tests.py} script to to check
  3180. whether the output programs produce the same result as the input
  3181. programs.
  3182. \fi}
  3183. \end{exercise}
  3184. \section{Challenge: Partial Evaluator for \LangVar{}}
  3185. \label{sec:pe-Rvar}
  3186. \index{subject}{partial evaluation}
  3187. This section describes optional challenge exercises that involve
  3188. adapting and improving the partial evaluator for \LangInt{} that was
  3189. introduced in Section~\ref{sec:partial-evaluation}.
  3190. \begin{exercise}\label{ex:pe-Rvar}
  3191. \normalfont
  3192. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3193. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3194. instead of \LangInt{} programs. Recall that \LangVar{} adds
  3195. \racket{\key{let} binding}\python{assignment}
  3196. and variables to the \LangInt{} language, so you will need to add cases for
  3197. them in the \code{pe\_exp} \racket{function}\python{and \code{pe\_stmt functions}}. Once complete, add the partial
  3198. evaluation pass to the front of your compiler and make sure that your
  3199. compiler still passes all of the tests.
  3200. \end{exercise}
  3201. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  3202. \begin{exercise}
  3203. \normalfont
  3204. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3205. \code{pe\_add} auxiliary functions with functions that know more about
  3206. arithmetic. For example, your partial evaluator should translate
  3207. {\if\edition\racketEd\color{olive}
  3208. \[
  3209. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3210. \code{(+ 2 (read))}
  3211. \]
  3212. \fi}
  3213. {\if\edition\pythonEd\color{purple}
  3214. \[
  3215. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3216. \code{2 + input\_int()}
  3217. \]
  3218. \fi}
  3219. To accomplish this, the \code{pe\_exp} function should produce output
  3220. in the form of the $\itm{residual}$ non-terminal of the following
  3221. grammar. The idea is that when processing an addition expression, we
  3222. can always produce either 1) an integer constant, 2) an addition
  3223. expression with an integer constant on the left-hand side but not the
  3224. right-hand side, or 3) or an addition expression in which neither
  3225. subexpression is a constant.
  3226. {\if\edition\racketEd\color{olive}
  3227. \[
  3228. \begin{array}{lcl}
  3229. \itm{inert} &::=& \Var
  3230. \MID \LP\key{read}\RP
  3231. \MID \LP\key{-} ~\Var\RP
  3232. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3233. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3234. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3235. \itm{residual} &::=& \Int
  3236. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3237. \MID \itm{inert}
  3238. \end{array}
  3239. \]
  3240. \fi}
  3241. {\if\edition\pythonEd\color{purple}
  3242. \[
  3243. \begin{array}{lcl}
  3244. \itm{inert} &::=& \Var
  3245. \MID \key{input\_int}\LP\RP
  3246. \MID \key{-} \Var
  3247. \MID \key{-} \key{input\_int}\LP\RP
  3248. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3249. \itm{residual} &::=& \Int
  3250. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3251. \MID \itm{inert}
  3252. \end{array}
  3253. \]
  3254. \fi}
  3255. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3256. inputs are $\itm{residual}$ expressions and they should return
  3257. $\itm{residual}$ expressions. Once the improvements are complete,
  3258. make sure that your compiler still passes all of the tests. After
  3259. all, fast code is useless if it produces incorrect results!
  3260. \end{exercise}
  3261. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3262. \chapter{Register Allocation}
  3263. \label{ch:register-allocation-Rvar}
  3264. \index{subject}{register allocation}
  3265. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  3266. stack. In this Chapter we learn how to improve the performance of the
  3267. generated code by placing some variables into registers. The CPU can
  3268. access a register in a single cycle, whereas accessing the stack can
  3269. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3270. serves as a running example. The source program is on the left and the
  3271. output of instruction selection is on the right. The program is almost
  3272. in the x86 assembly language but it still uses variables.
  3273. \begin{figure}
  3274. \begin{minipage}{0.45\textwidth}
  3275. Example \LangVar{} program:
  3276. % var_test_28.rkt
  3277. {\if\edition\racketEd\color{olive}
  3278. \begin{lstlisting}
  3279. (let ([v 1])
  3280. (let ([w 42])
  3281. (let ([x (+ v 7)])
  3282. (let ([y x])
  3283. (let ([z (+ x w)])
  3284. (+ z (- y)))))))
  3285. \end{lstlisting}
  3286. \fi}
  3287. {\if\edition\pythonEd\color{purple}
  3288. \begin{lstlisting}
  3289. v = 1
  3290. w = 42
  3291. x = v + 7
  3292. y = x
  3293. z = x + w
  3294. print(z + (- y))
  3295. \end{lstlisting}
  3296. \fi}
  3297. \end{minipage}
  3298. \begin{minipage}{0.45\textwidth}
  3299. After instruction selection:
  3300. {\if\edition\racketEd\color{olive}
  3301. \begin{lstlisting}
  3302. locals-types:
  3303. x : Integer, y : Integer,
  3304. z : Integer, t : Integer,
  3305. v : Integer, w : Integer
  3306. start:
  3307. movq $1, v
  3308. movq $42, w
  3309. movq v, x
  3310. addq $7, x
  3311. movq x, y
  3312. movq x, z
  3313. addq w, z
  3314. movq y, t
  3315. negq t
  3316. movq z, %rax
  3317. addq t, %rax
  3318. jmp conclusion
  3319. \end{lstlisting}
  3320. \fi}
  3321. {\if\edition\pythonEd\color{purple}
  3322. \begin{lstlisting}
  3323. movq $1, v
  3324. movq $42, w
  3325. movq v, x
  3326. addq $7, x
  3327. movq x, y
  3328. movq x, z
  3329. addq w, z
  3330. movq y, tmp_0
  3331. negq tmp_0
  3332. movq z, tmp_1
  3333. addq tmp_0, tmp_1
  3334. movq tmp_1, %rdi
  3335. callq print_int
  3336. \end{lstlisting}
  3337. \fi}
  3338. \end{minipage}
  3339. \caption{A running example for register allocation.}
  3340. \label{fig:reg-eg}
  3341. \end{figure}
  3342. The goal of register allocation is to fit as many variables into
  3343. registers as possible. Some programs have more variables than
  3344. registers so we cannot always map each variable to a different
  3345. register. Fortunately, it is common for different variables to be
  3346. needed during different periods of time during program execution, and
  3347. in such cases several variables can be mapped to the same register.
  3348. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3349. After the variable \code{x} is moved to \code{z} it is no longer
  3350. needed. Variable \code{z}, on the other hand, is used only after this
  3351. point, so \code{x} and \code{z} could share the same register. The
  3352. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  3353. where a variable is needed. Once we have that information, we compute
  3354. which variables are needed at the same time, i.e., which ones
  3355. \emph{interfere} with each other, and represent this relation as an
  3356. undirected graph whose vertices are variables and edges indicate when
  3357. two variables interfere (Section~\ref{sec:build-interference}). We
  3358. then model register allocation as a graph coloring problem
  3359. (Section~\ref{sec:graph-coloring}).
  3360. If we run out of registers despite these efforts, we place the
  3361. remaining variables on the stack, similar to what we did in
  3362. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  3363. for assigning a variable to a stack location. The decision to spill a
  3364. variable is handled as part of the graph coloring process
  3365. (Section~\ref{sec:graph-coloring}).
  3366. We make the simplifying assumption that each variable is assigned to
  3367. one location (a register or stack address). A more sophisticated
  3368. approach is to assign a variable to one or more locations in different
  3369. regions of the program. For example, if a variable is used many times
  3370. in short sequence and then only used again after many other
  3371. instructions, it could be more efficient to assign the variable to a
  3372. register during the initial sequence and then move it to the stack for
  3373. the rest of its lifetime. We refer the interested reader to
  3374. \citet{Cooper:2011aa} for more information about that approach.
  3375. % discuss prioritizing variables based on how much they are used.
  3376. \section{Registers and Calling Conventions}
  3377. \label{sec:calling-conventions}
  3378. \index{subject}{calling conventions}
  3379. As we perform register allocation, we need to be aware of the
  3380. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3381. functions calls are performed in x86.
  3382. %
  3383. Even though \LangVar{} does not include programmer-defined functions,
  3384. our generated code includes a \code{main} function that is called by
  3385. the operating system and our generated code contains calls to the
  3386. \code{read\_int} function.
  3387. Function calls require coordination between two pieces of code that
  3388. may be written by different programmers or generated by different
  3389. compilers. Here we follow the System V calling conventions that are
  3390. used by the GNU C compiler on Linux and
  3391. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3392. %
  3393. The calling conventions include rules about how functions share the
  3394. use of registers. In particular, the caller is responsible for freeing
  3395. up some registers prior to the function call for use by the callee.
  3396. These are called the \emph{caller-saved registers}
  3397. \index{subject}{caller-saved registers}
  3398. and they are
  3399. \begin{lstlisting}
  3400. rax rcx rdx rsi rdi r8 r9 r10 r11
  3401. \end{lstlisting}
  3402. On the other hand, the callee is responsible for preserving the values
  3403. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3404. which are
  3405. \begin{lstlisting}
  3406. rsp rbp rbx r12 r13 r14 r15
  3407. \end{lstlisting}
  3408. We can think about this caller/callee convention from two points of
  3409. view, the caller view and the callee view:
  3410. \begin{itemize}
  3411. \item The caller should assume that all the caller-saved registers get
  3412. overwritten with arbitrary values by the callee. On the other hand,
  3413. the caller can safely assume that all the callee-saved registers
  3414. contain the same values after the call that they did before the
  3415. call.
  3416. \item The callee can freely use any of the caller-saved registers.
  3417. However, if the callee wants to use a callee-saved register, the
  3418. callee must arrange to put the original value back in the register
  3419. prior to returning to the caller. This can be accomplished by saving
  3420. the value to the stack in the prelude of the function and restoring
  3421. the value in the conclusion of the function.
  3422. \end{itemize}
  3423. In x86, registers are also used for passing arguments to a function
  3424. and for the return value. In particular, the first six arguments to a
  3425. function are passed in the following six registers, in this order.
  3426. \begin{lstlisting}
  3427. rdi rsi rdx rcx r8 r9
  3428. \end{lstlisting}
  3429. If there are more than six arguments, then the convention is to use
  3430. space on the frame of the caller for the rest of the
  3431. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3432. need more than six arguments. For now, the only function we care about
  3433. is \code{read\_int} and it takes zero arguments.
  3434. %
  3435. The register \code{rax} is used for the return value of a function.
  3436. The next question is how these calling conventions impact register
  3437. allocation. Consider the \LangVar{} program in
  3438. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3439. example from the caller point of view and then from the callee point
  3440. of view.
  3441. The program makes two calls to the \code{read} function. Also, the
  3442. variable \code{x} is in use during the second call to \code{read}, so
  3443. we need to make sure that the value in \code{x} does not get
  3444. accidentally wiped out by the call to \code{read}. One obvious
  3445. approach is to save all the values in caller-saved registers to the
  3446. stack prior to each function call, and restore them after each
  3447. call. That way, if the register allocator chooses to assign \code{x}
  3448. to a caller-saved register, its value will be preserved across the
  3449. call to \code{read}. However, saving and restoring to the stack is
  3450. relatively slow. If \code{x} is not used many times, it may be better
  3451. to assign \code{x} to a stack location in the first place. Or better
  3452. yet, if we can arrange for \code{x} to be placed in a callee-saved
  3453. register, then it won't need to be saved and restored during function
  3454. calls.
  3455. The approach that we recommend for variables that are in use during a
  3456. function call is to either assign them to callee-saved registers or to
  3457. spill them to the stack. On the other hand, for variables that are not
  3458. in use during a function call, we try the following alternatives in
  3459. order 1) look for an available caller-saved register (to leave room
  3460. for other variables in the callee-saved register), 2) look for a
  3461. callee-saved register, and 3) spill the variable to the stack.
  3462. It is straightforward to implement this approach in a graph coloring
  3463. register allocator. First, we know which variables are in use during
  3464. every function call because we compute that information for every
  3465. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  3466. build the interference graph (Section~\ref{sec:build-interference}),
  3467. we can place an edge between each of these variables and the
  3468. caller-saved registers in the interference graph. This will prevent
  3469. the graph coloring algorithm from assigning those variables to
  3470. caller-saved registers.
  3471. Returning to the example in
  3472. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3473. generated x86 code on the right-hand side, focusing on the
  3474. \code{start} block. Notice that variable \code{x} is assigned to
  3475. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  3476. place during the second call to \code{read\_int}. Next, notice that
  3477. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  3478. because there are no function calls in the remainder of the block.
  3479. Next we analyze the example from the callee point of view, focusing on
  3480. the prelude and conclusion of the \code{main} function. As usual the
  3481. prelude begins with saving the \code{rbp} register to the stack and
  3482. setting the \code{rbp} to the current stack pointer. We now know why
  3483. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3484. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3485. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3486. (\code{x}). The other callee-saved registers are not saved in the
  3487. prelude because they are not used. The prelude subtracts 8 bytes from
  3488. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3489. conclusion, we see that \code{rbx} is restored from the stack with a
  3490. \code{popq} instruction.
  3491. \index{subject}{prelude}\index{subject}{conclusion}
  3492. \begin{figure}[tp]
  3493. \begin{minipage}{0.45\textwidth}
  3494. Example \LangVar{} program:
  3495. %var_test_14.rkt
  3496. {\if\edition\racketEd\color{olive}
  3497. \begin{lstlisting}
  3498. (let ([x (read)])
  3499. (let ([y (read)])
  3500. (+ (+ x y) 42)))
  3501. \end{lstlisting}
  3502. \fi}
  3503. {\if\edition\pythonEd\color{purple}
  3504. \begin{lstlisting}
  3505. x = input_int()
  3506. y = input_int()
  3507. print((x + y) + 42)
  3508. \end{lstlisting}
  3509. \fi}
  3510. \end{minipage}
  3511. \begin{minipage}{0.45\textwidth}
  3512. Generated x86 assembly:
  3513. {\if\edition\racketEd\color{olive}
  3514. \begin{lstlisting}
  3515. start:
  3516. callq read_int
  3517. movq %rax, %rbx
  3518. callq read_int
  3519. movq %rax, %rcx
  3520. addq %rcx, %rbx
  3521. movq %rbx, %rax
  3522. addq $42, %rax
  3523. jmp _conclusion
  3524. .globl main
  3525. main:
  3526. pushq %rbp
  3527. movq %rsp, %rbp
  3528. pushq %rbx
  3529. subq $8, %rsp
  3530. jmp start
  3531. conclusion:
  3532. addq $8, %rsp
  3533. popq %rbx
  3534. popq %rbp
  3535. retq
  3536. \end{lstlisting}
  3537. \fi}
  3538. {\if\edition\pythonEd\color{purple}
  3539. \begin{lstlisting}
  3540. .globl main
  3541. main:
  3542. pushq %rbp
  3543. movq %rsp, %rbp
  3544. pushq %rbx
  3545. subq $8, %rsp
  3546. callq read_int
  3547. movq %rax, %rbx
  3548. callq read_int
  3549. movq %rax, %rcx
  3550. movq %rbx, %rdx
  3551. addq %rcx, %rdx
  3552. movq %rdx, %rcx
  3553. addq $42, %rcx
  3554. movq %rcx, %rdi
  3555. callq print_int
  3556. addq $8, %rsp
  3557. popq %rbx
  3558. popq %rbp
  3559. retq
  3560. \end{lstlisting}
  3561. \fi}
  3562. \end{minipage}
  3563. \caption{An example with function calls.}
  3564. \label{fig:example-calling-conventions}
  3565. \end{figure}
  3566. %\clearpage
  3567. \section{Liveness Analysis}
  3568. \label{sec:liveness-analysis-Rvar}
  3569. \index{subject}{liveness analysis}
  3570. The \code{uncover\_live} \racket{pass}\python{function}
  3571. performs \emph{liveness analysis}, that
  3572. is, it discovers which variables are in-use in different regions of a
  3573. program.
  3574. %
  3575. A variable or register is \emph{live} at a program point if its
  3576. current value is used at some later point in the program. We
  3577. refer to variables and registers collectively as \emph{locations}.
  3578. %
  3579. Consider the following code fragment in which there are two writes to
  3580. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3581. \begin{center}
  3582. \begin{minipage}{0.96\textwidth}
  3583. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3584. movq $5, a
  3585. movq $30, b
  3586. movq a, c
  3587. movq $10, b
  3588. addq b, c
  3589. \end{lstlisting}
  3590. \end{minipage}
  3591. \end{center}
  3592. The answer is no because \code{a} is live from line 1 to 3 and
  3593. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3594. line 2 is never used because it is overwritten (line 4) before the
  3595. next read (line 5).
  3596. The live locations can be computed by traversing the instruction
  3597. sequence back to front (i.e., backwards in execution order). Let
  3598. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3599. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3600. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3601. locations before instruction $I_k$.
  3602. \racket{We recommend representing these
  3603. sets with the Racket \code{set} data structure described in
  3604. Figure~\ref{fig:set}.}
  3605. \python{We recommend representing these sets with the Python
  3606. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3607. data structure.}
  3608. {\if\edition\racketEd\color{olive}
  3609. \begin{figure}[tp]
  3610. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3611. \small
  3612. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3613. A \emph{set} is an unordered collection of elements without duplicates.
  3614. Here are some of the operations defined on sets.
  3615. \index{subject}{set}
  3616. \begin{description}
  3617. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3618. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3619. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3620. difference of the two sets.
  3621. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3622. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3623. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3624. \end{description}
  3625. \end{tcolorbox}
  3626. %\end{wrapfigure}
  3627. \caption{The \code{set} data structure.}
  3628. \label{fig:set}
  3629. \end{figure}
  3630. \fi}
  3631. The live locations after an instruction are always the same as the
  3632. live locations before the next instruction.
  3633. \index{subject}{live-after} \index{subject}{live-before}
  3634. \begin{equation} \label{eq:live-after-before-next}
  3635. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3636. \end{equation}
  3637. To start things off, there are no live locations after the last
  3638. instruction, so
  3639. \begin{equation}\label{eq:live-last-empty}
  3640. L_{\mathsf{after}}(n) = \emptyset
  3641. \end{equation}
  3642. We then apply the following rule repeatedly, traversing the
  3643. instruction sequence back to front.
  3644. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3645. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3646. \end{equation}
  3647. where $W(k)$ are the locations written to by instruction $I_k$ and
  3648. $R(k)$ are the locations read by instruction $I_k$.
  3649. {\if\edition\racketEd\color{olive}
  3650. There is a special case for \code{jmp} instructions. The locations
  3651. that are live before a \code{jmp} should be the locations in
  3652. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3653. maintaining an alist named \code{label->live} that maps each label to
  3654. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3655. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3656. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3657. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3658. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3659. \fi}
  3660. Let us walk through the above example, applying these formulas
  3661. starting with the instruction on line 5. We collect the answers in
  3662. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3663. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3664. instruction (formula~\ref{eq:live-last-empty}). The
  3665. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3666. because it reads from variables \code{b} and \code{c}
  3667. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3668. \[
  3669. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3670. \]
  3671. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3672. the live-before set from line 5 to be the live-after set for this
  3673. instruction (formula~\ref{eq:live-after-before-next}).
  3674. \[
  3675. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3676. \]
  3677. This move instruction writes to \code{b} and does not read from any
  3678. variables, so we have the following live-before set
  3679. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3680. \[
  3681. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3682. \]
  3683. The live-before for instruction \code{movq a, c}
  3684. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3685. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3686. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3687. variable that is not live and does not read from a variable.
  3688. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3689. because it writes to variable \code{a}.
  3690. \begin{figure}[tbp]
  3691. \begin{minipage}{0.45\textwidth}
  3692. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3693. movq $5, a
  3694. movq $30, b
  3695. movq a, c
  3696. movq $10, b
  3697. addq b, c
  3698. \end{lstlisting}
  3699. \end{minipage}
  3700. \vrule\hspace{10pt}
  3701. \begin{minipage}{0.45\textwidth}
  3702. \begin{align*}
  3703. L_{\mathsf{before}}(1)= \emptyset,
  3704. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3705. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3706. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3707. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3708. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3709. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3710. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3711. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3712. L_{\mathsf{after}}(5)= \emptyset
  3713. \end{align*}
  3714. \end{minipage}
  3715. \caption{Example output of liveness analysis on a short example.}
  3716. \label{fig:liveness-example-0}
  3717. \end{figure}
  3718. \begin{exercise}\normalfont
  3719. Perform liveness analysis on the running example in
  3720. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3721. sets for each instruction. Compare your answers to the solution
  3722. shown in Figure~\ref{fig:live-eg}.
  3723. \end{exercise}
  3724. \begin{figure}[tp]
  3725. \hspace{20pt}
  3726. \begin{minipage}{0.45\textwidth}
  3727. {\if\edition\racketEd\color{olive}
  3728. \begin{lstlisting}
  3729. |$\{\ttm{rsp}\}$|
  3730. movq $1, v
  3731. |$\{\ttm{v},\ttm{rsp}\}$|
  3732. movq $42, w
  3733. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3734. movq v, x
  3735. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3736. addq $7, x
  3737. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3738. movq x, y
  3739. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3740. movq x, z
  3741. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3742. addq w, z
  3743. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3744. movq y, t
  3745. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3746. negq t
  3747. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3748. movq z, %rax
  3749. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3750. addq t, %rax
  3751. |$\{\ttm{rax},\ttm{rsp}\}$|
  3752. jmp conclusion
  3753. \end{lstlisting}
  3754. \fi}
  3755. {\if\edition\pythonEd\color{purple}
  3756. \begin{lstlisting}
  3757. movq $1, v
  3758. |$\{\ttm{v}\}$|
  3759. movq $42, w
  3760. |$\{\ttm{w}, \ttm{v}\}$|
  3761. movq v, x
  3762. |$\{\ttm{w}, \ttm{x}\}$|
  3763. addq $7, x
  3764. |$\{\ttm{w}, \ttm{x}\}$|
  3765. movq x, y
  3766. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  3767. movq x, z
  3768. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  3769. addq w, z
  3770. |$\{\ttm{y}, \ttm{z}\}$|
  3771. movq y, tmp_0
  3772. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3773. negq tmp_0
  3774. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  3775. movq z, tmp_1
  3776. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  3777. addq tmp_0, tmp_1
  3778. |$\{\ttm{tmp\_1}\}$|
  3779. movq tmp_1, %rdi
  3780. |$\{\ttm{rdi}\}$|
  3781. callq print_int
  3782. |$\{\}$|
  3783. \end{lstlisting}
  3784. \fi}
  3785. \end{minipage}
  3786. \caption{The running example annotated with live-after sets.}
  3787. \label{fig:live-eg}
  3788. \end{figure}
  3789. \begin{exercise}\normalfont
  3790. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  3791. %
  3792. \racket{Store the sequence of live-after sets in the $\itm{info}$
  3793. field of the \code{Block} structure.}
  3794. %
  3795. \python{Return a dictionary that maps each instruction to its
  3796. live-after set.}
  3797. %
  3798. \racket{We recommend creating an auxiliary function that takes a list
  3799. of instructions and an initial live-after set (typically empty) and
  3800. returns the list of live-after sets.}
  3801. %
  3802. We recommend creating auxiliary functions to 1) compute the set
  3803. of locations that appear in an \Arg{}, 2) compute the locations read
  3804. by an instruction (the $R$ function), and 3) the locations written by
  3805. an instruction (the $W$ function). The \code{callq} instruction should
  3806. include all of the caller-saved registers in its write-set $W$ because
  3807. the calling convention says that those registers may be written to
  3808. during the function call. Likewise, the \code{callq} instruction
  3809. should include the appropriate argument-passing registers in its
  3810. read-set $R$, depending on the arity of the function being
  3811. called. (This is why the abstract syntax for \code{callq} includes the
  3812. arity.)
  3813. \end{exercise}
  3814. %\clearpage
  3815. \section{Build the Interference Graph}
  3816. \label{sec:build-interference}
  3817. {\if\edition\racketEd\color{olive}
  3818. \begin{figure}[tp]
  3819. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  3820. \small
  3821. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3822. A \emph{graph} is a collection of vertices and edges where each
  3823. edge connects two vertices. A graph is \emph{directed} if each
  3824. edge points from a source to a target. Otherwise the graph is
  3825. \emph{undirected}.
  3826. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  3827. \begin{description}
  3828. %% We currently don't use directed graphs. We instead use
  3829. %% directed multi-graphs. -Jeremy
  3830. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3831. directed graph from a list of edges. Each edge is a list
  3832. containing the source and target vertex.
  3833. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3834. undirected graph from a list of edges. Each edge is represented by
  3835. a list containing two vertices.
  3836. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3837. inserts a vertex into the graph.
  3838. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3839. inserts an edge between the two vertices.
  3840. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3841. returns a sequence of vertices adjacent to the vertex.
  3842. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3843. returns a sequence of all vertices in the graph.
  3844. \end{description}
  3845. \end{tcolorbox}
  3846. %\end{wrapfigure}
  3847. \caption{The Racket \code{graph} package.}
  3848. \label{fig:graph}
  3849. \end{figure}
  3850. \fi}
  3851. Based on the liveness analysis, we know where each location is live.
  3852. However, during register allocation, we need to answer questions of
  3853. the specific form: are locations $u$ and $v$ live at the same time?
  3854. (And therefore cannot be assigned to the same register.) To make this
  3855. question more efficient to answer, we create an explicit data
  3856. structure, an \emph{interference graph}\index{subject}{interference
  3857. graph}. An interference graph is an undirected graph that has an
  3858. edge between two locations if they are live at the same time, that is,
  3859. if they interfere with each other.
  3860. %
  3861. \racket{We recommend using the Racket \code{graph} package
  3862. (Figure~\ref{fig:graph}) to represent the interference graph.}
  3863. %
  3864. \python{We provide implementations of directed and undirected graph
  3865. data structures in the file \code{graph.py} of the support code.}
  3866. A straightforward way to compute the interference graph is to look at
  3867. the set of live locations between each instruction and the next and
  3868. add an edge to the graph for every pair of variables in the same set.
  3869. This approach is less than ideal for two reasons. First, it can be
  3870. expensive because it takes $O(n^2)$ time to consider at every pair in
  3871. a set of $n$ live locations. Second, in the special case where two
  3872. locations hold the same value (because one was assigned to the other),
  3873. they can be live at the same time without interfering with each other.
  3874. A better way to compute the interference graph is to focus on
  3875. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3876. must not overwrite something in a live location. So for each
  3877. instruction, we create an edge between the locations being written to
  3878. and the live locations. (Except that one should not create self
  3879. edges.) Note that for the \key{callq} instruction, we consider all of
  3880. the caller-saved registers as being written to, so an edge is added
  3881. between every live variable and every caller-saved register. For
  3882. \key{movq}, we deal with the above-mentioned special case by not
  3883. adding an edge between a live variable $v$ and the destination if $v$
  3884. matches the source. So we have the following two rules.
  3885. \begin{enumerate}
  3886. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3887. $d$, then add the edge $(d,v)$ for every $v \in
  3888. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3889. \item For any other instruction $I_k$, for every $d \in W(k)$
  3890. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3891. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3892. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3893. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3894. %% \item If instruction $I_k$ is of the form \key{callq}
  3895. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3896. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3897. \end{enumerate}
  3898. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3899. the above rules to each instruction. We highlight a few of the
  3900. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  3901. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  3902. so \code{v} interferes with \code{rsp}.}
  3903. %
  3904. \python{The first instruction is \lstinline{movq $1, v} and the
  3905. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  3906. no interference because $\ttm{v}$ is the destination of the move.}
  3907. %
  3908. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  3909. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  3910. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  3911. %
  3912. \python{The fourth instruction is \lstinline{addq $7, x} and the
  3913. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  3914. $\ttm{x}$ interferes with \ttm{w}.}
  3915. %
  3916. \racket{The next instruction is \lstinline{movq x, y} and the
  3917. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  3918. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  3919. \ttm{x} because \ttm{x} is the source of the move and therefore
  3920. \ttm{x} and \ttm{y} hold the same value.}
  3921. %
  3922. \python{The next instruction is \lstinline{movq x, y} and the
  3923. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  3924. applies, so \ttm{y} interferes with \ttm{w} but not
  3925. \ttm{x} because \ttm{x} is the source of the move and therefore
  3926. \ttm{x} and \ttm{y} hold the same value.}
  3927. %
  3928. Figure~\ref{fig:interference-results} lists the interference results
  3929. for all of the instructions and the resulting interference graph is
  3930. shown in Figure~\ref{fig:interfere}.
  3931. \begin{figure}[tbp]
  3932. \begin{quote}
  3933. {\if\edition\racketEd\color{olive}
  3934. \begin{tabular}{ll}
  3935. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3936. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3937. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3938. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3939. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3940. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3941. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3942. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3943. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3944. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3945. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3946. \lstinline!jmp conclusion!& no interference.
  3947. \end{tabular}
  3948. \fi}
  3949. {\if\edition\pythonEd\color{purple}
  3950. \begin{tabular}{ll}
  3951. \lstinline!movq $1, v!& no interference\\
  3952. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  3953. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  3954. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  3955. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  3956. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  3957. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  3958. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  3959. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  3960. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  3961. \lstinline!addq tmp_0, tmp_1! & no interference\\
  3962. \lstinline!movq tmp_1, %rdi! & no interference \\
  3963. \lstinline!callq print_int!& no interference.
  3964. \end{tabular}
  3965. \fi}
  3966. \end{quote}
  3967. \caption{Interference results for the running example.}
  3968. \label{fig:interference-results}
  3969. \end{figure}
  3970. \begin{figure}[tbp]
  3971. \large
  3972. {\if\edition\racketEd\color{olive}
  3973. \[
  3974. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3975. \node (rax) at (0,0) {$\ttm{rax}$};
  3976. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3977. \node (t1) at (0,2) {$\ttm{t}$};
  3978. \node (z) at (3,2) {$\ttm{z}$};
  3979. \node (x) at (6,2) {$\ttm{x}$};
  3980. \node (y) at (3,0) {$\ttm{y}$};
  3981. \node (w) at (6,0) {$\ttm{w}$};
  3982. \node (v) at (9,0) {$\ttm{v}$};
  3983. \draw (t1) to (rax);
  3984. \draw (t1) to (z);
  3985. \draw (z) to (y);
  3986. \draw (z) to (w);
  3987. \draw (x) to (w);
  3988. \draw (y) to (w);
  3989. \draw (v) to (w);
  3990. \draw (v) to (rsp);
  3991. \draw (w) to (rsp);
  3992. \draw (x) to (rsp);
  3993. \draw (y) to (rsp);
  3994. \path[-.,bend left=15] (z) edge node {} (rsp);
  3995. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3996. \draw (rax) to (rsp);
  3997. \end{tikzpicture}
  3998. \]
  3999. \fi}
  4000. {\if\edition\pythonEd\color{purple}
  4001. \[
  4002. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4003. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4004. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4005. \node (z) at (3,2) {$\ttm{z}$};
  4006. \node (x) at (6,2) {$\ttm{x}$};
  4007. \node (y) at (3,0) {$\ttm{y}$};
  4008. \node (w) at (6,0) {$\ttm{w}$};
  4009. \node (v) at (9,0) {$\ttm{v}$};
  4010. \draw (t0) to (t1);
  4011. \draw (t0) to (z);
  4012. \draw (z) to (y);
  4013. \draw (z) to (w);
  4014. \draw (x) to (w);
  4015. \draw (y) to (w);
  4016. \draw (v) to (w);
  4017. \end{tikzpicture}
  4018. \]
  4019. \fi}
  4020. \caption{The interference graph of the example program.}
  4021. \label{fig:interfere}
  4022. \end{figure}
  4023. %% Our next concern is to choose a data structure for representing the
  4024. %% interference graph. There are many choices for how to represent a
  4025. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4026. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4027. %% data structure is to study the algorithm that uses the data structure,
  4028. %% determine what operations need to be performed, and then choose the
  4029. %% data structure that provide the most efficient implementations of
  4030. %% those operations. Often times the choice of data structure can have an
  4031. %% effect on the time complexity of the algorithm, as it does here. If
  4032. %% you skim the next section, you will see that the register allocation
  4033. %% algorithm needs to ask the graph for all of its vertices and, given a
  4034. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4035. %% correct choice of graph representation is that of an adjacency
  4036. %% list. There are helper functions in \code{utilities.rkt} for
  4037. %% representing graphs using the adjacency list representation:
  4038. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4039. %% (Appendix~\ref{appendix:utilities}).
  4040. %% %
  4041. %% \margincomment{\footnotesize To do: change to use the
  4042. %% Racket graph library. \\ --Jeremy}
  4043. %% %
  4044. %% In particular, those functions use a hash table to map each vertex to
  4045. %% the set of adjacent vertices, and the sets are represented using
  4046. %% Racket's \key{set}, which is also a hash table.
  4047. \begin{exercise}\normalfont
  4048. \racket{Implement the compiler pass named \code{build\_interference} according
  4049. to the algorithm suggested above. We recommend using the Racket
  4050. \code{graph} package to create and inspect the interference graph.
  4051. The output graph of this pass should be stored in the $\itm{info}$ field of
  4052. the program, under the key \code{conflicts}.}
  4053. %
  4054. \python{Implement a function named \code{build\_interference}
  4055. according to the algorithm suggested above that
  4056. returns the interference graph.}
  4057. \end{exercise}
  4058. \section{Graph Coloring via Sudoku}
  4059. \label{sec:graph-coloring}
  4060. \index{subject}{graph coloring}
  4061. \index{subject}{Sudoku}
  4062. \index{subject}{color}
  4063. We come to the main event, mapping variables to registers and stack
  4064. locations. Variables that interfere with each other must be mapped to
  4065. different locations. In terms of the interference graph, this means
  4066. that adjacent vertices must be mapped to different locations. If we
  4067. think of locations as colors, the register allocation problem becomes
  4068. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4069. The reader may be more familiar with the graph coloring problem than he
  4070. or she realizes; the popular game of Sudoku is an instance of the
  4071. graph coloring problem. The following describes how to build a graph
  4072. out of an initial Sudoku board.
  4073. \begin{itemize}
  4074. \item There is one vertex in the graph for each Sudoku square.
  4075. \item There is an edge between two vertices if the corresponding squares
  4076. are in the same row, in the same column, or if the squares are in
  4077. the same $3\times 3$ region.
  4078. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4079. \item Based on the initial assignment of numbers to squares in the
  4080. Sudoku board, assign the corresponding colors to the corresponding
  4081. vertices in the graph.
  4082. \end{itemize}
  4083. If you can color the remaining vertices in the graph with the nine
  4084. colors, then you have also solved the corresponding game of Sudoku.
  4085. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4086. the corresponding graph with colored vertices. We map the Sudoku
  4087. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4088. sampling of the vertices (the colored ones) because showing edges for
  4089. all of the vertices would make the graph unreadable.
  4090. \begin{figure}[tbp]
  4091. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4092. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4093. \caption{A Sudoku game board and the corresponding colored graph.}
  4094. \label{fig:sudoku-graph}
  4095. \end{figure}
  4096. Some techniques for playing Sudoku correspond to heuristics used in
  4097. graph coloring algorithms. For example, one of the basic techniques
  4098. for Sudoku is called Pencil Marks. The idea is to use a process of
  4099. elimination to determine what numbers are no longer available for a
  4100. square and write down those numbers in the square (writing very
  4101. small). For example, if the number $1$ is assigned to a square, then
  4102. write the pencil mark $1$ in all the squares in the same row, column,
  4103. and region to indicate that $1$ is no longer an option for those other
  4104. squares.
  4105. %
  4106. The Pencil Marks technique corresponds to the notion of
  4107. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4108. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4109. are no longer available. In graph terminology, we have the following
  4110. definition:
  4111. \begin{equation*}
  4112. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4113. \text{ and } \mathrm{color}(v) = c \}
  4114. \end{equation*}
  4115. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4116. edge with $u$.
  4117. Using the Pencil Marks technique leads to a simple strategy for
  4118. filling in numbers: if there is a square with only one possible number
  4119. left, then choose that number! But what if there are no squares with
  4120. only one possibility left? One brute-force approach is to try them
  4121. all: choose the first one and if that ultimately leads to a solution,
  4122. great. If not, backtrack and choose the next possibility. One good
  4123. thing about Pencil Marks is that it reduces the degree of branching in
  4124. the search tree. Nevertheless, backtracking can be terribly time
  4125. consuming. One way to reduce the amount of backtracking is to use the
  4126. most-constrained-first heuristic (aka. minimum remaining
  4127. values)~\citep{Russell2003}. That is, when choosing a square, always
  4128. choose one with the fewest possibilities left (the vertex with the
  4129. highest saturation). The idea is that choosing highly constrained
  4130. squares earlier rather than later is better because later on there may
  4131. not be any possibilities left in the highly saturated squares.
  4132. However, register allocation is easier than Sudoku because the
  4133. register allocator can map variables to stack locations when the
  4134. registers run out. Thus, it makes sense to replace backtracking with
  4135. greedy search: make the best choice at the time and keep going. We
  4136. still wish to minimize the number of colors needed, so we use the
  4137. most-constrained-first heuristic in the greedy search.
  4138. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4139. algorithm for register allocation based on saturation and the
  4140. most-constrained-first heuristic. It is roughly equivalent to the
  4141. DSATUR
  4142. algorithm~\citep{Brelaz:1979eu}.
  4143. %,Gebremedhin:1999fk,Omari:2006uq
  4144. Just as in Sudoku, the algorithm represents colors with integers. The
  4145. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4146. for register allocation. The integers $k$ and larger correspond to
  4147. stack locations. The registers that are not used for register
  4148. allocation, such as \code{rax}, are assigned to negative integers. In
  4149. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4150. %% One might wonder why we include registers at all in the liveness
  4151. %% analysis and interference graph. For example, we never allocate a
  4152. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4153. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  4154. %% to use register for passing arguments to functions, it will be
  4155. %% necessary for those registers to appear in the interference graph
  4156. %% because those registers will also be assigned to variables, and we
  4157. %% don't want those two uses to encroach on each other. Regarding
  4158. %% registers such as \code{rax} and \code{rsp} that are not used for
  4159. %% variables, we could omit them from the interference graph but that
  4160. %% would require adding special cases to our algorithm, which would
  4161. %% complicate the logic for little gain.
  4162. \begin{figure}[btp]
  4163. \centering
  4164. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4165. Algorithm: DSATUR
  4166. Input: a graph |$G$|
  4167. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4168. |$W \gets \mathrm{vertices}(G)$|
  4169. while |$W \neq \emptyset$| do
  4170. pick a vertex |$u$| from |$W$| with the highest saturation,
  4171. breaking ties randomly
  4172. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4173. |$\mathrm{color}[u] \gets c$|
  4174. |$W \gets W - \{u\}$|
  4175. \end{lstlisting}
  4176. \caption{The saturation-based greedy graph coloring algorithm.}
  4177. \label{fig:satur-algo}
  4178. \end{figure}
  4179. {\if\edition\racketEd\color{olive}
  4180. With the DSATUR algorithm in hand, let us return to the running
  4181. example and consider how to color the interference graph in
  4182. Figure~\ref{fig:interfere}.
  4183. %
  4184. We start by assigning the register nodes to their own color. For
  4185. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4186. assigned $-2$. The variables are not yet colored, so they are
  4187. annotated with a dash. We then update the saturation for vertices that
  4188. are adjacent to a register, obtaining the following annotated
  4189. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4190. it interferes with both \code{rax} and \code{rsp}.
  4191. \[
  4192. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4193. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4194. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4195. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4196. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4197. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4198. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4199. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4200. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4201. \draw (t1) to (rax);
  4202. \draw (t1) to (z);
  4203. \draw (z) to (y);
  4204. \draw (z) to (w);
  4205. \draw (x) to (w);
  4206. \draw (y) to (w);
  4207. \draw (v) to (w);
  4208. \draw (v) to (rsp);
  4209. \draw (w) to (rsp);
  4210. \draw (x) to (rsp);
  4211. \draw (y) to (rsp);
  4212. \path[-.,bend left=15] (z) edge node {} (rsp);
  4213. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4214. \draw (rax) to (rsp);
  4215. \end{tikzpicture}
  4216. \]
  4217. The algorithm says to select a maximally saturated vertex. So we pick
  4218. $\ttm{t}$ and color it with the first available integer, which is
  4219. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4220. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4221. \[
  4222. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4223. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4224. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4225. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4226. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4227. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4228. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4229. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4230. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4231. \draw (t1) to (rax);
  4232. \draw (t1) to (z);
  4233. \draw (z) to (y);
  4234. \draw (z) to (w);
  4235. \draw (x) to (w);
  4236. \draw (y) to (w);
  4237. \draw (v) to (w);
  4238. \draw (v) to (rsp);
  4239. \draw (w) to (rsp);
  4240. \draw (x) to (rsp);
  4241. \draw (y) to (rsp);
  4242. \path[-.,bend left=15] (z) edge node {} (rsp);
  4243. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4244. \draw (rax) to (rsp);
  4245. \end{tikzpicture}
  4246. \]
  4247. We repeat the process, selecting a maximally saturated vertex,
  4248. choosing is \code{z}, and color it with the first available number, which
  4249. is $1$. We add $1$ to the saturation for the neighboring vertices
  4250. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4251. \[
  4252. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4253. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4254. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4255. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4256. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4257. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4258. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4259. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4260. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4261. \draw (t1) to (rax);
  4262. \draw (t1) to (z);
  4263. \draw (z) to (y);
  4264. \draw (z) to (w);
  4265. \draw (x) to (w);
  4266. \draw (y) to (w);
  4267. \draw (v) to (w);
  4268. \draw (v) to (rsp);
  4269. \draw (w) to (rsp);
  4270. \draw (x) to (rsp);
  4271. \draw (y) to (rsp);
  4272. \path[-.,bend left=15] (z) edge node {} (rsp);
  4273. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4274. \draw (rax) to (rsp);
  4275. \end{tikzpicture}
  4276. \]
  4277. The most saturated vertices are now \code{w} and \code{y}. We color
  4278. \code{w} with the first available color, which is $0$.
  4279. \[
  4280. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4281. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4282. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4283. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4284. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4285. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4286. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4287. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4288. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4289. \draw (t1) to (rax);
  4290. \draw (t1) to (z);
  4291. \draw (z) to (y);
  4292. \draw (z) to (w);
  4293. \draw (x) to (w);
  4294. \draw (y) to (w);
  4295. \draw (v) to (w);
  4296. \draw (v) to (rsp);
  4297. \draw (w) to (rsp);
  4298. \draw (x) to (rsp);
  4299. \draw (y) to (rsp);
  4300. \path[-.,bend left=15] (z) edge node {} (rsp);
  4301. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4302. \draw (rax) to (rsp);
  4303. \end{tikzpicture}
  4304. \]
  4305. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4306. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4307. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4308. and \code{z}, whose colors are $0$ and $1$ respectively.
  4309. \[
  4310. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4311. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4312. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4313. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4314. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4315. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4316. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4317. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4318. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4319. \draw (t1) to (rax);
  4320. \draw (t1) to (z);
  4321. \draw (z) to (y);
  4322. \draw (z) to (w);
  4323. \draw (x) to (w);
  4324. \draw (y) to (w);
  4325. \draw (v) to (w);
  4326. \draw (v) to (rsp);
  4327. \draw (w) to (rsp);
  4328. \draw (x) to (rsp);
  4329. \draw (y) to (rsp);
  4330. \path[-.,bend left=15] (z) edge node {} (rsp);
  4331. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4332. \draw (rax) to (rsp);
  4333. \end{tikzpicture}
  4334. \]
  4335. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4336. \[
  4337. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4338. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4339. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4340. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4341. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4342. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4343. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4344. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4345. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4346. \draw (t1) to (rax);
  4347. \draw (t1) to (z);
  4348. \draw (z) to (y);
  4349. \draw (z) to (w);
  4350. \draw (x) to (w);
  4351. \draw (y) to (w);
  4352. \draw (v) to (w);
  4353. \draw (v) to (rsp);
  4354. \draw (w) to (rsp);
  4355. \draw (x) to (rsp);
  4356. \draw (y) to (rsp);
  4357. \path[-.,bend left=15] (z) edge node {} (rsp);
  4358. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4359. \draw (rax) to (rsp);
  4360. \end{tikzpicture}
  4361. \]
  4362. In the last step of the algorithm, we color \code{x} with $1$.
  4363. \[
  4364. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4365. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4366. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4367. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4368. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4369. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4370. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4371. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4372. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4373. \draw (t1) to (rax);
  4374. \draw (t1) to (z);
  4375. \draw (z) to (y);
  4376. \draw (z) to (w);
  4377. \draw (x) to (w);
  4378. \draw (y) to (w);
  4379. \draw (v) to (w);
  4380. \draw (v) to (rsp);
  4381. \draw (w) to (rsp);
  4382. \draw (x) to (rsp);
  4383. \draw (y) to (rsp);
  4384. \path[-.,bend left=15] (z) edge node {} (rsp);
  4385. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4386. \draw (rax) to (rsp);
  4387. \end{tikzpicture}
  4388. \]
  4389. So we obtain the following coloring:
  4390. \[
  4391. \{
  4392. \ttm{rax} \mapsto -1,
  4393. \ttm{rsp} \mapsto -2,
  4394. \ttm{t} \mapsto 0,
  4395. \ttm{z} \mapsto 1,
  4396. \ttm{x} \mapsto 1,
  4397. \ttm{y} \mapsto 2,
  4398. \ttm{w} \mapsto 0,
  4399. \ttm{v} \mapsto 1
  4400. \}
  4401. \]
  4402. \fi}
  4403. %
  4404. {\if\edition\pythonEd\color{purple}
  4405. %
  4406. With the DSATUR algorithm in hand, let us return to the running
  4407. example and consider how to color the interference graph in
  4408. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4409. to indicate that it has not yet been assigned a color. The saturation
  4410. sets are also shown for each node; all of them start as the empty set.
  4411. (We do not include the register nodes in the graph below because there
  4412. were no interference edges involving registers in this program, but in
  4413. general there can be.)
  4414. %
  4415. \[
  4416. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4417. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4418. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4419. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4420. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4421. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4422. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4423. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4424. \draw (t0) to (t1);
  4425. \draw (t0) to (z);
  4426. \draw (z) to (y);
  4427. \draw (z) to (w);
  4428. \draw (x) to (w);
  4429. \draw (y) to (w);
  4430. \draw (v) to (w);
  4431. \end{tikzpicture}
  4432. \]
  4433. The algorithm says to select a maximally saturated vertex. So we pick
  4434. $\ttm{tmp\_0}$ and color it with the first available integer, which is
  4435. $0$. We mark $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$
  4436. because they interfere with $\ttm{tmp\_0}$.
  4437. \[
  4438. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4439. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4440. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4441. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4442. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4443. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4444. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4445. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4446. \draw (t0) to (t1);
  4447. \draw (t0) to (z);
  4448. \draw (z) to (y);
  4449. \draw (z) to (w);
  4450. \draw (x) to (w);
  4451. \draw (y) to (w);
  4452. \draw (v) to (w);
  4453. \end{tikzpicture}
  4454. \]
  4455. We repeat the process, selecting a maximally saturated vertex,
  4456. choosing \code{z}, and color it with the first available number, which
  4457. is $1$. We add $1$ to the saturation for the neighboring vertices
  4458. \code{tmp\_0}, \code{y}, and \code{w}.
  4459. \[
  4460. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4461. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4462. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4463. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4464. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4465. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4466. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4467. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4468. \draw (t0) to (t1);
  4469. \draw (t0) to (z);
  4470. \draw (z) to (y);
  4471. \draw (z) to (w);
  4472. \draw (x) to (w);
  4473. \draw (y) to (w);
  4474. \draw (v) to (w);
  4475. \end{tikzpicture}
  4476. \]
  4477. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4478. \code{y}. We color \code{w} with the first available color, which
  4479. is $0$.
  4480. \[
  4481. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4482. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4483. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4484. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4485. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4486. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4487. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4488. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4489. \draw (t0) to (t1);
  4490. \draw (t0) to (z);
  4491. \draw (z) to (y);
  4492. \draw (z) to (w);
  4493. \draw (x) to (w);
  4494. \draw (y) to (w);
  4495. \draw (v) to (w);
  4496. \end{tikzpicture}
  4497. \]
  4498. Now \code{y} is the most saturated, so we color it with $2$.
  4499. \[
  4500. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4501. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4502. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4503. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4504. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4505. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4506. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4507. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4508. \draw (t0) to (t1);
  4509. \draw (t0) to (z);
  4510. \draw (z) to (y);
  4511. \draw (z) to (w);
  4512. \draw (x) to (w);
  4513. \draw (y) to (w);
  4514. \draw (v) to (w);
  4515. \end{tikzpicture}
  4516. \]
  4517. Now \code{tmp\_1}, \code{x}, and \code{v} are equally saturated.
  4518. We choose to color \code{v} with $1$.
  4519. \[
  4520. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4521. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4522. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4523. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4524. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4525. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4526. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4527. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4528. \draw (t0) to (t1);
  4529. \draw (t0) to (z);
  4530. \draw (z) to (y);
  4531. \draw (z) to (w);
  4532. \draw (x) to (w);
  4533. \draw (y) to (w);
  4534. \draw (v) to (w);
  4535. \end{tikzpicture}
  4536. \]
  4537. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4538. \[
  4539. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4540. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4541. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4542. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4543. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4544. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4545. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4546. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4547. \draw (t0) to (t1);
  4548. \draw (t0) to (z);
  4549. \draw (z) to (y);
  4550. \draw (z) to (w);
  4551. \draw (x) to (w);
  4552. \draw (y) to (w);
  4553. \draw (v) to (w);
  4554. \end{tikzpicture}
  4555. \]
  4556. So we obtain the following coloring:
  4557. \[
  4558. \{ \ttm{tmp\_0} \mapsto 0,
  4559. \ttm{tmp\_1} \mapsto 1,
  4560. \ttm{z} \mapsto 1,
  4561. \ttm{x} \mapsto 1,
  4562. \ttm{y} \mapsto 2,
  4563. \ttm{w} \mapsto 0,
  4564. \ttm{v} \mapsto 1 \}
  4565. \]
  4566. \fi}
  4567. We recommend creating an auxiliary function named \code{color\_graph}
  4568. that takes an interference graph and a list of all the variables in
  4569. the program. This function should return a mapping of variables to
  4570. their colors (represented as natural numbers). By creating this helper
  4571. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4572. when we add support for functions.
  4573. To prioritize the processing of highly saturated nodes inside the
  4574. \code{color\_graph} function, we recommend using the priority queue
  4575. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4576. addition, you will need to maintain a mapping from variables to their
  4577. ``handles'' in the priority queue so that you can notify the priority
  4578. queue when their saturation changes.}
  4579. {\if\edition\racketEd\color{olive}
  4580. \begin{figure}[tp]
  4581. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4582. \small
  4583. \begin{tcolorbox}[title=Priority Queue]
  4584. A \emph{priority queue} is a collection of items in which the
  4585. removal of items is governed by priority. In a ``min'' queue,
  4586. lower priority items are removed first. An implementation is in
  4587. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4588. queue} \index{subject}{minimum priority queue}
  4589. \begin{description}
  4590. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4591. priority queue that uses the $\itm{cmp}$ predicate to determine
  4592. whether its first argument has lower or equal priority to its
  4593. second argument.
  4594. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4595. items in the queue.
  4596. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4597. the item into the queue and returns a handle for the item in the
  4598. queue.
  4599. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4600. the lowest priority.
  4601. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4602. notifies the queue that the priority has decreased for the item
  4603. associated with the given handle.
  4604. \end{description}
  4605. \end{tcolorbox}
  4606. %\end{wrapfigure}
  4607. \caption{The priority queue data structure.}
  4608. \label{fig:priority-queue}
  4609. \end{figure}
  4610. \fi}
  4611. With the coloring complete, we finalize the assignment of variables to
  4612. registers and stack locations. We map the first $k$ colors to the $k$
  4613. registers and the rest of the colors to stack locations. Suppose for
  4614. the moment that we have just one register to use for register
  4615. allocation, \key{rcx}. Then we have the following map from colors to
  4616. locations.
  4617. \[
  4618. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4619. \]
  4620. Composing this mapping with the coloring, we arrive at the following
  4621. assignment of variables to locations.
  4622. {\if\edition\racketEd\color{olive}
  4623. \begin{gather*}
  4624. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4625. \ttm{w} \mapsto \key{\%rcx}, \,
  4626. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4627. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4628. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4629. \ttm{t} \mapsto \key{\%rcx} \}
  4630. \end{gather*}
  4631. \fi}
  4632. {\if\edition\pythonEd\color{purple}
  4633. \begin{gather*}
  4634. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4635. \ttm{w} \mapsto \key{\%rcx}, \,
  4636. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4637. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4638. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4639. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4640. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4641. \end{gather*}
  4642. \fi}
  4643. Adapt the code from the \code{assign\_homes} pass
  4644. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  4645. assigned location. Applying the above assignment to our running
  4646. example, on the left, yields the program on the right.
  4647. % why frame size of 32? -JGS
  4648. \begin{center}
  4649. {\if\edition\racketEd\color{olive}
  4650. \begin{minipage}{0.3\textwidth}
  4651. \begin{lstlisting}
  4652. movq $1, v
  4653. movq $42, w
  4654. movq v, x
  4655. addq $7, x
  4656. movq x, y
  4657. movq x, z
  4658. addq w, z
  4659. movq y, t
  4660. negq t
  4661. movq z, %rax
  4662. addq t, %rax
  4663. jmp conclusion
  4664. \end{lstlisting}
  4665. \end{minipage}
  4666. $\Rightarrow\qquad$
  4667. \begin{minipage}{0.45\textwidth}
  4668. \begin{lstlisting}
  4669. movq $1, -8(%rbp)
  4670. movq $42, %rcx
  4671. movq -8(%rbp), -8(%rbp)
  4672. addq $7, -8(%rbp)
  4673. movq -8(%rbp), -16(%rbp)
  4674. movq -8(%rbp), -8(%rbp)
  4675. addq %rcx, -8(%rbp)
  4676. movq -16(%rbp), %rcx
  4677. negq %rcx
  4678. movq -8(%rbp), %rax
  4679. addq %rcx, %rax
  4680. jmp conclusion
  4681. \end{lstlisting}
  4682. \end{minipage}
  4683. \fi}
  4684. {\if\edition\pythonEd\color{purple}
  4685. \begin{minipage}{0.3\textwidth}
  4686. \begin{lstlisting}
  4687. movq $1, v
  4688. movq $42, w
  4689. movq v, x
  4690. addq $7, x
  4691. movq x, y
  4692. movq x, z
  4693. addq w, z
  4694. movq y, tmp_0
  4695. negq tmp_0
  4696. movq z, tmp_1
  4697. addq tmp_0, tmp_1
  4698. movq tmp_1, %rdi
  4699. callq print_int
  4700. \end{lstlisting}
  4701. \end{minipage}
  4702. $\Rightarrow\qquad$
  4703. \begin{minipage}{0.45\textwidth}
  4704. \begin{lstlisting}
  4705. movq $1, -8(%rbp)
  4706. movq $42, %rcx
  4707. movq -8(%rbp), -8(%rbp)
  4708. addq $7, -8(%rbp)
  4709. movq -8(%rbp), -16(%rbp)
  4710. movq -8(%rbp), -8(%rbp)
  4711. addq %rcx, -8(%rbp)
  4712. movq -16(%rbp), %rcx
  4713. negq %rcx
  4714. movq -8(%rbp), -8(%rbp)
  4715. addq %rcx, -8(%rbp)
  4716. movq -8(%rbp), %rdi
  4717. callq print_int
  4718. \end{lstlisting}
  4719. \end{minipage}
  4720. \fi}
  4721. \end{center}
  4722. \begin{exercise}\normalfont
  4723. %
  4724. Implement the compiler pass \code{allocate\_registers}.
  4725. %
  4726. Create five programs that exercise all of the register allocation
  4727. algorithm, including spilling variables to the stack.
  4728. %
  4729. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  4730. \code{run-tests.rkt} script with the three new passes:
  4731. \code{uncover\_live}, \code{build\_interference}, and
  4732. \code{allocate\_registers}.
  4733. %
  4734. Temporarily remove the \code{print\_x86} pass from the list of passes
  4735. and the call to \code{compiler-tests}.
  4736. Run the script to test the register allocator.
  4737. }
  4738. %
  4739. \python{Run the \code{run-tests.py} script to to check whether the
  4740. output programs produce the same result as the input programs.}
  4741. \end{exercise}
  4742. \section{Patch Instructions}
  4743. \label{sec:patch-instructions}
  4744. The remaining step in the compilation to x86 is to ensure that the
  4745. instructions have at most one argument that is a memory access.
  4746. %
  4747. In the running example, the instruction \code{movq -8(\%rbp),
  4748. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  4749. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  4750. then move \code{rax} into \code{-16(\%rbp)}.
  4751. %
  4752. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4753. problematic, but it can simply be deleted. In general, we recommend
  4754. deleting all the trivial moves whose source and destination are the
  4755. same location.
  4756. %
  4757. The following is the output of \code{patch\_instructions} on the
  4758. running example.
  4759. \begin{center}
  4760. {\if\edition\racketEd\color{olive}
  4761. \begin{minipage}{0.4\textwidth}
  4762. \begin{lstlisting}
  4763. movq $1, -8(%rbp)
  4764. movq $42, %rcx
  4765. movq -8(%rbp), -8(%rbp)
  4766. addq $7, -8(%rbp)
  4767. movq -8(%rbp), -16(%rbp)
  4768. movq -8(%rbp), -8(%rbp)
  4769. addq %rcx, -8(%rbp)
  4770. movq -16(%rbp), %rcx
  4771. negq %rcx
  4772. movq -8(%rbp), %rax
  4773. addq %rcx, %rax
  4774. jmp conclusion
  4775. \end{lstlisting}
  4776. \end{minipage}
  4777. $\Rightarrow\qquad$
  4778. \begin{minipage}{0.45\textwidth}
  4779. \begin{lstlisting}
  4780. movq $1, -8(%rbp)
  4781. movq $42, %rcx
  4782. addq $7, -8(%rbp)
  4783. movq -8(%rbp), %rax
  4784. movq %rax, -16(%rbp)
  4785. addq %rcx, -8(%rbp)
  4786. movq -16(%rbp), %rcx
  4787. negq %rcx
  4788. movq -8(%rbp), %rax
  4789. addq %rcx, %rax
  4790. jmp conclusion
  4791. \end{lstlisting}
  4792. \end{minipage}
  4793. \fi}
  4794. {\if\edition\pythonEd\color{purple}
  4795. \begin{minipage}{0.4\textwidth}
  4796. \begin{lstlisting}
  4797. movq $1, -8(%rbp)
  4798. movq $42, %rcx
  4799. movq -8(%rbp), -8(%rbp)
  4800. addq $7, -8(%rbp)
  4801. movq -8(%rbp), -16(%rbp)
  4802. movq -8(%rbp), -8(%rbp)
  4803. addq %rcx, -8(%rbp)
  4804. movq -16(%rbp), %rcx
  4805. negq %rcx
  4806. movq -8(%rbp), -8(%rbp)
  4807. addq %rcx, -8(%rbp)
  4808. movq -8(%rbp), %rdi
  4809. callq print_int
  4810. \end{lstlisting}
  4811. \end{minipage}
  4812. $\Rightarrow\qquad$
  4813. \begin{minipage}{0.45\textwidth}
  4814. \begin{lstlisting}
  4815. movq $1, -8(%rbp)
  4816. movq $42, %rcx
  4817. addq $7, -8(%rbp)
  4818. movq -8(%rbp), %rax
  4819. movq %rax, -16(%rbp)
  4820. addq %rcx, -8(%rbp)
  4821. movq -16(%rbp), %rcx
  4822. negq %rcx
  4823. addq %rcx, -8(%rbp)
  4824. movq -8(%rbp), %rdi
  4825. callq print_int
  4826. \end{lstlisting}
  4827. \end{minipage}
  4828. \fi}
  4829. \end{center}
  4830. \begin{exercise}\normalfont
  4831. %
  4832. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  4833. %
  4834. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  4835. %in the \code{run-tests.rkt} script.
  4836. %
  4837. Run the script to test the \code{patch\_instructions} pass.
  4838. \end{exercise}
  4839. \section{Print x86}
  4840. \label{sec:print-x86-reg-alloc}
  4841. \index{subject}{calling conventions}
  4842. \index{subject}{prelude}\index{subject}{conclusion}
  4843. Recall that the \code{print\_x86} pass generates the prelude and
  4844. conclusion instructions to satisfy the x86 calling conventions
  4845. (Section~\ref{sec:calling-conventions}). With the addition of the
  4846. register allocator, the callee-saved registers used by the register
  4847. allocator must be saved in the prelude and restored in the conclusion.
  4848. In the \code{allocate\_registers} pass,
  4849. %
  4850. \racket{add an entry to the \itm{info}
  4851. of \code{X86Program} named \code{used\_callee}}
  4852. %
  4853. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  4854. %
  4855. that stores the set of
  4856. callee-saved registers that were assigned to variables. The
  4857. \code{print\_x86} pass can then access this information to decide which
  4858. callee-saved registers need to be saved and restored.
  4859. %
  4860. When calculating the size of the frame to adjust the \code{rsp} in the
  4861. prelude, make sure to take into account the space used for saving the
  4862. callee-saved registers. Also, don't forget that the frame needs to be
  4863. a multiple of 16 bytes!
  4864. An overview of all of the passes involved in register allocation is
  4865. shown in Figure~\ref{fig:reg-alloc-passes}.
  4866. \begin{figure}[tbp]
  4867. {\if\edition\racketEd\color{olive}
  4868. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4869. \node (Rvar) at (0,2) {\large \LangVar{}};
  4870. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4871. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  4872. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  4873. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  4874. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  4875. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  4876. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  4877. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  4878. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  4879. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  4880. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-3);
  4881. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  4882. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  4883. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  4884. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  4885. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  4886. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  4887. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  4888. \end{tikzpicture}
  4889. \fi}
  4890. {\if\edition\pythonEd\color{purple}
  4891. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4892. \node (Rvar-1) at (0,2) {\large \LangVar{}};
  4893. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4894. \node (x86-1) at (3,0) {\large \LangXVar{}};
  4895. \node (x86-2) at (6,0) {\large \LangXVar{}};
  4896. \node (x86-3) at (9,0) {\large \LangXInt{}};
  4897. \node (x86-4) at (11,0) {\large \LangXInt{}};
  4898. \path[->,bend left=15] (Rvar-1) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Rvar-2);
  4899. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  4900. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize allocate\_reg.} (x86-2);
  4901. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  4902. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize print\_x86} (x86-4);
  4903. \end{tikzpicture}
  4904. \fi}
  4905. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  4906. \label{fig:reg-alloc-passes}
  4907. \end{figure}
  4908. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  4909. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  4910. use of registers and the stack, we have limited the register allocator
  4911. to use just two registers: \code{rbx} and \code{rcx}. In the
  4912. prelude\index{subject}{prelude} of the \code{main} function, we push
  4913. \code{rbx} onto the stack because it is a callee-saved register and it
  4914. was assigned to variable by the register allocator. We subtract
  4915. \code{8} from the \code{rsp} at the end of the prelude to reserve
  4916. space for the one spilled variable. After that subtraction, the
  4917. \code{rsp} is aligned to 16 bytes.
  4918. Moving on to the program proper, we see how the registers were
  4919. allocated.
  4920. %
  4921. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  4922. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  4923. %
  4924. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  4925. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  4926. were assigned to \code{rbx}.}
  4927. %
  4928. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  4929. location \code{-16(\%rbp)}. Recall that the prelude saved the
  4930. callee-save register \code{rbx} onto the stack. The spilled variables
  4931. must be placed lower on the stack than the saved callee-save
  4932. registers, so in this case \racket{\code{w}}\python{z} is placed at
  4933. \code{-16(\%rbp)}.
  4934. In the conclusion\index{subject}{conclusion}, we undo the work that was
  4935. done in the prelude. We move the stack pointer up by \code{8} bytes
  4936. (the room for spilled variables), then we pop the old values of
  4937. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  4938. \code{retq} to return control to the operating system.
  4939. \begin{figure}[tbp]
  4940. % var_test_28.rkt
  4941. % (use-minimal-set-of-registers! #t)
  4942. % and only rbx rcx
  4943. % tmp 0 rbx
  4944. % z 1 rcx
  4945. % y 0 rbx
  4946. % w 2 16(%rbp)
  4947. % v 0 rbx
  4948. % x 0 rbx
  4949. {\if\edition\racketEd\color{olive}
  4950. \begin{lstlisting}
  4951. start:
  4952. movq $1, %rbx
  4953. movq $42, -16(%rbp)
  4954. addq $7, %rbx
  4955. movq %rbx, %rcx
  4956. addq -16(%rbp), %rcx
  4957. negq %rbx
  4958. movq %rcx, %rax
  4959. addq %rbx, %rax
  4960. jmp conclusion
  4961. .globl main
  4962. main:
  4963. pushq %rbp
  4964. movq %rsp, %rbp
  4965. pushq %rbx
  4966. subq $8, %rsp
  4967. jmp start
  4968. conclusion:
  4969. addq $8, %rsp
  4970. popq %rbx
  4971. popq %rbp
  4972. retq
  4973. \end{lstlisting}
  4974. \fi}
  4975. {\if\edition\pythonEd\color{purple}
  4976. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  4977. \begin{lstlisting}
  4978. .globl main
  4979. main:
  4980. pushq %rbp
  4981. movq %rsp, %rbp
  4982. pushq %rbx
  4983. subq $8, %rsp
  4984. movq $1, %rcx
  4985. movq $42, %rbx
  4986. addq $7, %rcx
  4987. movq %rcx, -16(%rbp)
  4988. addq %rbx, -16(%rbp)
  4989. negq %rcx
  4990. movq -16(%rbp), %rbx
  4991. addq %rcx, %rbx
  4992. movq %rbx, %rdi
  4993. callq print_int
  4994. addq $8, %rsp
  4995. popq %rbx
  4996. popq %rbp
  4997. retq
  4998. \end{lstlisting}
  4999. \fi}
  5000. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  5001. \label{fig:running-example-x86}
  5002. \end{figure}
  5003. \begin{exercise}\normalfont
  5004. Update the \code{print\_x86} pass as described in this section.
  5005. %
  5006. \racket{
  5007. In the \code{run-tests.rkt} script, reinstate \code{print\_x86} in the
  5008. list of passes and the call to \code{compiler-tests}.}
  5009. %
  5010. Run the script to test the complete compiler for \LangVar{} that
  5011. performs register allocation.
  5012. \end{exercise}
  5013. \section{Challenge: Move Biasing}
  5014. \label{sec:move-biasing}
  5015. \index{subject}{move biasing}
  5016. This section describes an enhancement to the register allocator for
  5017. students looking for an extra challenge or who have a deeper interest
  5018. in register allocation.
  5019. {\if\edition\racketEd\color{olive}
  5020. To motivate the need for move biasing we return to the running example
  5021. but this time use all of the general purpose registers. So we have
  5022. the following mapping of color numbers to registers.
  5023. \[
  5024. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5025. \]
  5026. Using the same assignment of variables to color numbers that was
  5027. produced by the register allocator described in the last section, we
  5028. get the following program.
  5029. \begin{center}
  5030. \begin{minipage}{0.3\textwidth}
  5031. \begin{lstlisting}
  5032. movq $1, v
  5033. movq $42, w
  5034. movq v, x
  5035. addq $7, x
  5036. movq x, y
  5037. movq x, z
  5038. addq w, z
  5039. movq y, t
  5040. negq t
  5041. movq z, %rax
  5042. addq t, %rax
  5043. jmp conclusion
  5044. \end{lstlisting}
  5045. \end{minipage}
  5046. $\Rightarrow\qquad$
  5047. \begin{minipage}{0.45\textwidth}
  5048. \begin{lstlisting}
  5049. movq $1, %rdx
  5050. movq $42, %rcx
  5051. movq %rdx, %rdx
  5052. addq $7, %rdx
  5053. movq %rdx, %rsi
  5054. movq %rdx, %rdx
  5055. addq %rcx, %rdx
  5056. movq %rsi, %rcx
  5057. negq %rcx
  5058. movq %rdx, %rax
  5059. addq %rcx, %rax
  5060. jmp conclusion
  5061. \end{lstlisting}
  5062. \end{minipage}
  5063. \end{center}
  5064. In the above output code there are two \key{movq} instructions that
  5065. can be removed because their source and target are the same. However,
  5066. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5067. register, we could instead remove three \key{movq} instructions. We
  5068. can accomplish this by taking into account which variables appear in
  5069. \key{movq} instructions with which other variables.
  5070. \fi}
  5071. {\if\edition\pythonEd\color{purple}
  5072. %
  5073. To motivate the need for move biasing we return to the running example
  5074. and recall that Section~\ref{sec:patch-instructions} we were able to
  5075. remove three trivial move instructions from the running
  5076. example. However, we could remove another trivial move if we were able
  5077. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5078. We say that two variables $p$ and $q$ are \emph{move
  5079. related}\index{subject}{move related} if they participate together in a
  5080. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5081. \key{movq} $q$\key{,} $p$. When deciding which variable to
  5082. color next, when there are multiple variables with the same
  5083. saturation, prefer variables that can be assigned the same
  5084. color as a move related variable that has already been colored.
  5085. Furthermore, when the register allocator chooses a color
  5086. for a variable, it should prefer a color that has already been used
  5087. for a move-related variable (assuming that they do not interfere). Of
  5088. course, this preference should not override the preference for
  5089. registers over stack locations. This preference should be used as a
  5090. tie breaker when choosing between registers or when choosing between
  5091. stack locations.
  5092. We recommend representing the move relationships in a graph, similar
  5093. to how we represented interference. The following is the \emph{move
  5094. graph} for our running example.
  5095. {\if\edition\racketEd\color{olive}
  5096. \[
  5097. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5098. \node (rax) at (0,0) {$\ttm{rax}$};
  5099. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5100. \node (t) at (0,2) {$\ttm{t}$};
  5101. \node (z) at (3,2) {$\ttm{z}$};
  5102. \node (x) at (6,2) {$\ttm{x}$};
  5103. \node (y) at (3,0) {$\ttm{y}$};
  5104. \node (w) at (6,0) {$\ttm{w}$};
  5105. \node (v) at (9,0) {$\ttm{v}$};
  5106. \draw (v) to (x);
  5107. \draw (x) to (y);
  5108. \draw (x) to (z);
  5109. \draw (y) to (t);
  5110. \end{tikzpicture}
  5111. \]
  5112. \fi}
  5113. %
  5114. {\if\edition\pythonEd\color{purple}
  5115. \[
  5116. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5117. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5118. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5119. \node (z) at (3,2) {$\ttm{z}$};
  5120. \node (x) at (6,2) {$\ttm{x}$};
  5121. \node (y) at (3,0) {$\ttm{y}$};
  5122. \node (w) at (6,0) {$\ttm{w}$};
  5123. \node (v) at (9,0) {$\ttm{v}$};
  5124. \draw (y) to (t0);
  5125. \draw (z) to (x);
  5126. \draw (z) to (t1);
  5127. \draw (x) to (y);
  5128. \draw (x) to (v);
  5129. \end{tikzpicture}
  5130. \]
  5131. \fi}
  5132. {\if\edition\racketEd\color{olive}
  5133. Now we replay the graph coloring, pausing to see the coloring of
  5134. \code{y}. Recall the following configuration. The most saturated vertices
  5135. were \code{w} and \code{y}.
  5136. \[
  5137. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5138. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5139. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5140. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5141. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5142. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5143. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5144. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5145. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5146. \draw (t1) to (rax);
  5147. \draw (t1) to (z);
  5148. \draw (z) to (y);
  5149. \draw (z) to (w);
  5150. \draw (x) to (w);
  5151. \draw (y) to (w);
  5152. \draw (v) to (w);
  5153. \draw (v) to (rsp);
  5154. \draw (w) to (rsp);
  5155. \draw (x) to (rsp);
  5156. \draw (y) to (rsp);
  5157. \path[-.,bend left=15] (z) edge node {} (rsp);
  5158. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5159. \draw (rax) to (rsp);
  5160. \end{tikzpicture}
  5161. \]
  5162. %
  5163. Last time we chose to color \code{w} with $0$. But this time we see
  5164. that \code{w} is not move related to any vertex, but \code{y} is move
  5165. related to \code{t}. So we choose to color \code{y} the same color as
  5166. \code{t}, $0$.
  5167. \[
  5168. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5169. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5170. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5171. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5172. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5173. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5174. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5175. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5176. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5177. \draw (t1) to (rax);
  5178. \draw (t1) to (z);
  5179. \draw (z) to (y);
  5180. \draw (z) to (w);
  5181. \draw (x) to (w);
  5182. \draw (y) to (w);
  5183. \draw (v) to (w);
  5184. \draw (v) to (rsp);
  5185. \draw (w) to (rsp);
  5186. \draw (x) to (rsp);
  5187. \draw (y) to (rsp);
  5188. \path[-.,bend left=15] (z) edge node {} (rsp);
  5189. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5190. \draw (rax) to (rsp);
  5191. \end{tikzpicture}
  5192. \]
  5193. Now \code{w} is the most saturated, so we color it $2$.
  5194. \[
  5195. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5196. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5197. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5198. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5199. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5200. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5201. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5202. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5203. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5204. \draw (t1) to (rax);
  5205. \draw (t1) to (z);
  5206. \draw (z) to (y);
  5207. \draw (z) to (w);
  5208. \draw (x) to (w);
  5209. \draw (y) to (w);
  5210. \draw (v) to (w);
  5211. \draw (v) to (rsp);
  5212. \draw (w) to (rsp);
  5213. \draw (x) to (rsp);
  5214. \draw (y) to (rsp);
  5215. \path[-.,bend left=15] (z) edge node {} (rsp);
  5216. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5217. \draw (rax) to (rsp);
  5218. \end{tikzpicture}
  5219. \]
  5220. At this point, vertices \code{x} and \code{v} are most saturated, but
  5221. \code{x} is move related to \code{y} and \code{z}, so we color
  5222. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5223. \[
  5224. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5225. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5226. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5227. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5228. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5229. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5230. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5231. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5232. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5233. \draw (t1) to (rax);
  5234. \draw (t) to (z);
  5235. \draw (z) to (y);
  5236. \draw (z) to (w);
  5237. \draw (x) to (w);
  5238. \draw (y) to (w);
  5239. \draw (v) to (w);
  5240. \draw (v) to (rsp);
  5241. \draw (w) to (rsp);
  5242. \draw (x) to (rsp);
  5243. \draw (y) to (rsp);
  5244. \path[-.,bend left=15] (z) edge node {} (rsp);
  5245. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5246. \draw (rax) to (rsp);
  5247. \end{tikzpicture}
  5248. \]
  5249. \fi}
  5250. %
  5251. {\if\edition\pythonEd\color{purple}
  5252. Now we replay the graph coloring, pausing before the coloring of
  5253. \code{w}. Recall the following configuration. The most saturated vertices
  5254. were \code{tmp\_1}, \code{w}, and \code{y}.
  5255. \[
  5256. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5257. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5258. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5259. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5260. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5261. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5262. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5263. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5264. \draw (t0) to (t1);
  5265. \draw (t0) to (z);
  5266. \draw (z) to (y);
  5267. \draw (z) to (w);
  5268. \draw (x) to (w);
  5269. \draw (y) to (w);
  5270. \draw (v) to (w);
  5271. \end{tikzpicture}
  5272. \]
  5273. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5274. or \code{y}, but note that \code{w} is not move related to any
  5275. variables, wheras \code{y} and \code{tmp\_1} are move related to
  5276. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5277. \code{y} and color it $0$, we can delete another move instruction.
  5278. \[
  5279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5280. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5281. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5282. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5283. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5284. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5285. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5286. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5287. \draw (t0) to (t1);
  5288. \draw (t0) to (z);
  5289. \draw (z) to (y);
  5290. \draw (z) to (w);
  5291. \draw (x) to (w);
  5292. \draw (y) to (w);
  5293. \draw (v) to (w);
  5294. \end{tikzpicture}
  5295. \]
  5296. Now \code{w} is the most saturated, so we color it $2$.
  5297. \[
  5298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5299. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5300. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5301. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5302. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5303. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5304. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5305. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5306. \draw (t0) to (t1);
  5307. \draw (t0) to (z);
  5308. \draw (z) to (y);
  5309. \draw (z) to (w);
  5310. \draw (x) to (w);
  5311. \draw (y) to (w);
  5312. \draw (v) to (w);
  5313. \end{tikzpicture}
  5314. \]
  5315. To finish the coloring, \code{x} and \code{v} get $0$ and
  5316. \code{tmp\_1} gets $1$.
  5317. \[
  5318. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5319. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5320. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5321. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5322. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5323. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5324. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5325. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5326. \draw (t0) to (t1);
  5327. \draw (t0) to (z);
  5328. \draw (z) to (y);
  5329. \draw (z) to (w);
  5330. \draw (x) to (w);
  5331. \draw (y) to (w);
  5332. \draw (v) to (w);
  5333. \end{tikzpicture}
  5334. \]
  5335. \fi}
  5336. So we have the following assignment of variables to registers.
  5337. {\if\edition\racketEd\color{olive}
  5338. \begin{gather*}
  5339. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5340. \ttm{w} \mapsto \key{\%rsi}, \,
  5341. \ttm{x} \mapsto \key{\%rcx}, \,
  5342. \ttm{y} \mapsto \key{\%rcx}, \,
  5343. \ttm{z} \mapsto \key{\%rdx}, \,
  5344. \ttm{t} \mapsto \key{\%rcx} \}
  5345. \end{gather*}
  5346. \fi}
  5347. {\if\edition\pythonEd\color{purple}
  5348. \begin{gather*}
  5349. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5350. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5351. \ttm{x} \mapsto \key{\%rcx}, \,
  5352. \ttm{y} \mapsto \key{\%rcx}, \\
  5353. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5354. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5355. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5356. \end{gather*}
  5357. \fi}
  5358. We apply this register assignment to the running example, on the left,
  5359. to obtain the code in the middle. The \code{patch\_instructions} then
  5360. deletes the trivial moves to obtain the code on the right.
  5361. {\if\edition\racketEd\color{olive}
  5362. \begin{minipage}{0.25\textwidth}
  5363. \begin{lstlisting}
  5364. movq $1, v
  5365. movq $42, w
  5366. movq v, x
  5367. addq $7, x
  5368. movq x, y
  5369. movq x, z
  5370. addq w, z
  5371. movq y, t
  5372. negq t
  5373. movq z, %rax
  5374. addq t, %rax
  5375. jmp conclusion
  5376. \end{lstlisting}
  5377. \end{minipage}
  5378. $\Rightarrow\qquad$
  5379. \begin{minipage}{0.25\textwidth}
  5380. \begin{lstlisting}
  5381. movq $1, %rcx
  5382. movq $42, %rsi
  5383. movq %rcx, %rcx
  5384. addq $7, %rcx
  5385. movq %rcx, %rcx
  5386. movq %rcx, %rdx
  5387. addq %rsi, %rdx
  5388. movq %rcx, %rcx
  5389. negq %rcx
  5390. movq %rdx, %rax
  5391. addq %rcx, %rax
  5392. jmp conclusion
  5393. \end{lstlisting}
  5394. \end{minipage}
  5395. $\Rightarrow\qquad$
  5396. \begin{minipage}{0.25\textwidth}
  5397. \begin{lstlisting}
  5398. movq $1, %rcx
  5399. movq $42, %rsi
  5400. addq $7, %rcx
  5401. movq %rcx, %rdx
  5402. addq %rsi, %rdx
  5403. negq %rcx
  5404. movq %rdx, %rax
  5405. addq %rcx, %rax
  5406. jmp conclusion
  5407. \end{lstlisting}
  5408. \end{minipage}
  5409. \fi}
  5410. {\if\edition\pythonEd\color{purple}
  5411. \begin{minipage}{0.25\textwidth}
  5412. \begin{lstlisting}
  5413. movq $1, v
  5414. movq $42, w
  5415. movq v, x
  5416. addq $7, x
  5417. movq x, y
  5418. movq x, z
  5419. addq w, z
  5420. movq y, tmp_0
  5421. negq tmp_0
  5422. movq z, tmp_1
  5423. addq tmp_0, tmp_1
  5424. movq tmp_1, %rdi
  5425. callq _print_int\end{lstlisting}
  5426. \end{minipage}
  5427. $\Rightarrow\qquad$
  5428. \begin{minipage}{0.25\textwidth}
  5429. \begin{lstlisting}
  5430. movq $1, %rcx
  5431. movq $42, -16(%rbp)
  5432. movq %rcx, %rcx
  5433. addq $7, %rcx
  5434. movq %rcx, %rcx
  5435. movq %rcx, -8(%rbp)
  5436. addq -16(%rbp), -8(%rbp)
  5437. movq %rcx, %rcx
  5438. negq %rcx
  5439. movq -8(%rbp), -8(%rbp)
  5440. addq %rcx, -8(%rbp)
  5441. movq -8(%rbp), %rdi
  5442. callq _print_int
  5443. \end{lstlisting}
  5444. \end{minipage}
  5445. $\Rightarrow\qquad$
  5446. \begin{minipage}{0.25\textwidth}
  5447. \begin{lstlisting}
  5448. movq $1, %rcx
  5449. movq $42, -16(%rbp)
  5450. addq $7, %rcx
  5451. movq %rcx, -8(%rbp)
  5452. movq -16(%rbp), %rax
  5453. addq %rax, -8(%rbp)
  5454. negq %rcx
  5455. addq %rcx, -8(%rbp)
  5456. movq -8(%rbp), %rdi
  5457. callq print_int
  5458. \end{lstlisting}
  5459. \end{minipage}
  5460. \fi}
  5461. \begin{exercise}\normalfont
  5462. Change your implementation of \code{allocate\_registers} to take move
  5463. biasing into account. Create two new tests that include at least one
  5464. opportunity for move biasing and visually inspect the output x86
  5465. programs to make sure that your move biasing is working properly. Make
  5466. sure that your compiler still passes all of the tests.
  5467. \end{exercise}
  5468. %To do: another neat challenge would be to do
  5469. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5470. %% \subsection{Output of the Running Example}
  5471. %% \label{sec:reg-alloc-output}
  5472. % challenge: prioritize variables based on execution frequencies
  5473. % and the number of uses of a variable
  5474. % challenge: enhance the coloring algorithm using Chaitin's
  5475. % approach of prioritizing high-degree variables
  5476. % by removing low-degree variables (coloring them later)
  5477. % from the interference graph
  5478. \section{Further Reading}
  5479. \label{sec:register-allocation-further-reading}
  5480. Early register allocation algorithms were developed for Fortran
  5481. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5482. of graph coloring began in the late 1970s and early 1980s with the
  5483. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5484. algorithm is based on the following observation of
  5485. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  5486. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  5487. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  5488. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5489. different colors, but since there are less than $k$ of them, there
  5490. will be one or more colors left over to use for coloring $v$ in $G$.
  5491. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5492. less than $k$ from the graph and recursively colors the rest of the
  5493. graph. Upon returning from the recursion, it colors $v$ with one of
  5494. the available colors and returns. \citet{Chaitin:1982vn} augments
  5495. this algorithm to handle spilling as follows. If there are no vertices
  5496. of degree lower than $k$ then pick a vertex at random, spill it,
  5497. remove it from the graph, and proceed recursively to color the rest of
  5498. the graph.
  5499. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5500. move-related and that don't interfere with each other, a process
  5501. called \emph{coalescing}. While coalescing decreases the number of
  5502. moves, it can make the graph more difficult to
  5503. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5504. which two variables are merged only if they have fewer than $k$
  5505. neighbors of high degree. \citet{George:1996aa} observe that
  5506. conservative coalescing is sometimes too conservative and make it more
  5507. aggressive by iterating the coalescing with the removal of low-degree
  5508. vertices.
  5509. %
  5510. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5511. also propose \emph{biased coloring} in which a variable is assigned to
  5512. the same color as another move-related variable if possible, as
  5513. discussed in Section~\ref{sec:move-biasing}.
  5514. %
  5515. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5516. performs coalescing, graph coloring, and spill code insertion until
  5517. all variables have been assigned a location.
  5518. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5519. spills variables that don't have to be: a high-degree variable can be
  5520. colorable if many of its neighbors are assigned the same color.
  5521. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5522. high-degree vertex is not immediately spilled. Instead the decision is
  5523. deferred until after the recursive call, at which point it is apparent
  5524. whether there is actually an available color or not. We observe that
  5525. this algorithm is equivalent to the smallest-last ordering
  5526. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5527. be registers and the rest to be stack locations.
  5528. %% biased coloring
  5529. Earlier editions of the compiler course at Indiana University
  5530. \citep{Dybvig:2010aa} were based on the algorithm of
  5531. \citet{Briggs:1994kx}.
  5532. The smallest-last ordering algorithm is one of many \emph{greedy}
  5533. coloring algorithms. A greedy coloring algorithm visits all the
  5534. vertices in a particular order and assigns each one the first
  5535. available color. An \emph{offline} greedy algorithm chooses the
  5536. ordering up-front, prior to assigning colors. The algorithm of
  5537. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5538. ordering does not depend on the colors assigned, so the algorithm
  5539. could be split into two phases. Other orderings are possible. For
  5540. example, \citet{Chow:1984ys} order variables according to an estimate
  5541. of runtime cost.
  5542. An \emph{online} greedy coloring algorithm uses information about the
  5543. current assignment of colors to influence the order in which the
  5544. remaining vertices are colored. The saturation-based algorithm
  5545. described in this chapter is one such algorithm. We choose to use
  5546. saturation-based coloring is because it is fun to introduce graph
  5547. coloring via Sudoku.
  5548. A register allocator may choose to map each variable to just one
  5549. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5550. variable to one or more locations. The later can be achieved by
  5551. \emph{live range splitting}, where a variable is replaced by several
  5552. variables that each handle part of its live
  5553. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5554. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5555. %% replacement algorithm, bottom-up local
  5556. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5557. %% Cooper: top-down (priority bassed), bottom-up
  5558. %% top-down
  5559. %% order variables by priority (estimated cost)
  5560. %% caveat: split variables into two groups:
  5561. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5562. %% color the constrained ones first
  5563. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5564. %% cite J. Cocke for an algorithm that colors variables
  5565. %% in a high-degree first ordering
  5566. %Register Allocation via Usage Counts, Freiburghouse CACM
  5567. \citet{Palsberg:2007si} observe that many of the interference graphs
  5568. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5569. that is, every cycle with four or more edges has an edge which is not
  5570. part of the cycle but which connects two vertices on the cycle. Such
  5571. graphs can be optimally colored by the greedy algorithm with a vertex
  5572. ordering determined by maximum cardinality search.
  5573. In situations where compile time is of utmost importance, such as in
  5574. just-in-time compilers, graph coloring algorithms can be too expensive
  5575. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  5576. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5577. \chapter{Booleans and Control Flow}
  5578. \label{ch:Rif}
  5579. \index{subject}{Boolean}
  5580. \index{subject}{control flow}
  5581. \index{subject}{conditional expression}
  5582. The \LangInt{} and \LangVar{} languages only have a single kind of
  5583. value, integers. In this chapter we add a second kind of value, the
  5584. Booleans, to create the \LangIf{} language. The Boolean values
  5585. \emph{true} and \emph{false} are written \racket{\key{\#t}}\python{\key{True}}
  5586. and \racket{\key{\#f}}\python{\key{False}}
  5587. respectively in \racket{Racket}\python{Python}.
  5588. The \LangIf{} language includes several
  5589. operations that involve Booleans (\key{and}, \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the conditional \key{if} expression. With the
  5590. addition of \key{if}, programs can have non-trivial control flow which
  5591. \racket{impacts \code{explicate\_control} and liveness analysis}
  5592. \python{impacts liveness analysis and motivates a new pass named
  5593. \code{explicate\_control}}. Also, because
  5594. we now have two kinds of values, we need to handle programs that apply
  5595. an operation to the wrong kind of value, such as \code{(not 1)}.
  5596. There are two language design options for such situations. One option
  5597. is to signal an error and the other is to provide a wider
  5598. interpretation of the operation. \racket{The Racket
  5599. language}\python{Python} uses a mixture of these two options,
  5600. depending on the operation and the kind of value. For example, the
  5601. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5602. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5603. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5604. %
  5605. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5606. in Racket because \code{car} expects a pair.}
  5607. %
  5608. \python{On the other hand, \code{1[0]} results in a run-time error
  5609. in Python because an ``\code{int} object is not subscriptable''.}
  5610. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5611. design choices as \racket{Racket}\python{Python}, except much of the
  5612. error detection happens at compile time instead of run
  5613. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5614. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5615. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5616. Racket}\python{MyPy} reports a compile-time error
  5617. %
  5618. \racket{because Racket expects the type of the argument to be of the form
  5619. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5620. %
  5621. \python{stating that a ``value of type \code{int} is not indexable''.}
  5622. The \LangIf{} language performs type checking during compilation like
  5623. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5624. alternative choice, that is, a dynamically typed language like
  5625. \racket{Racket}\python{Python}.
  5626. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5627. for some operations we are more restrictive, for example, rejecting
  5628. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5629. This chapter is organized as follows. We begin by defining the syntax
  5630. and interpreter for the \LangIf{} language
  5631. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5632. checking and build a type checker for \LangIf{}
  5633. (Section~\ref{sec:type-check-Rif}).
  5634. %
  5635. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5636. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5637. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5638. %
  5639. The remaining sections of this chapter discuss how our compiler passes
  5640. change to accommodate Booleans and conditional control flow. There is
  5641. one new pass, named \code{shrink}, that translates some operators into
  5642. others, thereby reducing the number of operators that need to be
  5643. handled in later passes.
  5644. %
  5645. \racket{The largest changes occur in \code{explicate\_control}, to
  5646. translate \code{if} expressions into control-flow graphs
  5647. (Section~\ref{sec:explicate-control-Rif}).}
  5648. %
  5649. \python{The largest addition is a new pass named
  5650. \code{explicate\_control} that translates \code{if} expressions and
  5651. statements into control-flow graphs
  5652. (Section~\ref{sec:explicate-control-Rif}).}
  5653. %
  5654. Regarding register allocation, liveness analysis now has multiple
  5655. basic blocks to process and there is the interesting question of how
  5656. to handle conditional jumps.
  5657. \section{The \LangIf{} Language}
  5658. \label{sec:lang-if}
  5659. The concrete syntax of the \LangIf{} language is defined in
  5660. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  5661. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  5662. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  5663. \code{\#f}, and the conditional \code{if} expression. We expand the
  5664. operators to include
  5665. \begin{enumerate}
  5666. \item subtraction on integers,
  5667. \item the logical operators \key{and}, \key{or} and \key{not},
  5668. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  5669. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5670. comparing integers.
  5671. \end{enumerate}
  5672. We reorganize the abstract syntax for the primitive operations in
  5673. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  5674. them. This means that the grammar no longer checks whether the arity
  5675. of an operators matches the number of arguments. That responsibility
  5676. is moved to the type checker for \LangIf{}, which we introduce in
  5677. Section~\ref{sec:type-check-Rif}.
  5678. \begin{figure}[tp]
  5679. \centering
  5680. \fbox{
  5681. \begin{minipage}{0.96\textwidth}
  5682. \[
  5683. \begin{array}{lcl}
  5684. \itm{bool} &::=& \key{\#t} \MID \key{\#f} \\
  5685. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5686. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} } \MID \CSUB{\Exp}{\Exp} \\
  5687. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} } \\
  5688. &\MID& \itm{bool}
  5689. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5690. \MID (\key{not}\;\Exp) \\
  5691. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5692. \LangIfM{} &::=& \Exp
  5693. \end{array}
  5694. \]
  5695. \end{minipage}
  5696. }
  5697. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  5698. (Figure~\ref{fig:Rvar-concrete-syntax}) with Booleans and conditionals.}
  5699. \label{fig:Rif-concrete-syntax}
  5700. \end{figure}
  5701. \begin{figure}[tp]
  5702. \centering
  5703. \fbox{
  5704. \begin{minipage}{0.96\textwidth}
  5705. \[
  5706. \begin{array}{lcl}
  5707. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5708. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5709. \itm{op} &::= & \itm{cmp} \MID \code{read} \MID \code{+} \MID \code{-}
  5710. \MID \code{and} \MID \code{or} \MID \code{not} \\
  5711. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  5712. &\MID& \PRIM{\itm{op}}{\Exp\ldots}\\
  5713. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5714. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  5715. \end{array}
  5716. \]
  5717. \end{minipage}
  5718. }
  5719. \caption{The abstract syntax of \LangIf{}.}
  5720. \label{fig:Rif-syntax}
  5721. \end{figure}
  5722. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  5723. which inherits from the interpreter for \LangVar{}
  5724. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  5725. evaluate to the corresponding Boolean values. The conditional
  5726. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  5727. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  5728. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  5729. operations \code{not} and \code{and} behave as you might expect, but
  5730. note that the \code{and} operation is short-circuiting. That is, given
  5731. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  5732. evaluated if $e_1$ evaluates to \code{\#f}.
  5733. With the increase in the number of primitive operations, the
  5734. interpreter would become repetitive without some care. We refactor
  5735. the case for \code{Prim}, moving the code that differs with each
  5736. operation into the \code{interp-op} method shown in in
  5737. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  5738. separately because of its short-circuiting behavior.
  5739. \begin{figure}[tbp]
  5740. \begin{lstlisting}
  5741. (define interp-Rif-class
  5742. (class interp-Rvar-class
  5743. (super-new)
  5744. (define/public (interp-op op) ...)
  5745. (define/override ((interp-exp env) e)
  5746. (define recur (interp-exp env))
  5747. (match e
  5748. [(Bool b) b]
  5749. [(If cnd thn els)
  5750. (match (recur cnd)
  5751. [#t (recur thn)]
  5752. [#f (recur els)])]
  5753. [(Prim 'and (list e1 e2))
  5754. (match (recur e1)
  5755. [#t (match (recur e2) [#t #t] [#f #f])]
  5756. [#f #f])]
  5757. [(Prim op args)
  5758. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  5759. [else ((super interp-exp env) e)]))
  5760. ))
  5761. (define (interp-Rif p)
  5762. (send (new interp-Rif-class) interp-program p))
  5763. \end{lstlisting}
  5764. \caption{Interpreter for the \LangIf{} language. (See
  5765. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  5766. \label{fig:interp-Rif}
  5767. \end{figure}
  5768. \begin{figure}[tbp]
  5769. \begin{lstlisting}
  5770. (define/public (interp-op op)
  5771. (match op
  5772. ['+ fx+]
  5773. ['- fx-]
  5774. ['read read-fixnum]
  5775. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  5776. ['or (lambda (v1 v2)
  5777. (cond [(and (boolean? v1) (boolean? v2))
  5778. (or v1 v2)]))]
  5779. ['eq? (lambda (v1 v2)
  5780. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5781. (and (boolean? v1) (boolean? v2))
  5782. (and (vector? v1) (vector? v2)))
  5783. (eq? v1 v2)]))]
  5784. ['< (lambda (v1 v2)
  5785. (cond [(and (fixnum? v1) (fixnum? v2))
  5786. (< v1 v2)]))]
  5787. ['<= (lambda (v1 v2)
  5788. (cond [(and (fixnum? v1) (fixnum? v2))
  5789. (<= v1 v2)]))]
  5790. ['> (lambda (v1 v2)
  5791. (cond [(and (fixnum? v1) (fixnum? v2))
  5792. (> v1 v2)]))]
  5793. ['>= (lambda (v1 v2)
  5794. (cond [(and (fixnum? v1) (fixnum? v2))
  5795. (>= v1 v2)]))]
  5796. [else (error 'interp-op "unknown operator")]))
  5797. \end{lstlisting}
  5798. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  5799. \label{fig:interp-op-Rif}
  5800. \end{figure}
  5801. \section{Type Checking \LangIf{} Programs}
  5802. \label{sec:type-check-Rif}
  5803. \index{subject}{type checking}
  5804. \index{subject}{semantic analysis}
  5805. It is helpful to think about type checking in two complementary
  5806. ways. A type checker predicts the type of value that will be produced
  5807. by each expression in the program. For \LangIf{}, we have just two types,
  5808. \key{Integer} and \key{Boolean}. So a type checker should predict that
  5809. \begin{lstlisting}
  5810. (+ 10 (- (+ 12 20)))
  5811. \end{lstlisting}
  5812. produces an \key{Integer} while
  5813. \begin{lstlisting}
  5814. (and (not #f) #t)
  5815. \end{lstlisting}
  5816. produces a \key{Boolean}.
  5817. Another way to think about type checking is that it enforces a set of
  5818. rules about which operators can be applied to which kinds of
  5819. values. For example, our type checker for \LangIf{} signals an error
  5820. for the below expression
  5821. \begin{lstlisting}
  5822. (not (+ 10 (- (+ 12 20))))
  5823. \end{lstlisting}
  5824. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  5825. but the type checker enforces the rule that the argument of \code{not}
  5826. must be a \key{Boolean}.
  5827. We implement type checking using classes and methods because they
  5828. provide the open recursion needed to reuse code as we extend the type
  5829. checker in later chapters, analogous to the use of classes and methods
  5830. for the interpreters (Section~\ref{sec:extensible-interp}).
  5831. We separate the type checker for the \LangVar{} fragment into its own
  5832. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  5833. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  5834. from the type checker for \LangVar{}. These type checkers are in the
  5835. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  5836. support code.
  5837. %
  5838. Each type checker is a structurally recursive function over the AST.
  5839. Given an input expression \code{e}, the type checker either signals an
  5840. error or returns an expression and its type (\key{Integer} or
  5841. \key{Boolean}). It returns an expression because there are situations
  5842. in which we want to change or update the expression.
  5843. Next we discuss the \code{match} cases in \code{type-check-exp} of
  5844. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  5845. \code{Integer}. To handle variables, the type checker uses the
  5846. environment \code{env} to map variables to types. Consider the case
  5847. for \key{let}. We type check the initializing expression to obtain
  5848. its type \key{T} and then associate type \code{T} with the variable
  5849. \code{x} in the environment used to type check the body of the
  5850. \key{let}. Thus, when the type checker encounters a use of variable
  5851. \code{x}, it can find its type in the environment. Regarding
  5852. primitive operators, we recursively analyze the arguments and then
  5853. invoke \code{type-check-op} to check whether the argument types are
  5854. allowed.
  5855. Several auxiliary methods are used in the type checker. The method
  5856. \code{operator-types} defines a dictionary that maps the operator
  5857. names to their parameter and return types. The \code{type-equal?}
  5858. method determines whether two types are equal, which for now simply
  5859. dispatches to \code{equal?} (deep equality). The
  5860. \code{check-type-equal?} method triggers an error if the two types are
  5861. not equal. The \code{type-check-op} method looks up the operator in
  5862. the \code{operator-types} dictionary and then checks whether the
  5863. argument types are equal to the parameter types. The result is the
  5864. return type of the operator.
  5865. \begin{figure}[tbp]
  5866. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5867. (define type-check-Rvar-class
  5868. (class object%
  5869. (super-new)
  5870. (define/public (operator-types)
  5871. '((+ . ((Integer Integer) . Integer))
  5872. (- . ((Integer) . Integer))
  5873. (read . (() . Integer))))
  5874. (define/public (type-equal? t1 t2) (equal? t1 t2))
  5875. (define/public (check-type-equal? t1 t2 e)
  5876. (unless (type-equal? t1 t2)
  5877. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  5878. (define/public (type-check-op op arg-types e)
  5879. (match (dict-ref (operator-types) op)
  5880. [`(,param-types . ,return-type)
  5881. (for ([at arg-types] [pt param-types])
  5882. (check-type-equal? at pt e))
  5883. return-type]
  5884. [else (error 'type-check-op "unrecognized ~a" op)]))
  5885. (define/public (type-check-exp env)
  5886. (lambda (e)
  5887. (match e
  5888. [(Int n) (values (Int n) 'Integer)]
  5889. [(Var x) (values (Var x) (dict-ref env x))]
  5890. [(Let x e body)
  5891. (define-values (e^ Te) ((type-check-exp env) e))
  5892. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  5893. (values (Let x e^ b) Tb)]
  5894. [(Prim op es)
  5895. (define-values (new-es ts)
  5896. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  5897. (values (Prim op new-es) (type-check-op op ts e))]
  5898. [else (error 'type-check-exp "couldn't match" e)])))
  5899. (define/public (type-check-program e)
  5900. (match e
  5901. [(Program info body)
  5902. (define-values (body^ Tb) ((type-check-exp '()) body))
  5903. (check-type-equal? Tb 'Integer body)
  5904. (Program info body^)]
  5905. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  5906. ))
  5907. (define (type-check-Rvar p)
  5908. (send (new type-check-Rvar-class) type-check-program p))
  5909. \end{lstlisting}
  5910. \caption{Type checker for the \LangVar{} language.}
  5911. \label{fig:type-check-Rvar}
  5912. \end{figure}
  5913. \begin{figure}[tbp]
  5914. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5915. (define type-check-Rif-class
  5916. (class type-check-Rvar-class
  5917. (super-new)
  5918. (inherit check-type-equal?)
  5919. (define/override (operator-types)
  5920. (append '((- . ((Integer Integer) . Integer))
  5921. (and . ((Boolean Boolean) . Boolean))
  5922. (or . ((Boolean Boolean) . Boolean))
  5923. (< . ((Integer Integer) . Boolean))
  5924. (<= . ((Integer Integer) . Boolean))
  5925. (> . ((Integer Integer) . Boolean))
  5926. (>= . ((Integer Integer) . Boolean))
  5927. (not . ((Boolean) . Boolean))
  5928. )
  5929. (super operator-types)))
  5930. (define/override (type-check-exp env)
  5931. (lambda (e)
  5932. (match e
  5933. [(Prim 'eq? (list e1 e2))
  5934. (define-values (e1^ T1) ((type-check-exp env) e1))
  5935. (define-values (e2^ T2) ((type-check-exp env) e2))
  5936. (check-type-equal? T1 T2 e)
  5937. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  5938. [(Bool b) (values (Bool b) 'Boolean)]
  5939. [(If cnd thn els)
  5940. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  5941. (define-values (thn^ Tt) ((type-check-exp env) thn))
  5942. (define-values (els^ Te) ((type-check-exp env) els))
  5943. (check-type-equal? Tc 'Boolean e)
  5944. (check-type-equal? Tt Te e)
  5945. (values (If cnd^ thn^ els^) Te)]
  5946. [else ((super type-check-exp env) e)])))
  5947. ))
  5948. (define (type-check-Rif p)
  5949. (send (new type-check-Rif-class) type-check-program p))
  5950. \end{lstlisting}
  5951. \caption{Type checker for the \LangIf{} language.}
  5952. \label{fig:type-check-Rif}
  5953. \end{figure}
  5954. Next we discuss the type checker for \LangIf{} in
  5955. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  5956. two arguments to have the same type. The type of a Boolean constant is
  5957. \code{Boolean}. The condition of an \code{if} must be of
  5958. \code{Boolean} type and the two branches must have the same type. The
  5959. \code{operator-types} function adds dictionary entries for the other
  5960. new operators.
  5961. \begin{exercise}\normalfont
  5962. Create 10 new test programs in \LangIf{}. Half of the programs should
  5963. have a type error. For those programs, create an empty file with the
  5964. same base name but with file extension \code{.tyerr}. For example, if
  5965. the test \code{cond\_test\_14.rkt} is expected to error, then create
  5966. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  5967. \code{interp-tests} and \code{compiler-tests} that a type error is
  5968. expected. The other half of the test programs should not have type
  5969. errors.
  5970. In the \code{run-tests.rkt} script, change the second argument of
  5971. \code{interp-tests} and \code{compiler-tests} to
  5972. \code{type-check-Rif}, which causes the type checker to run prior to
  5973. the compiler passes. Temporarily change the \code{passes} to an empty
  5974. list and run the script, thereby checking that the new test programs
  5975. either type check or not as intended.
  5976. \end{exercise}
  5977. \section{The \LangCIf{} Intermediate Language}
  5978. \label{sec:Cif}
  5979. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  5980. \LangCIf{} intermediate language. (The concrete syntax is in the
  5981. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  5982. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  5983. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  5984. \key{\#f} to the \Arg{} non-terminal.
  5985. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  5986. statements to the \Tail{} non-terminal. The condition of an \code{if}
  5987. statement is a comparison operation and the branches are \code{goto}
  5988. statements, making it straightforward to compile \code{if} statements
  5989. to x86.
  5990. \begin{figure}[tp]
  5991. \fbox{
  5992. \begin{minipage}{0.96\textwidth}
  5993. \small
  5994. \[
  5995. \begin{array}{lcl}
  5996. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  5997. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  5998. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  5999. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6000. &\MID& \UNIOP{\key{'not}}{\Atm}
  6001. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6002. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6003. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6004. \MID \GOTO{\itm{label}} \\
  6005. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6006. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6007. \end{array}
  6008. \]
  6009. \end{minipage}
  6010. }
  6011. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  6012. (Figure~\ref{fig:c0-syntax}).}
  6013. \label{fig:c1-syntax}
  6014. \end{figure}
  6015. \section{The \LangXIf{} Language}
  6016. \label{sec:x86-if}
  6017. \index{subject}{x86} To implement the new logical operations, the comparison
  6018. operations, and the \key{if} expression, we need to delve further into
  6019. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6020. define the concrete and abstract syntax for the \LangXIf{} subset
  6021. of x86, which includes instructions for logical operations,
  6022. comparisons, and conditional jumps.
  6023. One challenge is that x86 does not provide an instruction that
  6024. directly implements logical negation (\code{not} in \LangIf{} and
  6025. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6026. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6027. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6028. bit of its arguments, and writes the results into its second argument.
  6029. Recall the truth table for exclusive-or:
  6030. \begin{center}
  6031. \begin{tabular}{l|cc}
  6032. & 0 & 1 \\ \hline
  6033. 0 & 0 & 1 \\
  6034. 1 & 1 & 0
  6035. \end{tabular}
  6036. \end{center}
  6037. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6038. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6039. for the bit $1$, the result is the opposite of the second bit. Thus,
  6040. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6041. the first argument:
  6042. \[
  6043. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  6044. \qquad\Rightarrow\qquad
  6045. \begin{array}{l}
  6046. \key{movq}~ \Arg\key{,} \Var\\
  6047. \key{xorq}~ \key{\$1,} \Var
  6048. \end{array}
  6049. \]
  6050. \begin{figure}[tp]
  6051. \fbox{
  6052. \begin{minipage}{0.96\textwidth}
  6053. \[
  6054. \begin{array}{lcl}
  6055. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6056. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6057. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6058. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6059. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6060. \key{subq} \; \Arg\key{,} \Arg \MID
  6061. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6062. && \gray{ \key{callq} \; \itm{label} \MID
  6063. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} } \\
  6064. && \gray{ \itm{label}\key{:}\; \Instr }
  6065. \MID \key{xorq}~\Arg\key{,}~\Arg
  6066. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6067. && \key{set}cc~\Arg
  6068. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6069. \MID \key{j}cc~\itm{label}
  6070. \\
  6071. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6072. & & \gray{ \key{main:} \; \Instr\ldots }
  6073. \end{array}
  6074. \]
  6075. \end{minipage}
  6076. }
  6077. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6078. \label{fig:x86-1-concrete}
  6079. \end{figure}
  6080. \begin{figure}[tp]
  6081. \fbox{
  6082. \begin{minipage}{0.98\textwidth}
  6083. \small
  6084. \[
  6085. \begin{array}{lcl}
  6086. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6087. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6088. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6089. \MID \BYTEREG{\itm{bytereg}} \\
  6090. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6091. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6092. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6093. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6094. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6095. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6096. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6097. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6098. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6099. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6100. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6101. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  6102. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6103. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6104. \end{array}
  6105. \]
  6106. \end{minipage}
  6107. }
  6108. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6109. \label{fig:x86-1}
  6110. \end{figure}
  6111. Next we consider the x86 instructions that are relevant for compiling
  6112. the comparison operations. The \key{cmpq} instruction compares its two
  6113. arguments to determine whether one argument is less than, equal, or
  6114. greater than the other argument. The \key{cmpq} instruction is unusual
  6115. regarding the order of its arguments and where the result is
  6116. placed. The argument order is backwards: if you want to test whether
  6117. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6118. \key{cmpq} is placed in the special EFLAGS register. This register
  6119. cannot be accessed directly but it can be queried by a number of
  6120. instructions, including the \key{set} instruction. The instruction
  6121. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6122. depending on whether the comparison comes out according to the
  6123. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6124. for less-or-equal, \key{g} for greater, \key{ge} for
  6125. greater-or-equal). The \key{set} instruction has an annoying quirk in
  6126. that its destination argument must be single byte register, such as
  6127. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6128. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6129. instruction can be used to move from a single byte register to a
  6130. normal 64-bit register. The abstract syntax for the \code{set}
  6131. instruction differs from the concrete syntax in that it separates the
  6132. instruction name from the condition code.
  6133. The x86 instruction for conditional jump is relevant to the
  6134. compilation of \key{if} expressions. The instruction
  6135. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  6136. the instruction after \itm{label} depending on whether the result in
  6137. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  6138. jump instruction falls through to the next instruction. Like the
  6139. abstract syntax for \code{set}, the abstract syntax for conditional
  6140. jump separates the instruction name from the condition code. For
  6141. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  6142. the conditional jump instruction relies on the EFLAGS register, it is
  6143. common for it to be immediately preceded by a \key{cmpq} instruction
  6144. to set the EFLAGS register.
  6145. \section{Shrink the \LangIf{} Language}
  6146. \label{sec:shrink-Rif}
  6147. % TODO: consider dropping the shrinking of there operations where
  6148. % it hurts the generated x86 code, such as >, <, -, etc.
  6149. % (suggestion from Andrew Tolmach).
  6150. The \LangIf{} language includes several operators that are easily
  6151. expressible with other operators. For example, subtraction is
  6152. expressible using addition and negation.
  6153. \[
  6154. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6155. \]
  6156. Several of the comparison operations are expressible using less-than
  6157. and logical negation.
  6158. \[
  6159. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6160. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6161. \]
  6162. The \key{let} is needed in the above translation to ensure that
  6163. expression $e_1$ is evaluated before $e_2$.
  6164. By performing these translations in the front-end of the compiler, the
  6165. later passes of the compiler do not need to deal with these operators,
  6166. making the passes shorter.
  6167. %% On the other hand, sometimes
  6168. %% these translations make it more difficult to generate the most
  6169. %% efficient code with respect to the number of instructions. However,
  6170. %% these differences typically do not affect the number of accesses to
  6171. %% memory, which is the primary factor that determines execution time on
  6172. %% modern computer architectures.
  6173. \begin{exercise}\normalfont
  6174. Implement the pass \code{shrink} to remove subtraction, \key{and},
  6175. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  6176. translating them to other constructs in \LangIf{}.
  6177. %
  6178. Create six test programs that involve these operators.
  6179. %
  6180. In the \code{run-tests.rkt} script, add the following entry for
  6181. \code{shrink} to the list of passes (it should be the only pass at
  6182. this point).
  6183. \begin{lstlisting}
  6184. (list "shrink" shrink interp-Rif type-check-Rif)
  6185. \end{lstlisting}
  6186. This instructs \code{interp-tests} to run the intepreter
  6187. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  6188. output of \code{shrink}.
  6189. %
  6190. Run the script to test your compiler on all the test programs.
  6191. \end{exercise}
  6192. \section{Uniquify Variables}
  6193. \label{sec:uniquify-Rif}
  6194. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6195. \code{if} expressions.
  6196. \begin{exercise}\normalfont
  6197. Update the \code{uniquify-exp} for \LangIf{} and add the following
  6198. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6199. \begin{lstlisting}
  6200. (list "uniquify" uniquify interp-Rif type-check-Rif)
  6201. \end{lstlisting}
  6202. Run the script to test your compiler.
  6203. \end{exercise}
  6204. \section{Remove Complex Operands}
  6205. \label{sec:remove-complex-opera-Rif}
  6206. The output language for this pass is \LangIfANF{}
  6207. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  6208. \LangIf{}. The \code{Bool} form is an atomic expressions but
  6209. \code{If} is not. All three sub-expressions of an \code{If} are
  6210. allowed to be complex expressions but the operands of \code{not} and
  6211. the comparisons must be atoms.
  6212. Add cases for \code{Bool} and \code{If} to the \code{rco\_exp} and
  6213. \code{rco\_atom} functions according to whether the output needs to be
  6214. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  6215. Regarding \code{If}, it is particularly important to \textbf{not}
  6216. replace its condition with a temporary variable because that would
  6217. interfere with the generation of high-quality output in the
  6218. \code{explicate-control} pass.
  6219. \begin{figure}[tp]
  6220. \centering
  6221. \fbox{
  6222. \begin{minipage}{0.96\textwidth}
  6223. \[
  6224. \begin{array}{rcl}
  6225. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6226. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6227. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6228. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6229. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6230. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6231. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  6232. \end{array}
  6233. \]
  6234. \end{minipage}
  6235. }
  6236. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  6237. \label{fig:Rif-anf-syntax}
  6238. \end{figure}
  6239. \begin{exercise}\normalfont
  6240. %
  6241. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  6242. and \code{rco\_exp} functions in \code{compiler.rkt}.
  6243. %
  6244. Create three new \LangInt{} programs that exercise the interesting
  6245. code in this pass.
  6246. %
  6247. In the \code{run-tests.rkt} script, add the following entry to the
  6248. list of \code{passes} and then run the script to test your compiler.
  6249. \begin{lstlisting}
  6250. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  6251. \end{lstlisting}
  6252. \end{exercise}
  6253. \section{Explicate Control}
  6254. \label{sec:explicate-control-Rif}
  6255. Recall that the purpose of \code{explicate-control} is to make the
  6256. order of evaluation explicit in the syntax of the program. With the
  6257. addition of \key{if} this get more interesting.
  6258. As a motivating example, consider the following program that has an
  6259. \key{if} expression nested in the predicate of another \key{if}.
  6260. % cond_test_41.rkt, if_lt_eq.py
  6261. \begin{center}
  6262. \begin{minipage}{0.96\textwidth}
  6263. \begin{lstlisting}
  6264. (let ([x (read)])
  6265. (let ([y (read)])
  6266. (if (if (< x 1) (eq? x 0) (eq? x 2))
  6267. (+ y 2)
  6268. (+ y 10))))
  6269. \end{lstlisting}
  6270. \end{minipage}
  6271. \end{center}
  6272. %
  6273. The naive way to compile \key{if} and the comparison would be to
  6274. handle each of them in isolation, regardless of their context. Each
  6275. comparison would be translated into a \key{cmpq} instruction followed
  6276. by a couple instructions to move the result from the EFLAGS register
  6277. into a general purpose register or stack location. Each \key{if} would
  6278. be translated into a \key{cmpq} instruction followed by a conditional
  6279. jump. The generated code for the inner \key{if} in the above example
  6280. would be as follows.
  6281. \begin{center}
  6282. \begin{minipage}{0.96\textwidth}
  6283. \begin{lstlisting}
  6284. ...
  6285. cmpq $1, x ;; (< x 1)
  6286. setl %al
  6287. movzbq %al, tmp
  6288. cmpq $1, tmp ;; (if ...)
  6289. je then_branch_1
  6290. jmp else_branch_1
  6291. ...
  6292. \end{lstlisting}
  6293. \end{minipage}
  6294. \end{center}
  6295. However, if we take context into account we can do better and reduce
  6296. the use of \key{cmpq} instructions for accessing the EFLAG register.
  6297. Our goal will be compile \key{if} expressions so that the relevant
  6298. comparison instruction appears directly before the conditional jump.
  6299. For example, we want to generate the following code for the inner
  6300. \code{if}.
  6301. \begin{center}
  6302. \begin{minipage}{0.96\textwidth}
  6303. \begin{lstlisting}
  6304. ...
  6305. cmpq $1, x
  6306. je then_branch_1
  6307. jmp else_branch_1
  6308. ...
  6309. \end{lstlisting}
  6310. \end{minipage}
  6311. \end{center}
  6312. One way to achieve this is to reorganize the code at the level of
  6313. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  6314. the following code.
  6315. \begin{center}
  6316. \begin{minipage}{0.96\textwidth}
  6317. \begin{lstlisting}
  6318. (let ([x (read)])
  6319. (let ([y (read)])
  6320. (if (< x 1)
  6321. (if (eq? x 0)
  6322. (+ y 2)
  6323. (+ y 10))
  6324. (if (eq? x 2)
  6325. (+ y 2)
  6326. (+ y 10)))))
  6327. \end{lstlisting}
  6328. \end{minipage}
  6329. \end{center}
  6330. Unfortunately, this approach duplicates the two branches from the
  6331. outer \code{if} and a compiler must never duplicate code!
  6332. We need a way to perform the above transformation but without
  6333. duplicating code. That is, we need a way for different parts of a
  6334. program to refer to the same piece of code. At the level of x86
  6335. assembly this is straightforward because we can label the code for
  6336. each branch and insert jumps in all the places that need to execute
  6337. the branch. In our intermediate language, we need to move away from
  6338. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  6339. particular, we use a standard program representation called a
  6340. \emph{control flow graph} (CFG), due to Frances Elizabeth
  6341. \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex is a
  6342. labeled sequence of code, called a \emph{basic block}, and each edge
  6343. represents a jump to another block. The \key{CProgram} construct of
  6344. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  6345. as an alist mapping labels to basic blocks. Each basic block is
  6346. represented by the $\Tail$ non-terminal.
  6347. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  6348. \code{remove-complex-opera*} pass and then the
  6349. \code{explicate-control} pass on the example program. We walk through
  6350. the output program and then discuss the algorithm.
  6351. %
  6352. Following the order of evaluation in the output of
  6353. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  6354. and then the comparison \lstinline{(< x 1)} in the predicate of the
  6355. inner \key{if}. In the output of \code{explicate-control}, in the
  6356. block labeled \code{start}, is two assignment statements followed by a
  6357. \code{if} statement that branches to \code{block40} or
  6358. \code{block41}. The blocks associated with those labels contain the
  6359. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  6360. respectively. In particular, we start \code{block40} with the
  6361. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  6362. \code{block39}, the two branches of the outer \key{if}, i.e.,
  6363. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  6364. \code{block41} is similar.
  6365. \begin{figure}[tbp]
  6366. \begin{tabular}{lll}
  6367. \begin{minipage}{0.4\textwidth}
  6368. % cond_test_41.rkt
  6369. \begin{lstlisting}
  6370. (let ([x (read)])
  6371. (let ([y (read)])
  6372. (if (if (< x 1)
  6373. (eq? x 0)
  6374. (eq? x 2))
  6375. (+ y 2)
  6376. (+ y 10))))
  6377. \end{lstlisting}
  6378. \hspace{40pt}$\Downarrow$
  6379. \begin{lstlisting}
  6380. (let ([x (read)])
  6381. (let ([y (read)])
  6382. (if (if (< x 1)
  6383. (eq? x 0)
  6384. (eq? x 2))
  6385. (+ y 2)
  6386. (+ y 10))))
  6387. \end{lstlisting}
  6388. \end{minipage}
  6389. &
  6390. $\Rightarrow$
  6391. &
  6392. \begin{minipage}{0.55\textwidth}
  6393. \begin{lstlisting}
  6394. start:
  6395. x = (read);
  6396. y = (read);
  6397. if (< x 1) goto block40;
  6398. else goto block41;
  6399. block40:
  6400. if (eq? x 0) goto block38;
  6401. else goto block39;
  6402. block41:
  6403. if (eq? x 2) goto block38;
  6404. else goto block39;
  6405. block38:
  6406. return (+ y 2);
  6407. block39:
  6408. return (+ y 10);
  6409. \end{lstlisting}
  6410. \end{minipage}
  6411. \end{tabular}
  6412. \caption{Translation from \LangIf{} to \LangCIf{}
  6413. via the \code{explicate-control}.}
  6414. \label{fig:explicate-control-s1-38}
  6415. \end{figure}
  6416. %% The nice thing about the output of \code{explicate-control} is that
  6417. %% there are no unnecessary comparisons and every comparison is part of a
  6418. %% conditional jump.
  6419. %% The down-side of this output is that it includes
  6420. %% trivial blocks, such as the blocks labeled \code{block92} through
  6421. %% \code{block95}, that only jump to another block. We discuss a solution
  6422. %% to this problem in Section~\ref{sec:opt-jumps}.
  6423. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  6424. \code{explicate-control} for \LangVar{} using two mutually recursive
  6425. functions, \code{explicate-tail} and \code{explicate-assign}. The
  6426. former function translates expressions in tail position whereas the
  6427. later function translates expressions on the right-hand-side of a
  6428. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  6429. have a new kind of position to deal with: the predicate position of
  6430. the \key{if}. We need another function, \code{explicate-pred}, that
  6431. takes an \LangIf{} expression and two blocks for the then-branch and
  6432. else-branch. The output of \code{explicate-pred} is a block.
  6433. %
  6434. In the following paragraphs we discuss specific cases in the
  6435. \code{explicate-pred} function as well as additions to the
  6436. \code{explicate-tail} and \code{explicate-assign} functions.
  6437. \begin{figure}[tbp]
  6438. \begin{lstlisting}
  6439. (define (explicate-pred cnd thn els)
  6440. (match cnd
  6441. [(Var x) ___]
  6442. [(Let x rhs body) ___]
  6443. [(Prim 'not (list e)) ___]
  6444. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  6445. (IfStmt (Prim op arg*) (force (block->goto thn))
  6446. (force (block->goto els)))]
  6447. [(Bool b) (if b thn els)]
  6448. [(If cnd^ thn^ els^) ___]
  6449. [else (error "explicate-pred unhandled case" cnd)]))
  6450. \end{lstlisting}
  6451. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  6452. \label{fig:explicate-pred}
  6453. \end{figure}
  6454. The skeleton for the \code{explicate-pred} function is given in
  6455. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  6456. that can have type \code{Boolean}. We detail a few cases here and
  6457. leave the rest for the reader. The input to this function is an
  6458. expression and two blocks, \code{thn} and \code{els}, for the two
  6459. branches of the enclosing \key{if}.
  6460. %
  6461. Consider the case for Boolean constants in
  6462. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  6463. evaluation\index{subject}{partial evaluation} and output either the \code{thn}
  6464. or \code{els} branch depending on whether the constant is true or
  6465. false. This case demonstrates that we sometimes discard the \code{thn}
  6466. or \code{els} blocks that are input to \code{explicate-pred}.
  6467. The case for \key{if} in \code{explicate-pred} is particularly
  6468. illuminating because it deals with the challenges we discussed above
  6469. regarding nested \key{if} expressions
  6470. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  6471. \lstinline{els^} branches of the \key{if} inherit their context from
  6472. the current one, that is, predicate context. So you should recursively
  6473. apply \code{explicate-pred} to the \lstinline{thn^} and
  6474. \lstinline{els^} branches. For both of those recursive calls, pass
  6475. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  6476. and \code{els} may get used twice, once inside each recursive call. As
  6477. discussed above, to avoid duplicating code, we need to add them to the
  6478. control-flow graph so that we can instead refer to them by name and
  6479. execute them with a \key{goto}. However, as we saw in the cases above
  6480. for Boolean constants, the blocks \code{thn} and \code{els} may not
  6481. get used at all and we don't want to prematurely add them to the
  6482. control-flow graph if they end up being discarded.
  6483. The solution to this conundrum is to use \emph{lazy
  6484. evaluation}\index{subject}{lazy evaluation}\citep{Friedman:1976aa} to delay
  6485. adding the blocks to the control-flow graph until the points where we
  6486. know they will be used. Racket provides support for lazy evaluation
  6487. with the
  6488. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  6489. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  6490. \index{subject}{delay} creates a \emph{promise}\index{subject}{promise} in which the
  6491. evaluation of the expressions is postponed. When \key{(force}
  6492. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the first
  6493. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  6494. $e_n$ is cached in the promise and returned. If \code{force} is
  6495. applied again to the same promise, then the cached result is returned.
  6496. If \code{force} is applied to an argument that is not a promise,
  6497. \code{force} simply returns the argument.
  6498. We use lazy evaluation for the input and output blocks of the
  6499. functions \code{explicate-pred} and \code{explicate-assign} and for
  6500. the output block of \code{explicate-tail}. So instead of taking and
  6501. returning blocks, they take and return promises. Furthermore, when we
  6502. come to a situation in which we a block might be used more than once,
  6503. as in the case for \code{if} in \code{explicate-pred}, we transform
  6504. the promise into a new promise that will add the block to the
  6505. control-flow graph and return a \code{goto}. The following auxiliary
  6506. function named \code{block->goto} accomplishes this task. It begins
  6507. with \code{delay} to create a promise. When forced, this promise will
  6508. force the original promise. If that returns a \code{goto} (because the
  6509. block was already added to the control-flow graph), then we return the
  6510. \code{goto}. Otherwise we add the block to the control-flow graph with
  6511. another auxiliary function named \code{add-node}. That function
  6512. returns the label for the new block, which we use to create a
  6513. \code{goto}.
  6514. \begin{lstlisting}
  6515. (define (block->goto block)
  6516. (delay
  6517. (define b (force block))
  6518. (match b
  6519. [(Goto label) (Goto label)]
  6520. [else (Goto (add-node b))])))
  6521. \end{lstlisting}
  6522. Returning to the discussion of \code{explicate-pred}
  6523. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  6524. operators. This is one of the base cases of the recursive function so
  6525. we translate the comparison to an \code{if} statement. We apply
  6526. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  6527. that will add then to the control-flow graph, which we can immediately
  6528. \code{force} to obtain the two goto's that form the branches of the
  6529. \code{if} statement.
  6530. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  6531. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  6532. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  6533. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  6534. %% results from the two recursive calls. We complete the case for
  6535. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  6536. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  6537. %% the result $B_5$.
  6538. %% \[
  6539. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  6540. %% \quad\Rightarrow\quad
  6541. %% B_5
  6542. %% \]
  6543. The \code{explicate-tail} and \code{explicate-assign} functions need
  6544. additional cases for Boolean constants and \key{if}.
  6545. %
  6546. In the cases for \code{if}, the two branches inherit the current
  6547. context, so in \code{explicate-tail} they are in tail position and in
  6548. \code{explicate-assign} they are in assignment position. The
  6549. \code{cont} parameter of \code{explicate-assign} is used in both
  6550. recursive calls, so make sure to use \code{block->goto} on it.
  6551. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  6552. %% inherit the current context, so they are in tail position. Thus, the
  6553. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  6554. %% \code{explicate-tail}.
  6555. %% %
  6556. %% We need to pass $B_0$ as the accumulator argument for both of these
  6557. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  6558. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  6559. %% to the control-flow graph and obtain a promised goto $G_0$.
  6560. %% %
  6561. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  6562. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  6563. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  6564. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  6565. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  6566. %% \[
  6567. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  6568. %% \]
  6569. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  6570. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  6571. %% should not be confused with the labels for the blocks that appear in
  6572. %% the generated code. We initially construct unlabeled blocks; we only
  6573. %% attach labels to blocks when we add them to the control-flow graph, as
  6574. %% we see in the next case.
  6575. %% Next consider the case for \key{if} in the \code{explicate-assign}
  6576. %% function. The context of the \key{if} is an assignment to some
  6577. %% variable $x$ and then the control continues to some promised block
  6578. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  6579. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  6580. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  6581. %% branches of the \key{if} inherit the current context, so they are in
  6582. %% assignment positions. Let $B_2$ be the result of applying
  6583. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  6584. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  6585. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  6586. %% the result of applying \code{explicate-pred} to the predicate
  6587. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  6588. %% translates to the promise $B_4$.
  6589. %% \[
  6590. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  6591. %% \]
  6592. %% This completes the description of \code{explicate-control} for \LangIf{}.
  6593. The way in which the \code{shrink} pass transforms logical operations
  6594. such as \code{and} and \code{or} can impact the quality of code
  6595. generated by \code{explicate-control}. For example, consider the
  6596. following program.
  6597. % cond_test_21.rkt, and_eq_input.py
  6598. \begin{lstlisting}
  6599. (if (and (eq? (read) 0) (eq? (read) 1))
  6600. 0
  6601. 42)
  6602. \end{lstlisting}
  6603. The \code{and} operation should transform into something that the
  6604. \code{explicate-pred} function can still analyze and descend through to
  6605. reach the underlying \code{eq?} conditions. Ideally, your
  6606. \code{explicate-control} pass should generate code similar to the
  6607. following for the above program.
  6608. \begin{center}
  6609. \begin{lstlisting}
  6610. start:
  6611. tmp1 = (read);
  6612. if (eq? tmp1 0) goto block40;
  6613. else goto block39;
  6614. block40:
  6615. tmp2 = (read);
  6616. if (eq? tmp2 1) goto block38;
  6617. else goto block39;
  6618. block38:
  6619. return 0;
  6620. block39:
  6621. return 42;
  6622. \end{lstlisting}
  6623. \end{center}
  6624. \begin{exercise}\normalfont
  6625. Implement the pass \code{explicate-control} by adding the cases for
  6626. Boolean constants and \key{if} to the \code{explicate-tail} and
  6627. \code{explicate-assign}. Implement the auxiliary function
  6628. \code{explicate-pred} for predicate contexts.
  6629. %
  6630. Create test cases that exercise all of the new cases in the code for
  6631. this pass.
  6632. %
  6633. Add the following entry to the list of \code{passes} in
  6634. \code{run-tests.rkt} and then run this script to test your compiler.
  6635. \begin{lstlisting}
  6636. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  6637. \end{lstlisting}
  6638. \end{exercise}
  6639. \section{Select Instructions}
  6640. \label{sec:select-Rif}
  6641. \index{subject}{instruction selection}
  6642. The \code{select-instructions} pass translate \LangCIf{} to
  6643. \LangXIfVar{}. Recall that we implement this pass using three
  6644. auxiliary functions, one for each of the non-terminals $\Atm$,
  6645. $\Stmt$, and $\Tail$.
  6646. For $\Atm$, we have new cases for the Booleans. We take the usual
  6647. approach of encoding them as integers, with true as 1 and false as 0.
  6648. \[
  6649. \key{\#t} \Rightarrow \key{1}
  6650. \qquad
  6651. \key{\#f} \Rightarrow \key{0}
  6652. \]
  6653. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  6654. be implemented in terms of \code{xorq} as we discussed at the
  6655. beginning of this section. Given an assignment
  6656. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  6657. if the left-hand side $\itm{var}$ is
  6658. the same as $\Atm$, then just the \code{xorq} suffices.
  6659. \[
  6660. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  6661. \quad\Rightarrow\quad
  6662. \key{xorq}~\key{\$}1\key{,}~\Var
  6663. \]
  6664. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  6665. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  6666. x86. Then we have
  6667. \[
  6668. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  6669. \quad\Rightarrow\quad
  6670. \begin{array}{l}
  6671. \key{movq}~\Arg\key{,}~\Var\\
  6672. \key{xorq}~\key{\$}1\key{,}~\Var
  6673. \end{array}
  6674. \]
  6675. Next consider the cases for \code{eq?} and less-than comparison.
  6676. Translating these operations to x86 is slightly involved due to the
  6677. unusual nature of the \key{cmpq} instruction discussed above. We
  6678. recommend translating an assignment from \code{eq?} into the following
  6679. sequence of three instructions. \\
  6680. \begin{tabular}{lll}
  6681. \begin{minipage}{0.4\textwidth}
  6682. \begin{lstlisting}
  6683. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  6684. \end{lstlisting}
  6685. \end{minipage}
  6686. &
  6687. $\Rightarrow$
  6688. &
  6689. \begin{minipage}{0.4\textwidth}
  6690. \begin{lstlisting}
  6691. cmpq |$\Arg_2$|, |$\Arg_1$|
  6692. sete %al
  6693. movzbq %al, |$\Var$|
  6694. \end{lstlisting}
  6695. \end{minipage}
  6696. \end{tabular} \\
  6697. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  6698. and \key{if} statements. Both are straightforward to translate to
  6699. x86. A \key{goto} becomes a jump instruction.
  6700. \[
  6701. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  6702. \]
  6703. An \key{if} statement becomes a compare instruction followed by a
  6704. conditional jump (for the ``then'' branch) and the fall-through is to
  6705. a regular jump (for the ``else'' branch).\\
  6706. \begin{tabular}{lll}
  6707. \begin{minipage}{0.4\textwidth}
  6708. \begin{lstlisting}
  6709. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  6710. else goto |$\ell_2$|;
  6711. \end{lstlisting}
  6712. \end{minipage}
  6713. &
  6714. $\Rightarrow$
  6715. &
  6716. \begin{minipage}{0.4\textwidth}
  6717. \begin{lstlisting}
  6718. cmpq |$\Arg_2$|, |$\Arg_1$|
  6719. je |$\ell_1$|
  6720. jmp |$\ell_2$|
  6721. \end{lstlisting}
  6722. \end{minipage}
  6723. \end{tabular} \\
  6724. \begin{exercise}\normalfont
  6725. Expand your \code{select-instructions} pass to handle the new features
  6726. of the \LangIf{} language.
  6727. %
  6728. Add the following entry to the list of \code{passes} in
  6729. \code{run-tests.rkt}
  6730. \begin{lstlisting}
  6731. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  6732. \end{lstlisting}
  6733. %
  6734. Run the script to test your compiler on all the test programs.
  6735. \end{exercise}
  6736. \section{Register Allocation}
  6737. \label{sec:register-allocation-Rif}
  6738. \index{subject}{register allocation}
  6739. The changes required for \LangIf{} affect liveness analysis, building the
  6740. interference graph, and assigning homes, but the graph coloring
  6741. algorithm itself does not change.
  6742. \subsection{Liveness Analysis}
  6743. \label{sec:liveness-analysis-Rif}
  6744. \index{subject}{liveness analysis}
  6745. Recall that for \LangVar{} we implemented liveness analysis for a single
  6746. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  6747. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  6748. produces many basic blocks arranged in a control-flow graph. We
  6749. recommend that you create a new auxiliary function named
  6750. \code{uncover-live-CFG} that applies liveness analysis to a
  6751. control-flow graph.
  6752. The first question we is: what order should we process the basic
  6753. blocks in the control-flow graph? Recall that to perform liveness
  6754. analysis on a basic block we need to know its live-after set. If a
  6755. basic block has no successors (i.e. no out-edges in the control flow
  6756. graph), then it has an empty live-after set and we can immediately
  6757. apply liveness analysis to it. If a basic block has some successors,
  6758. then we need to complete liveness analysis on those blocks first. In
  6759. graph theory, a sequence of nodes is in \emph{topological
  6760. order}\index{subject}{topological order} if each vertex comes before its
  6761. successors. We need the opposite, so we can transpose the graph
  6762. before computing a topological order.
  6763. %
  6764. Use the \code{tsort} and \code{transpose} functions of the Racket
  6765. \code{graph} package to accomplish this.
  6766. %
  6767. As an aside, a topological ordering is only guaranteed to exist if the
  6768. graph does not contain any cycles. That is indeed the case for the
  6769. control-flow graphs that we generate from \LangIf{} programs.
  6770. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  6771. learn how to handle cycles in the control-flow graph.
  6772. You'll need to construct a directed graph to represent the
  6773. control-flow graph. Do not use the \code{directed-graph} of the
  6774. \code{graph} package because that only allows at most one edge between
  6775. each pair of vertices, but a control-flow graph may have multiple
  6776. edges between a pair of vertices. The \code{multigraph.rkt} file in
  6777. the support code implements a graph representation that allows
  6778. multiple edges between a pair of vertices.
  6779. The next question is how to analyze jump instructions. Recall that in
  6780. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  6781. \code{label->live} that maps each label to the set of live locations
  6782. at the beginning of its block. We use \code{label->live} to determine
  6783. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  6784. that we have many basic blocks, \code{label->live} needs to be updated
  6785. as we process the blocks. In particular, after performing liveness
  6786. analysis on a block, we take the live-before set of its first
  6787. instruction and associate that with the block's label in the
  6788. \code{label->live}.
  6789. In \LangXIfVar{} we also have the conditional jump
  6790. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  6791. this instruction is particularly interesting because during
  6792. compilation we do not know which way a conditional jump will go. So
  6793. we do not know whether to use the live-before set for the following
  6794. instruction or the live-before set for the $\itm{label}$. However,
  6795. there is no harm to the correctness of the compiler if we classify
  6796. more locations as live than the ones that are truly live during a
  6797. particular execution of the instruction. Thus, we can take the union
  6798. of the live-before sets from the following instruction and from the
  6799. mapping for $\itm{label}$ in \code{label->live}.
  6800. The auxiliary functions for computing the variables in an
  6801. instruction's argument and for computing the variables read-from ($R$)
  6802. or written-to ($W$) by an instruction need to be updated to handle the
  6803. new kinds of arguments and instructions in \LangXIfVar{}.
  6804. \begin{exercise}\normalfont
  6805. Update the \code{uncover\_live} \racket{pass}\python{function} and implement the
  6806. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  6807. to the control-flow graph. Add the following entry to the list of
  6808. \code{passes} in the \code{run-tests.rkt} script.
  6809. \begin{lstlisting}
  6810. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  6811. \end{lstlisting}
  6812. \end{exercise}
  6813. \subsection{Build the Interference Graph}
  6814. \label{sec:build-interference-Rif}
  6815. Many of the new instructions in \LangXIfVar{} can be handled in the
  6816. same way as the instructions in \LangXVar{}. Thus, if your code was
  6817. already quite general, it will not need to be changed to handle the
  6818. new instructions. If you code is not general enough, we recommend that
  6819. you change your code to be more general. For example, you can factor
  6820. out the computing of the the read and write sets for each kind of
  6821. instruction into two auxiliary functions.
  6822. Note that the \key{movzbq} instruction requires some special care,
  6823. similar to the \key{movq} instruction. See rule number 1 in
  6824. Section~\ref{sec:build-interference}.
  6825. \begin{exercise}\normalfont
  6826. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  6827. following entries to the list of \code{passes} in the
  6828. \code{run-tests.rkt} script.
  6829. \begin{lstlisting}
  6830. (list "build-interference" build-interference interp-pseudo-x86-1)
  6831. (list "allocate-registers" allocate-registers interp-x86-1)
  6832. \end{lstlisting}
  6833. Run the script to test your compiler on all the \LangIf{} test
  6834. programs.
  6835. \end{exercise}
  6836. \section{Patch Instructions}
  6837. The second argument of the \key{cmpq} instruction must not be an
  6838. immediate value (such as an integer). So if you are comparing two
  6839. immediates, we recommend inserting a \key{movq} instruction to put the
  6840. second argument in \key{rax}. Also, recall that instructions may have
  6841. at most one memory reference.
  6842. %
  6843. The second argument of the \key{movzbq} must be a register.
  6844. %
  6845. There are no special restrictions on the jump instructions.
  6846. \begin{exercise}\normalfont
  6847. %
  6848. Update \code{patch-instructions} pass for \LangXIfVar{}.
  6849. %
  6850. Add the following entry to the list of \code{passes} in
  6851. \code{run-tests.rkt} and then run this script to test your compiler.
  6852. \begin{lstlisting}
  6853. (list "patch-instructions" patch-instructions interp-x86-1)
  6854. \end{lstlisting}
  6855. \end{exercise}
  6856. \begin{figure}[tbp]
  6857. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6858. \node (Rif) at (0,2) {\large \LangIf{}};
  6859. \node (Rif-2) at (3,2) {\large \LangIf{}};
  6860. \node (Rif-3) at (6,2) {\large \LangIf{}};
  6861. \node (Rif-4) at (9,2) {\large \LangIf{}};
  6862. \node (Rif-5) at (12,2) {\large \LangIf{}};
  6863. \node (C1-1) at (3,0) {\large \LangCIf{}};
  6864. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  6865. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  6866. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  6867. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  6868. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  6869. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  6870. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  6871. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  6872. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  6873. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  6874. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  6875. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  6876. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6877. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6878. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6879. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6880. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  6881. \end{tikzpicture}
  6882. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  6883. \label{fig:Rif-passes}
  6884. \end{figure}
  6885. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  6886. compilation of \LangIf{}.
  6887. \section{An Example Translation}
  6888. Figure~\ref{fig:if-example-x86} shows a simple example program in
  6889. \LangIf{} translated to x86, showing the results of
  6890. \code{explicate-control}, \code{select-instructions}, and the final
  6891. x86 assembly code.
  6892. \begin{figure}[tbp]
  6893. \begin{tabular}{lll}
  6894. \begin{minipage}{0.4\textwidth}
  6895. % cond_test_20.rkt, eq_input.py
  6896. \begin{lstlisting}
  6897. (if (eq? (read) 1) 42 0)
  6898. \end{lstlisting}
  6899. $\Downarrow$
  6900. \begin{lstlisting}
  6901. start:
  6902. tmp7951 = (read);
  6903. if (eq? tmp7951 1)
  6904. goto block7952;
  6905. else
  6906. goto block7953;
  6907. block7952:
  6908. return 42;
  6909. block7953:
  6910. return 0;
  6911. \end{lstlisting}
  6912. $\Downarrow$
  6913. \begin{lstlisting}
  6914. start:
  6915. callq read_int
  6916. movq %rax, tmp7951
  6917. cmpq $1, tmp7951
  6918. je block7952
  6919. jmp block7953
  6920. block7953:
  6921. movq $0, %rax
  6922. jmp conclusion
  6923. block7952:
  6924. movq $42, %rax
  6925. jmp conclusion
  6926. \end{lstlisting}
  6927. \end{minipage}
  6928. &
  6929. $\Rightarrow\qquad$
  6930. \begin{minipage}{0.4\textwidth}
  6931. \begin{lstlisting}
  6932. start:
  6933. callq read_int
  6934. movq %rax, %rcx
  6935. cmpq $1, %rcx
  6936. je block7952
  6937. jmp block7953
  6938. block7953:
  6939. movq $0, %rax
  6940. jmp conclusion
  6941. block7952:
  6942. movq $42, %rax
  6943. jmp conclusion
  6944. .globl main
  6945. main:
  6946. pushq %rbp
  6947. movq %rsp, %rbp
  6948. pushq %r13
  6949. pushq %r12
  6950. pushq %rbx
  6951. pushq %r14
  6952. subq $0, %rsp
  6953. jmp start
  6954. conclusion:
  6955. addq $0, %rsp
  6956. popq %r14
  6957. popq %rbx
  6958. popq %r12
  6959. popq %r13
  6960. popq %rbp
  6961. retq
  6962. \end{lstlisting}
  6963. \end{minipage}
  6964. \end{tabular}
  6965. \caption{Example compilation of an \key{if} expression to x86.}
  6966. \label{fig:if-example-x86}
  6967. \end{figure}
  6968. \section{Challenge: Remove Jumps}
  6969. \label{sec:opt-jumps}
  6970. %% Recall that in the example output of \code{explicate-control} in
  6971. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  6972. %% \code{block60} are trivial blocks, they do nothing but jump to another
  6973. %% block. The first goal of this challenge assignment is to remove those
  6974. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  6975. %% \code{explicate-control} on the left and shows the result of bypassing
  6976. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  6977. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  6978. %% \code{block55}. The optimized code on the right of
  6979. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  6980. %% \code{then} branch jumping directly to \code{block55}. The story is
  6981. %% similar for the \code{else} branch, as well as for the two branches in
  6982. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  6983. %% have been optimized in this way, there are no longer any jumps to
  6984. %% blocks \code{block57} through \code{block60}, so they can be removed.
  6985. %% \begin{figure}[tbp]
  6986. %% \begin{tabular}{lll}
  6987. %% \begin{minipage}{0.4\textwidth}
  6988. %% \begin{lstlisting}
  6989. %% block62:
  6990. %% tmp54 = (read);
  6991. %% if (eq? tmp54 2) then
  6992. %% goto block59;
  6993. %% else
  6994. %% goto block60;
  6995. %% block61:
  6996. %% tmp53 = (read);
  6997. %% if (eq? tmp53 0) then
  6998. %% goto block57;
  6999. %% else
  7000. %% goto block58;
  7001. %% block60:
  7002. %% goto block56;
  7003. %% block59:
  7004. %% goto block55;
  7005. %% block58:
  7006. %% goto block56;
  7007. %% block57:
  7008. %% goto block55;
  7009. %% block56:
  7010. %% return (+ 700 77);
  7011. %% block55:
  7012. %% return (+ 10 32);
  7013. %% start:
  7014. %% tmp52 = (read);
  7015. %% if (eq? tmp52 1) then
  7016. %% goto block61;
  7017. %% else
  7018. %% goto block62;
  7019. %% \end{lstlisting}
  7020. %% \end{minipage}
  7021. %% &
  7022. %% $\Rightarrow$
  7023. %% &
  7024. %% \begin{minipage}{0.55\textwidth}
  7025. %% \begin{lstlisting}
  7026. %% block62:
  7027. %% tmp54 = (read);
  7028. %% if (eq? tmp54 2) then
  7029. %% goto block55;
  7030. %% else
  7031. %% goto block56;
  7032. %% block61:
  7033. %% tmp53 = (read);
  7034. %% if (eq? tmp53 0) then
  7035. %% goto block55;
  7036. %% else
  7037. %% goto block56;
  7038. %% block56:
  7039. %% return (+ 700 77);
  7040. %% block55:
  7041. %% return (+ 10 32);
  7042. %% start:
  7043. %% tmp52 = (read);
  7044. %% if (eq? tmp52 1) then
  7045. %% goto block61;
  7046. %% else
  7047. %% goto block62;
  7048. %% \end{lstlisting}
  7049. %% \end{minipage}
  7050. %% \end{tabular}
  7051. %% \caption{Optimize jumps by removing trivial blocks.}
  7052. %% \label{fig:optimize-jumps}
  7053. %% \end{figure}
  7054. %% The name of this pass is \code{optimize-jumps}. We recommend
  7055. %% implementing this pass in two phases. The first phrase builds a hash
  7056. %% table that maps labels to possibly improved labels. The second phase
  7057. %% changes the target of each \code{goto} to use the improved label. If
  7058. %% the label is for a trivial block, then the hash table should map the
  7059. %% label to the first non-trivial block that can be reached from this
  7060. %% label by jumping through trivial blocks. If the label is for a
  7061. %% non-trivial block, then the hash table should map the label to itself;
  7062. %% we do not want to change jumps to non-trivial blocks.
  7063. %% The first phase can be accomplished by constructing an empty hash
  7064. %% table, call it \code{short-cut}, and then iterating over the control
  7065. %% flow graph. Each time you encouter a block that is just a \code{goto},
  7066. %% then update the hash table, mapping the block's source to the target
  7067. %% of the \code{goto}. Also, the hash table may already have mapped some
  7068. %% labels to the block's source, to you must iterate through the hash
  7069. %% table and update all of those so that they instead map to the target
  7070. %% of the \code{goto}.
  7071. %% For the second phase, we recommend iterating through the $\Tail$ of
  7072. %% each block in the program, updating the target of every \code{goto}
  7073. %% according to the mapping in \code{short-cut}.
  7074. %% \begin{exercise}\normalfont
  7075. %% Implement the \code{optimize-jumps} pass as a transformation from
  7076. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  7077. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  7078. %% example programs. Then check that your compiler still passes all of
  7079. %% your tests.
  7080. %% \end{exercise}
  7081. There is an opportunity for optimizing jumps that is apparent in the
  7082. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  7083. ends with a jump to \code{block7953} and there are no other jumps to
  7084. \code{block7953} in the rest of the program. In this situation we can
  7085. avoid the runtime overhead of this jump by merging \code{block7953}
  7086. into the preceding block, in this case the \code{start} block.
  7087. Figure~\ref{fig:remove-jumps} shows the output of
  7088. \code{select-instructions} on the left and the result of this
  7089. optimization on the right.
  7090. \begin{figure}[tbp]
  7091. \begin{tabular}{lll}
  7092. \begin{minipage}{0.5\textwidth}
  7093. % cond_test_20.rkt
  7094. \begin{lstlisting}
  7095. start:
  7096. callq read_int
  7097. movq %rax, tmp7951
  7098. cmpq $1, tmp7951
  7099. je block7952
  7100. jmp block7953
  7101. block7953:
  7102. movq $0, %rax
  7103. jmp conclusion
  7104. block7952:
  7105. movq $42, %rax
  7106. jmp conclusion
  7107. \end{lstlisting}
  7108. \end{minipage}
  7109. &
  7110. $\Rightarrow\qquad$
  7111. \begin{minipage}{0.4\textwidth}
  7112. \begin{lstlisting}
  7113. start:
  7114. callq read_int
  7115. movq %rax, tmp7951
  7116. cmpq $1, tmp7951
  7117. je block7952
  7118. movq $0, %rax
  7119. jmp conclusion
  7120. block7952:
  7121. movq $42, %rax
  7122. jmp conclusion
  7123. \end{lstlisting}
  7124. \end{minipage}
  7125. \end{tabular}
  7126. \caption{Merging basic blocks by removing unnecessary jumps.}
  7127. \label{fig:remove-jumps}
  7128. \end{figure}
  7129. \begin{exercise}\normalfont
  7130. %
  7131. Implement a pass named \code{remove-jumps} that merges basic blocks
  7132. into their preceding basic block, when there is only one preceding
  7133. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  7134. %
  7135. In the \code{run-tests.rkt} script, add the following entry to the
  7136. list of \code{passes} between \code{allocate-registers}
  7137. and \code{patch-instructions}.
  7138. \begin{lstlisting}
  7139. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  7140. \end{lstlisting}
  7141. Run this script to test your compiler.
  7142. %
  7143. Check that \code{remove-jumps} accomplishes the goal of merging basic
  7144. blocks on several test programs.
  7145. \end{exercise}
  7146. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7147. \chapter{Tuples and Garbage Collection}
  7148. \label{ch:Rvec}
  7149. \index{subject}{tuple}
  7150. \index{subject}{vector}
  7151. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  7152. %% all the IR grammars are spelled out! \\ --Jeremy}
  7153. %% \margincomment{\scriptsize Be more explicit about how to deal with
  7154. %% the root stack. \\ --Jeremy}
  7155. In this chapter we study the implementation of mutable tuples, called
  7156. vectors in Racket. This language feature is the first to use the
  7157. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  7158. tuple is indefinite, that is, a tuple lives forever from the
  7159. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  7160. is important to reclaim the space associated with a tuple when it is
  7161. no longer needed, which is why we also study \emph{garbage collection}
  7162. \emph{garbage collection} techniques in this chapter.
  7163. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  7164. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  7165. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  7166. \code{void} value. The reason for including the later is that the
  7167. \code{vector-set!} operation returns a value of type
  7168. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  7169. called the \code{Unit} type in the programming languages
  7170. literature. Racket's \code{Void} type is inhabited by a single value
  7171. \code{void} which corresponds to \code{unit} or \code{()} in the
  7172. literature~\citep{Pierce:2002hj}.}.
  7173. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  7174. copying live objects back and forth between two halves of the
  7175. heap. The garbage collector requires coordination with the compiler so
  7176. that it can see all of the \emph{root} pointers, that is, pointers in
  7177. registers or on the procedure call stack.
  7178. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  7179. discuss all the necessary changes and additions to the compiler
  7180. passes, including a new compiler pass named \code{expose-allocation}.
  7181. \section{The \LangVec{} Language}
  7182. \label{sec:r3}
  7183. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  7184. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  7185. \LangVec{} language includes three new forms: \code{vector} for creating a
  7186. tuple, \code{vector-ref} for reading an element of a tuple, and
  7187. \code{vector-set!} for writing to an element of a tuple. The program
  7188. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  7189. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  7190. the 3-tuple, demonstrating that tuples are first-class values. The
  7191. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  7192. of the \key{if} is taken. The element at index $0$ of \code{t} is
  7193. \code{40}, to which we add \code{2}, the element at index $0$ of the
  7194. 1-tuple. So the result of the program is \code{42}.
  7195. \begin{figure}[tbp]
  7196. \centering
  7197. \fbox{
  7198. \begin{minipage}{0.96\textwidth}
  7199. \[
  7200. \begin{array}{lcl}
  7201. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  7202. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  7203. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  7204. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  7205. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  7206. \MID \LP\key{and}\;\Exp\;\Exp\RP
  7207. \MID \LP\key{or}\;\Exp\;\Exp\RP
  7208. \MID \LP\key{not}\;\Exp\RP } \\
  7209. &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  7210. \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  7211. &\MID& \LP\key{vector}\;\Exp\ldots\RP
  7212. \MID \LP\key{vector-length}\;\Exp\RP \\
  7213. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  7214. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  7215. &\MID& \LP\key{void}\RP \MID \LP\key{has-type}~\Exp~\Type\RP\\
  7216. \LangVecM{} &::=& \Exp
  7217. \end{array}
  7218. \]
  7219. \end{minipage}
  7220. }
  7221. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  7222. (Figure~\ref{fig:Rif-concrete-syntax}).}
  7223. \label{fig:Rvec-concrete-syntax}
  7224. \end{figure}
  7225. \begin{figure}[tbp]
  7226. \begin{lstlisting}
  7227. (let ([t (vector 40 #t (vector 2))])
  7228. (if (vector-ref t 1)
  7229. (+ (vector-ref t 0)
  7230. (vector-ref (vector-ref t 2) 0))
  7231. 44))
  7232. \end{lstlisting}
  7233. \caption{Example program that creates tuples and reads from them.}
  7234. \label{fig:vector-eg}
  7235. \end{figure}
  7236. \begin{figure}[tp]
  7237. \centering
  7238. \fbox{
  7239. \begin{minipage}{0.96\textwidth}
  7240. \[
  7241. \begin{array}{lcl}
  7242. \itm{op} &::=& \ldots \MID \code{vector} \MID \code{vector-length} \\
  7243. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  7244. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  7245. \MID \BOOL{\itm{bool}}
  7246. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  7247. &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  7248. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  7249. &\MID& \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP \\
  7250. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  7251. \end{array}
  7252. \]
  7253. \end{minipage}
  7254. }
  7255. \caption{The abstract syntax of \LangVec{}.}
  7256. \label{fig:Rvec-syntax}
  7257. \end{figure}
  7258. \index{subject}{allocate}
  7259. \index{subject}{heap allocate}
  7260. Tuples are our first encounter with heap-allocated data, which raises
  7261. several interesting issues. First, variable binding performs a
  7262. shallow-copy when dealing with tuples, which means that different
  7263. variables can refer to the same tuple, that is, different variables
  7264. can be \emph{aliases} for the same entity. Consider the following
  7265. example in which both \code{t1} and \code{t2} refer to the same tuple.
  7266. Thus, the mutation through \code{t2} is visible when referencing the
  7267. tuple from \code{t1}, so the result of this program is \code{42}.
  7268. \index{subject}{alias}\index{subject}{mutation}
  7269. \begin{center}
  7270. \begin{minipage}{0.96\textwidth}
  7271. \begin{lstlisting}
  7272. (let ([t1 (vector 3 7)])
  7273. (let ([t2 t1])
  7274. (let ([_ (vector-set! t2 0 42)])
  7275. (vector-ref t1 0))))
  7276. \end{lstlisting}
  7277. \end{minipage}
  7278. \end{center}
  7279. The next issue concerns the lifetime of tuples. Of course, they are
  7280. created by the \code{vector} form, but when does their lifetime end?
  7281. Notice that \LangVec{} does not include an operation for deleting
  7282. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  7283. of static scoping. For example, the following program returns
  7284. \code{42} even though the variable \code{w} goes out of scope prior to
  7285. the \code{vector-ref} that reads from the vector it was bound to.
  7286. \begin{center}
  7287. \begin{minipage}{0.96\textwidth}
  7288. \begin{lstlisting}
  7289. (let ([v (vector (vector 44))])
  7290. (let ([x (let ([w (vector 42)])
  7291. (let ([_ (vector-set! v 0 w)])
  7292. 0))])
  7293. (+ x (vector-ref (vector-ref v 0) 0))))
  7294. \end{lstlisting}
  7295. \end{minipage}
  7296. \end{center}
  7297. From the perspective of programmer-observable behavior, tuples live
  7298. forever. Of course, if they really lived forever, then many programs
  7299. would run out of memory.\footnote{The \LangVec{} language does not have
  7300. looping or recursive functions, so it is nigh impossible to write a
  7301. program in \LangVec{} that will run out of memory. However, we add
  7302. recursive functions in the next Chapter!} A Racket implementation
  7303. must therefore perform automatic garbage collection.
  7304. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  7305. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  7306. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  7307. terms of the corresponding operations in Racket. One subtle point is
  7308. that the \code{vector-set!} operation returns the \code{\#<void>}
  7309. value. The \code{\#<void>} value can be passed around just like other
  7310. values inside an \LangVec{} program and a \code{\#<void>} value can be
  7311. compared for equality with another \code{\#<void>} value. However,
  7312. there are no other operations specific to the the \code{\#<void>}
  7313. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  7314. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  7315. otherwise.
  7316. \begin{figure}[tbp]
  7317. \begin{lstlisting}
  7318. (define interp-Rvec-class
  7319. (class interp-Rif-class
  7320. (super-new)
  7321. (define/override (interp-op op)
  7322. (match op
  7323. ['eq? (lambda (v1 v2)
  7324. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7325. (and (boolean? v1) (boolean? v2))
  7326. (and (vector? v1) (vector? v2))
  7327. (and (void? v1) (void? v2)))
  7328. (eq? v1 v2)]))]
  7329. ['vector vector]
  7330. ['vector-length vector-length]
  7331. ['vector-ref vector-ref]
  7332. ['vector-set! vector-set!]
  7333. [else (super interp-op op)]
  7334. ))
  7335. (define/override ((interp-exp env) e)
  7336. (define recur (interp-exp env))
  7337. (match e
  7338. [(HasType e t) (recur e)]
  7339. [(Void) (void)]
  7340. [else ((super interp-exp env) e)]
  7341. ))
  7342. ))
  7343. (define (interp-Rvec p)
  7344. (send (new interp-Rvec-class) interp-program p))
  7345. \end{lstlisting}
  7346. \caption{Interpreter for the \LangVec{} language.}
  7347. \label{fig:interp-Rvec}
  7348. \end{figure}
  7349. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  7350. deserves some explanation. When allocating a vector, we need to know
  7351. which elements of the vector are pointers (i.e. are also vectors). We
  7352. can obtain this information during type checking. The type checker in
  7353. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  7354. expression, it also wraps every \key{vector} creation with the form
  7355. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  7356. %
  7357. To create the s-expression for the \code{Vector} type in
  7358. Figure~\ref{fig:type-check-Rvec}, we use the
  7359. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  7360. operator} \code{,@} to insert the list \code{t*} without its usual
  7361. start and end parentheses. \index{subject}{unquote-slicing}
  7362. \begin{figure}[tp]
  7363. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7364. (define type-check-Rvec-class
  7365. (class type-check-Rif-class
  7366. (super-new)
  7367. (inherit check-type-equal?)
  7368. (define/override (type-check-exp env)
  7369. (lambda (e)
  7370. (define recur (type-check-exp env))
  7371. (match e
  7372. [(Void) (values (Void) 'Void)]
  7373. [(Prim 'vector es)
  7374. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  7375. (define t `(Vector ,@t*))
  7376. (values (HasType (Prim 'vector e*) t) t)]
  7377. [(Prim 'vector-ref (list e1 (Int i)))
  7378. (define-values (e1^ t) (recur e1))
  7379. (match t
  7380. [`(Vector ,ts ...)
  7381. (unless (and (0 . <= . i) (i . < . (length ts)))
  7382. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  7383. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  7384. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  7385. [(Prim 'vector-set! (list e1 (Int i) arg) )
  7386. (define-values (e-vec t-vec) (recur e1))
  7387. (define-values (e-arg^ t-arg) (recur arg))
  7388. (match t-vec
  7389. [`(Vector ,ts ...)
  7390. (unless (and (0 . <= . i) (i . < . (length ts)))
  7391. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  7392. (check-type-equal? (list-ref ts i) t-arg e)
  7393. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  7394. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  7395. [(Prim 'vector-length (list e))
  7396. (define-values (e^ t) (recur e))
  7397. (match t
  7398. [`(Vector ,ts ...)
  7399. (values (Prim 'vector-length (list e^)) 'Integer)]
  7400. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  7401. [(Prim 'eq? (list arg1 arg2))
  7402. (define-values (e1 t1) (recur arg1))
  7403. (define-values (e2 t2) (recur arg2))
  7404. (match* (t1 t2)
  7405. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  7406. [(other wise) (check-type-equal? t1 t2 e)])
  7407. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  7408. [(HasType (Prim 'vector es) t)
  7409. ((type-check-exp env) (Prim 'vector es))]
  7410. [(HasType e1 t)
  7411. (define-values (e1^ t^) (recur e1))
  7412. (check-type-equal? t t^ e)
  7413. (values (HasType e1^ t) t)]
  7414. [else ((super type-check-exp env) e)]
  7415. )))
  7416. ))
  7417. (define (type-check-Rvec p)
  7418. (send (new type-check-Rvec-class) type-check-program p))
  7419. \end{lstlisting}
  7420. \caption{Type checker for the \LangVec{} language.}
  7421. \label{fig:type-check-Rvec}
  7422. \end{figure}
  7423. \section{Garbage Collection}
  7424. \label{sec:GC}
  7425. Here we study a relatively simple algorithm for garbage collection
  7426. that is the basis of state-of-the-art garbage
  7427. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  7428. particular, we describe a two-space copying
  7429. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  7430. perform the
  7431. copy~\citep{Cheney:1970aa}.
  7432. \index{subject}{copying collector}
  7433. \index{subject}{two-space copying collector}
  7434. Figure~\ref{fig:copying-collector} gives a
  7435. coarse-grained depiction of what happens in a two-space collector,
  7436. showing two time steps, prior to garbage collection (on the top) and
  7437. after garbage collection (on the bottom). In a two-space collector,
  7438. the heap is divided into two parts named the FromSpace and the
  7439. ToSpace. Initially, all allocations go to the FromSpace until there is
  7440. not enough room for the next allocation request. At that point, the
  7441. garbage collector goes to work to make more room.
  7442. \index{subject}{ToSpace}
  7443. \index{subject}{FromSpace}
  7444. The garbage collector must be careful not to reclaim tuples that will
  7445. be used by the program in the future. Of course, it is impossible in
  7446. general to predict what a program will do, but we can over approximate
  7447. the will-be-used tuples by preserving all tuples that could be
  7448. accessed by \emph{any} program given the current computer state. A
  7449. program could access any tuple whose address is in a register or on
  7450. the procedure call stack. These addresses are called the \emph{root
  7451. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  7452. transitively reachable from the root set. Thus, it is safe for the
  7453. garbage collector to reclaim the tuples that are not reachable in this
  7454. way.
  7455. So the goal of the garbage collector is twofold:
  7456. \begin{enumerate}
  7457. \item preserve all tuple that are reachable from the root set via a
  7458. path of pointers, that is, the \emph{live} tuples, and
  7459. \item reclaim the memory of everything else, that is, the
  7460. \emph{garbage}.
  7461. \end{enumerate}
  7462. A copying collector accomplishes this by copying all of the live
  7463. objects from the FromSpace into the ToSpace and then performs a sleight
  7464. of hand, treating the ToSpace as the new FromSpace and the old
  7465. FromSpace as the new ToSpace. In the example of
  7466. Figure~\ref{fig:copying-collector}, there are three pointers in the
  7467. root set, one in a register and two on the stack. All of the live
  7468. objects have been copied to the ToSpace (the right-hand side of
  7469. Figure~\ref{fig:copying-collector}) in a way that preserves the
  7470. pointer relationships. For example, the pointer in the register still
  7471. points to a 2-tuple whose first element is a 3-tuple and whose second
  7472. element is a 2-tuple. There are four tuples that are not reachable
  7473. from the root set and therefore do not get copied into the ToSpace.
  7474. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  7475. created by a well-typed program in \LangVec{} because it contains a
  7476. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  7477. We design the garbage collector to deal with cycles to begin with so
  7478. we will not need to revisit this issue.
  7479. \begin{figure}[tbp]
  7480. \centering
  7481. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  7482. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  7483. \caption{A copying collector in action.}
  7484. \label{fig:copying-collector}
  7485. \end{figure}
  7486. There are many alternatives to copying collectors (and their bigger
  7487. siblings, the generational collectors) when its comes to garbage
  7488. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  7489. reference counting~\citep{Collins:1960aa}. The strengths of copying
  7490. collectors are that allocation is fast (just a comparison and pointer
  7491. increment), there is no fragmentation, cyclic garbage is collected,
  7492. and the time complexity of collection only depends on the amount of
  7493. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  7494. main disadvantages of a two-space copying collector is that it uses a
  7495. lot of space and takes a long time to perform the copy, though these
  7496. problems are ameliorated in generational collectors. Racket and
  7497. Scheme programs tend to allocate many small objects and generate a lot
  7498. of garbage, so copying and generational collectors are a good fit.
  7499. Garbage collection is an active research topic, especially concurrent
  7500. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  7501. developing new techniques and revisiting old
  7502. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  7503. meet every year at the International Symposium on Memory Management to
  7504. present these findings.
  7505. \subsection{Graph Copying via Cheney's Algorithm}
  7506. \label{sec:cheney}
  7507. \index{subject}{Cheney's algorithm}
  7508. Let us take a closer look at the copying of the live objects. The
  7509. allocated objects and pointers can be viewed as a graph and we need to
  7510. copy the part of the graph that is reachable from the root set. To
  7511. make sure we copy all of the reachable vertices in the graph, we need
  7512. an exhaustive graph traversal algorithm, such as depth-first search or
  7513. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  7514. such algorithms take into account the possibility of cycles by marking
  7515. which vertices have already been visited, so as to ensure termination
  7516. of the algorithm. These search algorithms also use a data structure
  7517. such as a stack or queue as a to-do list to keep track of the vertices
  7518. that need to be visited. We use breadth-first search and a trick
  7519. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  7520. and copying tuples into the ToSpace.
  7521. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  7522. copy progresses. The queue is represented by a chunk of contiguous
  7523. memory at the beginning of the ToSpace, using two pointers to track
  7524. the front and the back of the queue. The algorithm starts by copying
  7525. all tuples that are immediately reachable from the root set into the
  7526. ToSpace to form the initial queue. When we copy a tuple, we mark the
  7527. old tuple to indicate that it has been visited. We discuss how this
  7528. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  7529. pointers inside the copied tuples in the queue still point back to the
  7530. FromSpace. Once the initial queue has been created, the algorithm
  7531. enters a loop in which it repeatedly processes the tuple at the front
  7532. of the queue and pops it off the queue. To process a tuple, the
  7533. algorithm copies all the tuple that are directly reachable from it to
  7534. the ToSpace, placing them at the back of the queue. The algorithm then
  7535. updates the pointers in the popped tuple so they point to the newly
  7536. copied tuples.
  7537. \begin{figure}[tbp]
  7538. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  7539. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  7540. \label{fig:cheney}
  7541. \end{figure}
  7542. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  7543. tuple whose second element is $42$ to the back of the queue. The other
  7544. pointer goes to a tuple that has already been copied, so we do not
  7545. need to copy it again, but we do need to update the pointer to the new
  7546. location. This can be accomplished by storing a \emph{forwarding
  7547. pointer} to the new location in the old tuple, back when we initially
  7548. copied the tuple into the ToSpace. This completes one step of the
  7549. algorithm. The algorithm continues in this way until the front of the
  7550. queue is empty, that is, until the front catches up with the back.
  7551. \subsection{Data Representation}
  7552. \label{sec:data-rep-gc}
  7553. The garbage collector places some requirements on the data
  7554. representations used by our compiler. First, the garbage collector
  7555. needs to distinguish between pointers and other kinds of data. There
  7556. are several ways to accomplish this.
  7557. \begin{enumerate}
  7558. \item Attached a tag to each object that identifies what type of
  7559. object it is~\citep{McCarthy:1960dz}.
  7560. \item Store different types of objects in different
  7561. regions~\citep{Steele:1977ab}.
  7562. \item Use type information from the program to either generate
  7563. type-specific code for collecting or to generate tables that can
  7564. guide the
  7565. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  7566. \end{enumerate}
  7567. Dynamically typed languages, such as Lisp, need to tag objects
  7568. anyways, so option 1 is a natural choice for those languages.
  7569. However, \LangVec{} is a statically typed language, so it would be
  7570. unfortunate to require tags on every object, especially small and
  7571. pervasive objects like integers and Booleans. Option 3 is the
  7572. best-performing choice for statically typed languages, but comes with
  7573. a relatively high implementation complexity. To keep this chapter
  7574. within a 2-week time budget, we recommend a combination of options 1
  7575. and 2, using separate strategies for the stack and the heap.
  7576. Regarding the stack, we recommend using a separate stack for pointers,
  7577. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  7578. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  7579. is, when a local variable needs to be spilled and is of type
  7580. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  7581. stack instead of the normal procedure call stack. Furthermore, we
  7582. always spill vector-typed variables if they are live during a call to
  7583. the collector, thereby ensuring that no pointers are in registers
  7584. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  7585. example from Figure~\ref{fig:copying-collector} and contrasts it with
  7586. the data layout using a root stack. The root stack contains the two
  7587. pointers from the regular stack and also the pointer in the second
  7588. register.
  7589. \begin{figure}[tbp]
  7590. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  7591. \caption{Maintaining a root stack to facilitate garbage collection.}
  7592. \label{fig:shadow-stack}
  7593. \end{figure}
  7594. The problem of distinguishing between pointers and other kinds of data
  7595. also arises inside of each tuple on the heap. We solve this problem by
  7596. attaching a tag, an extra 64-bits, to each
  7597. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  7598. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  7599. that we have drawn the bits in a big-endian way, from right-to-left,
  7600. with bit location 0 (the least significant bit) on the far right,
  7601. which corresponds to the direction of the x86 shifting instructions
  7602. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  7603. is dedicated to specifying which elements of the tuple are pointers,
  7604. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  7605. indicates there is a pointer and a 0 bit indicates some other kind of
  7606. data. The pointer mask starts at bit location 7. We have limited
  7607. tuples to a maximum size of 50 elements, so we just need 50 bits for
  7608. the pointer mask. The tag also contains two other pieces of
  7609. information. The length of the tuple (number of elements) is stored in
  7610. bits location 1 through 6. Finally, the bit at location 0 indicates
  7611. whether the tuple has yet to be copied to the ToSpace. If the bit has
  7612. value 1, then this tuple has not yet been copied. If the bit has
  7613. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  7614. of a pointer are always zero anyways because our tuples are 8-byte
  7615. aligned.)
  7616. \begin{figure}[tbp]
  7617. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  7618. \caption{Representation of tuples in the heap.}
  7619. \label{fig:tuple-rep}
  7620. \end{figure}
  7621. \subsection{Implementation of the Garbage Collector}
  7622. \label{sec:organize-gz}
  7623. \index{subject}{prelude}
  7624. An implementation of the copying collector is provided in the
  7625. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  7626. interface to the garbage collector that is used by the compiler. The
  7627. \code{initialize} function creates the FromSpace, ToSpace, and root
  7628. stack and should be called in the prelude of the \code{main}
  7629. function. The arguments of \code{initialize} are the root stack size
  7630. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  7631. good choice for both. The \code{initialize} function puts the address
  7632. of the beginning of the FromSpace into the global variable
  7633. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  7634. the address that is 1-past the last element of the FromSpace. (We use
  7635. half-open intervals to represent chunks of
  7636. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  7637. points to the first element of the root stack.
  7638. As long as there is room left in the FromSpace, your generated code
  7639. can allocate tuples simply by moving the \code{free\_ptr} forward.
  7640. %
  7641. The amount of room left in FromSpace is the difference between the
  7642. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  7643. function should be called when there is not enough room left in the
  7644. FromSpace for the next allocation. The \code{collect} function takes
  7645. a pointer to the current top of the root stack (one past the last item
  7646. that was pushed) and the number of bytes that need to be
  7647. allocated. The \code{collect} function performs the copying collection
  7648. and leaves the heap in a state such that the next allocation will
  7649. succeed.
  7650. \begin{figure}[tbp]
  7651. \begin{lstlisting}
  7652. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  7653. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  7654. int64_t* free_ptr;
  7655. int64_t* fromspace_begin;
  7656. int64_t* fromspace_end;
  7657. int64_t** rootstack_begin;
  7658. \end{lstlisting}
  7659. \caption{The compiler's interface to the garbage collector.}
  7660. \label{fig:gc-header}
  7661. \end{figure}
  7662. %% \begin{exercise}
  7663. %% In the file \code{runtime.c} you will find the implementation of
  7664. %% \code{initialize} and a partial implementation of \code{collect}.
  7665. %% The \code{collect} function calls another function, \code{cheney},
  7666. %% to perform the actual copy, and that function is left to the reader
  7667. %% to implement. The following is the prototype for \code{cheney}.
  7668. %% \begin{lstlisting}
  7669. %% static void cheney(int64_t** rootstack_ptr);
  7670. %% \end{lstlisting}
  7671. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  7672. %% rootstack (which is an array of pointers). The \code{cheney} function
  7673. %% also communicates with \code{collect} through the global
  7674. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  7675. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  7676. %% the ToSpace:
  7677. %% \begin{lstlisting}
  7678. %% static int64_t* tospace_begin;
  7679. %% static int64_t* tospace_end;
  7680. %% \end{lstlisting}
  7681. %% The job of the \code{cheney} function is to copy all the live
  7682. %% objects (reachable from the root stack) into the ToSpace, update
  7683. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  7684. %% update the root stack so that it points to the objects in the
  7685. %% ToSpace, and finally to swap the global pointers for the FromSpace
  7686. %% and ToSpace.
  7687. %% \end{exercise}
  7688. %% \section{Compiler Passes}
  7689. %% \label{sec:code-generation-gc}
  7690. The introduction of garbage collection has a non-trivial impact on our
  7691. compiler passes. We introduce a new compiler pass named
  7692. \code{expose-allocation}. We make
  7693. significant changes to \code{select-instructions},
  7694. \code{build-interference}, \code{allocate-registers}, and
  7695. \code{print\_x86} and make minor changes in several more passes. The
  7696. following program will serve as our running example. It creates two
  7697. tuples, one nested inside the other. Both tuples have length one. The
  7698. program accesses the element in the inner tuple tuple via two vector
  7699. references.
  7700. % tests/s2_17.rkt
  7701. \begin{lstlisting}
  7702. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  7703. \end{lstlisting}
  7704. \section{Shrink}
  7705. \label{sec:shrink-Rvec}
  7706. Recall that the \code{shrink} pass translates the primitives operators
  7707. into a smaller set of primitives. Because this pass comes after type
  7708. checking, but before the passes that require the type information in
  7709. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  7710. to wrap \code{HasType} around each AST node that it generates.
  7711. \section{Expose Allocation}
  7712. \label{sec:expose-allocation}
  7713. The pass \code{expose-allocation} lowers the \code{vector} creation
  7714. form into a conditional call to the collector followed by the
  7715. allocation. We choose to place the \code{expose-allocation} pass
  7716. before \code{remove-complex-opera*} because the code generated by
  7717. \code{expose-allocation} contains complex operands. We also place
  7718. \code{expose-allocation} before \code{explicate-control} because
  7719. \code{expose-allocation} introduces new variables using \code{let},
  7720. but \code{let} is gone after \code{explicate-control}.
  7721. The output of \code{expose-allocation} is a language \LangAlloc{} that
  7722. extends \LangVec{} with the three new forms that we use in the translation
  7723. of the \code{vector} form.
  7724. \[
  7725. \begin{array}{lcl}
  7726. \Exp &::=& \cdots
  7727. \MID (\key{collect} \,\itm{int})
  7728. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  7729. \MID (\key{global-value} \,\itm{name})
  7730. \end{array}
  7731. \]
  7732. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  7733. $n$ bytes. It will become a call to the \code{collect} function in
  7734. \code{runtime.c} in \code{select-instructions}. The
  7735. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  7736. \index{subject}{allocate}
  7737. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  7738. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  7739. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  7740. a global variable, such as \code{free\_ptr}.
  7741. In the following, we show the transformation for the \code{vector}
  7742. form into 1) a sequence of let-bindings for the initializing
  7743. expressions, 2) a conditional call to \code{collect}, 3) a call to
  7744. \code{allocate}, and 4) the initialization of the vector. In the
  7745. following, \itm{len} refers to the length of the vector and
  7746. \itm{bytes} is how many total bytes need to be allocated for the
  7747. vector, which is 8 for the tag plus \itm{len} times 8.
  7748. \begin{lstlisting}
  7749. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  7750. |$\Longrightarrow$|
  7751. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  7752. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  7753. (global-value fromspace_end))
  7754. (void)
  7755. (collect |\itm{bytes}|))])
  7756. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  7757. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  7758. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  7759. |$v$|) ... )))) ...)
  7760. \end{lstlisting}
  7761. In the above, we suppressed all of the \code{has-type} forms in the
  7762. output for the sake of readability. The placement of the initializing
  7763. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  7764. sequence of \code{vector-set!} is important, as those expressions may
  7765. trigger garbage collection and we cannot have an allocated but
  7766. uninitialized tuple on the heap during a collection.
  7767. Figure~\ref{fig:expose-alloc-output} shows the output of the
  7768. \code{expose-allocation} pass on our running example.
  7769. \begin{figure}[tbp]
  7770. % tests/s2_17.rkt
  7771. \begin{lstlisting}
  7772. (vector-ref
  7773. (vector-ref
  7774. (let ([vecinit7976
  7775. (let ([vecinit7972 42])
  7776. (let ([collectret7974
  7777. (if (< (+ (global-value free_ptr) 16)
  7778. (global-value fromspace_end))
  7779. (void)
  7780. (collect 16)
  7781. )])
  7782. (let ([alloc7971 (allocate 1 (Vector Integer))])
  7783. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  7784. alloc7971)
  7785. )
  7786. )
  7787. )
  7788. ])
  7789. (let ([collectret7978
  7790. (if (< (+ (global-value free_ptr) 16)
  7791. (global-value fromspace_end))
  7792. (void)
  7793. (collect 16)
  7794. )])
  7795. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  7796. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  7797. alloc7975)
  7798. )
  7799. )
  7800. )
  7801. 0)
  7802. 0)
  7803. \end{lstlisting}
  7804. \caption{Output of the \code{expose-allocation} pass, minus
  7805. all of the \code{has-type} forms.}
  7806. \label{fig:expose-alloc-output}
  7807. \end{figure}
  7808. \section{Remove Complex Operands}
  7809. \label{sec:remove-complex-opera-Rvec}
  7810. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  7811. should all be treated as complex operands.
  7812. %% A new case for
  7813. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  7814. %% handled carefully to prevent the \code{Prim} node from being separated
  7815. %% from its enclosing \code{HasType}.
  7816. Figure~\ref{fig:Rvec-anf-syntax}
  7817. shows the grammar for the output language \LangVecANF{} of this
  7818. pass, which is \LangVec{} in administrative normal form.
  7819. \begin{figure}[tp]
  7820. \centering
  7821. \fbox{
  7822. \begin{minipage}{0.96\textwidth}
  7823. \small
  7824. \[
  7825. \begin{array}{rcl}
  7826. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }
  7827. \MID \VOID{} \\
  7828. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7829. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7830. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7831. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7832. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  7833. &\MID& \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  7834. \MID \LP\key{GlobalValue}~\Var\RP\\
  7835. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  7836. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  7837. \end{array}
  7838. \]
  7839. \end{minipage}
  7840. }
  7841. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  7842. \label{fig:Rvec-anf-syntax}
  7843. \end{figure}
  7844. \section{Explicate Control and the \LangCVec{} language}
  7845. \label{sec:explicate-control-r3}
  7846. \begin{figure}[tp]
  7847. \fbox{
  7848. \begin{minipage}{0.96\textwidth}
  7849. \small
  7850. \[
  7851. \begin{array}{lcl}
  7852. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  7853. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  7854. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  7855. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  7856. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7857. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  7858. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  7859. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  7860. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  7861. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  7862. \MID \LP\key{Collect} \,\itm{int}\RP \\
  7863. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  7864. \MID \GOTO{\itm{label}} } \\
  7865. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7866. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  7867. \end{array}
  7868. \]
  7869. \end{minipage}
  7870. }
  7871. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  7872. (Figure~\ref{fig:c1-syntax}).}
  7873. \label{fig:c2-syntax}
  7874. \end{figure}
  7875. The output of \code{explicate-control} is a program in the
  7876. intermediate language \LangCVec{}, whose abstract syntax is defined in
  7877. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  7878. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  7879. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  7880. \key{vector-set!}, and \key{global-value} expressions and the
  7881. \code{collect} statement. The \code{explicate-control} pass can treat
  7882. these new forms much like the other expression forms that we've
  7883. already encoutered.
  7884. \section{Select Instructions and the \LangXGlobal{} Language}
  7885. \label{sec:select-instructions-gc}
  7886. \index{subject}{instruction selection}
  7887. %% void (rep as zero)
  7888. %% allocate
  7889. %% collect (callq collect)
  7890. %% vector-ref
  7891. %% vector-set!
  7892. %% global (postpone)
  7893. In this pass we generate x86 code for most of the new operations that
  7894. were needed to compile tuples, including \code{Allocate},
  7895. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  7896. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  7897. the later has a different concrete syntax (see
  7898. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  7899. \index{subject}{x86}
  7900. The \code{vector-ref} and \code{vector-set!} forms translate into
  7901. \code{movq} instructions. (The plus one in the offset is to get past
  7902. the tag at the beginning of the tuple representation.)
  7903. \begin{lstlisting}
  7904. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  7905. |$\Longrightarrow$|
  7906. movq |$\itm{vec}'$|, %r11
  7907. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  7908. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  7909. |$\Longrightarrow$|
  7910. movq |$\itm{vec}'$|, %r11
  7911. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  7912. movq $0, |$\itm{lhs'}$|
  7913. \end{lstlisting}
  7914. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  7915. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  7916. register \code{r11} ensures that offset expression
  7917. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  7918. removing \code{r11} from consideration by the register allocating.
  7919. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  7920. \code{rax}. Then the generated code for \code{vector-set!} would be
  7921. \begin{lstlisting}
  7922. movq |$\itm{vec}'$|, %rax
  7923. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  7924. movq $0, |$\itm{lhs}'$|
  7925. \end{lstlisting}
  7926. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  7927. \code{patch-instructions} would insert a move through \code{rax}
  7928. as follows.
  7929. \begin{lstlisting}
  7930. movq |$\itm{vec}'$|, %rax
  7931. movq |$\itm{arg}'$|, %rax
  7932. movq %rax, |$8(n+1)$|(%rax)
  7933. movq $0, |$\itm{lhs}'$|
  7934. \end{lstlisting}
  7935. But the above sequence of instructions does not work because we're
  7936. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  7937. $\itm{arg}'$) at the same time!
  7938. We compile the \code{allocate} form to operations on the
  7939. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  7940. is the next free address in the FromSpace, so we copy it into
  7941. \code{r11} and then move it forward by enough space for the tuple
  7942. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  7943. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  7944. initialize the \itm{tag} and finally copy the address in \code{r11} to
  7945. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  7946. tag is organized. We recommend using the Racket operations
  7947. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  7948. during compilation. The type annotation in the \code{vector} form is
  7949. used to determine the pointer mask region of the tag.
  7950. \begin{lstlisting}
  7951. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  7952. |$\Longrightarrow$|
  7953. movq free_ptr(%rip), %r11
  7954. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  7955. movq $|$\itm{tag}$|, 0(%r11)
  7956. movq %r11, |$\itm{lhs}'$|
  7957. \end{lstlisting}
  7958. The \code{collect} form is compiled to a call to the \code{collect}
  7959. function in the runtime. The arguments to \code{collect} are 1) the
  7960. top of the root stack and 2) the number of bytes that need to be
  7961. allocated. We use another dedicated register, \code{r15}, to
  7962. store the pointer to the top of the root stack. So \code{r15} is not
  7963. available for use by the register allocator.
  7964. \begin{lstlisting}
  7965. (collect |$\itm{bytes}$|)
  7966. |$\Longrightarrow$|
  7967. movq %r15, %rdi
  7968. movq $|\itm{bytes}|, %rsi
  7969. callq collect
  7970. \end{lstlisting}
  7971. \begin{figure}[tp]
  7972. \fbox{
  7973. \begin{minipage}{0.96\textwidth}
  7974. \[
  7975. \begin{array}{lcl}
  7976. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  7977. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  7978. & & \gray{ \key{main:} \; \Instr\ldots }
  7979. \end{array}
  7980. \]
  7981. \end{minipage}
  7982. }
  7983. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  7984. \label{fig:x86-2-concrete}
  7985. \end{figure}
  7986. \begin{figure}[tp]
  7987. \fbox{
  7988. \begin{minipage}{0.96\textwidth}
  7989. \small
  7990. \[
  7991. \begin{array}{lcl}
  7992. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  7993. \MID \BYTEREG{\Reg}} \\
  7994. &\MID& (\key{Global}~\Var) \\
  7995. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  7996. \end{array}
  7997. \]
  7998. \end{minipage}
  7999. }
  8000. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  8001. \label{fig:x86-2}
  8002. \end{figure}
  8003. The concrete and abstract syntax of the \LangXGlobal{} language is
  8004. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  8005. differs from \LangXIf{} just in the addition of the form for global
  8006. variables.
  8007. %
  8008. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  8009. \code{select-instructions} pass on the running example.
  8010. \begin{figure}[tbp]
  8011. \centering
  8012. % tests/s2_17.rkt
  8013. \begin{minipage}[t]{0.5\textwidth}
  8014. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8015. block35:
  8016. movq free_ptr(%rip), alloc9024
  8017. addq $16, free_ptr(%rip)
  8018. movq alloc9024, %r11
  8019. movq $131, 0(%r11)
  8020. movq alloc9024, %r11
  8021. movq vecinit9025, 8(%r11)
  8022. movq $0, initret9026
  8023. movq alloc9024, %r11
  8024. movq 8(%r11), tmp9034
  8025. movq tmp9034, %r11
  8026. movq 8(%r11), %rax
  8027. jmp conclusion
  8028. block36:
  8029. movq $0, collectret9027
  8030. jmp block35
  8031. block38:
  8032. movq free_ptr(%rip), alloc9020
  8033. addq $16, free_ptr(%rip)
  8034. movq alloc9020, %r11
  8035. movq $3, 0(%r11)
  8036. movq alloc9020, %r11
  8037. movq vecinit9021, 8(%r11)
  8038. movq $0, initret9022
  8039. movq alloc9020, vecinit9025
  8040. movq free_ptr(%rip), tmp9031
  8041. movq tmp9031, tmp9032
  8042. addq $16, tmp9032
  8043. movq fromspace_end(%rip), tmp9033
  8044. cmpq tmp9033, tmp9032
  8045. jl block36
  8046. jmp block37
  8047. block37:
  8048. movq %r15, %rdi
  8049. movq $16, %rsi
  8050. callq 'collect
  8051. jmp block35
  8052. block39:
  8053. movq $0, collectret9023
  8054. jmp block38
  8055. \end{lstlisting}
  8056. \end{minipage}
  8057. \begin{minipage}[t]{0.45\textwidth}
  8058. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8059. start:
  8060. movq $42, vecinit9021
  8061. movq free_ptr(%rip), tmp9028
  8062. movq tmp9028, tmp9029
  8063. addq $16, tmp9029
  8064. movq fromspace_end(%rip), tmp9030
  8065. cmpq tmp9030, tmp9029
  8066. jl block39
  8067. jmp block40
  8068. block40:
  8069. movq %r15, %rdi
  8070. movq $16, %rsi
  8071. callq 'collect
  8072. jmp block38
  8073. \end{lstlisting}
  8074. \end{minipage}
  8075. \caption{Output of the \code{select-instructions} pass.}
  8076. \label{fig:select-instr-output-gc}
  8077. \end{figure}
  8078. \clearpage
  8079. \section{Register Allocation}
  8080. \label{sec:reg-alloc-gc}
  8081. \index{subject}{register allocation}
  8082. As discussed earlier in this chapter, the garbage collector needs to
  8083. access all the pointers in the root set, that is, all variables that
  8084. are vectors. It will be the responsibility of the register allocator
  8085. to make sure that:
  8086. \begin{enumerate}
  8087. \item the root stack is used for spilling vector-typed variables, and
  8088. \item if a vector-typed variable is live during a call to the
  8089. collector, it must be spilled to ensure it is visible to the
  8090. collector.
  8091. \end{enumerate}
  8092. The later responsibility can be handled during construction of the
  8093. interference graph, by adding interference edges between the call-live
  8094. vector-typed variables and all the callee-saved registers. (They
  8095. already interfere with the caller-saved registers.) The type
  8096. information for variables is in the \code{Program} form, so we
  8097. recommend adding another parameter to the \code{build-interference}
  8098. function to communicate this alist.
  8099. The spilling of vector-typed variables to the root stack can be
  8100. handled after graph coloring, when choosing how to assign the colors
  8101. (integers) to registers and stack locations. The \code{Program} output
  8102. of this pass changes to also record the number of spills to the root
  8103. stack.
  8104. % build-interference
  8105. %
  8106. % callq
  8107. % extra parameter for var->type assoc. list
  8108. % update 'program' and 'if'
  8109. % allocate-registers
  8110. % allocate spilled vectors to the rootstack
  8111. % don't change color-graph
  8112. \section{Print x86}
  8113. \label{sec:print-x86-gc}
  8114. \index{subject}{prelude}\index{subject}{conclusion}
  8115. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  8116. \code{print\_x86} pass on the running example. In the prelude and
  8117. conclusion of the \code{main} function, we treat the root stack very
  8118. much like the regular stack in that we move the root stack pointer
  8119. (\code{r15}) to make room for the spills to the root stack, except
  8120. that the root stack grows up instead of down. For the running
  8121. example, there was just one spill so we increment \code{r15} by 8
  8122. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  8123. One issue that deserves special care is that there may be a call to
  8124. \code{collect} prior to the initializing assignments for all the
  8125. variables in the root stack. We do not want the garbage collector to
  8126. accidentally think that some uninitialized variable is a pointer that
  8127. needs to be followed. Thus, we zero-out all locations on the root
  8128. stack in the prelude of \code{main}. In
  8129. Figure~\ref{fig:print-x86-output-gc}, the instruction
  8130. %
  8131. \lstinline{movq $0, (%r15)}
  8132. %
  8133. accomplishes this task. The garbage collector tests each root to see
  8134. if it is null prior to dereferencing it.
  8135. \begin{figure}[htbp]
  8136. \begin{minipage}[t]{0.5\textwidth}
  8137. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8138. block35:
  8139. movq free_ptr(%rip), %rcx
  8140. addq $16, free_ptr(%rip)
  8141. movq %rcx, %r11
  8142. movq $131, 0(%r11)
  8143. movq %rcx, %r11
  8144. movq -8(%r15), %rax
  8145. movq %rax, 8(%r11)
  8146. movq $0, %rdx
  8147. movq %rcx, %r11
  8148. movq 8(%r11), %rcx
  8149. movq %rcx, %r11
  8150. movq 8(%r11), %rax
  8151. jmp conclusion
  8152. block36:
  8153. movq $0, %rcx
  8154. jmp block35
  8155. block38:
  8156. movq free_ptr(%rip), %rcx
  8157. addq $16, free_ptr(%rip)
  8158. movq %rcx, %r11
  8159. movq $3, 0(%r11)
  8160. movq %rcx, %r11
  8161. movq %rbx, 8(%r11)
  8162. movq $0, %rdx
  8163. movq %rcx, -8(%r15)
  8164. movq free_ptr(%rip), %rcx
  8165. addq $16, %rcx
  8166. movq fromspace_end(%rip), %rdx
  8167. cmpq %rdx, %rcx
  8168. jl block36
  8169. movq %r15, %rdi
  8170. movq $16, %rsi
  8171. callq collect
  8172. jmp block35
  8173. block39:
  8174. movq $0, %rcx
  8175. jmp block38
  8176. \end{lstlisting}
  8177. \end{minipage}
  8178. \begin{minipage}[t]{0.45\textwidth}
  8179. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8180. start:
  8181. movq $42, %rbx
  8182. movq free_ptr(%rip), %rdx
  8183. addq $16, %rdx
  8184. movq fromspace_end(%rip), %rcx
  8185. cmpq %rcx, %rdx
  8186. jl block39
  8187. movq %r15, %rdi
  8188. movq $16, %rsi
  8189. callq collect
  8190. jmp block38
  8191. .globl main
  8192. main:
  8193. pushq %rbp
  8194. movq %rsp, %rbp
  8195. pushq %r13
  8196. pushq %r12
  8197. pushq %rbx
  8198. pushq %r14
  8199. subq $0, %rsp
  8200. movq $16384, %rdi
  8201. movq $16384, %rsi
  8202. callq initialize
  8203. movq rootstack_begin(%rip), %r15
  8204. movq $0, (%r15)
  8205. addq $8, %r15
  8206. jmp start
  8207. conclusion:
  8208. subq $8, %r15
  8209. addq $0, %rsp
  8210. popq %r14
  8211. popq %rbx
  8212. popq %r12
  8213. popq %r13
  8214. popq %rbp
  8215. retq
  8216. \end{lstlisting}
  8217. \end{minipage}
  8218. \caption{Output of the \code{print\_x86} pass.}
  8219. \label{fig:print-x86-output-gc}
  8220. \end{figure}
  8221. \begin{figure}[p]
  8222. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8223. \node (Rvec) at (0,2) {\large \LangVec{}};
  8224. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  8225. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  8226. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  8227. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  8228. \node (C2-4) at (3,0) {\large \LangCVec{}};
  8229. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  8230. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  8231. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  8232. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  8233. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  8234. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  8235. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  8236. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  8237. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  8238. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  8239. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  8240. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  8241. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  8242. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8243. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8244. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8245. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  8246. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  8247. \end{tikzpicture}
  8248. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  8249. \label{fig:Rvec-passes}
  8250. \end{figure}
  8251. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  8252. for the compilation of \LangVec{}.
  8253. \section{Challenge: Simple Structures}
  8254. \label{sec:simple-structures}
  8255. \index{subject}{struct}
  8256. \index{subject}{structure}
  8257. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  8258. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  8259. Recall that a \code{struct} in Typed Racket is a user-defined data
  8260. type that contains named fields and that is heap allocated, similar to
  8261. a vector. The following is an example of a structure definition, in
  8262. this case the definition of a \code{point} type.
  8263. \begin{lstlisting}
  8264. (struct point ([x : Integer] [y : Integer]) #:mutable)
  8265. \end{lstlisting}
  8266. \begin{figure}[tbp]
  8267. \centering
  8268. \fbox{
  8269. \begin{minipage}{0.96\textwidth}
  8270. \[
  8271. \begin{array}{lcl}
  8272. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  8273. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  8274. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  8275. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  8276. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  8277. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  8278. \MID (\key{and}\;\Exp\;\Exp)
  8279. \MID (\key{or}\;\Exp\;\Exp)
  8280. \MID (\key{not}\;\Exp) } \\
  8281. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  8282. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  8283. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  8284. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  8285. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  8286. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  8287. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  8288. \LangStruct{} &::=& \Def \ldots \; \Exp
  8289. \end{array}
  8290. \]
  8291. \end{minipage}
  8292. }
  8293. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  8294. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  8295. \label{fig:r3s-concrete-syntax}
  8296. \end{figure}
  8297. An instance of a structure is created using function call syntax, with
  8298. the name of the structure in the function position:
  8299. \begin{lstlisting}
  8300. (point 7 12)
  8301. \end{lstlisting}
  8302. Function-call syntax is also used to read the value in a field of a
  8303. structure. The function name is formed by the structure name, a dash,
  8304. and the field name. The following example uses \code{point-x} and
  8305. \code{point-y} to access the \code{x} and \code{y} fields of two point
  8306. instances.
  8307. \begin{center}
  8308. \begin{lstlisting}
  8309. (let ([pt1 (point 7 12)])
  8310. (let ([pt2 (point 4 3)])
  8311. (+ (- (point-x pt1) (point-x pt2))
  8312. (- (point-y pt1) (point-y pt2)))))
  8313. \end{lstlisting}
  8314. \end{center}
  8315. Similarly, to write to a field of a structure, use its set function,
  8316. whose name starts with \code{set-}, followed by the structure name,
  8317. then a dash, then the field name, and concluded with an exclamation
  8318. mark. The following example uses \code{set-point-x!} to change the
  8319. \code{x} field from \code{7} to \code{42}.
  8320. \begin{center}
  8321. \begin{lstlisting}
  8322. (let ([pt (point 7 12)])
  8323. (let ([_ (set-point-x! pt 42)])
  8324. (point-x pt)))
  8325. \end{lstlisting}
  8326. \end{center}
  8327. \begin{exercise}\normalfont
  8328. Extend your compiler with support for simple structures, compiling
  8329. \LangStruct{} to x86 assembly code. Create five new test cases that use
  8330. structures and test your compiler.
  8331. \end{exercise}
  8332. \section{Challenge: Generational Collection}
  8333. The copying collector described in Section~\ref{sec:GC} can incur
  8334. significant runtime overhead because the call to \code{collect} takes
  8335. time proportional to all of the live data. One way to reduce this
  8336. overhead is to reduce how much data is inspected in each call to
  8337. \code{collect}. In particular, researchers have observed that recently
  8338. allocated data is more likely to become garbage then data that has
  8339. survived one or more previous calls to \code{collect}. This insight
  8340. motivated the creation of \emph{generational garbage collectors}
  8341. \index{subject}{generational garbage collector} that
  8342. 1) segregates data according to its age into two or more generations,
  8343. 2) allocates less space for younger generations, so collecting them is
  8344. faster, and more space for the older generations, and 3) performs
  8345. collection on the younger generations more frequently then for older
  8346. generations~\citep{Wilson:1992fk}.
  8347. For this challenge assignment, the goal is to adapt the copying
  8348. collector implemented in \code{runtime.c} to use two generations, one
  8349. for young data and one for old data. Each generation consists of a
  8350. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  8351. \code{collect} function to use the two generations.
  8352. \begin{enumerate}
  8353. \item Copy the young generation's FromSpace to its ToSpace then switch
  8354. the role of the ToSpace and FromSpace
  8355. \item If there is enough space for the requested number of bytes in
  8356. the young FromSpace, then return from \code{collect}.
  8357. \item If there is not enough space in the young FromSpace for the
  8358. requested bytes, then move the data from the young generation to the
  8359. old one with the following steps:
  8360. \begin{enumerate}
  8361. \item If there is enough room in the old FromSpace, copy the young
  8362. FromSpace to the old FromSpace and then return.
  8363. \item If there is not enough room in the old FromSpace, then collect
  8364. the old generation by copying the old FromSpace to the old ToSpace
  8365. and swap the roles of the old FromSpace and ToSpace.
  8366. \item If there is enough room now, copy the young FromSpace to the
  8367. old FromSpace and return. Otherwise, allocate a larger FromSpace
  8368. and ToSpace for the old generation. Copy the young FromSpace and
  8369. the old FromSpace into the larger FromSpace for the old
  8370. generation and then return.
  8371. \end{enumerate}
  8372. \end{enumerate}
  8373. We recommend that you generalize the \code{cheney} function so that it
  8374. can be used for all the copies mentioned above: between the young
  8375. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  8376. between the young FromSpace and old FromSpace. This can be
  8377. accomplished by adding parameters to \code{cheney} that replace its
  8378. use of the global variables \code{fromspace\_begin},
  8379. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  8380. Note that the collection of the young generation does not traverse the
  8381. old generation. This introduces a potential problem: there may be
  8382. young data that is only reachable through pointers in the old
  8383. generation. If these pointers are not taken into account, the
  8384. collector could throw away young data that is live! One solution,
  8385. called \emph{pointer recording}, is to maintain a set of all the
  8386. pointers from the old generation into the new generation and consider
  8387. this set as part of the root set. To maintain this set, the compiler
  8388. must insert extra instructions around every \code{vector-set!}. If the
  8389. vector being modified is in the old generation, and if the value being
  8390. written is a pointer into the new generation, than that pointer must
  8391. be added to the set. Also, if the value being overwritten was a
  8392. pointer into the new generation, then that pointer should be removed
  8393. from the set.
  8394. \begin{exercise}\normalfont
  8395. Adapt the \code{collect} function in \code{runtime.c} to implement
  8396. generational garbage collection, as outlined in this section.
  8397. Update the code generation for \code{vector-set!} to implement
  8398. pointer recording. Make sure that your new compiler and runtime
  8399. passes your test suite.
  8400. \end{exercise}
  8401. % Further Reading
  8402. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8403. \chapter{Functions}
  8404. \label{ch:Rfun}
  8405. \index{subject}{function}
  8406. This chapter studies the compilation of functions similar to those
  8407. found in the C language. This corresponds to a subset of Typed Racket
  8408. in which only top-level function definitions are allowed. This kind of
  8409. function is an important stepping stone to implementing
  8410. lexically-scoped functions, that is, \key{lambda} abstractions, which
  8411. is the topic of Chapter~\ref{ch:Rlam}.
  8412. \section{The \LangFun{} Language}
  8413. The concrete and abstract syntax for function definitions and function
  8414. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  8415. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  8416. \LangFun{} begin with zero or more function definitions. The function
  8417. names from these definitions are in-scope for the entire program,
  8418. including all other function definitions (so the ordering of function
  8419. definitions does not matter). The concrete syntax for function
  8420. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  8421. where the first expression must
  8422. evaluate to a function and the rest are the arguments.
  8423. The abstract syntax for function application is
  8424. $\APPLY{\Exp}{\Exp\ldots}$.
  8425. %% The syntax for function application does not include an explicit
  8426. %% keyword, which is error prone when using \code{match}. To alleviate
  8427. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  8428. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  8429. Functions are first-class in the sense that a function pointer
  8430. \index{subject}{function pointer} is data and can be stored in memory or passed
  8431. as a parameter to another function. Thus, we introduce a function
  8432. type, written
  8433. \begin{lstlisting}
  8434. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  8435. \end{lstlisting}
  8436. for a function whose $n$ parameters have the types $\Type_1$ through
  8437. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  8438. these functions (with respect to Racket functions) is that they are
  8439. not lexically scoped. That is, the only external entities that can be
  8440. referenced from inside a function body are other globally-defined
  8441. functions. The syntax of \LangFun{} prevents functions from being nested
  8442. inside each other.
  8443. \begin{figure}[tp]
  8444. \centering
  8445. \fbox{
  8446. \begin{minipage}{0.96\textwidth}
  8447. \small
  8448. \[
  8449. \begin{array}{lcl}
  8450. \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  8451. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  8452. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  8453. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  8454. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  8455. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  8456. \MID (\key{and}\;\Exp\;\Exp)
  8457. \MID (\key{or}\;\Exp\;\Exp)
  8458. \MID (\key{not}\;\Exp)} \\
  8459. &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  8460. &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  8461. (\key{vector-ref}\;\Exp\;\Int)} \\
  8462. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  8463. \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  8464. &\MID& \LP\Exp \; \Exp \ldots\RP \\
  8465. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  8466. \LangFunM{} &::=& \Def \ldots \; \Exp
  8467. \end{array}
  8468. \]
  8469. \end{minipage}
  8470. }
  8471. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  8472. \label{fig:Rfun-concrete-syntax}
  8473. \end{figure}
  8474. \begin{figure}[tp]
  8475. \centering
  8476. \fbox{
  8477. \begin{minipage}{0.96\textwidth}
  8478. \small
  8479. \[
  8480. \begin{array}{lcl}
  8481. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  8482. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8483. &\MID& \gray{ \BOOL{\itm{bool}}
  8484. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  8485. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  8486. \MID \APPLY{\Exp}{\Exp\ldots}\\
  8487. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  8488. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  8489. \end{array}
  8490. \]
  8491. \end{minipage}
  8492. }
  8493. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  8494. \label{fig:Rfun-syntax}
  8495. \end{figure}
  8496. The program in Figure~\ref{fig:Rfun-function-example} is a
  8497. representative example of defining and using functions in \LangFun{}. We
  8498. define a function \code{map-vec} that applies some other function
  8499. \code{f} to both elements of a vector and returns a new
  8500. vector containing the results. We also define a function \code{add1}.
  8501. The program applies
  8502. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  8503. \code{(vector 1 42)}, from which we return the \code{42}.
  8504. \begin{figure}[tbp]
  8505. \begin{lstlisting}
  8506. (define (map-vec [f : (Integer -> Integer)]
  8507. [v : (Vector Integer Integer)])
  8508. : (Vector Integer Integer)
  8509. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  8510. (define (add1 [x : Integer]) : Integer
  8511. (+ x 1))
  8512. (vector-ref (map-vec add1 (vector 0 41)) 1)
  8513. \end{lstlisting}
  8514. \caption{Example of using functions in \LangFun{}.}
  8515. \label{fig:Rfun-function-example}
  8516. \end{figure}
  8517. The definitional interpreter for \LangFun{} is in
  8518. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  8519. responsible for setting up the mutual recursion between the top-level
  8520. function definitions. We use the classic back-patching \index{subject}{back-patching}
  8521. approach that uses mutable variables and makes two passes over the function
  8522. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  8523. top-level environment using a mutable cons cell for each function
  8524. definition. Note that the \code{lambda} value for each function is
  8525. incomplete; it does not yet include the environment. Once the
  8526. top-level environment is constructed, we then iterate over it and
  8527. update the \code{lambda} values to use the top-level environment.
  8528. \begin{figure}[tp]
  8529. \begin{lstlisting}
  8530. (define interp-Rfun-class
  8531. (class interp-Rvec-class
  8532. (super-new)
  8533. (define/override ((interp-exp env) e)
  8534. (define recur (interp-exp env))
  8535. (match e
  8536. [(Var x) (unbox (dict-ref env x))]
  8537. [(Let x e body)
  8538. (define new-env (dict-set env x (box (recur e))))
  8539. ((interp-exp new-env) body)]
  8540. [(Apply fun args)
  8541. (define fun-val (recur fun))
  8542. (define arg-vals (for/list ([e args]) (recur e)))
  8543. (match fun-val
  8544. [`(function (,xs ...) ,body ,fun-env)
  8545. (define params-args (for/list ([x xs] [arg arg-vals])
  8546. (cons x (box arg))))
  8547. (define new-env (append params-args fun-env))
  8548. ((interp-exp new-env) body)]
  8549. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  8550. [else ((super interp-exp env) e)]
  8551. ))
  8552. (define/public (interp-def d)
  8553. (match d
  8554. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  8555. (cons f (box `(function ,xs ,body ())))]))
  8556. (define/override (interp-program p)
  8557. (match p
  8558. [(ProgramDefsExp info ds body)
  8559. (let ([top-level (for/list ([d ds]) (interp-def d))])
  8560. (for/list ([f (in-dict-values top-level)])
  8561. (set-box! f (match (unbox f)
  8562. [`(function ,xs ,body ())
  8563. `(function ,xs ,body ,top-level)])))
  8564. ((interp-exp top-level) body))]))
  8565. ))
  8566. (define (interp-Rfun p)
  8567. (send (new interp-Rfun-class) interp-program p))
  8568. \end{lstlisting}
  8569. \caption{Interpreter for the \LangFun{} language.}
  8570. \label{fig:interp-Rfun}
  8571. \end{figure}
  8572. %\margincomment{TODO: explain type checker}
  8573. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  8574. \begin{figure}[tp]
  8575. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8576. (define type-check-Rfun-class
  8577. (class type-check-Rvec-class
  8578. (super-new)
  8579. (inherit check-type-equal?)
  8580. (define/public (type-check-apply env e es)
  8581. (define-values (e^ ty) ((type-check-exp env) e))
  8582. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  8583. ((type-check-exp env) e)))
  8584. (match ty
  8585. [`(,ty^* ... -> ,rt)
  8586. (for ([arg-ty ty*] [param-ty ty^*])
  8587. (check-type-equal? arg-ty param-ty (Apply e es)))
  8588. (values e^ e* rt)]))
  8589. (define/override (type-check-exp env)
  8590. (lambda (e)
  8591. (match e
  8592. [(FunRef f)
  8593. (values (FunRef f) (dict-ref env f))]
  8594. [(Apply e es)
  8595. (define-values (e^ es^ rt) (type-check-apply env e es))
  8596. (values (Apply e^ es^) rt)]
  8597. [(Call e es)
  8598. (define-values (e^ es^ rt) (type-check-apply env e es))
  8599. (values (Call e^ es^) rt)]
  8600. [else ((super type-check-exp env) e)])))
  8601. (define/public (type-check-def env)
  8602. (lambda (e)
  8603. (match e
  8604. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  8605. (define new-env (append (map cons xs ps) env))
  8606. (define-values (body^ ty^) ((type-check-exp new-env) body))
  8607. (check-type-equal? ty^ rt body)
  8608. (Def f p:t* rt info body^)])))
  8609. (define/public (fun-def-type d)
  8610. (match d
  8611. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  8612. (define/override (type-check-program e)
  8613. (match e
  8614. [(ProgramDefsExp info ds body)
  8615. (define new-env (for/list ([d ds])
  8616. (cons (Def-name d) (fun-def-type d))))
  8617. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  8618. (define-values (body^ ty) ((type-check-exp new-env) body))
  8619. (check-type-equal? ty 'Integer body)
  8620. (ProgramDefsExp info ds^ body^)]))))
  8621. (define (type-check-Rfun p)
  8622. (send (new type-check-Rfun-class) type-check-program p))
  8623. \end{lstlisting}
  8624. \caption{Type checker for the \LangFun{} language.}
  8625. \label{fig:type-check-Rfun}
  8626. \end{figure}
  8627. \section{Functions in x86}
  8628. \label{sec:fun-x86}
  8629. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  8630. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  8631. %% \margincomment{\tiny Talk about the return address on the
  8632. %% stack and what callq and retq does.\\ --Jeremy }
  8633. The x86 architecture provides a few features to support the
  8634. implementation of functions. We have already seen that x86 provides
  8635. labels so that one can refer to the location of an instruction, as is
  8636. needed for jump instructions. Labels can also be used to mark the
  8637. beginning of the instructions for a function. Going further, we can
  8638. obtain the address of a label by using the \key{leaq} instruction and
  8639. PC-relative addressing. For example, the following puts the
  8640. address of the \code{add1} label into the \code{rbx} register.
  8641. \begin{lstlisting}
  8642. leaq add1(%rip), %rbx
  8643. \end{lstlisting}
  8644. The instruction pointer register \key{rip} (aka. the program counter
  8645. \index{subject}{program counter}) always points to the next instruction to be
  8646. executed. When combined with an label, as in \code{add1(\%rip)}, the
  8647. linker computes the distance $d$ between the address of \code{add1}
  8648. and where the \code{rip} would be at that moment and then changes
  8649. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  8650. the address of \code{add1}.
  8651. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  8652. jump to a function whose location is given by a label. To support
  8653. function calls in this chapter we instead will be jumping to a
  8654. function whose location is given by an address in a register, that is,
  8655. we need to make an \emph{indirect function call}. The x86 syntax for
  8656. this is a \code{callq} instruction but with an asterisk before the
  8657. register name.\index{subject}{indirect function call}
  8658. \begin{lstlisting}
  8659. callq *%rbx
  8660. \end{lstlisting}
  8661. \subsection{Calling Conventions}
  8662. \index{subject}{calling conventions}
  8663. The \code{callq} instruction provides partial support for implementing
  8664. functions: it pushes the return address on the stack and it jumps to
  8665. the target. However, \code{callq} does not handle
  8666. \begin{enumerate}
  8667. \item parameter passing,
  8668. \item pushing frames on the procedure call stack and popping them off,
  8669. or
  8670. \item determining how registers are shared by different functions.
  8671. \end{enumerate}
  8672. Regarding (1) parameter passing, recall that the following six
  8673. registers are used to pass arguments to a function, in this order.
  8674. \begin{lstlisting}
  8675. rdi rsi rdx rcx r8 r9
  8676. \end{lstlisting}
  8677. If there are
  8678. more than six arguments, then the convention is to use space on the
  8679. frame of the caller for the rest of the arguments. However, to ease
  8680. the implementation of efficient tail calls
  8681. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  8682. arguments.
  8683. %
  8684. Also recall that the register \code{rax} is for the return value of
  8685. the function.
  8686. \index{subject}{prelude}\index{subject}{conclusion}
  8687. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  8688. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  8689. the stack grows down, with each function call using a chunk of space
  8690. called a frame. The caller sets the stack pointer, register
  8691. \code{rsp}, to the last data item in its frame. The callee must not
  8692. change anything in the caller's frame, that is, anything that is at or
  8693. above the stack pointer. The callee is free to use locations that are
  8694. below the stack pointer.
  8695. Recall that we are storing variables of vector type on the root stack.
  8696. So the prelude needs to move the root stack pointer \code{r15} up and
  8697. the conclusion needs to move the root stack pointer back down. Also,
  8698. the prelude must initialize to \code{0} this frame's slots in the root
  8699. stack to signal to the garbage collector that those slots do not yet
  8700. contain a pointer to a vector. Otherwise the garbage collector will
  8701. interpret the garbage bits in those slots as memory addresses and try
  8702. to traverse them, causing serious mayhem!
  8703. Regarding (3) the sharing of registers between different functions,
  8704. recall from Section~\ref{sec:calling-conventions} that the registers
  8705. are divided into two groups, the caller-saved registers and the
  8706. callee-saved registers. The caller should assume that all the
  8707. caller-saved registers get overwritten with arbitrary values by the
  8708. callee. That is why we recommend in
  8709. Section~\ref{sec:calling-conventions} that variables that are live
  8710. during a function call should not be assigned to caller-saved
  8711. registers.
  8712. On the flip side, if the callee wants to use a callee-saved register,
  8713. the callee must save the contents of those registers on their stack
  8714. frame and then put them back prior to returning to the caller. That
  8715. is why we recommended in Section~\ref{sec:calling-conventions} that if
  8716. the register allocator assigns a variable to a callee-saved register,
  8717. then the prelude of the \code{main} function must save that register
  8718. to the stack and the conclusion of \code{main} must restore it. This
  8719. recommendation now generalizes to all functions.
  8720. Also recall that the base pointer, register \code{rbp}, is used as a
  8721. point-of-reference within a frame, so that each local variable can be
  8722. accessed at a fixed offset from the base pointer
  8723. (Section~\ref{sec:x86}).
  8724. %
  8725. Figure~\ref{fig:call-frames} shows the general layout of the caller
  8726. and callee frames.
  8727. \begin{figure}[tbp]
  8728. \centering
  8729. \begin{tabular}{r|r|l|l} \hline
  8730. Caller View & Callee View & Contents & Frame \\ \hline
  8731. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  8732. 0(\key{\%rbp}) & & old \key{rbp} \\
  8733. -8(\key{\%rbp}) & & callee-saved $1$ \\
  8734. \ldots & & \ldots \\
  8735. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  8736. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  8737. \ldots & & \ldots \\
  8738. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  8739. %% & & \\
  8740. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  8741. %% & \ldots & \ldots \\
  8742. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  8743. \hline
  8744. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  8745. & 0(\key{\%rbp}) & old \key{rbp} \\
  8746. & -8(\key{\%rbp}) & callee-saved $1$ \\
  8747. & \ldots & \ldots \\
  8748. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  8749. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  8750. & \ldots & \ldots \\
  8751. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  8752. \end{tabular}
  8753. \caption{Memory layout of caller and callee frames.}
  8754. \label{fig:call-frames}
  8755. \end{figure}
  8756. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  8757. %% local variables and for storing the values of callee-saved registers
  8758. %% (we shall refer to all of these collectively as ``locals''), and that
  8759. %% at the beginning of a function we move the stack pointer \code{rsp}
  8760. %% down to make room for them.
  8761. %% We recommend storing the local variables
  8762. %% first and then the callee-saved registers, so that the local variables
  8763. %% can be accessed using \code{rbp} the same as before the addition of
  8764. %% functions.
  8765. %% To make additional room for passing arguments, we shall
  8766. %% move the stack pointer even further down. We count how many stack
  8767. %% arguments are needed for each function call that occurs inside the
  8768. %% body of the function and find their maximum. Adding this number to the
  8769. %% number of locals gives us how much the \code{rsp} should be moved at
  8770. %% the beginning of the function. In preparation for a function call, we
  8771. %% offset from \code{rsp} to set up the stack arguments. We put the first
  8772. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  8773. %% so on.
  8774. %% Upon calling the function, the stack arguments are retrieved by the
  8775. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  8776. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  8777. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  8778. %% the layout of the caller and callee frames. Notice how important it is
  8779. %% that we correctly compute the maximum number of arguments needed for
  8780. %% function calls; if that number is too small then the arguments and
  8781. %% local variables will smash into each other!
  8782. \subsection{Efficient Tail Calls}
  8783. \label{sec:tail-call}
  8784. In general, the amount of stack space used by a program is determined
  8785. by the longest chain of nested function calls. That is, if function
  8786. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  8787. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  8788. $n$ can grow quite large in the case of recursive or mutually
  8789. recursive functions. However, in some cases we can arrange to use only
  8790. constant space, i.e. $O(1)$, instead of $O(n)$.
  8791. If a function call is the last action in a function body, then that
  8792. call is said to be a \emph{tail call}\index{subject}{tail call}.
  8793. For example, in the following
  8794. program, the recursive call to \code{tail-sum} is a tail call.
  8795. \begin{center}
  8796. \begin{lstlisting}
  8797. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8798. (if (eq? n 0)
  8799. r
  8800. (tail-sum (- n 1) (+ n r))))
  8801. (+ (tail-sum 5 0) 27)
  8802. \end{lstlisting}
  8803. \end{center}
  8804. At a tail call, the frame of the caller is no longer needed, so we
  8805. can pop the caller's frame before making the tail call. With this
  8806. approach, a recursive function that only makes tail calls will only
  8807. use $O(1)$ stack space. Functional languages like Racket typically
  8808. rely heavily on recursive functions, so they typically guarantee that
  8809. all tail calls will be optimized in this way.
  8810. \index{subject}{frame}
  8811. However, some care is needed with regards to argument passing in tail
  8812. calls. As mentioned above, for arguments beyond the sixth, the
  8813. convention is to use space in the caller's frame for passing
  8814. arguments. But for a tail call we pop the caller's frame and can no
  8815. longer use it. Another alternative is to use space in the callee's
  8816. frame for passing arguments. However, this option is also problematic
  8817. because the caller and callee's frame overlap in memory. As we begin
  8818. to copy the arguments from their sources in the caller's frame, the
  8819. target locations in the callee's frame might overlap with the sources
  8820. for later arguments! We solve this problem by using the heap instead
  8821. of the stack for passing more than six arguments, as we describe in
  8822. the Section~\ref{sec:limit-functions-r4}.
  8823. As mentioned above, for a tail call we pop the caller's frame prior to
  8824. making the tail call. The instructions for popping a frame are the
  8825. instructions that we usually place in the conclusion of a
  8826. function. Thus, we also need to place such code immediately before
  8827. each tail call. These instructions include restoring the callee-saved
  8828. registers, so it is good that the argument passing registers are all
  8829. caller-saved registers.
  8830. One last note regarding which instruction to use to make the tail
  8831. call. When the callee is finished, it should not return to the current
  8832. function, but it should return to the function that called the current
  8833. one. Thus, the return address that is already on the stack is the
  8834. right one, and we should not use \key{callq} to make the tail call, as
  8835. that would unnecessarily overwrite the return address. Instead we can
  8836. simply use the \key{jmp} instruction. Like the indirect function call,
  8837. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  8838. prefixed with an asterisk. We recommend using \code{rax} to hold the
  8839. jump target because the preceding conclusion overwrites just about
  8840. everything else.
  8841. \begin{lstlisting}
  8842. jmp *%rax
  8843. \end{lstlisting}
  8844. \section{Shrink \LangFun{}}
  8845. \label{sec:shrink-r4}
  8846. The \code{shrink} pass performs a minor modification to ease the
  8847. later passes. This pass introduces an explicit \code{main} function
  8848. and changes the top \code{ProgramDefsExp} form to
  8849. \code{ProgramDefs} as follows.
  8850. \begin{lstlisting}
  8851. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  8852. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  8853. \end{lstlisting}
  8854. where $\itm{mainDef}$ is
  8855. \begin{lstlisting}
  8856. (Def 'main '() 'Integer '() |$\Exp'$|)
  8857. \end{lstlisting}
  8858. \section{Reveal Functions and the \LangFunRef{} language}
  8859. \label{sec:reveal-functions-r4}
  8860. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  8861. respect: it conflates the use of function names and local
  8862. variables. This is a problem because we need to compile the use of a
  8863. function name differently than the use of a local variable; we need to
  8864. use \code{leaq} to convert the function name (a label in x86) to an
  8865. address in a register. Thus, it is a good idea to create a new pass
  8866. that changes function references from just a symbol $f$ to
  8867. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  8868. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  8869. The concrete syntax for a function reference is $\CFUNREF{f}$.
  8870. \begin{figure}[tp]
  8871. \centering
  8872. \fbox{
  8873. \begin{minipage}{0.96\textwidth}
  8874. \[
  8875. \begin{array}{lcl}
  8876. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  8877. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8878. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  8879. \end{array}
  8880. \]
  8881. \end{minipage}
  8882. }
  8883. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  8884. (Figure~\ref{fig:Rfun-syntax}).}
  8885. \label{fig:f1-syntax}
  8886. \end{figure}
  8887. %% Distinguishing between calls in tail position and non-tail position
  8888. %% requires the pass to have some notion of context. We recommend using
  8889. %% two mutually recursive functions, one for processing expressions in
  8890. %% tail position and another for the rest.
  8891. Placing this pass after \code{uniquify} will make sure that there are
  8892. no local variables and functions that share the same name. On the
  8893. other hand, \code{reveal-functions} needs to come before the
  8894. \code{explicate-control} pass because that pass helps us compile
  8895. \code{FunRef} forms into assignment statements.
  8896. \section{Limit Functions}
  8897. \label{sec:limit-functions-r4}
  8898. Recall that we wish to limit the number of function parameters to six
  8899. so that we do not need to use the stack for argument passing, which
  8900. makes it easier to implement efficient tail calls. However, because
  8901. the input language \LangFun{} supports arbitrary numbers of function
  8902. arguments, we have some work to do!
  8903. This pass transforms functions and function calls that involve more
  8904. than six arguments to pass the first five arguments as usual, but it
  8905. packs the rest of the arguments into a vector and passes it as the
  8906. sixth argument.
  8907. Each function definition with too many parameters is transformed as
  8908. follows.
  8909. \begin{lstlisting}
  8910. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  8911. |$\Rightarrow$|
  8912. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  8913. \end{lstlisting}
  8914. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  8915. the occurrences of the later parameters with vector references.
  8916. \begin{lstlisting}
  8917. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  8918. \end{lstlisting}
  8919. For function calls with too many arguments, the \code{limit-functions}
  8920. pass transforms them in the following way.
  8921. \begin{tabular}{lll}
  8922. \begin{minipage}{0.2\textwidth}
  8923. \begin{lstlisting}
  8924. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  8925. \end{lstlisting}
  8926. \end{minipage}
  8927. &
  8928. $\Rightarrow$
  8929. &
  8930. \begin{minipage}{0.4\textwidth}
  8931. \begin{lstlisting}
  8932. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  8933. \end{lstlisting}
  8934. \end{minipage}
  8935. \end{tabular}
  8936. \section{Remove Complex Operands}
  8937. \label{sec:rco-r4}
  8938. The primary decisions to make for this pass is whether to classify
  8939. \code{FunRef} and \code{Apply} as either atomic or complex
  8940. expressions. Recall that a simple expression will eventually end up as
  8941. just an immediate argument of an x86 instruction. Function
  8942. application will be translated to a sequence of instructions, so
  8943. \code{Apply} must be classified as complex expression.
  8944. On the other hand, the arguments of \code{Apply} should be
  8945. atomic expressions.
  8946. %
  8947. Regarding \code{FunRef}, as discussed above, the function label needs
  8948. to be converted to an address using the \code{leaq} instruction. Thus,
  8949. even though \code{FunRef} seems rather simple, it needs to be
  8950. classified as a complex expression so that we generate an assignment
  8951. statement with a left-hand side that can serve as the target of the
  8952. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  8953. output language \LangFunANF{} of this pass.
  8954. \begin{figure}[tp]
  8955. \centering
  8956. \fbox{
  8957. \begin{minipage}{0.96\textwidth}
  8958. \small
  8959. \[
  8960. \begin{array}{rcl}
  8961. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  8962. \MID \VOID{} } \\
  8963. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  8964. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  8965. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8966. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  8967. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  8968. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  8969. \MID \LP\key{GlobalValue}~\Var\RP }\\
  8970. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  8971. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8972. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  8973. \end{array}
  8974. \]
  8975. \end{minipage}
  8976. }
  8977. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  8978. \label{fig:Rfun-anf-syntax}
  8979. \end{figure}
  8980. \section{Explicate Control and the \LangCFun{} language}
  8981. \label{sec:explicate-control-r4}
  8982. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  8983. output of \key{explicate-control}. (The concrete syntax is given in
  8984. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  8985. functions for assignment and tail contexts should be updated with
  8986. cases for \code{Apply} and \code{FunRef} and the function for
  8987. predicate context should be updated for \code{Apply} but not
  8988. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  8989. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  8990. tail position \code{Apply} becomes \code{TailCall}. We recommend
  8991. defining a new auxiliary function for processing function definitions.
  8992. This code is similar to the case for \code{Program} in \LangVec{}. The
  8993. top-level \code{explicate-control} function that handles the
  8994. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  8995. all the function definitions.
  8996. \begin{figure}[tp]
  8997. \fbox{
  8998. \begin{minipage}{0.96\textwidth}
  8999. \small
  9000. \[
  9001. \begin{array}{lcl}
  9002. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  9003. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  9004. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  9005. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  9006. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  9007. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  9008. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  9009. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  9010. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  9011. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  9012. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9013. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9014. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  9015. \MID \GOTO{\itm{label}} } \\
  9016. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9017. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  9018. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9019. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9020. \end{array}
  9021. \]
  9022. \end{minipage}
  9023. }
  9024. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  9025. \label{fig:c3-syntax}
  9026. \end{figure}
  9027. \section{Select Instructions and the \LangXIndCall{} Language}
  9028. \label{sec:select-r4}
  9029. \index{subject}{instruction selection}
  9030. The output of select instructions is a program in the \LangXIndCall{}
  9031. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  9032. \index{subject}{x86}
  9033. \begin{figure}[tp]
  9034. \fbox{
  9035. \begin{minipage}{0.96\textwidth}
  9036. \small
  9037. \[
  9038. \begin{array}{lcl}
  9039. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  9040. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  9041. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  9042. \Instr &::=& \ldots
  9043. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  9044. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  9045. \Block &::= & \Instr\ldots \\
  9046. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  9047. \LangXIndCallM{} &::= & \Def\ldots
  9048. \end{array}
  9049. \]
  9050. \end{minipage}
  9051. }
  9052. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  9053. \label{fig:x86-3-concrete}
  9054. \end{figure}
  9055. \begin{figure}[tp]
  9056. \fbox{
  9057. \begin{minipage}{0.96\textwidth}
  9058. \small
  9059. \[
  9060. \begin{array}{lcl}
  9061. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  9062. \MID \BYTEREG{\Reg} } \\
  9063. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  9064. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  9065. \MID \TAILJMP{\Arg}{\itm{int}}\\
  9066. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  9067. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  9068. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  9069. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9070. \end{array}
  9071. \]
  9072. \end{minipage}
  9073. }
  9074. \caption{The abstract syntax of \LangXIndCall{} (extends
  9075. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  9076. \label{fig:x86-3}
  9077. \end{figure}
  9078. An assignment of a function reference to a variable becomes a
  9079. load-effective-address instruction as follows: \\
  9080. \begin{tabular}{lcl}
  9081. \begin{minipage}{0.35\textwidth}
  9082. \begin{lstlisting}
  9083. |$\itm{lhs}$| = (fun-ref |$f$|);
  9084. \end{lstlisting}
  9085. \end{minipage}
  9086. &
  9087. $\Rightarrow$\qquad\qquad
  9088. &
  9089. \begin{minipage}{0.3\textwidth}
  9090. \begin{lstlisting}
  9091. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  9092. \end{lstlisting}
  9093. \end{minipage}
  9094. \end{tabular} \\
  9095. Regarding function definitions, we need to remove the parameters and
  9096. instead perform parameter passing using the conventions discussed in
  9097. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  9098. registers. We recommend turning the parameters into local variables
  9099. and generating instructions at the beginning of the function to move
  9100. from the argument passing registers to these local variables.
  9101. \begin{lstlisting}
  9102. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  9103. |$\Rightarrow$|
  9104. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  9105. \end{lstlisting}
  9106. The $G'$ control-flow graph is the same as $G$ except that the
  9107. \code{start} block is modified to add the instructions for moving from
  9108. the argument registers to the parameter variables. So the \code{start}
  9109. block of $G$ shown on the left is changed to the code on the right.
  9110. \begin{center}
  9111. \begin{minipage}{0.3\textwidth}
  9112. \begin{lstlisting}
  9113. start:
  9114. |$\itm{instr}_1$|
  9115. |$\vdots$|
  9116. |$\itm{instr}_n$|
  9117. \end{lstlisting}
  9118. \end{minipage}
  9119. $\Rightarrow$
  9120. \begin{minipage}{0.3\textwidth}
  9121. \begin{lstlisting}
  9122. start:
  9123. movq %rdi, |$x_1$|
  9124. movq %rsi, |$x_2$|
  9125. |$\vdots$|
  9126. |$\itm{instr}_1$|
  9127. |$\vdots$|
  9128. |$\itm{instr}_n$|
  9129. \end{lstlisting}
  9130. \end{minipage}
  9131. \end{center}
  9132. By changing the parameters to local variables, we are giving the
  9133. register allocator control over which registers or stack locations to
  9134. use for them. If you implemented the move-biasing challenge
  9135. (Section~\ref{sec:move-biasing}), the register allocator will try to
  9136. assign the parameter variables to the corresponding argument register,
  9137. in which case the \code{patch-instructions} pass will remove the
  9138. \code{movq} instruction. This happens in the example translation in
  9139. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  9140. the \code{add} function.
  9141. %
  9142. Also, note that the register allocator will perform liveness analysis
  9143. on this sequence of move instructions and build the interference
  9144. graph. So, for example, $x_1$ will be marked as interfering with
  9145. \code{rsi} and that will prevent the assignment of $x_1$ to
  9146. \code{rsi}, which is good, because that would overwrite the argument
  9147. that needs to move into $x_2$.
  9148. Next, consider the compilation of function calls. In the mirror image
  9149. of handling the parameters of function definitions, the arguments need
  9150. to be moved to the argument passing registers. The function call
  9151. itself is performed with an indirect function call. The return value
  9152. from the function is stored in \code{rax}, so it needs to be moved
  9153. into the \itm{lhs}.
  9154. \begin{lstlisting}
  9155. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  9156. |$\Rightarrow$|
  9157. movq |$\itm{arg}_1$|, %rdi
  9158. movq |$\itm{arg}_2$|, %rsi
  9159. |$\vdots$|
  9160. callq *|\itm{fun}|
  9161. movq %rax, |\itm{lhs}|
  9162. \end{lstlisting}
  9163. The \code{IndirectCallq} AST node includes an integer for the arity of
  9164. the function, i.e., the number of parameters. That information is
  9165. useful in the \code{uncover-live} pass for determining which
  9166. argument-passing registers are potentially read during the call.
  9167. For tail calls, the parameter passing is the same as non-tail calls:
  9168. generate instructions to move the arguments into to the argument
  9169. passing registers. After that we need to pop the frame from the
  9170. procedure call stack. However, we do not yet know how big the frame
  9171. is; that gets determined during register allocation. So instead of
  9172. generating those instructions here, we invent a new instruction that
  9173. means ``pop the frame and then do an indirect jump'', which we name
  9174. \code{TailJmp}. The abstract syntax for this instruction includes an
  9175. argument that specifies where to jump and an integer that represents
  9176. the arity of the function being called.
  9177. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  9178. using the label \code{start} for the initial block of a program, and
  9179. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  9180. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  9181. can be compiled to an assignment to \code{rax} followed by a jump to
  9182. \code{conclusion}. With the addition of function definitions, we will
  9183. have a starting block and conclusion for each function, but their
  9184. labels need to be unique. We recommend prepending the function's name
  9185. to \code{start} and \code{conclusion}, respectively, to obtain unique
  9186. labels. (Alternatively, one could \code{gensym} labels for the start
  9187. and conclusion and store them in the $\itm{info}$ field of the
  9188. function definition.)
  9189. \section{Register Allocation}
  9190. \label{sec:register-allocation-r4}
  9191. \subsection{Liveness Analysis}
  9192. \label{sec:liveness-analysis-r4}
  9193. \index{subject}{liveness analysis}
  9194. %% The rest of the passes need only minor modifications to handle the new
  9195. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  9196. %% \code{leaq}.
  9197. The \code{IndirectCallq} instruction should be treated like
  9198. \code{Callq} regarding its written locations $W$, in that they should
  9199. include all the caller-saved registers. Recall that the reason for
  9200. that is to force call-live variables to be assigned to callee-saved
  9201. registers or to be spilled to the stack.
  9202. Regarding the set of read locations $R$ the arity field of
  9203. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  9204. argument-passing registers should be considered as read by those
  9205. instructions.
  9206. \subsection{Build Interference Graph}
  9207. \label{sec:build-interference-r4}
  9208. With the addition of function definitions, we compute an interference
  9209. graph for each function (not just one for the whole program).
  9210. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  9211. spill vector-typed variables that are live during a call to the
  9212. \code{collect}. With the addition of functions to our language, we
  9213. need to revisit this issue. Many functions perform allocation and
  9214. therefore have calls to the collector inside of them. Thus, we should
  9215. not only spill a vector-typed variable when it is live during a call
  9216. to \code{collect}, but we should spill the variable if it is live
  9217. during any function call. Thus, in the \code{build-interference} pass,
  9218. we recommend adding interference edges between call-live vector-typed
  9219. variables and the callee-saved registers (in addition to the usual
  9220. addition of edges between call-live variables and the caller-saved
  9221. registers).
  9222. \subsection{Allocate Registers}
  9223. The primary change to the \code{allocate-registers} pass is adding an
  9224. auxiliary function for handling definitions (the \Def{} non-terminal
  9225. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  9226. logic is the same as described in
  9227. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  9228. allocation is performed many times, once for each function definition,
  9229. instead of just once for the whole program.
  9230. \section{Patch Instructions}
  9231. In \code{patch-instructions}, you should deal with the x86
  9232. idiosyncrasy that the destination argument of \code{leaq} must be a
  9233. register. Additionally, you should ensure that the argument of
  9234. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  9235. code generation more convenient, because we trample many registers
  9236. before the tail call (as explained in the next section).
  9237. \section{Print x86}
  9238. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  9239. \code{IndirectCallq} are straightforward: output their concrete
  9240. syntax.
  9241. \begin{lstlisting}
  9242. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  9243. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  9244. \end{lstlisting}
  9245. The \code{TailJmp} node requires a bit work. A straightforward
  9246. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  9247. before the jump we need to pop the current frame. This sequence of
  9248. instructions is the same as the code for the conclusion of a function,
  9249. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  9250. Regarding function definitions, you will need to generate a prelude
  9251. and conclusion for each one. This code is similar to the prelude and
  9252. conclusion that you generated for the \code{main} function in
  9253. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  9254. should carry out the following steps.
  9255. \begin{enumerate}
  9256. \item Start with \code{.global} and \code{.align} directives followed
  9257. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  9258. example.)
  9259. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  9260. pointer.
  9261. \item Push to the stack all of the callee-saved registers that were
  9262. used for register allocation.
  9263. \item Move the stack pointer \code{rsp} down by the size of the stack
  9264. frame for this function, which depends on the number of regular
  9265. spills. (Aligned to 16 bytes.)
  9266. \item Move the root stack pointer \code{r15} up by the size of the
  9267. root-stack frame for this function, which depends on the number of
  9268. spilled vectors. \label{root-stack-init}
  9269. \item Initialize to zero all of the entries in the root-stack frame.
  9270. \item Jump to the start block.
  9271. \end{enumerate}
  9272. The prelude of the \code{main} function has one additional task: call
  9273. the \code{initialize} function to set up the garbage collector and
  9274. move the value of the global \code{rootstack\_begin} in
  9275. \code{r15}. This should happen before step \ref{root-stack-init}
  9276. above, which depends on \code{r15}.
  9277. The conclusion of every function should do the following.
  9278. \begin{enumerate}
  9279. \item Move the stack pointer back up by the size of the stack frame
  9280. for this function.
  9281. \item Restore the callee-saved registers by popping them from the
  9282. stack.
  9283. \item Move the root stack pointer back down by the size of the
  9284. root-stack frame for this function.
  9285. \item Restore \code{rbp} by popping it from the stack.
  9286. \item Return to the caller with the \code{retq} instruction.
  9287. \end{enumerate}
  9288. \begin{exercise}\normalfont
  9289. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  9290. Create 5 new programs that use functions, including examples that pass
  9291. functions and return functions from other functions, recursive
  9292. functions, functions that create vectors, and functions that make tail
  9293. calls. Test your compiler on these new programs and all of your
  9294. previously created test programs.
  9295. \end{exercise}
  9296. \begin{figure}[tbp]
  9297. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9298. \node (Rfun) at (0,2) {\large \LangFun{}};
  9299. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  9300. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  9301. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  9302. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  9303. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  9304. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  9305. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  9306. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9307. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9308. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9309. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9310. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9311. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9312. \path[->,bend left=15] (Rfun) edge [above] node
  9313. {\ttfamily\footnotesize shrink} (Rfun-1);
  9314. \path[->,bend left=15] (Rfun-1) edge [above] node
  9315. {\ttfamily\footnotesize uniquify} (Rfun-2);
  9316. \path[->,bend left=15] (Rfun-2) edge [right] node
  9317. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  9318. \path[->,bend left=15] (F1-1) edge [below] node
  9319. {\ttfamily\footnotesize limit-functions} (F1-2);
  9320. \path[->,bend right=15] (F1-2) edge [above] node
  9321. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  9322. \path[->,bend right=15] (F1-3) edge [above] node
  9323. {\ttfamily\footnotesize remove-complex.} (F1-4);
  9324. \path[->,bend left=15] (F1-4) edge [right] node
  9325. {\ttfamily\footnotesize explicate-control} (C3-2);
  9326. \path[->,bend right=15] (C3-2) edge [left] node
  9327. {\ttfamily\footnotesize select-instr.} (x86-2);
  9328. \path[->,bend left=15] (x86-2) edge [left] node
  9329. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9330. \path[->,bend right=15] (x86-2-1) edge [below] node
  9331. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9332. \path[->,bend right=15] (x86-2-2) edge [left] node
  9333. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9334. \path[->,bend left=15] (x86-3) edge [above] node
  9335. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9336. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  9337. \end{tikzpicture}
  9338. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  9339. \label{fig:Rfun-passes}
  9340. \end{figure}
  9341. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  9342. compiling \LangFun{} to x86.
  9343. \section{An Example Translation}
  9344. \label{sec:functions-example}
  9345. Figure~\ref{fig:add-fun} shows an example translation of a simple
  9346. function in \LangFun{} to x86. The figure also includes the results of the
  9347. \code{explicate-control} and \code{select-instructions} passes.
  9348. \begin{figure}[htbp]
  9349. \begin{tabular}{ll}
  9350. \begin{minipage}{0.5\textwidth}
  9351. % s3_2.rkt
  9352. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9353. (define (add [x : Integer] [y : Integer])
  9354. : Integer
  9355. (+ x y))
  9356. (add 40 2)
  9357. \end{lstlisting}
  9358. $\Downarrow$
  9359. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9360. (define (add86 [x87 : Integer]
  9361. [y88 : Integer]) : Integer
  9362. add86start:
  9363. return (+ x87 y88);
  9364. )
  9365. (define (main) : Integer ()
  9366. mainstart:
  9367. tmp89 = (fun-ref add86);
  9368. (tail-call tmp89 40 2)
  9369. )
  9370. \end{lstlisting}
  9371. \end{minipage}
  9372. &
  9373. $\Rightarrow$
  9374. \begin{minipage}{0.5\textwidth}
  9375. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9376. (define (add86) : Integer
  9377. add86start:
  9378. movq %rdi, x87
  9379. movq %rsi, y88
  9380. movq x87, %rax
  9381. addq y88, %rax
  9382. jmp add11389conclusion
  9383. )
  9384. (define (main) : Integer
  9385. mainstart:
  9386. leaq (fun-ref add86), tmp89
  9387. movq $40, %rdi
  9388. movq $2, %rsi
  9389. tail-jmp tmp89
  9390. )
  9391. \end{lstlisting}
  9392. $\Downarrow$
  9393. \end{minipage}
  9394. \end{tabular}
  9395. \begin{tabular}{ll}
  9396. \begin{minipage}{0.3\textwidth}
  9397. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9398. .globl add86
  9399. .align 16
  9400. add86:
  9401. pushq %rbp
  9402. movq %rsp, %rbp
  9403. jmp add86start
  9404. add86start:
  9405. movq %rdi, %rax
  9406. addq %rsi, %rax
  9407. jmp add86conclusion
  9408. add86conclusion:
  9409. popq %rbp
  9410. retq
  9411. \end{lstlisting}
  9412. \end{minipage}
  9413. &
  9414. \begin{minipage}{0.5\textwidth}
  9415. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9416. .globl main
  9417. .align 16
  9418. main:
  9419. pushq %rbp
  9420. movq %rsp, %rbp
  9421. movq $16384, %rdi
  9422. movq $16384, %rsi
  9423. callq initialize
  9424. movq rootstack_begin(%rip), %r15
  9425. jmp mainstart
  9426. mainstart:
  9427. leaq add86(%rip), %rcx
  9428. movq $40, %rdi
  9429. movq $2, %rsi
  9430. movq %rcx, %rax
  9431. popq %rbp
  9432. jmp *%rax
  9433. mainconclusion:
  9434. popq %rbp
  9435. retq
  9436. \end{lstlisting}
  9437. \end{minipage}
  9438. \end{tabular}
  9439. \caption{Example compilation of a simple function to x86.}
  9440. \label{fig:add-fun}
  9441. \end{figure}
  9442. % Challenge idea: inlining! (simple version)
  9443. % Further Reading
  9444. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9445. \chapter{Lexically Scoped Functions}
  9446. \label{ch:Rlam}
  9447. \index{subject}{lambda}
  9448. \index{subject}{lexical scoping}
  9449. This chapter studies lexically scoped functions as they appear in
  9450. functional languages such as Racket. By lexical scoping we mean that a
  9451. function's body may refer to variables whose binding site is outside
  9452. of the function, in an enclosing scope.
  9453. %
  9454. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  9455. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  9456. \key{lambda} form. The body of the \key{lambda}, refers to three
  9457. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  9458. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  9459. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  9460. parameter of function \code{f}. The \key{lambda} is returned from the
  9461. function \code{f}. The main expression of the program includes two
  9462. calls to \code{f} with different arguments for \code{x}, first
  9463. \code{5} then \code{3}. The functions returned from \code{f} are bound
  9464. to variables \code{g} and \code{h}. Even though these two functions
  9465. were created by the same \code{lambda}, they are really different
  9466. functions because they use different values for \code{x}. Applying
  9467. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  9468. \code{15} produces \code{22}. The result of this program is \code{42}.
  9469. \begin{figure}[btp]
  9470. % s4_6.rkt
  9471. \begin{lstlisting}
  9472. (define (f [x : Integer]) : (Integer -> Integer)
  9473. (let ([y 4])
  9474. (lambda: ([z : Integer]) : Integer
  9475. (+ x (+ y z)))))
  9476. (let ([g (f 5)])
  9477. (let ([h (f 3)])
  9478. (+ (g 11) (h 15))))
  9479. \end{lstlisting}
  9480. \caption{Example of a lexically scoped function.}
  9481. \label{fig:lexical-scoping}
  9482. \end{figure}
  9483. The approach that we take for implementing lexically scoped
  9484. functions is to compile them into top-level function definitions,
  9485. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  9486. provide special treatment for variable occurrences such as \code{x}
  9487. and \code{y} in the body of the \code{lambda} of
  9488. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  9489. refer to variables defined outside of it. To identify such variable
  9490. occurrences, we review the standard notion of free variable.
  9491. \begin{definition}
  9492. A variable is \emph{free in expression} $e$ if the variable occurs
  9493. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  9494. variable}
  9495. \end{definition}
  9496. For example, in the expression \code{(+ x (+ y z))} the variables
  9497. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  9498. only \code{x} and \code{y} are free in the following expression
  9499. because \code{z} is bound by the \code{lambda}.
  9500. \begin{lstlisting}
  9501. (lambda: ([z : Integer]) : Integer
  9502. (+ x (+ y z)))
  9503. \end{lstlisting}
  9504. So the free variables of a \code{lambda} are the ones that will need
  9505. special treatment. We need to arrange for some way to transport, at
  9506. runtime, the values of those variables from the point where the
  9507. \code{lambda} was created to the point where the \code{lambda} is
  9508. applied. An efficient solution to the problem, due to
  9509. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  9510. free variables together with the function pointer for the lambda's
  9511. code, an arrangement called a \emph{flat closure} (which we shorten to
  9512. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  9513. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  9514. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  9515. pointers. The function pointer resides at index $0$ and the
  9516. values for the free variables will fill in the rest of the vector.
  9517. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  9518. how closures work. It's a three-step dance. The program first calls
  9519. function \code{f}, which creates a closure for the \code{lambda}. The
  9520. closure is a vector whose first element is a pointer to the top-level
  9521. function that we will generate for the \code{lambda}, the second
  9522. element is the value of \code{x}, which is \code{5}, and the third
  9523. element is \code{4}, the value of \code{y}. The closure does not
  9524. contain an element for \code{z} because \code{z} is not a free
  9525. variable of the \code{lambda}. Creating the closure is step 1 of the
  9526. dance. The closure is returned from \code{f} and bound to \code{g}, as
  9527. shown in Figure~\ref{fig:closures}.
  9528. %
  9529. The second call to \code{f} creates another closure, this time with
  9530. \code{3} in the second slot (for \code{x}). This closure is also
  9531. returned from \code{f} but bound to \code{h}, which is also shown in
  9532. Figure~\ref{fig:closures}.
  9533. \begin{figure}[tbp]
  9534. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  9535. \caption{Example closure representation for the \key{lambda}'s
  9536. in Figure~\ref{fig:lexical-scoping}.}
  9537. \label{fig:closures}
  9538. \end{figure}
  9539. Continuing with the example, consider the application of \code{g} to
  9540. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  9541. obtain the function pointer in the first element of the closure and
  9542. call it, passing in the closure itself and then the regular arguments,
  9543. in this case \code{11}. This technique for applying a closure is step
  9544. 2 of the dance.
  9545. %
  9546. But doesn't this \code{lambda} only take 1 argument, for parameter
  9547. \code{z}? The third and final step of the dance is generating a
  9548. top-level function for a \code{lambda}. We add an additional
  9549. parameter for the closure and we insert a \code{let} at the beginning
  9550. of the function for each free variable, to bind those variables to the
  9551. appropriate elements from the closure parameter.
  9552. %
  9553. This three-step dance is known as \emph{closure conversion}. We
  9554. discuss the details of closure conversion in
  9555. Section~\ref{sec:closure-conversion} and the code generated from the
  9556. example in Section~\ref{sec:example-lambda}. But first we define the
  9557. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  9558. \section{The \LangLam{} Language}
  9559. \label{sec:r5}
  9560. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  9561. functions and lexical scoping, is defined in
  9562. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  9563. the \key{lambda} form to the grammar for \LangFun{}, which already has
  9564. syntax for function application.
  9565. \begin{figure}[tp]
  9566. \centering
  9567. \fbox{
  9568. \begin{minipage}{0.96\textwidth}
  9569. \small
  9570. \[
  9571. \begin{array}{lcl}
  9572. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  9573. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  9574. \MID (\Type\ldots \; \key{->}\; \Type)} \\
  9575. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  9576. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  9577. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9578. &\MID& \gray{\key{\#t} \MID \key{\#f}
  9579. \MID (\key{and}\;\Exp\;\Exp)
  9580. \MID (\key{or}\;\Exp\;\Exp)
  9581. \MID (\key{not}\;\Exp) } \\
  9582. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9583. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  9584. (\key{vector-ref}\;\Exp\;\Int)} \\
  9585. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  9586. \MID (\Exp \; \Exp\ldots) } \\
  9587. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  9588. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  9589. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9590. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  9591. \end{array}
  9592. \]
  9593. \end{minipage}
  9594. }
  9595. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  9596. with \key{lambda}.}
  9597. \label{fig:Rlam-concrete-syntax}
  9598. \end{figure}
  9599. \begin{figure}[tp]
  9600. \centering
  9601. \fbox{
  9602. \begin{minipage}{0.96\textwidth}
  9603. \small
  9604. \[
  9605. \begin{array}{lcl}
  9606. \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  9607. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  9608. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9609. &\MID& \gray{ \BOOL{\itm{bool}}
  9610. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  9611. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  9612. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  9613. &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  9614. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9615. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9616. \end{array}
  9617. \]
  9618. \end{minipage}
  9619. }
  9620. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  9621. \label{fig:Rlam-syntax}
  9622. \end{figure}
  9623. \index{subject}{interpreter}
  9624. \label{sec:interp-Rlambda}
  9625. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  9626. \LangLam{}. The case for \key{lambda} saves the current environment
  9627. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  9628. the environment from the \key{lambda}, the \code{lam-env}, when
  9629. interpreting the body of the \key{lambda}. The \code{lam-env}
  9630. environment is extended with the mapping of parameters to argument
  9631. values.
  9632. \begin{figure}[tbp]
  9633. \begin{lstlisting}
  9634. (define interp-Rlambda-class
  9635. (class interp-Rfun-class
  9636. (super-new)
  9637. (define/override (interp-op op)
  9638. (match op
  9639. ['procedure-arity
  9640. (lambda (v)
  9641. (match v
  9642. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  9643. [else (error 'interp-op "expected a function, not ~a" v)]))]
  9644. [else (super interp-op op)]))
  9645. (define/override ((interp-exp env) e)
  9646. (define recur (interp-exp env))
  9647. (match e
  9648. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  9649. `(function ,xs ,body ,env)]
  9650. [else ((super interp-exp env) e)]))
  9651. ))
  9652. (define (interp-Rlambda p)
  9653. (send (new interp-Rlambda-class) interp-program p))
  9654. \end{lstlisting}
  9655. \caption{Interpreter for \LangLam{}.}
  9656. \label{fig:interp-Rlambda}
  9657. \end{figure}
  9658. \label{sec:type-check-r5}
  9659. \index{subject}{type checking}
  9660. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  9661. \key{lambda} form. The body of the \key{lambda} is checked in an
  9662. environment that includes the current environment (because it is
  9663. lexically scoped) and also includes the \key{lambda}'s parameters. We
  9664. require the body's type to match the declared return type.
  9665. \begin{figure}[tbp]
  9666. \begin{lstlisting}
  9667. (define (type-check-Rlambda env)
  9668. (lambda (e)
  9669. (match e
  9670. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  9671. (define-values (new-body bodyT)
  9672. ((type-check-exp (append (map cons xs Ts) env)) body))
  9673. (define ty `(,@Ts -> ,rT))
  9674. (cond
  9675. [(equal? rT bodyT)
  9676. (values (HasType (Lambda params rT new-body) ty) ty)]
  9677. [else
  9678. (error "mismatch in return type" bodyT rT)])]
  9679. ...
  9680. )))
  9681. \end{lstlisting}
  9682. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  9683. \label{fig:type-check-Rlambda}
  9684. \end{figure}
  9685. \section{Reveal Functions and the $F_2$ language}
  9686. \label{sec:reveal-functions-r5}
  9687. To support the \code{procedure-arity} operator we need to communicate
  9688. the arity of a function to the point of closure creation. We can
  9689. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  9690. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  9691. output of this pass is the language $F_2$, whose syntax is defined in
  9692. Figure~\ref{fig:f2-syntax}.
  9693. \begin{figure}[tp]
  9694. \centering
  9695. \fbox{
  9696. \begin{minipage}{0.96\textwidth}
  9697. \[
  9698. \begin{array}{lcl}
  9699. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  9700. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9701. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  9702. \end{array}
  9703. \]
  9704. \end{minipage}
  9705. }
  9706. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  9707. (Figure~\ref{fig:Rlam-syntax}).}
  9708. \label{fig:f2-syntax}
  9709. \end{figure}
  9710. \section{Closure Conversion}
  9711. \label{sec:closure-conversion}
  9712. \index{subject}{closure conversion}
  9713. The compiling of lexically-scoped functions into top-level function
  9714. definitions is accomplished in the pass \code{convert-to-closures}
  9715. that comes after \code{reveal-functions} and before
  9716. \code{limit-functions}.
  9717. As usual, we implement the pass as a recursive function over the
  9718. AST. All of the action is in the cases for \key{Lambda} and
  9719. \key{Apply}. We transform a \key{Lambda} expression into an expression
  9720. that creates a closure, that is, a vector whose first element is a
  9721. function pointer and the rest of the elements are the free variables
  9722. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  9723. using \code{vector} so that we can distinguish closures from vectors
  9724. in Section~\ref{sec:optimize-closures} and to record the arity. In
  9725. the generated code below, the \itm{name} is a unique symbol generated
  9726. to identify the function and the \itm{arity} is the number of
  9727. parameters (the length of \itm{ps}).
  9728. \begin{lstlisting}
  9729. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  9730. |$\Rightarrow$|
  9731. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  9732. \end{lstlisting}
  9733. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  9734. create a top-level function definition for each \key{Lambda}, as
  9735. shown below.\\
  9736. \begin{minipage}{0.8\textwidth}
  9737. \begin{lstlisting}
  9738. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  9739. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  9740. ...
  9741. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  9742. |\itm{body'}|)...))
  9743. \end{lstlisting}
  9744. \end{minipage}\\
  9745. The \code{clos} parameter refers to the closure. Translate the type
  9746. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  9747. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  9748. $\itm{fvts}$ are the types of the free variables in the lambda and the
  9749. underscore \code{\_} is a dummy type that we use because it is rather
  9750. difficult to give a type to the function in the closure's
  9751. type.\footnote{To give an accurate type to a closure, we would need to
  9752. add existential types to the type checker~\citep{Minamide:1996ys}.}
  9753. The dummy type is considered to be equal to any other type during type
  9754. checking. The sequence of \key{Let} forms bind the free variables to
  9755. their values obtained from the closure.
  9756. Closure conversion turns functions into vectors, so the type
  9757. annotations in the program must also be translated. We recommend
  9758. defining a auxiliary recursive function for this purpose. Function
  9759. types should be translated as follows.
  9760. \begin{lstlisting}
  9761. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  9762. |$\Rightarrow$|
  9763. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  9764. \end{lstlisting}
  9765. The above type says that the first thing in the vector is a function
  9766. pointer. The first parameter of the function pointer is a vector (a
  9767. closure) and the rest of the parameters are the ones from the original
  9768. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  9769. the closure omits the types of the free variables because 1) those
  9770. types are not available in this context and 2) we do not need them in
  9771. the code that is generated for function application.
  9772. We transform function application into code that retrieves the
  9773. function pointer from the closure and then calls the function, passing
  9774. in the closure as the first argument. We bind $e'$ to a temporary
  9775. variable to avoid code duplication.
  9776. \begin{lstlisting}
  9777. (Apply |$e$| |\itm{es}|)
  9778. |$\Rightarrow$|
  9779. (Let |\itm{tmp}| |$e'$|
  9780. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  9781. \end{lstlisting}
  9782. There is also the question of what to do with references top-level
  9783. function definitions. To maintain a uniform translation of function
  9784. application, we turn function references into closures.
  9785. \begin{tabular}{lll}
  9786. \begin{minipage}{0.3\textwidth}
  9787. \begin{lstlisting}
  9788. (FunRefArity |$f$| |$n$|)
  9789. \end{lstlisting}
  9790. \end{minipage}
  9791. &
  9792. $\Rightarrow$
  9793. &
  9794. \begin{minipage}{0.5\textwidth}
  9795. \begin{lstlisting}
  9796. (Closure |$n$| (FunRef |$f$|) '())
  9797. \end{lstlisting}
  9798. \end{minipage}
  9799. \end{tabular} \\
  9800. %
  9801. The top-level function definitions need to be updated as well to take
  9802. an extra closure parameter.
  9803. \section{An Example Translation}
  9804. \label{sec:example-lambda}
  9805. Figure~\ref{fig:lexical-functions-example} shows the result of
  9806. \code{reveal-functions} and \code{convert-to-closures} for the example
  9807. program demonstrating lexical scoping that we discussed at the
  9808. beginning of this chapter.
  9809. \begin{figure}[tbp]
  9810. \begin{minipage}{0.8\textwidth}
  9811. % tests/lambda_test_6.rkt
  9812. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9813. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  9814. (let ([y8 4])
  9815. (lambda: ([z9 : Integer]) : Integer
  9816. (+ x7 (+ y8 z9)))))
  9817. (define (main) : Integer
  9818. (let ([g0 ((fun-ref-arity f6 1) 5)])
  9819. (let ([h1 ((fun-ref-arity f6 1) 3)])
  9820. (+ (g0 11) (h1 15)))))
  9821. \end{lstlisting}
  9822. $\Rightarrow$
  9823. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9824. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  9825. (let ([y8 4])
  9826. (closure 1 (list (fun-ref lambda2) x7 y8))))
  9827. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  9828. (let ([x7 (vector-ref fvs3 1)])
  9829. (let ([y8 (vector-ref fvs3 2)])
  9830. (+ x7 (+ y8 z9)))))
  9831. (define (main) : Integer
  9832. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  9833. ((vector-ref clos5 0) clos5 5))])
  9834. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  9835. ((vector-ref clos6 0) clos6 3))])
  9836. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  9837. \end{lstlisting}
  9838. \end{minipage}
  9839. \caption{Example of closure conversion.}
  9840. \label{fig:lexical-functions-example}
  9841. \end{figure}
  9842. \begin{exercise}\normalfont
  9843. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  9844. Create 5 new programs that use \key{lambda} functions and make use of
  9845. lexical scoping. Test your compiler on these new programs and all of
  9846. your previously created test programs.
  9847. \end{exercise}
  9848. \section{Expose Allocation}
  9849. \label{sec:expose-allocation-r5}
  9850. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  9851. that allocates and initializes a vector, similar to the translation of
  9852. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  9853. The only difference is replacing the use of
  9854. \ALLOC{\itm{len}}{\itm{type}} with
  9855. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  9856. \section{Explicate Control and \LangCLam{}}
  9857. \label{sec:explicate-r5}
  9858. The output language of \code{explicate-control} is \LangCLam{} whose
  9859. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  9860. difference with respect to \LangCFun{} is the addition of the
  9861. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  9862. of \code{AllocateClosure} in the \code{explicate-control} pass is
  9863. similar to the handling of other expressions such as primitive
  9864. operators.
  9865. \begin{figure}[tp]
  9866. \fbox{
  9867. \begin{minipage}{0.96\textwidth}
  9868. \small
  9869. \[
  9870. \begin{array}{lcl}
  9871. \Exp &::= & \ldots
  9872. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  9873. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9874. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9875. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  9876. \MID \GOTO{\itm{label}} } \\
  9877. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9878. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  9879. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9880. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9881. \end{array}
  9882. \]
  9883. \end{minipage}
  9884. }
  9885. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  9886. \label{fig:c4-syntax}
  9887. \end{figure}
  9888. \section{Select Instructions}
  9889. \label{sec:select-instructions-Rlambda}
  9890. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  9891. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  9892. (Section~\ref{sec:select-instructions-gc}). The only difference is
  9893. that you should place the \itm{arity} in the tag that is stored at
  9894. position $0$ of the vector. Recall that in
  9895. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  9896. was not used. We store the arity in the $5$ bits starting at position
  9897. $58$.
  9898. Compile the \code{procedure-arity} operator into a sequence of
  9899. instructions that access the tag from position $0$ of the vector and
  9900. extract the $5$-bits starting at position $58$ from the tag.
  9901. \begin{figure}[p]
  9902. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9903. \node (Rfun) at (0,2) {\large \LangFun{}};
  9904. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  9905. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  9906. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  9907. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  9908. \node (F1-3) at (6,0) {\large $F_1$};
  9909. \node (F1-4) at (3,0) {\large $F_1$};
  9910. \node (F1-5) at (0,0) {\large $F_1$};
  9911. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  9912. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9913. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9914. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9915. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9916. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9917. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9918. \path[->,bend left=15] (Rfun) edge [above] node
  9919. {\ttfamily\footnotesize shrink} (Rfun-2);
  9920. \path[->,bend left=15] (Rfun-2) edge [above] node
  9921. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9922. \path[->,bend left=15] (Rfun-3) edge [right] node
  9923. {\ttfamily\footnotesize reveal-functions} (F1-1);
  9924. \path[->,bend left=15] (F1-1) edge [below] node
  9925. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9926. \path[->,bend right=15] (F1-2) edge [above] node
  9927. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9928. \path[->,bend right=15] (F1-3) edge [above] node
  9929. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9930. \path[->,bend right=15] (F1-4) edge [above] node
  9931. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9932. \path[->,bend right=15] (F1-5) edge [right] node
  9933. {\ttfamily\footnotesize explicate-control} (C3-2);
  9934. \path[->,bend left=15] (C3-2) edge [left] node
  9935. {\ttfamily\footnotesize select-instr.} (x86-2);
  9936. \path[->,bend right=15] (x86-2) edge [left] node
  9937. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9938. \path[->,bend right=15] (x86-2-1) edge [below] node
  9939. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9940. \path[->,bend right=15] (x86-2-2) edge [left] node
  9941. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9942. \path[->,bend left=15] (x86-3) edge [above] node
  9943. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9944. \path[->,bend left=15] (x86-4) edge [right] node
  9945. {\ttfamily\footnotesize print-x86} (x86-5);
  9946. \end{tikzpicture}
  9947. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  9948. functions.}
  9949. \label{fig:Rlambda-passes}
  9950. \end{figure}
  9951. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  9952. for the compilation of \LangLam{}.
  9953. \clearpage
  9954. \section{Challenge: Optimize Closures}
  9955. \label{sec:optimize-closures}
  9956. In this chapter we compiled lexically-scoped functions into a
  9957. relatively efficient representation: flat closures. However, even this
  9958. representation comes with some overhead. For example, consider the
  9959. following program with a function \code{tail-sum} that does not have
  9960. any free variables and where all the uses of \code{tail-sum} are in
  9961. applications where we know that only \code{tail-sum} is being applied
  9962. (and not any other functions).
  9963. \begin{center}
  9964. \begin{minipage}{0.95\textwidth}
  9965. \begin{lstlisting}
  9966. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  9967. (if (eq? n 0)
  9968. r
  9969. (tail-sum (- n 1) (+ n r))))
  9970. (+ (tail-sum 5 0) 27)
  9971. \end{lstlisting}
  9972. \end{minipage}
  9973. \end{center}
  9974. As described in this chapter, we uniformly apply closure conversion to
  9975. all functions, obtaining the following output for this program.
  9976. \begin{center}
  9977. \begin{minipage}{0.95\textwidth}
  9978. \begin{lstlisting}
  9979. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  9980. (if (eq? n2 0)
  9981. r3
  9982. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  9983. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  9984. (define (main) : Integer
  9985. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  9986. ((vector-ref clos6 0) clos6 5 0)) 27))
  9987. \end{lstlisting}
  9988. \end{minipage}
  9989. \end{center}
  9990. In the previous Chapter, there would be no allocation in the program
  9991. and the calls to \code{tail-sum} would be direct calls. In contrast,
  9992. the above program allocates memory for each \code{closure} and the
  9993. calls to \code{tail-sum} are indirect. These two differences incur
  9994. considerable overhead in a program such as this one, where the
  9995. allocations and indirect calls occur inside a tight loop.
  9996. One might think that this problem is trivial to solve: can't we just
  9997. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  9998. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  9999. e'_n$)} instead of treating it like a call to a closure? We would
  10000. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  10001. %
  10002. However, this problem is not so trivial because a global function may
  10003. ``escape'' and become involved in applications that also involve
  10004. closures. Consider the following example in which the application
  10005. \code{(f 41)} needs to be compiled into a closure application, because
  10006. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  10007. function might also get bound to \code{f}.
  10008. \begin{lstlisting}
  10009. (define (add1 [x : Integer]) : Integer
  10010. (+ x 1))
  10011. (let ([y (read)])
  10012. (let ([f (if (eq? (read) 0)
  10013. add1
  10014. (lambda: ([x : Integer]) : Integer (- x y)))])
  10015. (f 41)))
  10016. \end{lstlisting}
  10017. If a global function name is used in any way other than as the
  10018. operator in a direct call, then we say that the function
  10019. \emph{escapes}. If a global function does not escape, then we do not
  10020. need to perform closure conversion on the function.
  10021. \begin{exercise}\normalfont
  10022. Implement an auxiliary function for detecting which global
  10023. functions escape. Using that function, implement an improved version
  10024. of closure conversion that does not apply closure conversion to
  10025. global functions that do not escape but instead compiles them as
  10026. regular functions. Create several new test cases that check whether
  10027. you properly detect whether global functions escape or not.
  10028. \end{exercise}
  10029. So far we have reduced the overhead of calling global functions, but
  10030. it would also be nice to reduce the overhead of calling a
  10031. \code{lambda} when we can determine at compile time which
  10032. \code{lambda} will be called. We refer to such calls as \emph{known
  10033. calls}. Consider the following example in which a \code{lambda} is
  10034. bound to \code{f} and then applied.
  10035. \begin{lstlisting}
  10036. (let ([y (read)])
  10037. (let ([f (lambda: ([x : Integer]) : Integer
  10038. (+ x y))])
  10039. (f 21)))
  10040. \end{lstlisting}
  10041. Closure conversion compiles \code{(f 21)} into an indirect call:
  10042. \begin{lstlisting}
  10043. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  10044. (let ([y2 (vector-ref fvs6 1)])
  10045. (+ x3 y2)))
  10046. (define (main) : Integer
  10047. (let ([y2 (read)])
  10048. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  10049. ((vector-ref f4 0) f4 21))))
  10050. \end{lstlisting}
  10051. but we can instead compile the application \code{(f 21)} into a direct call
  10052. to \code{lambda5}:
  10053. \begin{lstlisting}
  10054. (define (main) : Integer
  10055. (let ([y2 (read)])
  10056. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  10057. ((fun-ref lambda5) f4 21))))
  10058. \end{lstlisting}
  10059. The problem of determining which lambda will be called from a
  10060. particular application is quite challenging in general and the topic
  10061. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  10062. following exercise we recommend that you compile an application to a
  10063. direct call when the operator is a variable and the variable is
  10064. \code{let}-bound to a closure. This can be accomplished by maintaining
  10065. an environment mapping \code{let}-bound variables to function names.
  10066. Extend the environment whenever you encounter a closure on the
  10067. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  10068. to the name of the global function for the closure. This pass should
  10069. come after closure conversion.
  10070. \begin{exercise}\normalfont
  10071. Implement a compiler pass, named \code{optimize-known-calls}, that
  10072. compiles known calls into direct calls. Verify that your compiler is
  10073. successful in this regard on several example programs.
  10074. \end{exercise}
  10075. These exercises only scratches the surface of optimizing of
  10076. closures. A good next step for the interested reader is to look at the
  10077. work of \citet{Keep:2012ab}.
  10078. \section{Further Reading}
  10079. The notion of lexically scoped anonymous functions predates modern
  10080. computers by about a decade. They were invented by
  10081. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  10082. foundation for logic. Anonymous functions were included in the
  10083. LISP~\citep{McCarthy:1960dz} programming language but were initially
  10084. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  10085. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  10086. compile Scheme programs. However, environments were represented as
  10087. linked lists, so variable lookup was linear in the size of the
  10088. environment. In this chapter we represent environments using flat
  10089. closures, which were invented by
  10090. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  10091. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  10092. closures, variable lookup is constant time but the time to create a
  10093. closure is proportional to the number of its free variables. Flat
  10094. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  10095. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  10096. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10097. \chapter{Dynamic Typing}
  10098. \label{ch:Rdyn}
  10099. \index{subject}{dynamic typing}
  10100. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  10101. typed language that is a subset of Racket. This is in contrast to the
  10102. previous chapters, which have studied the compilation of Typed
  10103. Racket. In dynamically typed languages such as \LangDyn{}, a given
  10104. expression may produce a value of a different type each time it is
  10105. executed. Consider the following example with a conditional \code{if}
  10106. expression that may return a Boolean or an integer depending on the
  10107. input to the program.
  10108. % part of dynamic_test_25.rkt
  10109. \begin{lstlisting}
  10110. (not (if (eq? (read) 1) #f 0))
  10111. \end{lstlisting}
  10112. Languages that allow expressions to produce different kinds of values
  10113. are called \emph{polymorphic}, a word composed of the Greek roots
  10114. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  10115. are several kinds of polymorphism in programming languages, such as
  10116. subtype polymorphism and parametric
  10117. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  10118. study in this chapter does not have a special name but it is the kind
  10119. that arises in dynamically typed languages.
  10120. Another characteristic of dynamically typed languages is that
  10121. primitive operations, such as \code{not}, are often defined to operate
  10122. on many different types of values. In fact, in Racket, the \code{not}
  10123. operator produces a result for any kind of value: given \code{\#f} it
  10124. returns \code{\#t} and given anything else it returns \code{\#f}.
  10125. Furthermore, even when primitive operations restrict their inputs to
  10126. values of a certain type, this restriction is enforced at runtime
  10127. instead of during compilation. For example, the following vector
  10128. reference results in a run-time contract violation because the index
  10129. must be in integer, not a Boolean such as \code{\#t}.
  10130. \begin{lstlisting}
  10131. (vector-ref (vector 42) #t)
  10132. \end{lstlisting}
  10133. \begin{figure}[tp]
  10134. \centering
  10135. \fbox{
  10136. \begin{minipage}{0.97\textwidth}
  10137. \[
  10138. \begin{array}{rcl}
  10139. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  10140. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  10141. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  10142. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  10143. &\MID& \key{\#t} \MID \key{\#f}
  10144. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  10145. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  10146. \MID \CUNIOP{\key{not}}{\Exp} \\
  10147. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  10148. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  10149. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  10150. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  10151. &\MID& \LP\Exp \; \Exp\ldots\RP
  10152. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  10153. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  10154. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  10155. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  10156. \LangDynM{} &::=& \Def\ldots\; \Exp
  10157. \end{array}
  10158. \]
  10159. \end{minipage}
  10160. }
  10161. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  10162. \label{fig:r7-concrete-syntax}
  10163. \end{figure}
  10164. \begin{figure}[tp]
  10165. \centering
  10166. \fbox{
  10167. \begin{minipage}{0.96\textwidth}
  10168. \small
  10169. \[
  10170. \begin{array}{lcl}
  10171. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  10172. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  10173. &\MID& \BOOL{\itm{bool}}
  10174. \MID \IF{\Exp}{\Exp}{\Exp} \\
  10175. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  10176. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  10177. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  10178. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  10179. \end{array}
  10180. \]
  10181. \end{minipage}
  10182. }
  10183. \caption{The abstract syntax of \LangDyn{}.}
  10184. \label{fig:r7-syntax}
  10185. \end{figure}
  10186. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  10187. defined in Figures~\ref{fig:r7-concrete-syntax} and
  10188. \ref{fig:r7-syntax}.
  10189. %
  10190. There is no type checker for \LangDyn{} because it is not a statically
  10191. typed language (it's dynamically typed!).
  10192. The definitional interpreter for \LangDyn{} is presented in
  10193. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  10194. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  10195. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  10196. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  10197. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  10198. value} that combines an underlying value with a tag that identifies
  10199. what kind of value it is. We define the following struct
  10200. to represented tagged values.
  10201. \begin{lstlisting}
  10202. (struct Tagged (value tag) #:transparent)
  10203. \end{lstlisting}
  10204. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  10205. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  10206. but don't always capture all the information that a type does. For
  10207. example, a vector of type \code{(Vector Any Any)} is tagged with
  10208. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  10209. is tagged with \code{Procedure}.
  10210. Next consider the match case for \code{vector-ref}. The
  10211. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  10212. is used to ensure that the first argument is a vector and the second
  10213. is an integer. If they are not, a \code{trapped-error} is raised.
  10214. Recall from Section~\ref{sec:interp_Rint} that when a definition
  10215. interpreter raises a \code{trapped-error} error, the compiled code
  10216. must also signal an error by exiting with return code \code{255}. A
  10217. \code{trapped-error} is also raised if the index is not less than
  10218. length of the vector.
  10219. \begin{figure}[tbp]
  10220. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10221. (define ((interp-Rdyn-exp env) ast)
  10222. (define recur (interp-Rdyn-exp env))
  10223. (match ast
  10224. [(Var x) (lookup x env)]
  10225. [(Int n) (Tagged n 'Integer)]
  10226. [(Bool b) (Tagged b 'Boolean)]
  10227. [(Lambda xs rt body)
  10228. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  10229. [(Prim 'vector es)
  10230. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  10231. [(Prim 'vector-ref (list e1 e2))
  10232. (define vec (recur e1)) (define i (recur e2))
  10233. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  10234. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  10235. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  10236. (vector-ref (Tagged-value vec) (Tagged-value i))]
  10237. [(Prim 'vector-set! (list e1 e2 e3))
  10238. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  10239. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  10240. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  10241. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  10242. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  10243. (Tagged (void) 'Void)]
  10244. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  10245. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  10246. [(Prim 'or (list e1 e2))
  10247. (define v1 (recur e1))
  10248. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  10249. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  10250. [(Prim op (list e1))
  10251. #:when (set-member? type-predicates op)
  10252. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  10253. [(Prim op es)
  10254. (define args (map recur es))
  10255. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  10256. (unless (for/or ([expected-tags (op-tags op)])
  10257. (equal? expected-tags tags))
  10258. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  10259. (tag-value
  10260. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  10261. [(If q t f)
  10262. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  10263. [(Apply f es)
  10264. (define new-f (recur f)) (define args (map recur es))
  10265. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  10266. (match f-val
  10267. [`(function ,xs ,body ,lam-env)
  10268. (unless (eq? (length xs) (length args))
  10269. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  10270. (define new-env (append (map cons xs args) lam-env))
  10271. ((interp-Rdyn-exp new-env) body)]
  10272. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  10273. \end{lstlisting}
  10274. \caption{Interpreter for the \LangDyn{} language.}
  10275. \label{fig:interp-Rdyn}
  10276. \end{figure}
  10277. \begin{figure}[tbp]
  10278. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10279. (define (interp-op op)
  10280. (match op
  10281. ['+ fx+]
  10282. ['- fx-]
  10283. ['read read-fixnum]
  10284. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  10285. ['< (lambda (v1 v2)
  10286. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  10287. ['<= (lambda (v1 v2)
  10288. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  10289. ['> (lambda (v1 v2)
  10290. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  10291. ['>= (lambda (v1 v2)
  10292. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  10293. ['boolean? boolean?]
  10294. ['integer? fixnum?]
  10295. ['void? void?]
  10296. ['vector? vector?]
  10297. ['vector-length vector-length]
  10298. ['procedure? (match-lambda
  10299. [`(functions ,xs ,body ,env) #t] [else #f])]
  10300. [else (error 'interp-op "unknown operator" op)]))
  10301. (define (op-tags op)
  10302. (match op
  10303. ['+ '((Integer Integer))]
  10304. ['- '((Integer Integer) (Integer))]
  10305. ['read '(())]
  10306. ['not '((Boolean))]
  10307. ['< '((Integer Integer))]
  10308. ['<= '((Integer Integer))]
  10309. ['> '((Integer Integer))]
  10310. ['>= '((Integer Integer))]
  10311. ['vector-length '((Vector))]))
  10312. (define type-predicates
  10313. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  10314. (define (tag-value v)
  10315. (cond [(boolean? v) (Tagged v 'Boolean)]
  10316. [(fixnum? v) (Tagged v 'Integer)]
  10317. [(procedure? v) (Tagged v 'Procedure)]
  10318. [(vector? v) (Tagged v 'Vector)]
  10319. [(void? v) (Tagged v 'Void)]
  10320. [else (error 'tag-value "unidentified value ~a" v)]))
  10321. (define (check-tag val expected ast)
  10322. (define tag (Tagged-tag val))
  10323. (unless (eq? tag expected)
  10324. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  10325. \end{lstlisting}
  10326. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  10327. \label{fig:interp-Rdyn-aux}
  10328. \end{figure}
  10329. \clearpage
  10330. \section{Representation of Tagged Values}
  10331. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  10332. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  10333. values at the bit level. Because almost every operation in \LangDyn{}
  10334. involves manipulating tagged values, the representation must be
  10335. efficient. Recall that all of our values are 64 bits. We shall steal
  10336. the 3 right-most bits to encode the tag. We use $001$ to identify
  10337. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  10338. and $101$ for the void value. We define the following auxiliary
  10339. function for mapping types to tag codes.
  10340. \begin{align*}
  10341. \itm{tagof}(\key{Integer}) &= 001 \\
  10342. \itm{tagof}(\key{Boolean}) &= 100 \\
  10343. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  10344. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  10345. \itm{tagof}(\key{Void}) &= 101
  10346. \end{align*}
  10347. This stealing of 3 bits comes at some price: our integers are reduced
  10348. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  10349. affect vectors and procedures because those values are addresses, and
  10350. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  10351. they are always $000$. Thus, we do not lose information by overwriting
  10352. the rightmost 3 bits with the tag and we can simply zero-out the tag
  10353. to recover the original address.
  10354. To make tagged values into first-class entities, we can give them a
  10355. type, called \code{Any}, and define operations such as \code{Inject}
  10356. and \code{Project} for creating and using them, yielding the \LangAny{}
  10357. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  10358. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  10359. in greater detail.
  10360. \section{The \LangAny{} Language}
  10361. \label{sec:Rany-lang}
  10362. \begin{figure}[tp]
  10363. \centering
  10364. \fbox{
  10365. \begin{minipage}{0.96\textwidth}
  10366. \small
  10367. \[
  10368. \begin{array}{lcl}
  10369. \Type &::= & \ldots \MID \key{Any} \\
  10370. \itm{op} &::= & \ldots \MID \code{any-vector-length}
  10371. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  10372. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  10373. \MID \code{procedure?} \MID \code{void?} \\
  10374. \Exp &::=& \ldots
  10375. \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  10376. &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  10377. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  10378. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10379. \end{array}
  10380. \]
  10381. \end{minipage}
  10382. }
  10383. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  10384. \label{fig:Rany-syntax}
  10385. \end{figure}
  10386. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  10387. (The concrete syntax of \LangAny{} is in the Appendix,
  10388. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  10389. converts the value produced by expression $e$ of type $T$ into a
  10390. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  10391. produced by expression $e$ into a value of type $T$ or else halts the
  10392. program if the type tag is not equivalent to $T$.
  10393. %
  10394. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  10395. restricted to a flat type $\FType$, which simplifies the
  10396. implementation and corresponds with what is needed for compiling \LangDyn{}.
  10397. The \code{any-vector} operators adapt the vector operations so that
  10398. they can be applied to a value of type \code{Any}. They also
  10399. generalize the vector operations in that the index is not restricted
  10400. to be a literal integer in the grammar but is allowed to be any
  10401. expression.
  10402. The type predicates such as \key{boolean?} expect their argument to
  10403. produce a tagged value; they return \key{\#t} if the tag corresponds
  10404. to the predicate and they return \key{\#f} otherwise.
  10405. The type checker for \LangAny{} is shown in
  10406. Figures~\ref{fig:type-check-Rany-part-1} and
  10407. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  10408. Figure~\ref{fig:type-check-Rany-aux}.
  10409. %
  10410. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  10411. auxiliary functions \code{apply-inject} and \code{apply-project} are
  10412. in Figure~\ref{fig:apply-project}.
  10413. \begin{figure}[btp]
  10414. \begin{lstlisting}[basicstyle=\ttfamily\small]
  10415. (define type-check-Rany-class
  10416. (class type-check-Rlambda-class
  10417. (super-new)
  10418. (inherit check-type-equal?)
  10419. (define/override (type-check-exp env)
  10420. (lambda (e)
  10421. (define recur (type-check-exp env))
  10422. (match e
  10423. [(Inject e1 ty)
  10424. (unless (flat-ty? ty)
  10425. (error 'type-check "may only inject from flat type, not ~a" ty))
  10426. (define-values (new-e1 e-ty) (recur e1))
  10427. (check-type-equal? e-ty ty e)
  10428. (values (Inject new-e1 ty) 'Any)]
  10429. [(Project e1 ty)
  10430. (unless (flat-ty? ty)
  10431. (error 'type-check "may only project to flat type, not ~a" ty))
  10432. (define-values (new-e1 e-ty) (recur e1))
  10433. (check-type-equal? e-ty 'Any e)
  10434. (values (Project new-e1 ty) ty)]
  10435. [(Prim 'any-vector-length (list e1))
  10436. (define-values (e1^ t1) (recur e1))
  10437. (check-type-equal? t1 'Any e)
  10438. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  10439. [(Prim 'any-vector-ref (list e1 e2))
  10440. (define-values (e1^ t1) (recur e1))
  10441. (define-values (e2^ t2) (recur e2))
  10442. (check-type-equal? t1 'Any e)
  10443. (check-type-equal? t2 'Integer e)
  10444. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  10445. [(Prim 'any-vector-set! (list e1 e2 e3))
  10446. (define-values (e1^ t1) (recur e1))
  10447. (define-values (e2^ t2) (recur e2))
  10448. (define-values (e3^ t3) (recur e3))
  10449. (check-type-equal? t1 'Any e)
  10450. (check-type-equal? t2 'Integer e)
  10451. (check-type-equal? t3 'Any e)
  10452. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  10453. \end{lstlisting}
  10454. \caption{Type checker for the \LangAny{} language, part 1.}
  10455. \label{fig:type-check-Rany-part-1}
  10456. \end{figure}
  10457. \begin{figure}[btp]
  10458. \begin{lstlisting}[basicstyle=\ttfamily\small]
  10459. [(ValueOf e ty)
  10460. (define-values (new-e e-ty) (recur e))
  10461. (values (ValueOf new-e ty) ty)]
  10462. [(Prim pred (list e1))
  10463. #:when (set-member? (type-predicates) pred)
  10464. (define-values (new-e1 e-ty) (recur e1))
  10465. (check-type-equal? e-ty 'Any e)
  10466. (values (Prim pred (list new-e1)) 'Boolean)]
  10467. [(If cnd thn els)
  10468. (define-values (cnd^ Tc) (recur cnd))
  10469. (define-values (thn^ Tt) (recur thn))
  10470. (define-values (els^ Te) (recur els))
  10471. (check-type-equal? Tc 'Boolean cnd)
  10472. (check-type-equal? Tt Te e)
  10473. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  10474. [(Exit) (values (Exit) '_)]
  10475. [(Prim 'eq? (list arg1 arg2))
  10476. (define-values (e1 t1) (recur arg1))
  10477. (define-values (e2 t2) (recur arg2))
  10478. (match* (t1 t2)
  10479. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10480. [(other wise) (check-type-equal? t1 t2 e)])
  10481. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10482. [else ((super type-check-exp env) e)])))
  10483. ))
  10484. \end{lstlisting}
  10485. \caption{Type checker for the \LangAny{} language, part 2.}
  10486. \label{fig:type-check-Rany-part-2}
  10487. \end{figure}
  10488. \begin{figure}[tbp]
  10489. \begin{lstlisting}
  10490. (define/override (operator-types)
  10491. (append
  10492. '((integer? . ((Any) . Boolean))
  10493. (vector? . ((Any) . Boolean))
  10494. (procedure? . ((Any) . Boolean))
  10495. (void? . ((Any) . Boolean))
  10496. (tag-of-any . ((Any) . Integer))
  10497. (make-any . ((_ Integer) . Any))
  10498. )
  10499. (super operator-types)))
  10500. (define/public (type-predicates)
  10501. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  10502. (define/public (combine-types t1 t2)
  10503. (match (list t1 t2)
  10504. [(list '_ t2) t2]
  10505. [(list t1 '_) t1]
  10506. [(list `(Vector ,ts1 ...)
  10507. `(Vector ,ts2 ...))
  10508. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  10509. (combine-types t1 t2)))]
  10510. [(list `(,ts1 ... -> ,rt1)
  10511. `(,ts2 ... -> ,rt2))
  10512. `(,@(for/list ([t1 ts1] [t2 ts2])
  10513. (combine-types t1 t2))
  10514. -> ,(combine-types rt1 rt2))]
  10515. [else t1]))
  10516. (define/public (flat-ty? ty)
  10517. (match ty
  10518. [(or `Integer `Boolean '_ `Void) #t]
  10519. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  10520. [`(,ts ... -> ,rt)
  10521. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  10522. [else #f]))
  10523. \end{lstlisting}
  10524. \caption{Auxiliary methods for type checking \LangAny{}.}
  10525. \label{fig:type-check-Rany-aux}
  10526. \end{figure}
  10527. \begin{figure}[btp]
  10528. \begin{lstlisting}
  10529. (define interp-Rany-class
  10530. (class interp-Rlambda-class
  10531. (super-new)
  10532. (define/override (interp-op op)
  10533. (match op
  10534. ['boolean? (match-lambda
  10535. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  10536. [else #f])]
  10537. ['integer? (match-lambda
  10538. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  10539. [else #f])]
  10540. ['vector? (match-lambda
  10541. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  10542. [else #f])]
  10543. ['procedure? (match-lambda
  10544. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  10545. [else #f])]
  10546. ['eq? (match-lambda*
  10547. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  10548. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  10549. [ls (apply (super interp-op op) ls)])]
  10550. ['any-vector-ref (lambda (v i)
  10551. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  10552. ['any-vector-set! (lambda (v i a)
  10553. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  10554. ['any-vector-length (lambda (v)
  10555. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  10556. [else (super interp-op op)]))
  10557. (define/override ((interp-exp env) e)
  10558. (define recur (interp-exp env))
  10559. (match e
  10560. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  10561. [(Project e ty2) (apply-project (recur e) ty2)]
  10562. [else ((super interp-exp env) e)]))
  10563. ))
  10564. (define (interp-Rany p)
  10565. (send (new interp-Rany-class) interp-program p))
  10566. \end{lstlisting}
  10567. \caption{Interpreter for \LangAny{}.}
  10568. \label{fig:interp-Rany}
  10569. \end{figure}
  10570. \begin{figure}[tbp]
  10571. \begin{lstlisting}
  10572. (define/public (apply-inject v tg) (Tagged v tg))
  10573. (define/public (apply-project v ty2)
  10574. (define tag2 (any-tag ty2))
  10575. (match v
  10576. [(Tagged v1 tag1)
  10577. (cond
  10578. [(eq? tag1 tag2)
  10579. (match ty2
  10580. [`(Vector ,ts ...)
  10581. (define l1 ((interp-op 'vector-length) v1))
  10582. (cond
  10583. [(eq? l1 (length ts)) v1]
  10584. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  10585. l1 (length ts))])]
  10586. [`(,ts ... -> ,rt)
  10587. (match v1
  10588. [`(function ,xs ,body ,env)
  10589. (cond [(eq? (length xs) (length ts)) v1]
  10590. [else
  10591. (error 'apply-project "arity mismatch ~a != ~a"
  10592. (length xs) (length ts))])]
  10593. [else (error 'apply-project "expected function not ~a" v1)])]
  10594. [else v1])]
  10595. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  10596. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  10597. \end{lstlisting}
  10598. \caption{Auxiliary functions for injection and projection.}
  10599. \label{fig:apply-project}
  10600. \end{figure}
  10601. \clearpage
  10602. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  10603. \label{sec:compile-r7}
  10604. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  10605. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  10606. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  10607. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  10608. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  10609. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  10610. the Boolean \code{\#t}, which must be injected to produce an
  10611. expression of type \key{Any}.
  10612. %
  10613. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  10614. addition, is representative of compilation for many primitive
  10615. operations: the arguments have type \key{Any} and must be projected to
  10616. \key{Integer} before the addition can be performed.
  10617. The compilation of \key{lambda} (third row of
  10618. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  10619. produce type annotations: we simply use \key{Any}.
  10620. %
  10621. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  10622. has to account for some differences in behavior between \LangDyn{} and
  10623. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  10624. kind of values can be used in various places. For example, the
  10625. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  10626. the arguments need not be of the same type (in that case the
  10627. result is \code{\#f}).
  10628. \begin{figure}[btp]
  10629. \centering
  10630. \begin{tabular}{|lll|} \hline
  10631. \begin{minipage}{0.27\textwidth}
  10632. \begin{lstlisting}
  10633. #t
  10634. \end{lstlisting}
  10635. \end{minipage}
  10636. &
  10637. $\Rightarrow$
  10638. &
  10639. \begin{minipage}{0.65\textwidth}
  10640. \begin{lstlisting}
  10641. (inject #t Boolean)
  10642. \end{lstlisting}
  10643. \end{minipage}
  10644. \\[2ex]\hline
  10645. \begin{minipage}{0.27\textwidth}
  10646. \begin{lstlisting}
  10647. (+ |$e_1$| |$e_2$|)
  10648. \end{lstlisting}
  10649. \end{minipage}
  10650. &
  10651. $\Rightarrow$
  10652. &
  10653. \begin{minipage}{0.65\textwidth}
  10654. \begin{lstlisting}
  10655. (inject
  10656. (+ (project |$e'_1$| Integer)
  10657. (project |$e'_2$| Integer))
  10658. Integer)
  10659. \end{lstlisting}
  10660. \end{minipage}
  10661. \\[2ex]\hline
  10662. \begin{minipage}{0.27\textwidth}
  10663. \begin{lstlisting}
  10664. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  10665. \end{lstlisting}
  10666. \end{minipage}
  10667. &
  10668. $\Rightarrow$
  10669. &
  10670. \begin{minipage}{0.65\textwidth}
  10671. \begin{lstlisting}
  10672. (inject
  10673. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  10674. (Any|$\ldots$|Any -> Any))
  10675. \end{lstlisting}
  10676. \end{minipage}
  10677. \\[2ex]\hline
  10678. \begin{minipage}{0.27\textwidth}
  10679. \begin{lstlisting}
  10680. (|$e_0$| |$e_1 \ldots e_n$|)
  10681. \end{lstlisting}
  10682. \end{minipage}
  10683. &
  10684. $\Rightarrow$
  10685. &
  10686. \begin{minipage}{0.65\textwidth}
  10687. \begin{lstlisting}
  10688. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  10689. \end{lstlisting}
  10690. \end{minipage}
  10691. \\[2ex]\hline
  10692. \begin{minipage}{0.27\textwidth}
  10693. \begin{lstlisting}
  10694. (vector-ref |$e_1$| |$e_2$|)
  10695. \end{lstlisting}
  10696. \end{minipage}
  10697. &
  10698. $\Rightarrow$
  10699. &
  10700. \begin{minipage}{0.65\textwidth}
  10701. \begin{lstlisting}
  10702. (any-vector-ref |$e_1'$| |$e_2'$|)
  10703. \end{lstlisting}
  10704. \end{minipage}
  10705. \\[2ex]\hline
  10706. \begin{minipage}{0.27\textwidth}
  10707. \begin{lstlisting}
  10708. (if |$e_1$| |$e_2$| |$e_3$|)
  10709. \end{lstlisting}
  10710. \end{minipage}
  10711. &
  10712. $\Rightarrow$
  10713. &
  10714. \begin{minipage}{0.65\textwidth}
  10715. \begin{lstlisting}
  10716. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  10717. \end{lstlisting}
  10718. \end{minipage}
  10719. \\[2ex]\hline
  10720. \begin{minipage}{0.27\textwidth}
  10721. \begin{lstlisting}
  10722. (eq? |$e_1$| |$e_2$|)
  10723. \end{lstlisting}
  10724. \end{minipage}
  10725. &
  10726. $\Rightarrow$
  10727. &
  10728. \begin{minipage}{0.65\textwidth}
  10729. \begin{lstlisting}
  10730. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  10731. \end{lstlisting}
  10732. \end{minipage}
  10733. \\[2ex]\hline
  10734. \begin{minipage}{0.27\textwidth}
  10735. \begin{lstlisting}
  10736. (not |$e_1$|)
  10737. \end{lstlisting}
  10738. \end{minipage}
  10739. &
  10740. $\Rightarrow$
  10741. &
  10742. \begin{minipage}{0.65\textwidth}
  10743. \begin{lstlisting}
  10744. (if (eq? |$e'_1$| (inject #f Boolean))
  10745. (inject #t Boolean) (inject #f Boolean))
  10746. \end{lstlisting}
  10747. \end{minipage}
  10748. \\[2ex]\hline
  10749. \end{tabular}
  10750. \caption{Cast Insertion}
  10751. \label{fig:compile-r7-Rany}
  10752. \end{figure}
  10753. \section{Reveal Casts}
  10754. \label{sec:reveal-casts-Rany}
  10755. % TODO: define R'_6
  10756. In the \code{reveal-casts} pass we recommend compiling \code{project}
  10757. into an \code{if} expression that checks whether the value's tag
  10758. matches the target type; if it does, the value is converted to a value
  10759. of the target type by removing the tag; if it does not, the program
  10760. exits. To perform these actions we need a new primitive operation,
  10761. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  10762. The \code{tag-of-any} operation retrieves the type tag from a tagged
  10763. value of type \code{Any}. The \code{ValueOf} form retrieves the
  10764. underlying value from a tagged value. The \code{ValueOf} form
  10765. includes the type for the underlying value which is used by the type
  10766. checker. Finally, the \code{Exit} form ends the execution of the
  10767. program.
  10768. If the target type of the projection is \code{Boolean} or
  10769. \code{Integer}, then \code{Project} can be translated as follows.
  10770. \begin{center}
  10771. \begin{minipage}{1.0\textwidth}
  10772. \begin{lstlisting}
  10773. (Project |$e$| |$\FType$|)
  10774. |$\Rightarrow$|
  10775. (Let |$\itm{tmp}$| |$e'$|
  10776. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  10777. (Int |$\itm{tagof}(\FType)$|)))
  10778. (ValueOf |$\itm{tmp}$| |$\FType$|)
  10779. (Exit)))
  10780. \end{lstlisting}
  10781. \end{minipage}
  10782. \end{center}
  10783. If the target type of the projection is a vector or function type,
  10784. then there is a bit more work to do. For vectors, check that the
  10785. length of the vector type matches the length of the vector (using the
  10786. \code{vector-length} primitive). For functions, check that the number
  10787. of parameters in the function type matches the function's arity (using
  10788. \code{procedure-arity}).
  10789. Regarding \code{inject}, we recommend compiling it to a slightly
  10790. lower-level primitive operation named \code{make-any}. This operation
  10791. takes a tag instead of a type.
  10792. \begin{center}
  10793. \begin{minipage}{1.0\textwidth}
  10794. \begin{lstlisting}
  10795. (Inject |$e$| |$\FType$|)
  10796. |$\Rightarrow$|
  10797. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  10798. \end{lstlisting}
  10799. \end{minipage}
  10800. \end{center}
  10801. The type predicates (\code{boolean?}, etc.) can be translated into
  10802. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  10803. translation of \code{Project}.
  10804. The \code{any-vector-ref} and \code{any-vector-set!} operations
  10805. combine the projection action with the vector operation. Also, the
  10806. read and write operations allow arbitrary expressions for the index so
  10807. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  10808. cannot guarantee that the index is within bounds. Thus, we insert code
  10809. to perform bounds checking at runtime. The translation for
  10810. \code{any-vector-ref} is as follows and the other two operations are
  10811. translated in a similar way.
  10812. \begin{lstlisting}
  10813. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  10814. |$\Rightarrow$|
  10815. (Let |$v$| |$e'_1$|
  10816. (Let |$i$| |$e'_2$|
  10817. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  10818. (If (Prim '< (list (Var |$i$|)
  10819. (Prim 'any-vector-length (list (Var |$v$|)))))
  10820. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  10821. (Exit))))
  10822. \end{lstlisting}
  10823. \section{Remove Complex Operands}
  10824. \label{sec:rco-Rany}
  10825. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  10826. The subexpression of \code{ValueOf} must be atomic.
  10827. \section{Explicate Control and \LangCAny{}}
  10828. \label{sec:explicate-Rany}
  10829. The output of \code{explicate-control} is the \LangCAny{} language whose
  10830. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  10831. form that we added to \LangAny{} remains an expression and the \code{Exit}
  10832. expression becomes a $\Tail$. Also, note that the index argument of
  10833. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  10834. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  10835. \begin{figure}[tp]
  10836. \fbox{
  10837. \begin{minipage}{0.96\textwidth}
  10838. \small
  10839. \[
  10840. \begin{array}{lcl}
  10841. \Exp &::= & \ldots
  10842. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  10843. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  10844. &\MID& \VALUEOF{\Exp}{\FType} \\
  10845. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10846. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  10847. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10848. \MID \GOTO{\itm{label}} } \\
  10849. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10850. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  10851. \MID \LP\key{Exit}\RP \\
  10852. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  10853. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  10854. \end{array}
  10855. \]
  10856. \end{minipage}
  10857. }
  10858. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10859. \label{fig:c5-syntax}
  10860. \end{figure}
  10861. \section{Select Instructions}
  10862. \label{sec:select-Rany}
  10863. In the \code{select-instructions} pass we translate the primitive
  10864. operations on the \code{Any} type to x86 instructions that involve
  10865. manipulating the 3 tag bits of the tagged value.
  10866. \paragraph{Make-any}
  10867. We recommend compiling the \key{make-any} primitive as follows if the
  10868. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  10869. shifts the destination to the left by the number of bits specified its
  10870. source argument (in this case $3$, the length of the tag) and it
  10871. preserves the sign of the integer. We use the \key{orq} instruction to
  10872. combine the tag and the value to form the tagged value. \\
  10873. \begin{lstlisting}
  10874. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  10875. |$\Rightarrow$|
  10876. movq |$e'$|, |\itm{lhs'}|
  10877. salq $3, |\itm{lhs'}|
  10878. orq $|$\itm{tag}$|, |\itm{lhs'}|
  10879. \end{lstlisting}
  10880. The instruction selection for vectors and procedures is different
  10881. because their is no need to shift them to the left. The rightmost 3
  10882. bits are already zeros as described at the beginning of this
  10883. chapter. So we just combine the value and the tag using \key{orq}. \\
  10884. \begin{lstlisting}
  10885. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  10886. |$\Rightarrow$|
  10887. movq |$e'$|, |\itm{lhs'}|
  10888. orq $|$\itm{tag}$|, |\itm{lhs'}|
  10889. \end{lstlisting}
  10890. \paragraph{Tag-of-any}
  10891. Recall that the \code{tag-of-any} operation extracts the type tag from
  10892. a value of type \code{Any}. The type tag is the bottom three bits, so
  10893. we obtain the tag by taking the bitwise-and of the value with $111$
  10894. ($7$ in decimal).
  10895. \begin{lstlisting}
  10896. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  10897. |$\Rightarrow$|
  10898. movq |$e'$|, |\itm{lhs'}|
  10899. andq $7, |\itm{lhs'}|
  10900. \end{lstlisting}
  10901. \paragraph{ValueOf}
  10902. Like \key{make-any}, the instructions for \key{ValueOf} are different
  10903. depending on whether the type $T$ is a pointer (vector or procedure)
  10904. or not (Integer or Boolean). The following shows the instruction
  10905. selection for Integer and Boolean. We produce an untagged value by
  10906. shifting it to the right by 3 bits.
  10907. \begin{lstlisting}
  10908. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  10909. |$\Rightarrow$|
  10910. movq |$e'$|, |\itm{lhs'}|
  10911. sarq $3, |\itm{lhs'}|
  10912. \end{lstlisting}
  10913. %
  10914. In the case for vectors and procedures, there is no need to
  10915. shift. Instead we just need to zero-out the rightmost 3 bits. We
  10916. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  10917. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  10918. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  10919. then apply \code{andq} with the tagged value to get the desired
  10920. result. \\
  10921. \begin{lstlisting}
  10922. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  10923. |$\Rightarrow$|
  10924. movq $|$-8$|, |\itm{lhs'}|
  10925. andq |$e'$|, |\itm{lhs'}|
  10926. \end{lstlisting}
  10927. %% \paragraph{Type Predicates} We leave it to the reader to
  10928. %% devise a sequence of instructions to implement the type predicates
  10929. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  10930. \paragraph{Any-vector-length}
  10931. \begin{lstlisting}
  10932. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  10933. |$\Longrightarrow$|
  10934. movq |$\neg 111$|, %r11
  10935. andq |$a_1'$|, %r11
  10936. movq 0(%r11), %r11
  10937. andq $126, %r11
  10938. sarq $1, %r11
  10939. movq %r11, |$\itm{lhs'}$|
  10940. \end{lstlisting}
  10941. \paragraph{Any-vector-ref}
  10942. The index may be an arbitrary atom so instead of computing the offset
  10943. at compile time, instructions need to be generated to compute the
  10944. offset at runtime as follows. Note the use of the new instruction
  10945. \code{imulq}.
  10946. \begin{center}
  10947. \begin{minipage}{0.96\textwidth}
  10948. \begin{lstlisting}
  10949. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  10950. |$\Longrightarrow$|
  10951. movq |$\neg 111$|, %r11
  10952. andq |$a_1'$|, %r11
  10953. movq |$a_2'$|, %rax
  10954. addq $1, %rax
  10955. imulq $8, %rax
  10956. addq %rax, %r11
  10957. movq 0(%r11) |$\itm{lhs'}$|
  10958. \end{lstlisting}
  10959. \end{minipage}
  10960. \end{center}
  10961. \paragraph{Any-vector-set!}
  10962. The code generation for \code{any-vector-set!} is similar to the other
  10963. \code{any-vector} operations.
  10964. \section{Register Allocation for \LangAny{}}
  10965. \label{sec:register-allocation-Rany}
  10966. \index{subject}{register allocation}
  10967. There is an interesting interaction between tagged values and garbage
  10968. collection that has an impact on register allocation. A variable of
  10969. type \code{Any} might refer to a vector and therefore it might be a
  10970. root that needs to be inspected and copied during garbage
  10971. collection. Thus, we need to treat variables of type \code{Any} in a
  10972. similar way to variables of type \code{Vector} for purposes of
  10973. register allocation. In particular,
  10974. \begin{itemize}
  10975. \item If a variable of type \code{Any} is live during a function call,
  10976. then it must be spilled. This can be accomplished by changing
  10977. \code{build-interference} to mark all variables of type \code{Any}
  10978. that are live after a \code{callq} as interfering with all the
  10979. registers.
  10980. \item If a variable of type \code{Any} is spilled, it must be spilled
  10981. to the root stack instead of the normal procedure call stack.
  10982. \end{itemize}
  10983. Another concern regarding the root stack is that the garbage collector
  10984. needs to differentiate between (1) plain old pointers to tuples, (2) a
  10985. tagged value that points to a tuple, and (3) a tagged value that is
  10986. not a tuple. We enable this differentiation by choosing not to use the
  10987. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  10988. reserved for identifying plain old pointers to tuples. That way, if
  10989. one of the first three bits is set, then we have a tagged value and
  10990. inspecting the tag can differentiation between vectors ($010$) and the
  10991. other kinds of values.
  10992. \begin{exercise}\normalfont
  10993. Expand your compiler to handle \LangAny{} as discussed in the last few
  10994. sections. Create 5 new programs that use the \code{Any} type and the
  10995. new operations (\code{inject}, \code{project}, \code{boolean?},
  10996. etc.). Test your compiler on these new programs and all of your
  10997. previously created test programs.
  10998. \end{exercise}
  10999. \begin{exercise}\normalfont
  11000. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  11001. Create tests for \LangDyn{} by adapting ten of your previous test programs
  11002. by removing type annotations. Add 5 more tests programs that
  11003. specifically rely on the language being dynamically typed. That is,
  11004. they should not be legal programs in a statically typed language, but
  11005. nevertheless, they should be valid \LangDyn{} programs that run to
  11006. completion without error.
  11007. \end{exercise}
  11008. \begin{figure}[p]
  11009. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11010. \node (Rfun) at (0,4) {\large \LangDyn{}};
  11011. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  11012. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  11013. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  11014. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  11015. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  11016. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  11017. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  11018. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  11019. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  11020. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  11021. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  11022. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11023. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11024. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11025. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11026. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11027. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11028. \path[->,bend left=15] (Rfun) edge [above] node
  11029. {\ttfamily\footnotesize shrink} (Rfun-2);
  11030. \path[->,bend left=15] (Rfun-2) edge [above] node
  11031. {\ttfamily\footnotesize uniquify} (Rfun-3);
  11032. \path[->,bend left=15] (Rfun-3) edge [above] node
  11033. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  11034. \path[->,bend right=15] (Rfun-4) edge [left] node
  11035. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  11036. \path[->,bend left=15] (Rfun-5) edge [above] node
  11037. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  11038. \path[->,bend left=15] (Rfun-6) edge [left] node
  11039. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  11040. \path[->,bend left=15] (Rfun-7) edge [below] node
  11041. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11042. \path[->,bend right=15] (F1-2) edge [above] node
  11043. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11044. \path[->,bend right=15] (F1-3) edge [above] node
  11045. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11046. \path[->,bend right=15] (F1-4) edge [above] node
  11047. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11048. \path[->,bend right=15] (F1-5) edge [right] node
  11049. {\ttfamily\footnotesize explicate-control} (C3-2);
  11050. \path[->,bend left=15] (C3-2) edge [left] node
  11051. {\ttfamily\footnotesize select-instr.} (x86-2);
  11052. \path[->,bend right=15] (x86-2) edge [left] node
  11053. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11054. \path[->,bend right=15] (x86-2-1) edge [below] node
  11055. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11056. \path[->,bend right=15] (x86-2-2) edge [left] node
  11057. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11058. \path[->,bend left=15] (x86-3) edge [above] node
  11059. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11060. \path[->,bend left=15] (x86-4) edge [right] node
  11061. {\ttfamily\footnotesize print-x86} (x86-5);
  11062. \end{tikzpicture}
  11063. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  11064. \label{fig:Rdyn-passes}
  11065. \end{figure}
  11066. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  11067. for the compilation of \LangDyn{}.
  11068. % Further Reading
  11069. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11070. \chapter{Loops and Assignment}
  11071. \label{ch:Rwhile}
  11072. % TODO: define R'_8
  11073. % TODO: multi-graph
  11074. In this chapter we study two features that are the hallmarks of
  11075. imperative programming languages: loops and assignments to local
  11076. variables. The following example demonstrates these new features by
  11077. computing the sum of the first five positive integers.
  11078. % similar to loop_test_1.rkt
  11079. \begin{lstlisting}
  11080. (let ([sum 0])
  11081. (let ([i 5])
  11082. (begin
  11083. (while (> i 0)
  11084. (begin
  11085. (set! sum (+ sum i))
  11086. (set! i (- i 1))))
  11087. sum)))
  11088. \end{lstlisting}
  11089. The \code{while} loop consists of a condition and a body.
  11090. %
  11091. The \code{set!} consists of a variable and a right-hand-side expression.
  11092. %
  11093. The primary purpose of both the \code{while} loop and \code{set!} is
  11094. to cause side effects, so it is convenient to also include in a
  11095. language feature for sequencing side effects: the \code{begin}
  11096. expression. It consists of one or more subexpressions that are
  11097. evaluated left-to-right.
  11098. \section{The \LangLoop{} Language}
  11099. \begin{figure}[tp]
  11100. \centering
  11101. \fbox{
  11102. \begin{minipage}{0.96\textwidth}
  11103. \small
  11104. \[
  11105. \begin{array}{lcl}
  11106. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11107. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11108. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11109. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11110. \MID (\key{and}\;\Exp\;\Exp)
  11111. \MID (\key{or}\;\Exp\;\Exp)
  11112. \MID (\key{not}\;\Exp) } \\
  11113. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11114. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  11115. (\key{vector-ref}\;\Exp\;\Int)} \\
  11116. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11117. \MID (\Exp \; \Exp\ldots) } \\
  11118. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11119. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11120. &\MID& \CSETBANG{\Var}{\Exp}
  11121. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11122. \MID \CWHILE{\Exp}{\Exp} \\
  11123. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11124. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  11125. \end{array}
  11126. \]
  11127. \end{minipage}
  11128. }
  11129. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  11130. \label{fig:Rwhile-concrete-syntax}
  11131. \end{figure}
  11132. \begin{figure}[tp]
  11133. \centering
  11134. \fbox{
  11135. \begin{minipage}{0.96\textwidth}
  11136. \small
  11137. \[
  11138. \begin{array}{lcl}
  11139. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11140. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11141. &\MID& \gray{ \BOOL{\itm{bool}}
  11142. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11143. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  11144. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  11145. &\MID& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  11146. &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  11147. \MID \WHILE{\Exp}{\Exp} \\
  11148. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  11149. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11150. \end{array}
  11151. \]
  11152. \end{minipage}
  11153. }
  11154. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  11155. \label{fig:Rwhile-syntax}
  11156. \end{figure}
  11157. The concrete syntax of \LangLoop{} is defined in
  11158. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  11159. in Figure~\ref{fig:Rwhile-syntax}.
  11160. %
  11161. The definitional interpreter for \LangLoop{} is shown in
  11162. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  11163. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  11164. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  11165. support assignment to variables and to make their lifetimes indefinite
  11166. (see the second example in Section~\ref{sec:assignment-scoping}), we
  11167. box the value that is bound to each variable (in \code{Let}) and
  11168. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  11169. the value.
  11170. %
  11171. Now to discuss the new cases. For \code{SetBang}, we lookup the
  11172. variable in the environment to obtain a boxed value and then we change
  11173. it using \code{set-box!} to the result of evaluating the right-hand
  11174. side. The result value of a \code{SetBang} is \code{void}.
  11175. %
  11176. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  11177. if the result is true, 2) evaluate the body.
  11178. The result value of a \code{while} loop is also \code{void}.
  11179. %
  11180. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  11181. subexpressions \itm{es} for their effects and then evaluates
  11182. and returns the result from \itm{body}.
  11183. \begin{figure}[tbp]
  11184. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11185. (define interp-Rwhile-class
  11186. (class interp-Rany-class
  11187. (super-new)
  11188. (define/override ((interp-exp env) e)
  11189. (define recur (interp-exp env))
  11190. (match e
  11191. [(SetBang x rhs)
  11192. (set-box! (lookup x env) (recur rhs))]
  11193. [(WhileLoop cnd body)
  11194. (define (loop)
  11195. (cond [(recur cnd) (recur body) (loop)]
  11196. [else (void)]))
  11197. (loop)]
  11198. [(Begin es body)
  11199. (for ([e es]) (recur e))
  11200. (recur body)]
  11201. [else ((super interp-exp env) e)]))
  11202. ))
  11203. (define (interp-Rwhile p)
  11204. (send (new interp-Rwhile-class) interp-program p))
  11205. \end{lstlisting}
  11206. \caption{Interpreter for \LangLoop{}.}
  11207. \label{fig:interp-Rwhile}
  11208. \end{figure}
  11209. The type checker for \LangLoop{} is define in
  11210. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  11211. variable and the right-hand-side must agree. The result type is
  11212. \code{Void}. For the \code{WhileLoop}, the condition must be a
  11213. \code{Boolean}. The result type is also \code{Void}. For
  11214. \code{Begin}, the result type is the type of its last subexpression.
  11215. \begin{figure}[tbp]
  11216. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11217. (define type-check-Rwhile-class
  11218. (class type-check-Rany-class
  11219. (super-new)
  11220. (inherit check-type-equal?)
  11221. (define/override (type-check-exp env)
  11222. (lambda (e)
  11223. (define recur (type-check-exp env))
  11224. (match e
  11225. [(SetBang x rhs)
  11226. (define-values (rhs^ rhsT) (recur rhs))
  11227. (define varT (dict-ref env x))
  11228. (check-type-equal? rhsT varT e)
  11229. (values (SetBang x rhs^) 'Void)]
  11230. [(WhileLoop cnd body)
  11231. (define-values (cnd^ Tc) (recur cnd))
  11232. (check-type-equal? Tc 'Boolean e)
  11233. (define-values (body^ Tbody) ((type-check-exp env) body))
  11234. (values (WhileLoop cnd^ body^) 'Void)]
  11235. [(Begin es body)
  11236. (define-values (es^ ts)
  11237. (for/lists (l1 l2) ([e es]) (recur e)))
  11238. (define-values (body^ Tbody) (recur body))
  11239. (values (Begin es^ body^) Tbody)]
  11240. [else ((super type-check-exp env) e)])))
  11241. ))
  11242. (define (type-check-Rwhile p)
  11243. (send (new type-check-Rwhile-class) type-check-program p))
  11244. \end{lstlisting}
  11245. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  11246. and \code{Begin} in \LangLoop{}.}
  11247. \label{fig:type-check-Rwhile}
  11248. \end{figure}
  11249. At first glance, the translation of these language features to x86
  11250. seems straightforward because the \LangCFun{} intermediate language already
  11251. supports all of the ingredients that we need: assignment, \code{goto},
  11252. conditional branching, and sequencing. However, there are two
  11253. complications that arise which we discuss in the next two
  11254. sections. After that we introduce one new compiler pass and the
  11255. changes necessary to the existing passes.
  11256. \section{Assignment and Lexically Scoped Functions}
  11257. \label{sec:assignment-scoping}
  11258. The addition of assignment raises a problem with our approach to
  11259. implementing lexically-scoped functions. Consider the following
  11260. example in which function \code{f} has a free variable \code{x} that
  11261. is changed after \code{f} is created but before the call to \code{f}.
  11262. % loop_test_11.rkt
  11263. \begin{lstlisting}
  11264. (let ([x 0])
  11265. (let ([y 0])
  11266. (let ([z 20])
  11267. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  11268. (begin
  11269. (set! x 10)
  11270. (set! y 12)
  11271. (f y))))))
  11272. \end{lstlisting}
  11273. The correct output for this example is \code{42} because the call to
  11274. \code{f} is required to use the current value of \code{x} (which is
  11275. \code{10}). Unfortunately, the closure conversion pass
  11276. (Section~\ref{sec:closure-conversion}) generates code for the
  11277. \code{lambda} that copies the old value of \code{x} into a
  11278. closure. Thus, if we naively add support for assignment to our current
  11279. compiler, the output of this program would be \code{32}.
  11280. A first attempt at solving this problem would be to save a pointer to
  11281. \code{x} in the closure and change the occurrences of \code{x} inside
  11282. the lambda to dereference the pointer. Of course, this would require
  11283. assigning \code{x} to the stack and not to a register. However, the
  11284. problem goes a bit deeper. Consider the following example in which we
  11285. create a counter abstraction by creating a pair of functions that
  11286. share the free variable \code{x}.
  11287. % similar to loop_test_10.rkt
  11288. \begin{lstlisting}
  11289. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  11290. (vector
  11291. (lambda: () : Integer x)
  11292. (lambda: () : Void (set! x (+ 1 x)))))
  11293. (let ([counter (f 0)])
  11294. (let ([get (vector-ref counter 0)])
  11295. (let ([inc (vector-ref counter 1)])
  11296. (begin
  11297. (inc)
  11298. (get)))))
  11299. \end{lstlisting}
  11300. In this example, the lifetime of \code{x} extends beyond the lifetime
  11301. of the call to \code{f}. Thus, if we were to store \code{x} on the
  11302. stack frame for the call to \code{f}, it would be gone by the time we
  11303. call \code{inc} and \code{get}, leaving us with dangling pointers for
  11304. \code{x}. This example demonstrates that when a variable occurs free
  11305. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  11306. value of the variable needs to live on the heap. The verb ``box'' is
  11307. often used for allocating a single value on the heap, producing a
  11308. pointer, and ``unbox'' for dereferencing the pointer.
  11309. We recommend solving these problems by ``boxing'' the local variables
  11310. that are in the intersection of 1) variables that appear on the
  11311. left-hand-side of a \code{set!} and 2) variables that occur free
  11312. inside a \code{lambda}. We shall introduce a new pass named
  11313. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  11314. perform this translation. But before diving into the compiler passes,
  11315. we one more problem to discuss.
  11316. \section{Cyclic Control Flow and Dataflow Analysis}
  11317. \label{sec:dataflow-analysis}
  11318. Up until this point the control-flow graphs generated in
  11319. \code{explicate-control} were guaranteed to be acyclic. However, each
  11320. \code{while} loop introduces a cycle in the control-flow graph.
  11321. But does that matter?
  11322. %
  11323. Indeed it does. Recall that for register allocation, the compiler
  11324. performs liveness analysis to determine which variables can share the
  11325. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  11326. the control-flow graph in reverse topological order, but topological
  11327. order is only well-defined for acyclic graphs.
  11328. Let us return to the example of computing the sum of the first five
  11329. positive integers. Here is the program after instruction selection but
  11330. before register allocation.
  11331. \begin{center}
  11332. \begin{minipage}{0.45\textwidth}
  11333. \begin{lstlisting}
  11334. (define (main) : Integer
  11335. mainstart:
  11336. movq $0, sum1
  11337. movq $5, i2
  11338. jmp block5
  11339. block5:
  11340. movq i2, tmp3
  11341. cmpq tmp3, $0
  11342. jl block7
  11343. jmp block8
  11344. \end{lstlisting}
  11345. \end{minipage}
  11346. \begin{minipage}{0.45\textwidth}
  11347. \begin{lstlisting}
  11348. block7:
  11349. addq i2, sum1
  11350. movq $1, tmp4
  11351. negq tmp4
  11352. addq tmp4, i2
  11353. jmp block5
  11354. block8:
  11355. movq $27, %rax
  11356. addq sum1, %rax
  11357. jmp mainconclusion
  11358. )
  11359. \end{lstlisting}
  11360. \end{minipage}
  11361. \end{center}
  11362. Recall that liveness analysis works backwards, starting at the end
  11363. of each function. For this example we could start with \code{block8}
  11364. because we know what is live at the beginning of the conclusion,
  11365. just \code{rax} and \code{rsp}. So the live-before set
  11366. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  11367. %
  11368. Next we might try to analyze \code{block5} or \code{block7}, but
  11369. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  11370. we are stuck.
  11371. The way out of this impasse comes from the realization that one can
  11372. perform liveness analysis starting with an empty live-after set to
  11373. compute an under-approximation of the live-before set. By
  11374. \emph{under-approximation}, we mean that the set only contains
  11375. variables that are really live, but it may be missing some. Next, the
  11376. under-approximations for each block can be improved by 1) updating the
  11377. live-after set for each block using the approximate live-before sets
  11378. from the other blocks and 2) perform liveness analysis again on each
  11379. block. In fact, by iterating this process, the under-approximations
  11380. eventually become the correct solutions!
  11381. %
  11382. This approach of iteratively analyzing a control-flow graph is
  11383. applicable to many static analysis problems and goes by the name
  11384. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  11385. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  11386. Washington.
  11387. Let us apply this approach to the above example. We use the empty set
  11388. for the initial live-before set for each block. Let $m_0$ be the
  11389. following mapping from label names to sets of locations (variables and
  11390. registers).
  11391. \begin{center}
  11392. \begin{lstlisting}
  11393. mainstart: {}
  11394. block5: {}
  11395. block7: {}
  11396. block8: {}
  11397. \end{lstlisting}
  11398. \end{center}
  11399. Using the above live-before approximations, we determine the
  11400. live-after for each block and then apply liveness analysis to each
  11401. block. This produces our next approximation $m_1$ of the live-before
  11402. sets.
  11403. \begin{center}
  11404. \begin{lstlisting}
  11405. mainstart: {}
  11406. block5: {i2}
  11407. block7: {i2, sum1}
  11408. block8: {rsp, sum1}
  11409. \end{lstlisting}
  11410. \end{center}
  11411. For the second round, the live-after for \code{mainstart} is the
  11412. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  11413. liveness analysis for \code{mainstart} computes the empty set. The
  11414. live-after for \code{block5} is the union of the live-before sets for
  11415. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  11416. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  11417. sum1\}}. The live-after for \code{block7} is the live-before for
  11418. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  11419. So the liveness analysis for \code{block7} remains \code{\{i2,
  11420. sum1\}}. Together these yield the following approximation $m_2$ of
  11421. the live-before sets.
  11422. \begin{center}
  11423. \begin{lstlisting}
  11424. mainstart: {}
  11425. block5: {i2, rsp, sum1}
  11426. block7: {i2, sum1}
  11427. block8: {rsp, sum1}
  11428. \end{lstlisting}
  11429. \end{center}
  11430. In the preceding iteration, only \code{block5} changed, so we can
  11431. limit our attention to \code{mainstart} and \code{block7}, the two
  11432. blocks that jump to \code{block5}. As a result, the live-before sets
  11433. for \code{mainstart} and \code{block7} are updated to include
  11434. \code{rsp}, yielding the following approximation $m_3$.
  11435. \begin{center}
  11436. \begin{lstlisting}
  11437. mainstart: {rsp}
  11438. block5: {i2, rsp, sum1}
  11439. block7: {i2, rsp, sum1}
  11440. block8: {rsp, sum1}
  11441. \end{lstlisting}
  11442. \end{center}
  11443. Because \code{block7} changed, we analyze \code{block5} once more, but
  11444. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  11445. our approximations have converged, so $m_3$ is the solution.
  11446. This iteration process is guaranteed to converge to a solution by the
  11447. Kleene Fixed-Point Theorem, a general theorem about functions on
  11448. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  11449. any collection that comes with a partial ordering $\sqsubseteq$ on its
  11450. elements, a least element $\bot$ (pronounced bottom), and a join
  11451. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  11452. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  11453. working with join semi-lattices.} When two elements are ordered $m_i
  11454. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  11455. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  11456. approximation than $m_i$. The bottom element $\bot$ represents the
  11457. complete lack of information, i.e., the worst approximation. The join
  11458. operator takes two lattice elements and combines their information,
  11459. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  11460. bound}
  11461. A dataflow analysis typically involves two lattices: one lattice to
  11462. represent abstract states and another lattice that aggregates the
  11463. abstract states of all the blocks in the control-flow graph. For
  11464. liveness analysis, an abstract state is a set of locations. We form
  11465. the lattice $L$ by taking its elements to be sets of locations, the
  11466. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  11467. set, and the join operator to be set union.
  11468. %
  11469. We form a second lattice $M$ by taking its elements to be mappings
  11470. from the block labels to sets of locations (elements of $L$). We
  11471. order the mappings point-wise, using the ordering of $L$. So given any
  11472. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  11473. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  11474. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  11475. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  11476. We can think of one iteration of liveness analysis as being a function
  11477. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  11478. mapping.
  11479. \[
  11480. f(m_i) = m_{i+1}
  11481. \]
  11482. Next let us think for a moment about what a final solution $m_s$
  11483. should look like. If we perform liveness analysis using the solution
  11484. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  11485. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  11486. \[
  11487. f(m_s) = m_s
  11488. \]
  11489. Furthermore, the solution should only include locations that are
  11490. forced to be there by performing liveness analysis on the program, so
  11491. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  11492. The Kleene Fixed-Point Theorem states that if a function $f$ is
  11493. monotone (better inputs produce better outputs), then the least fixed
  11494. point of $f$ is the least upper bound of the \emph{ascending Kleene
  11495. chain} obtained by starting at $\bot$ and iterating $f$ as
  11496. follows.\index{subject}{Kleene Fixed-Point Theorem}
  11497. \[
  11498. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  11499. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  11500. \]
  11501. When a lattice contains only finitely-long ascending chains, then
  11502. every Kleene chain tops out at some fixed point after a number of
  11503. iterations of $f$. So that fixed point is also a least upper
  11504. bound of the chain.
  11505. \[
  11506. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  11507. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  11508. \]
  11509. The liveness analysis is indeed a monotone function and the lattice
  11510. $M$ only has finitely-long ascending chains because there are only a
  11511. finite number of variables and blocks in the program. Thus we are
  11512. guaranteed that iteratively applying liveness analysis to all blocks
  11513. in the program will eventually produce the least fixed point solution.
  11514. Next let us consider dataflow analysis in general and discuss the
  11515. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  11516. %
  11517. The algorithm has four parameters: the control-flow graph \code{G}, a
  11518. function \code{transfer} that applies the analysis to one block, the
  11519. \code{bottom} and \code{join} operator for the lattice of abstract
  11520. states. The algorithm begins by creating the bottom mapping,
  11521. represented by a hash table. It then pushes all of the nodes in the
  11522. control-flow graph onto the work list (a queue). The algorithm repeats
  11523. the \code{while} loop as long as there are items in the work list. In
  11524. each iteration, a node is popped from the work list and processed. The
  11525. \code{input} for the node is computed by taking the join of the
  11526. abstract states of all the predecessor nodes. The \code{transfer}
  11527. function is then applied to obtain the \code{output} abstract
  11528. state. If the output differs from the previous state for this block,
  11529. the mapping for this block is updated and its successor nodes are
  11530. pushed onto the work list.
  11531. \begin{figure}[tb]
  11532. \begin{lstlisting}
  11533. (define (analyze-dataflow G transfer bottom join)
  11534. (define mapping (make-hash))
  11535. (for ([v (in-vertices G)])
  11536. (dict-set! mapping v bottom))
  11537. (define worklist (make-queue))
  11538. (for ([v (in-vertices G)])
  11539. (enqueue! worklist v))
  11540. (define trans-G (transpose G))
  11541. (while (not (queue-empty? worklist))
  11542. (define node (dequeue! worklist))
  11543. (define input (for/fold ([state bottom])
  11544. ([pred (in-neighbors trans-G node)])
  11545. (join state (dict-ref mapping pred))))
  11546. (define output (transfer node input))
  11547. (cond [(not (equal? output (dict-ref mapping node)))
  11548. (dict-set! mapping node output)
  11549. (for ([v (in-neighbors G node)])
  11550. (enqueue! worklist v))]))
  11551. mapping)
  11552. \end{lstlisting}
  11553. \caption{Generic work list algorithm for dataflow analysis}
  11554. \label{fig:generic-dataflow}
  11555. \end{figure}
  11556. Having discussed the two complications that arise from adding support
  11557. for assignment and loops, we turn to discussing the one new compiler
  11558. pass and the significant changes to existing passes.
  11559. \section{Convert Assignments}
  11560. \label{sec:convert-assignments}
  11561. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  11562. the combination of assignments and lexically-scoped functions requires
  11563. that we box those variables that are both assigned-to and that appear
  11564. free inside a \code{lambda}. The purpose of the
  11565. \code{convert-assignments} pass is to carry out that transformation.
  11566. We recommend placing this pass after \code{uniquify} but before
  11567. \code{reveal-functions}.
  11568. Consider again the first example from
  11569. Section~\ref{sec:assignment-scoping}:
  11570. \begin{lstlisting}
  11571. (let ([x 0])
  11572. (let ([y 0])
  11573. (let ([z 20])
  11574. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  11575. (begin
  11576. (set! x 10)
  11577. (set! y 12)
  11578. (f y))))))
  11579. \end{lstlisting}
  11580. The variables \code{x} and \code{y} are assigned-to. The variables
  11581. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  11582. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  11583. The boxing of \code{x} consists of three transformations: initialize
  11584. \code{x} with a vector, replace reads from \code{x} with
  11585. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  11586. \code{vector-set!}. The output of \code{convert-assignments} for this
  11587. example is as follows.
  11588. \begin{lstlisting}
  11589. (define (main) : Integer
  11590. (let ([x0 (vector 0)])
  11591. (let ([y1 0])
  11592. (let ([z2 20])
  11593. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  11594. (+ a3 (+ (vector-ref x0 0) z2)))])
  11595. (begin
  11596. (vector-set! x0 0 10)
  11597. (set! y1 12)
  11598. (f4 y1)))))))
  11599. \end{lstlisting}
  11600. \paragraph{Assigned \& Free}
  11601. We recommend defining an auxiliary function named
  11602. \code{assigned\&free} that takes an expression and simultaneously
  11603. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  11604. that occur free within lambda's, and 3) a new version of the
  11605. expression that records which bound variables occurred in the
  11606. intersection of $A$ and $F$. You can use the struct
  11607. \code{AssignedFree} to do this. Consider the case for
  11608. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  11609. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  11610. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  11611. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  11612. \begin{lstlisting}
  11613. (Let |$x$| |$rhs$| |$body$|)
  11614. |$\Rightarrow$|
  11615. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  11616. \end{lstlisting}
  11617. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  11618. The set of assigned variables for this \code{Let} is
  11619. $A_r \cup (A_b - \{x\})$
  11620. and the set of variables free in lambda's is
  11621. $F_r \cup (F_b - \{x\})$.
  11622. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  11623. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  11624. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  11625. and $F_r$.
  11626. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  11627. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  11628. recursively processing \itm{body}. Wrap each of parameter that occurs
  11629. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  11630. Let $P$ be the set of parameter names in \itm{params}. The result is
  11631. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  11632. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  11633. variables of an expression (see Chapter~\ref{ch:Rlam}).
  11634. \paragraph{Convert Assignments}
  11635. Next we discuss the \code{convert-assignment} pass with its auxiliary
  11636. functions for expressions and definitions. The function for
  11637. expressions, \code{cnvt-assign-exp}, should take an expression and a
  11638. set of assigned-and-free variables (obtained from the result of
  11639. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  11640. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  11641. \code{vector-ref}.
  11642. \begin{lstlisting}
  11643. (Var |$x$|)
  11644. |$\Rightarrow$|
  11645. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  11646. \end{lstlisting}
  11647. %
  11648. In the case for $\LET{\LP\code{AssignedFree}\,
  11649. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  11650. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  11651. \itm{body'} but with $x$ added to the set of assigned-and-free
  11652. variables. Translate the let-expression as follows to bind $x$ to a
  11653. boxed value.
  11654. \begin{lstlisting}
  11655. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  11656. |$\Rightarrow$|
  11657. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  11658. \end{lstlisting}
  11659. %
  11660. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  11661. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  11662. variables, translate the \code{set!} into a \code{vector-set!}
  11663. as follows.
  11664. \begin{lstlisting}
  11665. (SetBang |$x$| |$\itm{rhs}$|)
  11666. |$\Rightarrow$|
  11667. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  11668. \end{lstlisting}
  11669. %
  11670. The case for \code{Lambda} is non-trivial, but it is similar to the
  11671. case for function definitions, which we discuss next.
  11672. The auxiliary function for definitions, \code{cnvt-assign-def},
  11673. applies assignment conversion to function definitions.
  11674. We translate a function definition as follows.
  11675. \begin{lstlisting}
  11676. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  11677. |$\Rightarrow$|
  11678. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  11679. \end{lstlisting}
  11680. So it remains to explain \itm{params'} and $\itm{body}_4$.
  11681. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  11682. \code{assigned\&free} on $\itm{body_1}$.
  11683. Let $P$ be the parameter names in \itm{params}.
  11684. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  11685. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  11686. as the set of assigned-and-free variables.
  11687. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  11688. in a sequence of let-expressions that box the parameters
  11689. that are in $A_b \cap F_b$.
  11690. %
  11691. Regarding \itm{params'}, change the names of the parameters that are
  11692. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  11693. variables can retain the original names). Recall the second example in
  11694. Section~\ref{sec:assignment-scoping} involving a counter
  11695. abstraction. The following is the output of assignment version for
  11696. function \code{f}.
  11697. \begin{lstlisting}
  11698. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  11699. (vector
  11700. (lambda: () : Integer x1)
  11701. (lambda: () : Void (set! x1 (+ 1 x1)))))
  11702. |$\Rightarrow$|
  11703. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  11704. (let ([x1 (vector param_x1)])
  11705. (vector (lambda: () : Integer (vector-ref x1 0))
  11706. (lambda: () : Void
  11707. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  11708. \end{lstlisting}
  11709. \section{Remove Complex Operands}
  11710. \label{sec:rco-loop}
  11711. The three new language forms, \code{while}, \code{set!}, and
  11712. \code{begin} are all complex expressions and their subexpressions are
  11713. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  11714. output language \LangFunANF{} of this pass.
  11715. \begin{figure}[tp]
  11716. \centering
  11717. \fbox{
  11718. \begin{minipage}{0.96\textwidth}
  11719. \small
  11720. \[
  11721. \begin{array}{rcl}
  11722. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  11723. \MID \VOID{} } \\
  11724. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  11725. &\MID& \WHILE{\Exp}{\Exp} \MID \SETBANG{\Var}{\Exp}
  11726. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  11727. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  11728. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  11729. \end{array}
  11730. \]
  11731. \end{minipage}
  11732. }
  11733. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  11734. \label{fig:Rwhile-anf-syntax}
  11735. \end{figure}
  11736. As usual, when a complex expression appears in a grammar position that
  11737. needs to be atomic, such as the argument of a primitive operator, we
  11738. must introduce a temporary variable and bind it to the complex
  11739. expression. This approach applies, unchanged, to handle the new
  11740. language forms. For example, in the following code there are two
  11741. \code{begin} expressions appearing as arguments to \code{+}. The
  11742. output of \code{rco-exp} is shown below, in which the \code{begin}
  11743. expressions have been bound to temporary variables. Recall that
  11744. \code{let} expressions in \LangLoopANF{} are allowed to have
  11745. arbitrary expressions in their right-hand-side expression, so it is
  11746. fine to place \code{begin} there.
  11747. \begin{lstlisting}
  11748. (let ([x0 10])
  11749. (let ([y1 0])
  11750. (+ (+ (begin (set! y1 (read)) x0)
  11751. (begin (set! x0 (read)) y1))
  11752. x0)))
  11753. |$\Rightarrow$|
  11754. (let ([x0 10])
  11755. (let ([y1 0])
  11756. (let ([tmp2 (begin (set! y1 (read)) x0)])
  11757. (let ([tmp3 (begin (set! x0 (read)) y1)])
  11758. (let ([tmp4 (+ tmp2 tmp3)])
  11759. (+ tmp4 x0))))))
  11760. \end{lstlisting}
  11761. \section{Explicate Control and \LangCLoop{}}
  11762. \label{sec:explicate-loop}
  11763. Recall that in the \code{explicate-control} pass we define one helper
  11764. function for each kind of position in the program. For the \LangVar{}
  11765. language of integers and variables we needed kinds of positions:
  11766. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  11767. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  11768. yet another kind of position: effect position. Except for the last
  11769. subexpression, the subexpressions inside a \code{begin} are evaluated
  11770. only for their effect. Their result values are discarded. We can
  11771. generate better code by taking this fact into account.
  11772. The output language of \code{explicate-control} is \LangCLoop{}
  11773. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  11774. \LangCLam{}. The only syntactic difference is that \code{Call},
  11775. \code{vector-set!}, and \code{read} may also appear as statements.
  11776. The most significant difference between \LangCLam{} and \LangCLoop{}
  11777. is that the control-flow graphs of the later may contain cycles.
  11778. \begin{figure}[tp]
  11779. \fbox{
  11780. \begin{minipage}{0.96\textwidth}
  11781. \small
  11782. \[
  11783. \begin{array}{lcl}
  11784. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  11785. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  11786. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  11787. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  11788. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  11789. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  11790. \end{array}
  11791. \]
  11792. \end{minipage}
  11793. }
  11794. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  11795. \label{fig:c7-syntax}
  11796. \end{figure}
  11797. The new auxiliary function \code{explicate-effect} takes an expression
  11798. (in an effect position) and a promise of a continuation block. The
  11799. function returns a promise for a $\Tail$ that includes the generated
  11800. code for the input expression followed by the continuation block. If
  11801. the expression is obviously pure, that is, never causes side effects,
  11802. then the expression can be removed, so the result is just the
  11803. continuation block.
  11804. %
  11805. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  11806. case. First, you will need a fresh label $\itm{loop}$ for the top of
  11807. the loop. Recursively process the \itm{body} (in effect position)
  11808. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  11809. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  11810. \itm{body'} as the then-branch and the continuation block as the
  11811. else-branch. The result should be added to the control-flow graph with
  11812. the label \itm{loop}. The result for the whole \code{while} loop is a
  11813. \code{goto} to the \itm{loop} label. Note that the loop should only be
  11814. added to the control-flow graph if the loop is indeed used, which can
  11815. be accomplished using \code{delay}.
  11816. The auxiliary functions for tail, assignment, and predicate positions
  11817. need to be updated. The three new language forms, \code{while},
  11818. \code{set!}, and \code{begin}, can appear in assignment and tail
  11819. positions. Only \code{begin} may appear in predicate positions; the
  11820. other two have result type \code{Void}.
  11821. \section{Select Instructions}
  11822. \label{sec:select-instructions-loop}
  11823. Only three small additions are needed in the
  11824. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  11825. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  11826. stand-alone statements instead of only appearing on the right-hand
  11827. side of an assignment statement. The code generation is nearly
  11828. identical; just leave off the instruction for moving the result into
  11829. the left-hand side.
  11830. \section{Register Allocation}
  11831. \label{sec:register-allocation-loop}
  11832. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  11833. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11834. which complicates the liveness analysis needed for register
  11835. allocation.
  11836. \subsection{Liveness Analysis}
  11837. \label{sec:liveness-analysis-r8}
  11838. We recommend using the generic \code{analyze-dataflow} function that
  11839. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  11840. perform liveness analysis, replacing the code in
  11841. \code{uncover-live-CFG} that processed the basic blocks in topological
  11842. order (Section~\ref{sec:liveness-analysis-Rif}).
  11843. The \code{analyze-dataflow} function has four parameters.
  11844. \begin{enumerate}
  11845. \item The first parameter \code{G} should be a directed graph from the
  11846. \code{racket/graph} package (see the sidebar in
  11847. Section~\ref{sec:build-interference}) that represents the
  11848. control-flow graph.
  11849. \item The second parameter \code{transfer} is a function that applies
  11850. liveness analysis to a basic block. It takes two parameters: the
  11851. label for the block to analyze and the live-after set for that
  11852. block. The transfer function should return the live-before set for
  11853. the block. Also, as a side-effect, it should update the block's
  11854. $\itm{info}$ with the liveness information for each instruction. To
  11855. implement the \code{transfer} function, you should be able to reuse
  11856. the code you already have for analyzing basic blocks.
  11857. \item The third and fourth parameters of \code{analyze-dataflow} are
  11858. \code{bottom} and \code{join} for the lattice of abstract states,
  11859. i.e. sets of locations. The bottom of the lattice is the empty set
  11860. \code{(set)} and the join operator is \code{set-union}.
  11861. \end{enumerate}
  11862. \begin{figure}[p]
  11863. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11864. \node (Rfun) at (0,2) {\large \LangLoop{}};
  11865. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  11866. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  11867. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  11868. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  11869. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  11870. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  11871. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  11872. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  11873. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  11874. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11875. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11876. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11877. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11878. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11879. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11880. %% \path[->,bend left=15] (Rfun) edge [above] node
  11881. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  11882. \path[->,bend left=15] (Rfun) edge [above] node
  11883. {\ttfamily\footnotesize shrink} (Rfun-2);
  11884. \path[->,bend left=15] (Rfun-2) edge [above] node
  11885. {\ttfamily\footnotesize uniquify} (Rfun-3);
  11886. \path[->,bend left=15] (Rfun-3) edge [above] node
  11887. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  11888. \path[->,bend left=15] (Rfun-4) edge [right] node
  11889. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11890. \path[->,bend left=15] (F1-1) edge [below] node
  11891. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11892. \path[->,bend right=15] (F1-2) edge [above] node
  11893. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11894. \path[->,bend right=15] (F1-3) edge [above] node
  11895. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11896. \path[->,bend right=15] (F1-4) edge [above] node
  11897. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11898. \path[->,bend right=15] (F1-5) edge [right] node
  11899. {\ttfamily\footnotesize explicate-control} (C3-2);
  11900. \path[->,bend left=15] (C3-2) edge [left] node
  11901. {\ttfamily\footnotesize select-instr.} (x86-2);
  11902. \path[->,bend right=15] (x86-2) edge [left] node
  11903. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11904. \path[->,bend right=15] (x86-2-1) edge [below] node
  11905. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11906. \path[->,bend right=15] (x86-2-2) edge [left] node
  11907. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11908. \path[->,bend left=15] (x86-3) edge [above] node
  11909. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11910. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11911. \end{tikzpicture}
  11912. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  11913. \label{fig:Rwhile-passes}
  11914. \end{figure}
  11915. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  11916. for the compilation of \LangLoop{}.
  11917. \section{Challenge: Arrays}
  11918. \label{sec:arrays}
  11919. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  11920. elements whose length is determined at compile-time and where each
  11921. element of a tuple may have a different type (they are
  11922. heterogeous). This challenge is also about sequences, but this time
  11923. the length is determined at run-time and all the elements have the same
  11924. type (they are homogeneous). We use the term ``array'' for this later
  11925. kind of sequence.
  11926. The Racket language does not distinguish between tuples and arrays,
  11927. they are both represented by vectors. However, Typed Racket
  11928. distinguishes between tuples and arrays: the \code{Vector} type is for
  11929. tuples and the \code{Vectorof} type is for arrays.
  11930. %
  11931. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  11932. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11933. and the \code{make-vector} primitive operator for creating an array,
  11934. whose arguments are the length of the array and an initial value for
  11935. all the elements in the array. The \code{vector-length},
  11936. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11937. for tuples become overloaded for use with arrays.
  11938. %
  11939. We also include integer multiplication in \LangArray{}, as it is
  11940. useful in many examples involving arrays such as computing the
  11941. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11942. \begin{figure}[tp]
  11943. \centering
  11944. \fbox{
  11945. \begin{minipage}{0.96\textwidth}
  11946. \small
  11947. \[
  11948. \begin{array}{lcl}
  11949. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11950. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11951. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11952. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11953. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11954. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11955. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11956. \MID \LP\key{not}\;\Exp\RP } \\
  11957. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11958. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11959. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11960. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11961. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11962. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11963. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11964. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11965. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11966. \MID \CWHILE{\Exp}{\Exp} } \\
  11967. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11968. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11969. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11970. \end{array}
  11971. \]
  11972. \end{minipage}
  11973. }
  11974. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11975. \label{fig:Rvecof-concrete-syntax}
  11976. \end{figure}
  11977. \begin{figure}[tp]
  11978. \begin{lstlisting}
  11979. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11980. [n : Integer]) : Integer
  11981. (let ([i 0])
  11982. (let ([prod 0])
  11983. (begin
  11984. (while (< i n)
  11985. (begin
  11986. (set! prod (+ prod (* (vector-ref A i)
  11987. (vector-ref B i))))
  11988. (set! i (+ i 1))
  11989. ))
  11990. prod))))
  11991. (let ([A (make-vector 2 2)])
  11992. (let ([B (make-vector 2 3)])
  11993. (+ (inner-product A B 2)
  11994. 30)))
  11995. \end{lstlisting}
  11996. \caption{Example program that computes the inner-product.}
  11997. \label{fig:inner-product}
  11998. \end{figure}
  11999. The type checker for \LangArray{} is define in
  12000. Figure~\ref{fig:type-check-Rvecof}. The result type of
  12001. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  12002. of the intializing expression. The length expression is required to
  12003. have type \code{Integer}. The type checking of the operators
  12004. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12005. updated to handle the situation where the vector has type
  12006. \code{Vectorof}. In these cases we translate the operators to their
  12007. \code{vectorof} form so that later passes can easily distinguish
  12008. between operations on tuples versus arrays. We override the
  12009. \code{operator-types} method to provide the type signature for
  12010. multiplication: it takes two integers and returns an integer. To
  12011. support injection and projection of arrays to the \code{Any} type
  12012. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  12013. predicate.
  12014. \begin{figure}[tbp]
  12015. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12016. (define type-check-Rvecof-class
  12017. (class type-check-Rwhile-class
  12018. (super-new)
  12019. (inherit check-type-equal?)
  12020. (define/override (flat-ty? ty)
  12021. (match ty
  12022. ['(Vectorof Any) #t]
  12023. [else (super flat-ty? ty)]))
  12024. (define/override (operator-types)
  12025. (append '((* . ((Integer Integer) . Integer)))
  12026. (super operator-types)))
  12027. (define/override (type-check-exp env)
  12028. (lambda (e)
  12029. (define recur (type-check-exp env))
  12030. (match e
  12031. [(Prim 'make-vector (list e1 e2))
  12032. (define-values (e1^ t1) (recur e1))
  12033. (define-values (e2^ elt-type) (recur e2))
  12034. (define vec-type `(Vectorof ,elt-type))
  12035. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  12036. vec-type)]
  12037. [(Prim 'vector-ref (list e1 e2))
  12038. (define-values (e1^ t1) (recur e1))
  12039. (define-values (e2^ t2) (recur e2))
  12040. (match* (t1 t2)
  12041. [(`(Vectorof ,elt-type) 'Integer)
  12042. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12043. [(other wise) ((super type-check-exp env) e)])]
  12044. [(Prim 'vector-set! (list e1 e2 e3) )
  12045. (define-values (e-vec t-vec) (recur e1))
  12046. (define-values (e2^ t2) (recur e2))
  12047. (define-values (e-arg^ t-arg) (recur e3))
  12048. (match t-vec
  12049. [`(Vectorof ,elt-type)
  12050. (check-type-equal? elt-type t-arg e)
  12051. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12052. [else ((super type-check-exp env) e)])]
  12053. [(Prim 'vector-length (list e1))
  12054. (define-values (e1^ t1) (recur e1))
  12055. (match t1
  12056. [`(Vectorof ,t)
  12057. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12058. [else ((super type-check-exp env) e)])]
  12059. [else ((super type-check-exp env) e)])))
  12060. ))
  12061. (define (type-check-Rvecof p)
  12062. (send (new type-check-Rvecof-class) type-check-program p))
  12063. \end{lstlisting}
  12064. \caption{Type checker for the \LangArray{} language.}
  12065. \label{fig:type-check-Rvecof}
  12066. \end{figure}
  12067. The interpreter for \LangArray{} is defined in
  12068. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  12069. implemented with Racket's \code{make-vector} function and
  12070. multiplication is \code{fx*}, multiplication for \code{fixnum}
  12071. integers.
  12072. \begin{figure}[tbp]
  12073. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12074. (define interp-Rvecof-class
  12075. (class interp-Rwhile-class
  12076. (super-new)
  12077. (define/override (interp-op op)
  12078. (verbose "Rvecof/interp-op" op)
  12079. (match op
  12080. ['make-vector make-vector]
  12081. ['* fx*]
  12082. [else (super interp-op op)]))
  12083. ))
  12084. (define (interp-Rvecof p)
  12085. (send (new interp-Rvecof-class) interp-program p))
  12086. \end{lstlisting}
  12087. \caption{Interpreter for \LangArray{}.}
  12088. \label{fig:interp-Rvecof}
  12089. \end{figure}
  12090. \subsection{Data Representation}
  12091. \label{sec:array-rep}
  12092. Just like tuples, we store arrays on the heap which means that the
  12093. garbage collector will need to inspect arrays. An immediate thought is
  12094. to use the same representation for arrays that we use for tuples.
  12095. However, we limit tuples to a length of $50$ so that their length and
  12096. pointer mask can fit into the 64-bit tag at the beginning of each
  12097. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12098. millions of elements, so we need more bits to store the length.
  12099. However, because arrays are homogeneous, we only need $1$ bit for the
  12100. pointer mask instead of one bit per array elements. Finally, the
  12101. garbage collector will need to be able to distinguish between tuples
  12102. and arrays, so we need to reserve $1$ bit for that purpose. So we
  12103. arrive at the following layout for the 64-bit tag at the beginning of
  12104. an array:
  12105. \begin{itemize}
  12106. \item The right-most bit is the forwarding bit, just like in a tuple.
  12107. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  12108. it is not.
  12109. \item The next bit to the left is the pointer mask. A $0$ indicates
  12110. that none of the elements are pointers to the heap and a $1$
  12111. indicates that all of the elements are pointers.
  12112. \item The next $61$ bits store the length of the array.
  12113. \item The left-most bit distinguishes between a tuple ($0$) versus an
  12114. array ($1$).
  12115. \end{itemize}
  12116. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  12117. differentiate the kinds of values that have been injected into the
  12118. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12119. to indicate that the value is an array.
  12120. In the following subsections we provide hints regarding how to update
  12121. the passes to handle arrays.
  12122. \subsection{Reveal Casts}
  12123. The array-access operators \code{vectorof-ref} and
  12124. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12125. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  12126. that the type checker cannot tell whether the index will be in bounds,
  12127. so the bounds check must be performed at run time. Recall that the
  12128. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  12129. an \code{If} arround a vector reference for update to check whether
  12130. the index is less than the length. You should do the same for
  12131. \code{vectorof-ref} and \code{vectorof-set!} .
  12132. In addition, the handling of the \code{any-vector} operators in
  12133. \code{reveal-casts} needs to be updated to account for arrays that are
  12134. injected to \code{Any}. For the \code{any-vector-length} operator, the
  12135. generated code should test whether the tag is for tuples (\code{010})
  12136. or arrays (\code{110}) and then dispatch to either
  12137. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12138. we add a case in \code{select-instructions} to generate the
  12139. appropriate instructions for accessing the array length from the
  12140. header of an array.
  12141. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12142. the generated code needs to check that the index is less than the
  12143. vector length, so like the code for \code{any-vector-length}, check
  12144. the tag to determine whether to use \code{any-vector-length} or
  12145. \code{any-vectorof-length} for this purpose. Once the bounds checking
  12146. is complete, the generated code can use \code{any-vector-ref} and
  12147. \code{any-vector-set!} for both tuples and arrays because the
  12148. instructions used for those operators do not look at the tag at the
  12149. front of the tuple or array.
  12150. \subsection{Expose Allocation}
  12151. This pass should translate the \code{make-vector} operator into
  12152. lower-level operations. In particular, the new AST node
  12153. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  12154. length specified by the $\Exp$, but does not initialize the elements
  12155. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  12156. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  12157. element type for the array. Regarding the initialization of the array,
  12158. we recommend generated a \code{while} loop that uses
  12159. \code{vector-set!} to put the initializing value into every element of
  12160. the array.
  12161. \subsection{Remove Complex Operands}
  12162. Add cases in the \code{rco-atom} and \code{rco-exp} for
  12163. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12164. complex and its subexpression must be atomic.
  12165. \subsection{Explicate Control}
  12166. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  12167. \code{explicate-assign}.
  12168. \subsection{Select Instructions}
  12169. Generate instructions for \code{AllocateArray} similar to those for
  12170. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  12171. that the tag at the front of the array should instead use the
  12172. representation discussed in Section~\ref{sec:array-rep}.
  12173. Regarding \code{vectorof-length}, extract the length from the tag
  12174. according to the representation discussed in
  12175. Section~\ref{sec:array-rep}.
  12176. The instructions generated for \code{vectorof-ref} differ from those
  12177. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  12178. that the index is not a constant so the offset must be computed at
  12179. runtime, similar to the instructions generated for
  12180. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  12181. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  12182. appear in an assignment and as a stand-alone statement, so make sure
  12183. to handle both situations in this pass.
  12184. Finally, the instructions for \code{any-vectorof-length} should be
  12185. similar to those for \code{vectorof-length}, except that one must
  12186. first project the array by writing zeroes into the $3$-bit tag
  12187. \begin{exercise}\normalfont
  12188. Implement a compiler for the \LangArray{} language by extending your
  12189. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12190. programs, including the one in Figure~\ref{fig:inner-product} and also
  12191. a program that multiplies two matrices. Note that matrices are
  12192. 2-dimensional arrays, but those can be encoded into 1-dimensional
  12193. arrays by laying out each row in the array, one after the next.
  12194. \end{exercise}
  12195. % Further Reading: dataflow analysis
  12196. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12197. \chapter{Gradual Typing}
  12198. \label{ch:Rgrad}
  12199. \index{subject}{gradual typing}
  12200. This chapter studies a language, \LangGrad{}, in which the programmer
  12201. can choose between static and dynamic type checking in different parts
  12202. of a program, thereby mixing the statically typed \LangLoop{} language
  12203. with the dynamically typed \LangDyn{}. There are several approaches to
  12204. mixing static and dynamic typing, including multi-language
  12205. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  12206. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  12207. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  12208. programmer controls the amount of static versus dynamic checking by
  12209. adding or removing type annotations on parameters and
  12210. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  12211. %
  12212. The concrete syntax of \LangGrad{} is defined in
  12213. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  12214. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  12215. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  12216. non-terminals that make type annotations optional. The return types
  12217. are not optional in the abstract syntax; the parser fills in
  12218. \code{Any} when the return type is not specified in the concrete
  12219. syntax.
  12220. \begin{figure}[tp]
  12221. \centering
  12222. \fbox{
  12223. \begin{minipage}{0.96\textwidth}
  12224. \small
  12225. \[
  12226. \begin{array}{lcl}
  12227. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  12228. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  12229. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12230. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  12231. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12232. &\MID& \gray{\key{\#t} \MID \key{\#f}
  12233. \MID (\key{and}\;\Exp\;\Exp)
  12234. \MID (\key{or}\;\Exp\;\Exp)
  12235. \MID (\key{not}\;\Exp) } \\
  12236. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12237. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  12238. (\key{vector-ref}\;\Exp\;\Int)} \\
  12239. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  12240. \MID (\Exp \; \Exp\ldots) } \\
  12241. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  12242. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  12243. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  12244. \MID \CBEGIN{\Exp\ldots}{\Exp}
  12245. \MID \CWHILE{\Exp}{\Exp} } \\
  12246. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  12247. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  12248. \end{array}
  12249. \]
  12250. \end{minipage}
  12251. }
  12252. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12253. \label{fig:Rgrad-concrete-syntax}
  12254. \end{figure}
  12255. \begin{figure}[tp]
  12256. \centering
  12257. \fbox{
  12258. \begin{minipage}{0.96\textwidth}
  12259. \small
  12260. \[
  12261. \begin{array}{lcl}
  12262. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  12263. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  12264. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  12265. &\MID& \gray{ \BOOL{\itm{bool}}
  12266. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  12267. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  12268. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  12269. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  12270. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  12271. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  12272. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  12273. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12274. \end{array}
  12275. \]
  12276. \end{minipage}
  12277. }
  12278. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  12279. \label{fig:Rgrad-syntax}
  12280. \end{figure}
  12281. Both the type checker and the interpreter for \LangGrad{} require some
  12282. interesting changes to enable gradual typing, which we discuss in the
  12283. next two sections in the context of the \code{map-vec} example from
  12284. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  12285. revised the \code{map-vec} example, omitting the type annotations from
  12286. the \code{add1} function.
  12287. \begin{figure}[btp]
  12288. % gradual_test_9.rkt
  12289. \begin{lstlisting}
  12290. (define (map-vec [f : (Integer -> Integer)]
  12291. [v : (Vector Integer Integer)])
  12292. : (Vector Integer Integer)
  12293. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12294. (define (add1 x) (+ x 1))
  12295. (vector-ref (map-vec add1 (vector 0 41)) 1)
  12296. \end{lstlisting}
  12297. \caption{A partially-typed version of the \code{map-vec} example.}
  12298. \label{fig:gradual-map-vec}
  12299. \end{figure}
  12300. \section{Type Checking \LangGrad{} and \LangCast{}}
  12301. \label{sec:gradual-type-check}
  12302. The type checker for \LangGrad{} uses the \code{Any} type for missing
  12303. parameter and return types. For example, the \code{x} parameter of
  12304. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  12305. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  12306. consider the \code{+} operator inside \code{add1}. It expects both
  12307. arguments to have type \code{Integer}, but its first argument \code{x}
  12308. has type \code{Any}. In a gradually typed language, such differences
  12309. are allowed so long as the types are \emph{consistent}, that is, they
  12310. are equal except in places where there is an \code{Any} type. The type
  12311. \code{Any} is consistent with every other type.
  12312. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  12313. \begin{figure}[tbp]
  12314. \begin{lstlisting}
  12315. (define/public (consistent? t1 t2)
  12316. (match* (t1 t2)
  12317. [('Integer 'Integer) #t]
  12318. [('Boolean 'Boolean) #t]
  12319. [('Void 'Void) #t]
  12320. [('Any t2) #t]
  12321. [(t1 'Any) #t]
  12322. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12323. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  12324. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12325. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  12326. (consistent? rt1 rt2))]
  12327. [(other wise) #f]))
  12328. \end{lstlisting}
  12329. \caption{The consistency predicate on types.}
  12330. \label{fig:consistent}
  12331. \end{figure}
  12332. Returning to the \code{map-vec} example of
  12333. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  12334. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  12335. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  12336. because the two types are consistent. In particular, \code{->} is
  12337. equal to \code{->} and because \code{Any} is consistent with
  12338. \code{Integer}.
  12339. Next consider a program with an error, such as applying the
  12340. \code{map-vec} to a function that sometimes returns a Boolean, as
  12341. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  12342. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  12343. consistent with the type of parameter \code{f} of \code{map-vec}, that
  12344. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  12345. Integer)}. One might say that a gradual type checker is optimistic
  12346. in that it accepts programs that might execute without a runtime type
  12347. error.
  12348. %
  12349. Unfortunately, running this program with input \code{1} triggers an
  12350. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  12351. performs checking at runtime to ensure the integrity of the static
  12352. types, such as the \code{(Integer -> Integer)} annotation on parameter
  12353. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  12354. new \code{Cast} form that is inserted by the type checker. Thus, the
  12355. output of the type checker is a program in the \LangCast{} language, which
  12356. adds \code{Cast} to \LangLoop{}, as shown in
  12357. Figure~\ref{fig:Rgrad-prime-syntax}.
  12358. \begin{figure}[tp]
  12359. \centering
  12360. \fbox{
  12361. \begin{minipage}{0.96\textwidth}
  12362. \small
  12363. \[
  12364. \begin{array}{lcl}
  12365. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  12366. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12367. \end{array}
  12368. \]
  12369. \end{minipage}
  12370. }
  12371. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  12372. \label{fig:Rgrad-prime-syntax}
  12373. \end{figure}
  12374. \begin{figure}[tbp]
  12375. \begin{lstlisting}
  12376. (define (map-vec [f : (Integer -> Integer)]
  12377. [v : (Vector Integer Integer)])
  12378. : (Vector Integer Integer)
  12379. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12380. (define (add1 x) (+ x 1))
  12381. (define (true) #t)
  12382. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  12383. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  12384. \end{lstlisting}
  12385. \caption{A variant of the \code{map-vec} example with an error.}
  12386. \label{fig:map-vec-maybe-add1}
  12387. \end{figure}
  12388. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  12389. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  12390. inserted every time the type checker sees two types that are
  12391. consistent but not equal. In the \code{add1} function, \code{x} is
  12392. cast to \code{Integer} and the result of the \code{+} is cast to
  12393. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  12394. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  12395. \begin{figure}[btp]
  12396. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12397. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12398. : (Vector Integer Integer)
  12399. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12400. (define (add1 [x : Any]) : Any
  12401. (cast (+ (cast x Any Integer) 1) Integer Any))
  12402. (define (true) : Any (cast #t Boolean Any))
  12403. (define (maybe-add1 [x : Any]) : Any
  12404. (if (eq? 0 (read)) (add1 x) (true)))
  12405. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  12406. (vector 0 41)) 0)
  12407. \end{lstlisting}
  12408. \caption{Output of type checking \code{map-vec}
  12409. and \code{maybe-add1}.}
  12410. \label{fig:map-vec-cast}
  12411. \end{figure}
  12412. The type checker for \LangGrad{} is defined in
  12413. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  12414. and \ref{fig:type-check-Rgradual-3}.
  12415. \begin{figure}[tbp]
  12416. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12417. (define type-check-gradual-class
  12418. (class type-check-Rwhile-class
  12419. (super-new)
  12420. (inherit operator-types type-predicates)
  12421. (define/override (type-check-exp env)
  12422. (lambda (e)
  12423. (define recur (type-check-exp env))
  12424. (match e
  12425. [(Prim 'vector-length (list e1))
  12426. (define-values (e1^ t) (recur e1))
  12427. (match t
  12428. [`(Vector ,ts ...)
  12429. (values (Prim 'vector-length (list e1^)) 'Integer)]
  12430. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  12431. [(Prim 'vector-ref (list e1 e2))
  12432. (define-values (e1^ t1) (recur e1))
  12433. (define-values (e2^ t2) (recur e2))
  12434. (check-consistent? t2 'Integer e)
  12435. (match t1
  12436. [`(Vector ,ts ...)
  12437. (match e2^
  12438. [(Int i)
  12439. (unless (and (0 . <= . i) (i . < . (length ts)))
  12440. (error 'type-check "invalid index ~a in ~a" i e))
  12441. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  12442. [else (define e1^^ (make-cast e1^ t1 'Any))
  12443. (define e2^^ (make-cast e2^ t2 'Integer))
  12444. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  12445. ['Any
  12446. (define e2^^ (make-cast e2^ t2 'Integer))
  12447. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  12448. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  12449. [(Prim 'vector-set! (list e1 e2 e3) )
  12450. (define-values (e1^ t1) (recur e1))
  12451. (define-values (e2^ t2) (recur e2))
  12452. (define-values (e3^ t3) (recur e3))
  12453. (check-consistent? t2 'Integer e)
  12454. (match t1
  12455. [`(Vector ,ts ...)
  12456. (match e2^
  12457. [(Int i)
  12458. (unless (and (0 . <= . i) (i . < . (length ts)))
  12459. (error 'type-check "invalid index ~a in ~a" i e))
  12460. (check-consistent? (list-ref ts i) t3 e)
  12461. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  12462. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  12463. [else
  12464. (define e1^^ (make-cast e1^ t1 'Any))
  12465. (define e2^^ (make-cast e2^ t2 'Integer))
  12466. (define e3^^ (make-cast e3^ t3 'Any))
  12467. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  12468. ['Any
  12469. (define e2^^ (make-cast e2^ t2 'Integer))
  12470. (define e3^^ (make-cast e3^ t3 'Any))
  12471. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  12472. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  12473. \end{lstlisting}
  12474. \caption{Type checker for the \LangGrad{} language, part 1.}
  12475. \label{fig:type-check-Rgradual-1}
  12476. \end{figure}
  12477. \begin{figure}[tbp]
  12478. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12479. [(Prim 'eq? (list e1 e2))
  12480. (define-values (e1^ t1) (recur e1))
  12481. (define-values (e2^ t2) (recur e2))
  12482. (check-consistent? t1 t2 e)
  12483. (define T (meet t1 t2))
  12484. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  12485. 'Boolean)]
  12486. [(Prim 'not (list e1))
  12487. (define-values (e1^ t1) (recur e1))
  12488. (match t1
  12489. ['Any
  12490. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  12491. (Bool #t) (Bool #f)))]
  12492. [else
  12493. (define-values (t-ret new-es^)
  12494. (type-check-op 'not (list t1) (list e1^) e))
  12495. (values (Prim 'not new-es^) t-ret)])]
  12496. [(Prim 'and (list e1 e2))
  12497. (recur (If e1 e2 (Bool #f)))]
  12498. [(Prim 'or (list e1 e2))
  12499. (define tmp (gensym 'tmp))
  12500. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  12501. [(Prim op es)
  12502. #:when (not (set-member? explicit-prim-ops op))
  12503. (define-values (new-es ts)
  12504. (for/lists (exprs types) ([e es])
  12505. (recur e)))
  12506. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  12507. (values (Prim op new-es^) t-ret)]
  12508. [(If e1 e2 e3)
  12509. (define-values (e1^ T1) (recur e1))
  12510. (define-values (e2^ T2) (recur e2))
  12511. (define-values (e3^ T3) (recur e3))
  12512. (check-consistent? T2 T3 e)
  12513. (match T1
  12514. ['Boolean
  12515. (define Tif (join T2 T3))
  12516. (values (If e1^ (make-cast e2^ T2 Tif)
  12517. (make-cast e3^ T3 Tif)) Tif)]
  12518. ['Any
  12519. (define Tif (meet T2 T3))
  12520. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  12521. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  12522. Tif)]
  12523. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  12524. [(HasType e1 T)
  12525. (define-values (e1^ T1) (recur e1))
  12526. (check-consistent? T1 T)
  12527. (values (make-cast e1^ T1 T) T)]
  12528. [(SetBang x e1)
  12529. (define-values (e1^ T1) (recur e1))
  12530. (define varT (dict-ref env x))
  12531. (check-consistent? T1 varT e)
  12532. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  12533. [(WhileLoop e1 e2)
  12534. (define-values (e1^ T1) (recur e1))
  12535. (check-consistent? T1 'Boolean e)
  12536. (define-values (e2^ T2) ((type-check-exp env) e2))
  12537. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  12538. \end{lstlisting}
  12539. \caption{Type checker for the \LangGrad{} language, part 2.}
  12540. \label{fig:type-check-Rgradual-2}
  12541. \end{figure}
  12542. \begin{figure}[tbp]
  12543. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12544. [(Apply e1 e2s)
  12545. (define-values (e1^ T1) (recur e1))
  12546. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  12547. (match T1
  12548. [`(,T1ps ... -> ,T1rt)
  12549. (for ([T2 T2s] [Tp T1ps])
  12550. (check-consistent? T2 Tp e))
  12551. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  12552. (make-cast e2 src tgt)))
  12553. (values (Apply e1^ e2s^^) T1rt)]
  12554. [`Any
  12555. (define e1^^ (make-cast e1^ 'Any
  12556. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  12557. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  12558. (make-cast e2 src 'Any)))
  12559. (values (Apply e1^^ e2s^^) 'Any)]
  12560. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  12561. [(Lambda params Tr e1)
  12562. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  12563. (match p
  12564. [`[,x : ,T] (values x T)]
  12565. [(? symbol? x) (values x 'Any)])))
  12566. (define-values (e1^ T1)
  12567. ((type-check-exp (append (map cons xs Ts) env)) e1))
  12568. (check-consistent? Tr T1 e)
  12569. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  12570. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  12571. [else ((super type-check-exp env) e)]
  12572. )))
  12573. \end{lstlisting}
  12574. \caption{Type checker for the \LangGrad{} language, part 3.}
  12575. \label{fig:type-check-Rgradual-3}
  12576. \end{figure}
  12577. \begin{figure}[tbp]
  12578. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12579. (define/public (join t1 t2)
  12580. (match* (t1 t2)
  12581. [('Integer 'Integer) 'Integer]
  12582. [('Boolean 'Boolean) 'Boolean]
  12583. [('Void 'Void) 'Void]
  12584. [('Any t2) t2]
  12585. [(t1 'Any) t1]
  12586. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12587. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  12588. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12589. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  12590. -> ,(join rt1 rt2))]))
  12591. (define/public (meet t1 t2)
  12592. (match* (t1 t2)
  12593. [('Integer 'Integer) 'Integer]
  12594. [('Boolean 'Boolean) 'Boolean]
  12595. [('Void 'Void) 'Void]
  12596. [('Any t2) 'Any]
  12597. [(t1 'Any) 'Any]
  12598. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12599. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  12600. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12601. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  12602. -> ,(meet rt1 rt2))]))
  12603. (define/public (make-cast e src tgt)
  12604. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  12605. (define/public (check-consistent? t1 t2 e)
  12606. (unless (consistent? t1 t2)
  12607. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  12608. (define/override (type-check-op op arg-types args e)
  12609. (match (dict-ref (operator-types) op)
  12610. [`(,param-types . ,return-type)
  12611. (for ([at arg-types] [pt param-types])
  12612. (check-consistent? at pt e))
  12613. (values return-type
  12614. (for/list ([e args] [s arg-types] [t param-types])
  12615. (make-cast e s t)))]
  12616. [else (error 'type-check-op "unrecognized ~a" op)]))
  12617. (define explicit-prim-ops
  12618. (set-union
  12619. (type-predicates)
  12620. (set 'procedure-arity 'eq?
  12621. 'vector 'vector-length 'vector-ref 'vector-set!
  12622. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  12623. (define/override (fun-def-type d)
  12624. (match d
  12625. [(Def f params rt info body)
  12626. (define ps
  12627. (for/list ([p params])
  12628. (match p
  12629. [`[,x : ,T] T]
  12630. [(? symbol?) 'Any]
  12631. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  12632. `(,@ps -> ,rt)]
  12633. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  12634. \end{lstlisting}
  12635. \caption{Auxiliary functions for type checking \LangGrad{}.}
  12636. \label{fig:type-check-Rgradual-aux}
  12637. \end{figure}
  12638. \clearpage
  12639. \section{Interpreting \LangCast{}}
  12640. \label{sec:interp-casts}
  12641. The runtime behavior of first-order casts is straightforward, that is,
  12642. casts involving simple types such as \code{Integer} and
  12643. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  12644. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  12645. puts the integer into a tagged value
  12646. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  12647. \code{Integer} is accomplished with the \code{Project} operator, that
  12648. is, by checking the value's tag and either retrieving the underlying
  12649. integer or signaling an error if it the tag is not the one for
  12650. integers (Figure~\ref{fig:apply-project}).
  12651. %
  12652. Things get more interesting for higher-order casts, that is, casts
  12653. involving function or vector types.
  12654. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  12655. Any)} to \code{(Integer -> Integer)}. When a function flows through
  12656. this cast at runtime, we can't know in general whether the function
  12657. will always return an integer.\footnote{Predicting the return value of
  12658. a function is equivalent to the halting problem, which is
  12659. undecidable.} The \LangCast{} interpreter therefore delays the checking
  12660. of the cast until the function is applied. This is accomplished by
  12661. wrapping \code{maybe-add1} in a new function that casts its parameter
  12662. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  12663. casts the return value from \code{Any} to \code{Integer}.
  12664. Turning our attention to casts involving vector types, we consider the
  12665. example in Figure~\ref{fig:map-vec-bang} that defines a
  12666. partially-typed version of \code{map-vec} whose parameter \code{v} has
  12667. type \code{(Vector Any Any)} and that updates \code{v} in place
  12668. instead of returning a new vector. So we name this function
  12669. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  12670. the type checker inserts a cast from \code{(Vector Integer Integer)}
  12671. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  12672. cast between vector types would be a build a new vector whose elements
  12673. are the result of casting each of the original elements to the
  12674. appropriate target type. However, this approach is only valid for
  12675. immutable vectors; and our vectors are mutable. In the example of
  12676. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  12677. the updates inside of \code{map-vec!} would happen to the new vector
  12678. and not the original one.
  12679. \begin{figure}[tbp]
  12680. % gradual_test_11.rkt
  12681. \begin{lstlisting}
  12682. (define (map-vec! [f : (Any -> Any)]
  12683. [v : (Vector Any Any)]) : Void
  12684. (begin
  12685. (vector-set! v 0 (f (vector-ref v 0)))
  12686. (vector-set! v 1 (f (vector-ref v 1)))))
  12687. (define (add1 x) (+ x 1))
  12688. (let ([v (vector 0 41)])
  12689. (begin (map-vec! add1 v) (vector-ref v 1)))
  12690. \end{lstlisting}
  12691. \caption{An example involving casts on vectors.}
  12692. \label{fig:map-vec-bang}
  12693. \end{figure}
  12694. Instead the interpreter needs to create a new kind of value, a
  12695. \emph{vector proxy}, that intercepts every vector operation. On a
  12696. read, the proxy reads from the underlying vector and then applies a
  12697. cast to the resulting value. On a write, the proxy casts the argument
  12698. value and then performs the write to the underlying vector. For the
  12699. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  12700. \code{0} from \code{Integer} to \code{Any}. For the first
  12701. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  12702. to \code{Integer}.
  12703. The final category of cast that we need to consider are casts between
  12704. the \code{Any} type and either a function or a vector
  12705. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  12706. in which parameter \code{v} does not have a type annotation, so it is
  12707. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  12708. type \code{(Vector Integer Integer)} so the type checker inserts a
  12709. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  12710. thought is to use \code{Inject}, but that doesn't work because
  12711. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  12712. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  12713. to \code{Any}.
  12714. \begin{figure}[tbp]
  12715. \begin{lstlisting}
  12716. (define (map-vec! [f : (Any -> Any)] v) : Void
  12717. (begin
  12718. (vector-set! v 0 (f (vector-ref v 0)))
  12719. (vector-set! v 1 (f (vector-ref v 1)))))
  12720. (define (add1 x) (+ x 1))
  12721. (let ([v (vector 0 41)])
  12722. (begin (map-vec! add1 v) (vector-ref v 1)))
  12723. \end{lstlisting}
  12724. \caption{Casting a vector to \code{Any}.}
  12725. \label{fig:map-vec-any}
  12726. \end{figure}
  12727. The \LangCast{} interpreter uses an auxiliary function named
  12728. \code{apply-cast} to cast a value from a source type to a target type,
  12729. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  12730. of the kinds of casts that we've discussed in this section.
  12731. \begin{figure}[tbp]
  12732. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12733. (define/public (apply-cast v s t)
  12734. (match* (s t)
  12735. [(t1 t2) #:when (equal? t1 t2) v]
  12736. [('Any t2)
  12737. (match t2
  12738. [`(,ts ... -> ,rt)
  12739. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  12740. (define v^ (apply-project v any->any))
  12741. (apply-cast v^ any->any `(,@ts -> ,rt))]
  12742. [`(Vector ,ts ...)
  12743. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  12744. (define v^ (apply-project v vec-any))
  12745. (apply-cast v^ vec-any `(Vector ,@ts))]
  12746. [else (apply-project v t2)])]
  12747. [(t1 'Any)
  12748. (match t1
  12749. [`(,ts ... -> ,rt)
  12750. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  12751. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  12752. (apply-inject v^ (any-tag any->any))]
  12753. [`(Vector ,ts ...)
  12754. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  12755. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  12756. (apply-inject v^ (any-tag vec-any))]
  12757. [else (apply-inject v (any-tag t1))])]
  12758. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  12759. (define x (gensym 'x))
  12760. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  12761. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  12762. (define cast-writes
  12763. (for/list ([t1 ts1] [t2 ts2])
  12764. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  12765. `(vector-proxy ,(vector v (apply vector cast-reads)
  12766. (apply vector cast-writes)))]
  12767. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  12768. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  12769. `(function ,xs ,(Cast
  12770. (Apply (Value v)
  12771. (for/list ([x xs][t1 ts1][t2 ts2])
  12772. (Cast (Var x) t2 t1)))
  12773. rt1 rt2) ())]
  12774. ))
  12775. \end{lstlisting}
  12776. \caption{The \code{apply-cast} auxiliary method.}
  12777. \label{fig:apply-cast}
  12778. \end{figure}
  12779. The interpreter for \LangCast{} is defined in
  12780. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  12781. dispatching to \code{apply-cast}. To handle the addition of vector
  12782. proxies, we update the vector primitives in \code{interp-op} using the
  12783. functions in Figure~\ref{fig:guarded-vector}.
  12784. \begin{figure}[tbp]
  12785. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12786. (define interp-Rcast-class
  12787. (class interp-Rwhile-class
  12788. (super-new)
  12789. (inherit apply-fun apply-inject apply-project)
  12790. (define/override (interp-op op)
  12791. (match op
  12792. ['vector-length guarded-vector-length]
  12793. ['vector-ref guarded-vector-ref]
  12794. ['vector-set! guarded-vector-set!]
  12795. ['any-vector-ref (lambda (v i)
  12796. (match v [`(tagged ,v^ ,tg)
  12797. (guarded-vector-ref v^ i)]))]
  12798. ['any-vector-set! (lambda (v i a)
  12799. (match v [`(tagged ,v^ ,tg)
  12800. (guarded-vector-set! v^ i a)]))]
  12801. ['any-vector-length (lambda (v)
  12802. (match v [`(tagged ,v^ ,tg)
  12803. (guarded-vector-length v^)]))]
  12804. [else (super interp-op op)]
  12805. ))
  12806. (define/override ((interp-exp env) e)
  12807. (define (recur e) ((interp-exp env) e))
  12808. (match e
  12809. [(Value v) v]
  12810. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  12811. [else ((super interp-exp env) e)]))
  12812. ))
  12813. (define (interp-Rcast p)
  12814. (send (new interp-Rcast-class) interp-program p))
  12815. \end{lstlisting}
  12816. \caption{The interpreter for \LangCast{}.}
  12817. \label{fig:interp-Rcast}
  12818. \end{figure}
  12819. \begin{figure}[tbp]
  12820. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12821. (define (guarded-vector-ref vec i)
  12822. (match vec
  12823. [`(vector-proxy ,proxy)
  12824. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  12825. (define rd (vector-ref (vector-ref proxy 1) i))
  12826. (apply-fun rd (list val) 'guarded-vector-ref)]
  12827. [else (vector-ref vec i)]))
  12828. (define (guarded-vector-set! vec i arg)
  12829. (match vec
  12830. [`(vector-proxy ,proxy)
  12831. (define wr (vector-ref (vector-ref proxy 2) i))
  12832. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  12833. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  12834. [else (vector-set! vec i arg)]))
  12835. (define (guarded-vector-length vec)
  12836. (match vec
  12837. [`(vector-proxy ,proxy)
  12838. (guarded-vector-length (vector-ref proxy 0))]
  12839. [else (vector-length vec)]))
  12840. \end{lstlisting}
  12841. \caption{The guarded-vector auxiliary functions.}
  12842. \label{fig:guarded-vector}
  12843. \end{figure}
  12844. \section{Lower Casts}
  12845. \label{sec:lower-casts}
  12846. The next step in the journey towards x86 is the \code{lower-casts}
  12847. pass that translates the casts in \LangCast{} to the lower-level
  12848. \code{Inject} and \code{Project} operators and a new operator for
  12849. creating vector proxies, extending the \LangLoop{} language to create
  12850. \LangProxy{}. We recommend creating an auxiliary function named
  12851. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  12852. and a target type, and translates it to expression in \LangProxy{} that has
  12853. the same behavior as casting the expression from the source to the
  12854. target type in the interpreter.
  12855. The \code{lower-cast} function can follow a code structure similar to
  12856. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  12857. the interpreter for \LangCast{} because it must handle the same cases as
  12858. \code{apply-cast} and it needs to mimic the behavior of
  12859. \code{apply-cast}. The most interesting cases are those concerning the
  12860. casts between two vector types and between two function types.
  12861. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  12862. type to another vector type is accomplished by creating a proxy that
  12863. intercepts the operations on the underlying vector. Here we make the
  12864. creation of the proxy explicit with the \code{vector-proxy} primitive
  12865. operation. It takes three arguments, the first is an expression for
  12866. the vector, the second is a vector of functions for casting an element
  12867. that is being read from the vector, and the third is a vector of
  12868. functions for casting an element that is being written to the vector.
  12869. You can create the functions using \code{Lambda}. Also, as we shall
  12870. see in the next section, we need to differentiate these vectors from
  12871. the user-created ones, so we recommend using a new primitive operator
  12872. named \code{raw-vector} instead of \code{vector} to create these
  12873. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  12874. the output of \code{lower-casts} on the example in
  12875. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  12876. integers to a vector of \code{Any}.
  12877. \begin{figure}[tbp]
  12878. \begin{lstlisting}
  12879. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  12880. (begin
  12881. (vector-set! v 0 (f (vector-ref v 0)))
  12882. (vector-set! v 1 (f (vector-ref v 1)))))
  12883. (define (add1 [x : Any]) : Any
  12884. (inject (+ (project x Integer) 1) Integer))
  12885. (let ([v (vector 0 41)])
  12886. (begin
  12887. (map-vec! add1 (vector-proxy v
  12888. (raw-vector (lambda: ([x9 : Integer]) : Any
  12889. (inject x9 Integer))
  12890. (lambda: ([x9 : Integer]) : Any
  12891. (inject x9 Integer)))
  12892. (raw-vector (lambda: ([x9 : Any]) : Integer
  12893. (project x9 Integer))
  12894. (lambda: ([x9 : Any]) : Integer
  12895. (project x9 Integer)))))
  12896. (vector-ref v 1)))
  12897. \end{lstlisting}
  12898. \caption{Output of \code{lower-casts} on the example in
  12899. Figure~\ref{fig:map-vec-bang}.}
  12900. \label{fig:map-vec-bang-lower-cast}
  12901. \end{figure}
  12902. A cast from one function type to another function type is accomplished
  12903. by generating a \code{Lambda} whose parameter and return types match
  12904. the target function type. The body of the \code{Lambda} should cast
  12905. the parameters from the target type to the source type (yes,
  12906. backwards! functions are contravariant\index{subject}{contravariant} in the
  12907. parameters), then call the underlying function, and finally cast the
  12908. result from the source return type to the target return type.
  12909. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  12910. \code{lower-casts} pass on the \code{map-vec} example in
  12911. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  12912. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  12913. \begin{figure}[tbp]
  12914. \begin{lstlisting}
  12915. (define (map-vec [f : (Integer -> Integer)]
  12916. [v : (Vector Integer Integer)])
  12917. : (Vector Integer Integer)
  12918. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12919. (define (add1 [x : Any]) : Any
  12920. (inject (+ (project x Integer) 1) Integer))
  12921. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  12922. (project (add1 (inject x9 Integer)) Integer))
  12923. (vector 0 41)) 1)
  12924. \end{lstlisting}
  12925. \caption{Output of \code{lower-casts} on the example in
  12926. Figure~\ref{fig:gradual-map-vec}.}
  12927. \label{fig:map-vec-lower-cast}
  12928. \end{figure}
  12929. \section{Differentiate Proxies}
  12930. \label{sec:differentiate-proxies}
  12931. So far the job of differentiating vectors and vector proxies has been
  12932. the job of the interpreter. For example, the interpreter for \LangCast{}
  12933. implements \code{vector-ref} using the \code{guarded-vector-ref}
  12934. function in Figure~\ref{fig:guarded-vector}. In the
  12935. \code{differentiate-proxies} pass we shift this responsibility to the
  12936. generated code.
  12937. We begin by designing the output language $R^p_8$. In
  12938. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  12939. proxies. In $R^p_8$ we return the \code{Vector} type to
  12940. its original meaning, as the type of real vectors, and we introduce a
  12941. new type, \code{PVector}, whose values can be either real vectors or
  12942. vector proxies. This new type comes with a suite of new primitive
  12943. operations for creating and using values of type \code{PVector}. We
  12944. don't need to introduce a new type to represent vector proxies. A
  12945. proxy is represented by a vector containing three things: 1) the
  12946. underlying vector, 2) a vector of functions for casting elements that
  12947. are read from the vector, and 3) a vector of functions for casting
  12948. values to be written to the vector. So we define the following
  12949. abbreviation for the type of a vector proxy:
  12950. \[
  12951. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  12952. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  12953. \to (\key{PVector}~ T' \ldots)
  12954. \]
  12955. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  12956. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  12957. %
  12958. Next we describe each of the new primitive operations.
  12959. \begin{description}
  12960. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  12961. (\key{PVector} $T \ldots$)]\ \\
  12962. %
  12963. This operation brands a vector as a value of the \code{PVector} type.
  12964. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  12965. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  12966. %
  12967. This operation brands a vector proxy as value of the \code{PVector} type.
  12968. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  12969. \code{Boolean}] \ \\
  12970. %
  12971. returns true if the value is a vector proxy and false if it is a
  12972. real vector.
  12973. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  12974. (\key{Vector} $T \ldots$)]\ \\
  12975. %
  12976. Assuming that the input is a vector (and not a proxy), this
  12977. operation returns the vector.
  12978. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  12979. $\to$ \code{Boolean}]\ \\
  12980. %
  12981. Given a vector proxy, this operation returns the length of the
  12982. underlying vector.
  12983. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  12984. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  12985. %
  12986. Given a vector proxy, this operation returns the $i$th element of
  12987. the underlying vector.
  12988. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  12989. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  12990. proxy, this operation writes a value to the $i$th element of the
  12991. underlying vector.
  12992. \end{description}
  12993. Now to discuss the translation that differentiates vectors from
  12994. proxies. First, every type annotation in the program must be
  12995. translated (recursively) to replace \code{Vector} with \code{PVector}.
  12996. Next, we must insert uses of \code{PVector} operations in the
  12997. appropriate places. For example, we wrap every vector creation with an
  12998. \code{inject-vector}.
  12999. \begin{lstlisting}
  13000. (vector |$e_1 \ldots e_n$|)
  13001. |$\Rightarrow$|
  13002. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  13003. \end{lstlisting}
  13004. The \code{raw-vector} operator that we introduced in the previous
  13005. section does not get injected.
  13006. \begin{lstlisting}
  13007. (raw-vector |$e_1 \ldots e_n$|)
  13008. |$\Rightarrow$|
  13009. (vector |$e'_1 \ldots e'_n$|)
  13010. \end{lstlisting}
  13011. The \code{vector-proxy} primitive translates as follows.
  13012. \begin{lstlisting}
  13013. (vector-proxy |$e_1~e_2~e_3$|)
  13014. |$\Rightarrow$|
  13015. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  13016. \end{lstlisting}
  13017. We translate the vector operations into conditional expressions that
  13018. check whether the value is a proxy and then dispatch to either the
  13019. appropriate proxy vector operation or the regular vector operation.
  13020. For example, the following is the translation for \code{vector-ref}.
  13021. \begin{lstlisting}
  13022. (vector-ref |$e_1$| |$i$|)
  13023. |$\Rightarrow$|
  13024. (let ([|$v~e_1$|])
  13025. (if (proxy? |$v$|)
  13026. (proxy-vector-ref |$v$| |$i$|)
  13027. (vector-ref (project-vector |$v$|) |$i$|)
  13028. \end{lstlisting}
  13029. Note in the case of a real vector, we must apply \code{project-vector}
  13030. before the \code{vector-ref}.
  13031. \section{Reveal Casts}
  13032. \label{sec:reveal-casts-gradual}
  13033. Recall that the \code{reveal-casts} pass
  13034. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  13035. \code{Inject} and \code{Project} into lower-level operations. In
  13036. particular, \code{Project} turns into a conditional expression that
  13037. inspects the tag and retrieves the underlying value. Here we need to
  13038. augment the translation of \code{Project} to handle the situation when
  13039. the target type is \code{PVector}. Instead of using
  13040. \code{vector-length} we need to use \code{proxy-vector-length}.
  13041. \begin{lstlisting}
  13042. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  13043. |$\Rightarrow$|
  13044. (let |$\itm{tmp}$| |$e'$|
  13045. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  13046. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  13047. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  13048. (exit)))
  13049. \end{lstlisting}
  13050. \section{Closure Conversion}
  13051. \label{sec:closure-conversion-gradual}
  13052. The closure conversion pass only requires one minor adjustment. The
  13053. auxiliary function that translates type annotations needs to be
  13054. updated to handle the \code{PVector} type.
  13055. \section{Explicate Control}
  13056. \label{sec:explicate-control-gradual}
  13057. Update the \code{explicate-control} pass to handle the new primitive
  13058. operations on the \code{PVector} type.
  13059. \section{Select Instructions}
  13060. \label{sec:select-instructions-gradual}
  13061. Recall that the \code{select-instructions} pass is responsible for
  13062. lowering the primitive operations into x86 instructions. So we need
  13063. to translate the new \code{PVector} operations to x86. To do so, the
  13064. first question we need to answer is how will we differentiate the two
  13065. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  13066. We need just one bit to accomplish this, and use the bit in position
  13067. $57$ of the 64-bit tag at the front of every vector (see
  13068. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  13069. for \code{inject-vector} we leave it that way.
  13070. \begin{lstlisting}
  13071. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  13072. |$\Rightarrow$|
  13073. movq |$e'_1$|, |$\itm{lhs'}$|
  13074. \end{lstlisting}
  13075. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  13076. \begin{lstlisting}
  13077. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  13078. |$\Rightarrow$|
  13079. movq |$e'_1$|, %r11
  13080. movq |$(1 << 57)$|, %rax
  13081. orq 0(%r11), %rax
  13082. movq %rax, 0(%r11)
  13083. movq %r11, |$\itm{lhs'}$|
  13084. \end{lstlisting}
  13085. The \code{proxy?} operation consumes the information so carefully
  13086. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  13087. isolates the $57$th bit to tell whether the value is a real vector or
  13088. a proxy.
  13089. \begin{lstlisting}
  13090. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  13091. |$\Rightarrow$|
  13092. movq |$e_1'$|, %r11
  13093. movq 0(%r11), %rax
  13094. sarq $57, %rax
  13095. andq $1, %rax
  13096. movq %rax, |$\itm{lhs'}$|
  13097. \end{lstlisting}
  13098. The \code{project-vector} operation is straightforward to translate,
  13099. so we leave it up to the reader.
  13100. Regarding the \code{proxy-vector} operations, the runtime provides
  13101. procedures that implement them (they are recursive functions!) so
  13102. here we simply need to translate these vector operations into the
  13103. appropriate function call. For example, here is the translation for
  13104. \code{proxy-vector-ref}.
  13105. \begin{lstlisting}
  13106. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  13107. |$\Rightarrow$|
  13108. movq |$e_1'$|, %rdi
  13109. movq |$e_2'$|, %rsi
  13110. callq proxy_vector_ref
  13111. movq %rax, |$\itm{lhs'}$|
  13112. \end{lstlisting}
  13113. We have another batch of vector operations to deal with, those for the
  13114. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  13115. \code{any-vector-ref} when there is a \code{vector-ref} on something
  13116. of type \code{Any}, and similarly for \code{any-vector-set!} and
  13117. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  13118. Section~\ref{sec:select-Rany} we selected instructions for these
  13119. operations based on the idea that the underlying value was a real
  13120. vector. But in the current setting, the underlying value is of type
  13121. \code{PVector}. So \code{any-vector-ref} can be translates to
  13122. pseudo-x86 as follows. We begin by projecting the underlying value out
  13123. of the tagged value and then call the \code{proxy\_vector\_ref}
  13124. procedure in the runtime.
  13125. \begin{lstlisting}
  13126. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  13127. movq |$\neg 111$|, %rdi
  13128. andq |$e_1'$|, %rdi
  13129. movq |$e_2'$|, %rsi
  13130. callq proxy_vector_ref
  13131. movq %rax, |$\itm{lhs'}$|
  13132. \end{lstlisting}
  13133. The \code{any-vector-set!} and \code{any-vector-length} operators can
  13134. be translated in a similar way.
  13135. \begin{exercise}\normalfont
  13136. Implement a compiler for the gradually-typed \LangGrad{} language by
  13137. extending and adapting your compiler for \LangLoop{}. Create 10 new
  13138. partially-typed test programs. In addition to testing with these
  13139. new programs, also test your compiler on all the tests for \LangLoop{}
  13140. and tests for \LangDyn{}. Sometimes you may get a type checking error
  13141. on the \LangDyn{} programs but you can adapt them by inserting
  13142. a cast to the \code{Any} type around each subexpression
  13143. causing a type error. While \LangDyn{} doesn't have explicit casts,
  13144. you can induce one by wrapping the subexpression \code{e}
  13145. with a call to an un-annotated identity function, like this:
  13146. \code{((lambda (x) x) e)}.
  13147. \end{exercise}
  13148. \begin{figure}[p]
  13149. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13150. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  13151. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  13152. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  13153. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  13154. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  13155. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  13156. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  13157. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  13158. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  13159. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  13160. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  13161. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  13162. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  13163. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  13164. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13165. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13166. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13167. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13168. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13169. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13170. \path[->,bend right=15] (Rgradual) edge [above] node
  13171. {\ttfamily\footnotesize type-check} (Rgradualp);
  13172. \path[->,bend right=15] (Rgradualp) edge [above] node
  13173. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  13174. \path[->,bend right=15] (Rwhilepp) edge [right] node
  13175. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  13176. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  13177. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  13178. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  13179. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  13180. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  13181. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  13182. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  13183. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  13184. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  13185. {\ttfamily\footnotesize convert-assignments} (F1-1);
  13186. \path[->,bend left=15] (F1-1) edge [below] node
  13187. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  13188. \path[->,bend right=15] (F1-2) edge [above] node
  13189. {\ttfamily\footnotesize limit-fun.} (F1-3);
  13190. \path[->,bend right=15] (F1-3) edge [above] node
  13191. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  13192. \path[->,bend right=15] (F1-4) edge [above] node
  13193. {\ttfamily\footnotesize remove-complex.} (F1-5);
  13194. \path[->,bend right=15] (F1-5) edge [right] node
  13195. {\ttfamily\footnotesize explicate-control} (C3-2);
  13196. \path[->,bend left=15] (C3-2) edge [left] node
  13197. {\ttfamily\footnotesize select-instr.} (x86-2);
  13198. \path[->,bend right=15] (x86-2) edge [left] node
  13199. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  13200. \path[->,bend right=15] (x86-2-1) edge [below] node
  13201. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  13202. \path[->,bend right=15] (x86-2-2) edge [left] node
  13203. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  13204. \path[->,bend left=15] (x86-3) edge [above] node
  13205. {\ttfamily\footnotesize patch-instr.} (x86-4);
  13206. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  13207. \end{tikzpicture}
  13208. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  13209. \label{fig:Rgradual-passes}
  13210. \end{figure}
  13211. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  13212. for the compilation of \LangGrad{}.
  13213. \section{Further Reading}
  13214. This chapter just scratches the surface of gradual typing. The basic
  13215. approach described here is missing two key ingredients that one would
  13216. want in a implementation of gradual typing: blame
  13217. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  13218. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  13219. problem addressed by blame tracking is that when a cast on a
  13220. higher-order value fails, it often does so at a point in the program
  13221. that is far removed from the original cast. Blame tracking is a
  13222. technique for propagating extra information through casts and proxies
  13223. so that when a cast fails, the error message can point back to the
  13224. original location of the cast in the source program.
  13225. The problem addressed by space-efficient casts also relates to
  13226. higher-order casts. It turns out that in partially typed programs, a
  13227. function or vector can flow through very-many casts at runtime. With
  13228. the approach described in this chapter, each cast adds another
  13229. \code{lambda} wrapper or a vector proxy. Not only does this take up
  13230. considerable space, but it also makes the function calls and vector
  13231. operations slow. For example, a partially-typed version of quicksort
  13232. could, in the worst case, build a chain of proxies of length $O(n)$
  13233. around the vector, changing the overall time complexity of the
  13234. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  13235. solution to this problem by representing casts using the coercion
  13236. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  13237. long chains of proxies by compressing them into a concise normal
  13238. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  13239. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  13240. the Grift compiler.
  13241. \begin{center}
  13242. \url{https://github.com/Gradual-Typing/Grift}
  13243. \end{center}
  13244. There are also interesting interactions between gradual typing and
  13245. other language features, such as parametetric polymorphism,
  13246. information-flow types, and type inference, to name a few. We
  13247. recommend the reader to the online gradual typing bibliography:
  13248. \begin{center}
  13249. \url{http://samth.github.io/gradual-typing-bib/}
  13250. \end{center}
  13251. % TODO: challenge problem:
  13252. % type analysis and type specialization?
  13253. % coercions?
  13254. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13255. \chapter{Parametric Polymorphism}
  13256. \label{ch:Rpoly}
  13257. \index{subject}{parametric polymorphism}
  13258. \index{subject}{generics}
  13259. This chapter studies the compilation of parametric
  13260. polymorphism\index{subject}{parametric polymorphism}
  13261. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  13262. Racket. Parametric polymorphism enables improved code reuse by
  13263. parameterizing functions and data structures with respect to the types
  13264. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  13265. revisits the \code{map-vec} example but this time gives it a more
  13266. fitting type. This \code{map-vec} function is parameterized with
  13267. respect to the element type of the vector. The type of \code{map-vec}
  13268. is the following polymorphic type as specified by the \code{All} and
  13269. the type parameter \code{a}.
  13270. \begin{lstlisting}
  13271. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  13272. \end{lstlisting}
  13273. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  13274. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  13275. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  13276. \code{a}, but we could have just as well applied \code{map-vec} to a
  13277. vector of Booleans (and a function on Booleans).
  13278. \begin{figure}[tbp]
  13279. % poly_test_2.rkt
  13280. \begin{lstlisting}
  13281. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  13282. (define (map-vec f v)
  13283. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13284. (define (add1 [x : Integer]) : Integer (+ x 1))
  13285. (vector-ref (map-vec add1 (vector 0 41)) 1)
  13286. \end{lstlisting}
  13287. \caption{The \code{map-vec} example using parametric polymorphism.}
  13288. \label{fig:map-vec-poly}
  13289. \end{figure}
  13290. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  13291. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  13292. syntax. We add a second form for function definitions in which a type
  13293. declaration comes before the \code{define}. In the abstract syntax,
  13294. the return type in the \code{Def} is \code{Any}, but that should be
  13295. ignored in favor of the return type in the type declaration. (The
  13296. \code{Any} comes from using the same parser as in
  13297. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  13298. enables the use of an \code{All} type for a function, thereby making
  13299. it polymorphic. The grammar for types is extended to include
  13300. polymorphic types and type variables.
  13301. \begin{figure}[tp]
  13302. \centering
  13303. \fbox{
  13304. \begin{minipage}{0.96\textwidth}
  13305. \small
  13306. \[
  13307. \begin{array}{lcl}
  13308. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  13309. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  13310. &\MID& \LP\key{:}~\Var~\Type\RP \\
  13311. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  13312. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  13313. \end{array}
  13314. \]
  13315. \end{minipage}
  13316. }
  13317. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  13318. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  13319. \label{fig:Rpoly-concrete-syntax}
  13320. \end{figure}
  13321. \begin{figure}[tp]
  13322. \centering
  13323. \fbox{
  13324. \begin{minipage}{0.96\textwidth}
  13325. \small
  13326. \[
  13327. \begin{array}{lcl}
  13328. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  13329. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  13330. &\MID& \DECL{\Var}{\Type} \\
  13331. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  13332. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13333. \end{array}
  13334. \]
  13335. \end{minipage}
  13336. }
  13337. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  13338. (Figure~\ref{fig:Rwhile-syntax}).}
  13339. \label{fig:Rpoly-syntax}
  13340. \end{figure}
  13341. By including polymorphic types in the $\Type$ non-terminal we choose
  13342. to make them first-class which has interesting repercussions on the
  13343. compiler. Many languages with polymorphism, such as
  13344. C++~\citep{stroustrup88:_param_types} and Standard
  13345. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  13346. it is useful to see an example of first-class polymorphism. In
  13347. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  13348. whose parameter is a polymorphic function. The occurrence of a
  13349. polymorphic type underneath a function type is enabled by the normal
  13350. recursive structure of the grammar for $\Type$ and the categorization
  13351. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  13352. applies the polymorphic function to a Boolean and to an integer.
  13353. \begin{figure}[tbp]
  13354. \begin{lstlisting}
  13355. (: apply-twice ((All (b) (b -> b)) -> Integer))
  13356. (define (apply-twice f)
  13357. (if (f #t) (f 42) (f 777)))
  13358. (: id (All (a) (a -> a)))
  13359. (define (id x) x)
  13360. (apply-twice id)
  13361. \end{lstlisting}
  13362. \caption{An example illustrating first-class polymorphism.}
  13363. \label{fig:apply-twice}
  13364. \end{figure}
  13365. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  13366. three new responsibilities (compared to \LangLoop{}). The type checking of
  13367. function application is extended to handle the case where the operator
  13368. expression is a polymorphic function. In that case the type arguments
  13369. are deduced by matching the type of the parameters with the types of
  13370. the arguments.
  13371. %
  13372. The \code{match-types} auxiliary function carries out this deduction
  13373. by recursively descending through a parameter type \code{pt} and the
  13374. corresponding argument type \code{at}, making sure that they are equal
  13375. except when there is a type parameter on the left (in the parameter
  13376. type). If it's the first time that the type parameter has been
  13377. encountered, then the algorithm deduces an association of the type
  13378. parameter to the corresponding type on the right (in the argument
  13379. type). If it's not the first time that the type parameter has been
  13380. encountered, the algorithm looks up its deduced type and makes sure
  13381. that it is equal to the type on the right.
  13382. %
  13383. Once the type arguments are deduced, the operator expression is
  13384. wrapped in an \code{Inst} AST node (for instantiate) that records the
  13385. type of the operator, but more importantly, records the deduced type
  13386. arguments. The return type of the application is the return type of
  13387. the polymorphic function, but with the type parameters replaced by the
  13388. deduced type arguments, using the \code{subst-type} function.
  13389. The second responsibility of the type checker is extending the
  13390. function \code{type-equal?} to handle the \code{All} type. This is
  13391. not quite a simple as equal on other types, such as function and
  13392. vector types, because two polymorphic types can be syntactically
  13393. different even though they are equivalent types. For example,
  13394. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  13395. Two polymorphic types should be considered equal if they differ only
  13396. in the choice of the names of the type parameters. The
  13397. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  13398. renames the type parameters of the first type to match the type
  13399. parameters of the second type.
  13400. The third responsibility of the type checker is making sure that only
  13401. defined type variables appear in type annotations. The
  13402. \code{check-well-formed} function defined in
  13403. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  13404. sure that each type variable has been defined.
  13405. The output language of the type checker is \LangInst{}, defined in
  13406. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  13407. declaration and polymorphic function into a single definition, using
  13408. the \code{Poly} form, to make polymorphic functions more convenient to
  13409. process in next pass of the compiler.
  13410. \begin{figure}[tp]
  13411. \centering
  13412. \fbox{
  13413. \begin{minipage}{0.96\textwidth}
  13414. \small
  13415. \[
  13416. \begin{array}{lcl}
  13417. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  13418. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  13419. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  13420. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  13421. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13422. \end{array}
  13423. \]
  13424. \end{minipage}
  13425. }
  13426. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  13427. (Figure~\ref{fig:Rwhile-syntax}).}
  13428. \label{fig:Rpoly-prime-syntax}
  13429. \end{figure}
  13430. The output of the type checker on the polymorphic \code{map-vec}
  13431. example is listed in Figure~\ref{fig:map-vec-type-check}.
  13432. \begin{figure}[tbp]
  13433. % poly_test_2.rkt
  13434. \begin{lstlisting}
  13435. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  13436. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  13437. (define (add1 [x : Integer]) : Integer (+ x 1))
  13438. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  13439. (Integer))
  13440. add1 (vector 0 41)) 1)
  13441. \end{lstlisting}
  13442. \caption{Output of the type checker on the \code{map-vec} example.}
  13443. \label{fig:map-vec-type-check}
  13444. \end{figure}
  13445. \begin{figure}[tbp]
  13446. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13447. (define type-check-poly-class
  13448. (class type-check-Rwhile-class
  13449. (super-new)
  13450. (inherit check-type-equal?)
  13451. (define/override (type-check-apply env e1 es)
  13452. (define-values (e^ ty) ((type-check-exp env) e1))
  13453. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  13454. ((type-check-exp env) e)))
  13455. (match ty
  13456. [`(,ty^* ... -> ,rt)
  13457. (for ([arg-ty ty*] [param-ty ty^*])
  13458. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  13459. (values e^ es^ rt)]
  13460. [`(All ,xs (,tys ... -> ,rt))
  13461. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  13462. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  13463. (match-types env^^ param-ty arg-ty)))
  13464. (define targs
  13465. (for/list ([x xs])
  13466. (match (dict-ref env^^ x (lambda () #f))
  13467. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  13468. x (Apply e1 es))]
  13469. [ty ty])))
  13470. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  13471. [else (error 'type-check "expected a function, not ~a" ty)]))
  13472. (define/override ((type-check-exp env) e)
  13473. (match e
  13474. [(Lambda `([,xs : ,Ts] ...) rT body)
  13475. (for ([T Ts]) ((check-well-formed env) T))
  13476. ((check-well-formed env) rT)
  13477. ((super type-check-exp env) e)]
  13478. [(HasType e1 ty)
  13479. ((check-well-formed env) ty)
  13480. ((super type-check-exp env) e)]
  13481. [else ((super type-check-exp env) e)]))
  13482. (define/override ((type-check-def env) d)
  13483. (verbose 'type-check "poly/def" d)
  13484. (match d
  13485. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  13486. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  13487. (for ([p ps]) ((check-well-formed ts-env) p))
  13488. ((check-well-formed ts-env) rt)
  13489. (define new-env (append ts-env (map cons xs ps) env))
  13490. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13491. (check-type-equal? ty^ rt body)
  13492. (Generic ts (Def f p:t* rt info body^))]
  13493. [else ((super type-check-def env) d)]))
  13494. (define/override (type-check-program p)
  13495. (match p
  13496. [(Program info body)
  13497. (type-check-program (ProgramDefsExp info '() body))]
  13498. [(ProgramDefsExp info ds body)
  13499. (define ds^ (combine-decls-defs ds))
  13500. (define new-env (for/list ([d ds^])
  13501. (cons (def-name d) (fun-def-type d))))
  13502. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  13503. (define-values (body^ ty) ((type-check-exp new-env) body))
  13504. (check-type-equal? ty 'Integer body)
  13505. (ProgramDefsExp info ds^^ body^)]))
  13506. ))
  13507. \end{lstlisting}
  13508. \caption{Type checker for the \LangPoly{} language.}
  13509. \label{fig:type-check-Rvar0}
  13510. \end{figure}
  13511. \begin{figure}[tbp]
  13512. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  13513. (define/override (type-equal? t1 t2)
  13514. (match* (t1 t2)
  13515. [(`(All ,xs ,T1) `(All ,ys ,T2))
  13516. (define env (map cons xs ys))
  13517. (type-equal? (subst-type env T1) T2)]
  13518. [(other wise)
  13519. (super type-equal? t1 t2)]))
  13520. (define/public (match-types env pt at)
  13521. (match* (pt at)
  13522. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  13523. [('Void 'Void) env] [('Any 'Any) env]
  13524. [(`(Vector ,pts ...) `(Vector ,ats ...))
  13525. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  13526. (match-types env^ pt1 at1))]
  13527. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  13528. (define env^ (match-types env prt art))
  13529. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  13530. (match-types env^^ pt1 at1))]
  13531. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  13532. (define env^ (append (map cons pxs axs) env))
  13533. (match-types env^ pt1 at1)]
  13534. [((? symbol? x) at)
  13535. (match (dict-ref env x (lambda () #f))
  13536. [#f (error 'type-check "undefined type variable ~a" x)]
  13537. ['Type (cons (cons x at) env)]
  13538. [t^ (check-type-equal? at t^ 'matching) env])]
  13539. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  13540. (define/public (subst-type env pt)
  13541. (match pt
  13542. ['Integer 'Integer] ['Boolean 'Boolean]
  13543. ['Void 'Void] ['Any 'Any]
  13544. [`(Vector ,ts ...)
  13545. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  13546. [`(,ts ... -> ,rt)
  13547. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  13548. [`(All ,xs ,t)
  13549. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  13550. [(? symbol? x) (dict-ref env x)]
  13551. [else (error 'type-check "expected a type not ~a" pt)]))
  13552. (define/public (combine-decls-defs ds)
  13553. (match ds
  13554. ['() '()]
  13555. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  13556. (unless (equal? name f)
  13557. (error 'type-check "name mismatch, ~a != ~a" name f))
  13558. (match type
  13559. [`(All ,xs (,ps ... -> ,rt))
  13560. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  13561. (cons (Generic xs (Def name params^ rt info body))
  13562. (combine-decls-defs ds^))]
  13563. [`(,ps ... -> ,rt)
  13564. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  13565. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  13566. [else (error 'type-check "expected a function type, not ~a" type) ])]
  13567. [`(,(Def f params rt info body) . ,ds^)
  13568. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  13569. \end{lstlisting}
  13570. \caption{Auxiliary functions for type checking \LangPoly{}.}
  13571. \label{fig:type-check-Rvar0-aux}
  13572. \end{figure}
  13573. \begin{figure}[tbp]
  13574. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  13575. (define/public ((check-well-formed env) ty)
  13576. (match ty
  13577. ['Integer (void)]
  13578. ['Boolean (void)]
  13579. ['Void (void)]
  13580. [(? symbol? a)
  13581. (match (dict-ref env a (lambda () #f))
  13582. ['Type (void)]
  13583. [else (error 'type-check "undefined type variable ~a" a)])]
  13584. [`(Vector ,ts ...)
  13585. (for ([t ts]) ((check-well-formed env) t))]
  13586. [`(,ts ... -> ,t)
  13587. (for ([t ts]) ((check-well-formed env) t))
  13588. ((check-well-formed env) t)]
  13589. [`(All ,xs ,t)
  13590. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  13591. ((check-well-formed env^) t)]
  13592. [else (error 'type-check "unrecognized type ~a" ty)]))
  13593. \end{lstlisting}
  13594. \caption{Well-formed types.}
  13595. \label{fig:well-formed-types}
  13596. \end{figure}
  13597. % TODO: interpreter for R'_10
  13598. \section{Compiling Polymorphism}
  13599. \label{sec:compiling-poly}
  13600. Broadly speaking, there are four approaches to compiling parametric
  13601. polymorphism, which we describe below.
  13602. \begin{description}
  13603. \item[Monomorphization] generates a different version of a polymorphic
  13604. function for each set of type arguments that it is used with,
  13605. producing type-specialized code. This approach results in the most
  13606. efficient code but requires whole-program compilation (no separate
  13607. compilation) and increases code size. For our current purposes
  13608. monomorphization is a non-starter because, with first-class
  13609. polymorphism, it is sometimes not possible to determine which
  13610. generic functions are used with which type arguments during
  13611. compilation. (It can be done at runtime, with just-in-time
  13612. compilation.) This approach is used to compile C++
  13613. templates~\citep{stroustrup88:_param_types} and polymorphic
  13614. functions in NESL~\citep{Blelloch:1993aa} and
  13615. ML~\citep{Weeks:2006aa}.
  13616. \item[Uniform representation] generates one version of each
  13617. polymorphic function but requires all values have a common ``boxed''
  13618. format, such as the tagged values of type \code{Any} in
  13619. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  13620. similarly to code in a dynamically typed language (like \LangDyn{}),
  13621. in which primitive operators require their arguments to be projected
  13622. from \code{Any} and their results are injected into \code{Any}. (In
  13623. object-oriented languages, the projection is accomplished via
  13624. virtual method dispatch.) The uniform representation approach is
  13625. compatible with separate compilation and with first-class
  13626. polymorphism. However, it produces the least-efficient code because
  13627. it introduces overhead in the entire program, including
  13628. non-polymorphic code. This approach is used in implementations of
  13629. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  13630. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  13631. Java~\citep{Bracha:1998fk}.
  13632. \item[Mixed representation] generates one version of each polymorphic
  13633. function, using a boxed representation for type
  13634. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  13635. and conversions are performed at the boundaries between monomorphic
  13636. and polymorphic (e.g. when a polymorphic function is instantiated
  13637. and called). This approach is compatible with separate compilation
  13638. and first-class polymorphism and maintains the efficiency of
  13639. monomorphic code. The tradeoff is increased overhead at the boundary
  13640. between monomorphic and polymorphic code. This approach is used in
  13641. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  13642. Java 5 with the addition of autoboxing.
  13643. \item[Type passing] uses the unboxed representation in both
  13644. monomorphic and polymorphic code. Each polymorphic function is
  13645. compiled to a single function with extra parameters that describe
  13646. the type arguments. The type information is used by the generated
  13647. code to know how to access the unboxed values at runtime. This
  13648. approach is used in implementation of the Napier88
  13649. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  13650. passing is compatible with separate compilation and first-class
  13651. polymorphism and maintains the efficiency for monomorphic
  13652. code. There is runtime overhead in polymorphic code from dispatching
  13653. on type information.
  13654. \end{description}
  13655. In this chapter we use the mixed representation approach, partly
  13656. because of its favorable attributes, and partly because it is
  13657. straightforward to implement using the tools that we have already
  13658. built to support gradual typing. To compile polymorphic functions, we
  13659. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  13660. \LangCast{}.
  13661. \section{Erase Types}
  13662. \label{sec:erase-types}
  13663. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  13664. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  13665. shows the output of the \code{erase-types} pass on the polymorphic
  13666. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  13667. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  13668. \code{All} types are removed from the type of \code{map-vec}.
  13669. \begin{figure}[tbp]
  13670. \begin{lstlisting}
  13671. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  13672. : (Vector Any Any)
  13673. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13674. (define (add1 [x : Integer]) : Integer (+ x 1))
  13675. (vector-ref ((cast map-vec
  13676. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  13677. ((Integer -> Integer) (Vector Integer Integer)
  13678. -> (Vector Integer Integer)))
  13679. add1 (vector 0 41)) 1)
  13680. \end{lstlisting}
  13681. \caption{The polymorphic \code{map-vec} example after type erasure.}
  13682. \label{fig:map-vec-erase}
  13683. \end{figure}
  13684. This process of type erasure creates a challenge at points of
  13685. instantiation. For example, consider the instantiation of
  13686. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  13687. The type of \code{map-vec} is
  13688. \begin{lstlisting}
  13689. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  13690. \end{lstlisting}
  13691. and it is instantiated to
  13692. \begin{lstlisting}
  13693. ((Integer -> Integer) (Vector Integer Integer)
  13694. -> (Vector Integer Integer))
  13695. \end{lstlisting}
  13696. After erasure, the type of \code{map-vec} is
  13697. \begin{lstlisting}
  13698. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  13699. \end{lstlisting}
  13700. but we need to convert it to the instantiated type. This is easy to
  13701. do in the target language \LangCast{} with a single \code{cast}. In
  13702. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  13703. has been compiled to a \code{cast} from the type of \code{map-vec} to
  13704. the instantiated type. The source and target type of a cast must be
  13705. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  13706. because both the source and target are obtained from the same
  13707. polymorphic type of \code{map-vec}, replacing the type parameters with
  13708. \code{Any} in the former and with the deduced type arguments in the
  13709. later. (Recall that the \code{Any} type is consistent with any type.)
  13710. To implement the \code{erase-types} pass, we recommend defining a
  13711. recursive auxiliary function named \code{erase-type} that applies the
  13712. following two transformations. It replaces type variables with
  13713. \code{Any}
  13714. \begin{lstlisting}
  13715. |$x$|
  13716. |$\Rightarrow$|
  13717. Any
  13718. \end{lstlisting}
  13719. and it removes the polymorphic \code{All} types.
  13720. \begin{lstlisting}
  13721. (All |$xs$| |$T_1$|)
  13722. |$\Rightarrow$|
  13723. |$T'_1$|
  13724. \end{lstlisting}
  13725. Apply the \code{erase-type} function to all of the type annotations in
  13726. the program.
  13727. Regarding the translation of expressions, the case for \code{Inst} is
  13728. the interesting one. We translate it into a \code{Cast}, as shown
  13729. below. The type of the subexpression $e$ is the polymorphic type
  13730. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  13731. $T$, the type $T'$. The target type $T''$ is the result of
  13732. substituting the arguments types $ts$ for the type parameters $xs$ in
  13733. $T$ followed by doing type erasure.
  13734. \begin{lstlisting}
  13735. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  13736. |$\Rightarrow$|
  13737. (Cast |$e'$| |$T'$| |$T''$|)
  13738. \end{lstlisting}
  13739. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  13740. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  13741. Finally, each polymorphic function is translated to a regular
  13742. functions in which type erasure has been applied to all the type
  13743. annotations and the body.
  13744. \begin{lstlisting}
  13745. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  13746. |$\Rightarrow$|
  13747. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  13748. \end{lstlisting}
  13749. \begin{exercise}\normalfont
  13750. Implement a compiler for the polymorphic language \LangPoly{} by
  13751. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  13752. programs that use polymorphic functions. Some of them should make
  13753. use of first-class polymorphism.
  13754. \end{exercise}
  13755. \begin{figure}[p]
  13756. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13757. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  13758. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  13759. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  13760. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  13761. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  13762. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  13763. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  13764. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  13765. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  13766. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  13767. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  13768. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  13769. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  13770. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  13771. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  13772. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13773. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13774. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13775. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13776. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13777. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13778. \path[->,bend right=15] (Rpoly) edge [above] node
  13779. {\ttfamily\footnotesize type-check} (Rpolyp);
  13780. \path[->,bend right=15] (Rpolyp) edge [above] node
  13781. {\ttfamily\footnotesize erase-types} (Rgradualp);
  13782. \path[->,bend right=15] (Rgradualp) edge [above] node
  13783. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  13784. \path[->,bend right=15] (Rwhilepp) edge [right] node
  13785. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  13786. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  13787. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  13788. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  13789. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  13790. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  13791. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  13792. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  13793. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  13794. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  13795. {\ttfamily\footnotesize convert-assignments} (F1-1);
  13796. \path[->,bend left=15] (F1-1) edge [below] node
  13797. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  13798. \path[->,bend right=15] (F1-2) edge [above] node
  13799. {\ttfamily\footnotesize limit-fun.} (F1-3);
  13800. \path[->,bend right=15] (F1-3) edge [above] node
  13801. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  13802. \path[->,bend right=15] (F1-4) edge [above] node
  13803. {\ttfamily\footnotesize remove-complex.} (F1-5);
  13804. \path[->,bend right=15] (F1-5) edge [right] node
  13805. {\ttfamily\footnotesize explicate-control} (C3-2);
  13806. \path[->,bend left=15] (C3-2) edge [left] node
  13807. {\ttfamily\footnotesize select-instr.} (x86-2);
  13808. \path[->,bend right=15] (x86-2) edge [left] node
  13809. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  13810. \path[->,bend right=15] (x86-2-1) edge [below] node
  13811. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  13812. \path[->,bend right=15] (x86-2-2) edge [left] node
  13813. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  13814. \path[->,bend left=15] (x86-3) edge [above] node
  13815. {\ttfamily\footnotesize patch-instr.} (x86-4);
  13816. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  13817. \end{tikzpicture}
  13818. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  13819. \label{fig:Rpoly-passes}
  13820. \end{figure}
  13821. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  13822. for the compilation of \LangPoly{}.
  13823. % TODO: challenge problem: specialization of instantiations
  13824. % Further Reading
  13825. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13826. \clearpage
  13827. \appendix
  13828. \chapter{Appendix}
  13829. \section{Interpreters}
  13830. \label{appendix:interp}
  13831. \index{subject}{interpreter}
  13832. We provide interpreters for each of the source languages \LangInt{},
  13833. \LangVar{}, $\ldots$ in the files \code{interp\_Rint.rkt},
  13834. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  13835. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  13836. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  13837. and x86 are in the \key{interp.rkt} file.
  13838. \section{Utility Functions}
  13839. \label{appendix:utilities}
  13840. The utility functions described in this section are in the
  13841. \key{utilities.rkt} file of the support code.
  13842. \paragraph{\code{interp-tests}}
  13843. The \key{interp-tests} function runs the compiler passes and the
  13844. interpreters on each of the specified tests to check whether each pass
  13845. is correct. The \key{interp-tests} function has the following
  13846. parameters:
  13847. \begin{description}
  13848. \item[name (a string)] a name to identify the compiler,
  13849. \item[typechecker] a function of exactly one argument that either
  13850. raises an error using the \code{error} function when it encounters a
  13851. type error, or returns \code{\#f} when it encounters a type
  13852. error. If there is no type error, the type checker returns the
  13853. program.
  13854. \item[passes] a list with one entry per pass. An entry is a list with
  13855. four things:
  13856. \begin{enumerate}
  13857. \item a string giving the name of the pass,
  13858. \item the function that implements the pass (a translator from AST
  13859. to AST),
  13860. \item a function that implements the interpreter (a function from
  13861. AST to result value) for the output language,
  13862. \item and a type checker for the output language. Type checkers for
  13863. the $R$ and $C$ languages are provided in the support code. For
  13864. example, the type checkers for \LangVar{} and \LangCVar{} are in
  13865. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  13866. type checker entry is optional. The support code does not provide
  13867. type checkers for the x86 languages.
  13868. \end{enumerate}
  13869. \item[source-interp] an interpreter for the source language. The
  13870. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  13871. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  13872. \item[tests] a list of test numbers that specifies which tests to
  13873. run. (see below)
  13874. \end{description}
  13875. %
  13876. The \key{interp-tests} function assumes that the subdirectory
  13877. \key{tests} has a collection of Racket programs whose names all start
  13878. with the family name, followed by an underscore and then the test
  13879. number, ending with the file extension \key{.rkt}. Also, for each test
  13880. program that calls \code{read} one or more times, there is a file with
  13881. the same name except that the file extension is \key{.in} that
  13882. provides the input for the Racket program. If the test program is
  13883. expected to fail type checking, then there should be an empty file of
  13884. the same name but with extension \key{.tyerr}.
  13885. \paragraph{\code{compiler-tests}}
  13886. runs the compiler passes to generate x86 (a \key{.s} file) and then
  13887. runs the GNU C compiler (gcc) to generate machine code. It runs the
  13888. machine code and checks that the output is $42$. The parameters to the
  13889. \code{compiler-tests} function are similar to those of the
  13890. \code{interp-tests} function, and consist of
  13891. \begin{itemize}
  13892. \item a compiler name (a string),
  13893. \item a type checker,
  13894. \item description of the passes,
  13895. \item name of a test-family, and
  13896. \item a list of test numbers.
  13897. \end{itemize}
  13898. \paragraph{\code{compile-file}}
  13899. takes a description of the compiler passes (see the comment for
  13900. \key{interp-tests}) and returns a function that, given a program file
  13901. name (a string ending in \key{.rkt}), applies all of the passes and
  13902. writes the output to a file whose name is the same as the program file
  13903. name but with \key{.rkt} replaced with \key{.s}.
  13904. \paragraph{\code{read-program}}
  13905. takes a file path and parses that file (it must be a Racket program)
  13906. into an abstract syntax tree.
  13907. \paragraph{\code{parse-program}}
  13908. takes an S-expression representation of an abstract syntax tree and converts it into
  13909. the struct-based representation.
  13910. \paragraph{\code{assert}}
  13911. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  13912. and displays the message \key{msg} if the Boolean \key{bool} is false.
  13913. \paragraph{\code{lookup}}
  13914. % remove discussion of lookup? -Jeremy
  13915. takes a key and an alist, and returns the first value that is
  13916. associated with the given key, if there is one. If not, an error is
  13917. triggered. The alist may contain both immutable pairs (built with
  13918. \key{cons}) and mutable pairs (built with \key{mcons}).
  13919. %The \key{map2} function ...
  13920. \section{x86 Instruction Set Quick-Reference}
  13921. \label{sec:x86-quick-reference}
  13922. \index{subject}{x86}
  13923. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  13924. do. We write $A \to B$ to mean that the value of $A$ is written into
  13925. location $B$. Address offsets are given in bytes. The instruction
  13926. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  13927. registers (such as \code{\%rax}), or memory references (such as
  13928. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  13929. reference per instruction. Other operands must be immediates or
  13930. registers.
  13931. \begin{table}[tbp]
  13932. \centering
  13933. \begin{tabular}{l|l}
  13934. \textbf{Instruction} & \textbf{Operation} \\ \hline
  13935. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  13936. \texttt{negq} $A$ & $- A \to A$ \\
  13937. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  13938. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  13939. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  13940. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  13941. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  13942. \texttt{retq} & Pops the return address and jumps to it \\
  13943. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  13944. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  13945. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  13946. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  13947. be an immediate) \\
  13948. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  13949. matches the condition code of the instruction, otherwise go to the
  13950. next instructions. The condition codes are \key{e} for ``equal'',
  13951. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  13952. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  13953. \texttt{jl} $L$ & \\
  13954. \texttt{jle} $L$ & \\
  13955. \texttt{jg} $L$ & \\
  13956. \texttt{jge} $L$ & \\
  13957. \texttt{jmp} $L$ & Jump to label $L$ \\
  13958. \texttt{movq} $A$, $B$ & $A \to B$ \\
  13959. \texttt{movzbq} $A$, $B$ &
  13960. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  13961. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  13962. and the extra bytes of $B$ are set to zero.} \\
  13963. & \\
  13964. & \\
  13965. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  13966. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  13967. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  13968. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  13969. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  13970. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  13971. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  13972. description of the condition codes. $A$ must be a single byte register
  13973. (e.g., \texttt{al} or \texttt{cl}).} \\
  13974. \texttt{setl} $A$ & \\
  13975. \texttt{setle} $A$ & \\
  13976. \texttt{setg} $A$ & \\
  13977. \texttt{setge} $A$ &
  13978. \end{tabular}
  13979. \vspace{5pt}
  13980. \caption{Quick-reference for the x86 instructions used in this book.}
  13981. \label{tab:x86-instr}
  13982. \end{table}
  13983. \cleardoublepage
  13984. \section{Concrete Syntax for Intermediate Languages}
  13985. The concrete syntax of \LangAny{} is defined in
  13986. Figure~\ref{fig:Rany-concrete-syntax}.
  13987. \begin{figure}[tp]
  13988. \centering
  13989. \fbox{
  13990. \begin{minipage}{0.97\textwidth}\small
  13991. \[
  13992. \begin{array}{lcl}
  13993. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  13994. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  13995. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  13996. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  13997. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  13998. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  13999. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  14000. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  14001. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  14002. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  14003. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  14004. \MID \LP\key{void?}\;\Exp\RP \\
  14005. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  14006. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  14007. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  14008. \end{array}
  14009. \]
  14010. \end{minipage}
  14011. }
  14012. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  14013. (Figure~\ref{fig:Rlam-syntax}).}
  14014. \label{fig:Rany-concrete-syntax}
  14015. \end{figure}
  14016. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  14017. defined in Figures~\ref{fig:c0-concrete-syntax},
  14018. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  14019. and \ref{fig:c3-concrete-syntax}, respectively.
  14020. \begin{figure}[tbp]
  14021. \fbox{
  14022. \begin{minipage}{0.96\textwidth}
  14023. \[
  14024. \begin{array}{lcl}
  14025. \Atm &::=& \Int \MID \Var \\
  14026. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  14027. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  14028. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  14029. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  14030. \end{array}
  14031. \]
  14032. \end{minipage}
  14033. }
  14034. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  14035. \label{fig:c0-concrete-syntax}
  14036. \end{figure}
  14037. \begin{figure}[tbp]
  14038. \fbox{
  14039. \begin{minipage}{0.96\textwidth}
  14040. \small
  14041. \[
  14042. \begin{array}{lcl}
  14043. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  14044. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  14045. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  14046. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  14047. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  14048. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  14049. \MID \key{goto}~\itm{label}\key{;}\\
  14050. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  14051. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  14052. \end{array}
  14053. \]
  14054. \end{minipage}
  14055. }
  14056. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  14057. \label{fig:c1-concrete-syntax}
  14058. \end{figure}
  14059. \begin{figure}[tbp]
  14060. \fbox{
  14061. \begin{minipage}{0.96\textwidth}
  14062. \small
  14063. \[
  14064. \begin{array}{lcl}
  14065. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  14066. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  14067. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  14068. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  14069. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  14070. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  14071. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  14072. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  14073. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  14074. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  14075. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  14076. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  14077. \end{array}
  14078. \]
  14079. \end{minipage}
  14080. }
  14081. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  14082. \label{fig:c2-concrete-syntax}
  14083. \end{figure}
  14084. \begin{figure}[tp]
  14085. \fbox{
  14086. \begin{minipage}{0.96\textwidth}
  14087. \small
  14088. \[
  14089. \begin{array}{lcl}
  14090. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  14091. \\
  14092. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  14093. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  14094. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  14095. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  14096. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  14097. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  14098. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  14099. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  14100. \MID \LP\key{collect} \,\itm{int}\RP }\\
  14101. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  14102. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  14103. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  14104. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  14105. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  14106. \LangCFunM{} & ::= & \Def\ldots
  14107. \end{array}
  14108. \]
  14109. \end{minipage}
  14110. }
  14111. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  14112. \label{fig:c3-concrete-syntax}
  14113. \end{figure}
  14114. \backmatter
  14115. \addtocontents{toc}{\vspace{11pt}}
  14116. %% \addtocontents{toc}{\vspace{11pt}}
  14117. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  14118. \nocite{*}\let\bibname\refname
  14119. \addcontentsline{toc}{fmbm}{\refname}
  14120. \printbibliography
  14121. \printindex{authors}{Author Index}
  14122. \printindex{subject}{Subject Index}
  14123. \end{document}