book.tex 648 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. \usepackage[utf8]{inputenc}
  3. %% \usepackage{setspace}
  4. %% \doublespacing
  5. \usepackage{listings}
  6. \usepackage{verbatim}
  7. \usepackage{amssymb}
  8. \usepackage{lmodern} % better typewriter font for code
  9. %\usepackage{wrapfig}
  10. \usepackage{multirow}
  11. \usepackage{tcolorbox}
  12. \usepackage{color}
  13. %\usepackage{ifthen}
  14. \usepackage{upquote}
  15. \definecolor{lightgray}{gray}{1}
  16. \newcommand{\black}[1]{{\color{black} #1}}
  17. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  18. \newcommand{\gray}[1]{{\color{gray} #1}}
  19. \def\racketEd{0}
  20. \def\pythonEd{1}
  21. \def\edition{1}
  22. % material that is specific to the Racket edition of the book
  23. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  24. % would like a command for: \if\edition\racketEd\color{olive}
  25. % and : \fi\color{black}
  26. % material that is specific to the Python edition of the book
  27. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  28. %% For multiple indices:
  29. \usepackage{multind}
  30. \makeindex{subject}
  31. \makeindex{authors}
  32. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  33. \if\edition\racketEd
  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. \fi
  45. \if\edition\pythonEd
  46. \lstset{%
  47. language=Python,
  48. basicstyle=\ttfamily\small,
  49. morekeywords={match,case,bool,int},
  50. deletekeywords={},
  51. escapechar=|,
  52. columns=flexible,
  53. moredelim=[is][\color{red}]{~}{~},
  54. showstringspaces=false
  55. }
  56. \fi
  57. %%% Any shortcut own defined macros place here
  58. %% sample of author macro:
  59. \input{defs}
  60. \newtheorem{exercise}[theorem]{Exercise}
  61. % Adjusted settings
  62. \setlength{\columnsep}{4pt}
  63. %% \begingroup
  64. %% \setlength{\intextsep}{0pt}%
  65. %% \setlength{\columnsep}{0pt}%
  66. %% \begin{wrapfigure}{r}{0.5\textwidth}
  67. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  68. %% \caption{Basic layout}
  69. %% \end{wrapfigure}
  70. %% \lipsum[1]
  71. %% \endgroup
  72. \newbox\oiintbox
  73. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  74. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  75. \def\oiint{\copy\oiintbox}
  76. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  77. %\usepackage{showframe}
  78. \def\ShowFrameLinethickness{0.125pt}
  79. \addbibresource{book.bib}
  80. \begin{document}
  81. \frontmatter
  82. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  83. \halftitlepage
  84. \Title{Essentials of Compilation}
  85. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  86. %\edition{First Edition}
  87. \BookAuthor{Jeremy G. Siek}
  88. \imprint{The MIT Press\\
  89. Cambridge, Massachusetts\\
  90. London, England}
  91. \begin{copyrightpage}
  92. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  93. or personal downloading under the
  94. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  95. license.
  96. Copyright in this monograph has been licensed exclusively to The MIT
  97. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  98. version to the public in 2022. All inquiries regarding rights should
  99. be addressed to The MIT Press, Rights and Permissions Department.
  100. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  101. %% All rights reserved. No part of this book may be reproduced in any
  102. %% form by any electronic or mechanical means (including photocopying,
  103. %% recording, or information storage and retrieval) without permission in
  104. %% writing from the publisher.
  105. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  106. %% United States of America.
  107. %% Library of Congress Cataloging-in-Publication Data is available.
  108. %% ISBN:
  109. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  110. \end{copyrightpage}
  111. \dedication{This book is dedicated to the programming language wonks
  112. at Indiana University.}
  113. %% \begin{epigraphpage}
  114. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  115. %% \textit{Book Name if any}}
  116. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  117. %% \end{epigraphpage}
  118. \tableofcontents
  119. %\listoffigures
  120. %\listoftables
  121. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  122. \chapter*{Preface}
  123. \addcontentsline{toc}{fmbm}{Preface}
  124. There is a magical moment when a programmer presses the ``run'' button
  125. and the software begins to execute. Somehow a program written in a
  126. high-level language is running on a computer that is only capable of
  127. shuffling bits. Here we reveal the wizardry that makes that moment
  128. possible. Beginning with the ground breaking work of Backus and
  129. colleagues in the 1950s, computer scientists discovered techniques for
  130. constructing programs, called \emph{compilers}, that automatically
  131. translate high-level programs into machine code.
  132. We take you on a journey by constructing your own compiler for a small
  133. but powerful language. Along the way we explain the essential
  134. concepts, algorithms, and data structures that underlie compilers. We
  135. develop your understanding of how programs are mapped onto computer
  136. hardware, which is helpful when reasoning about properties at the
  137. junction between hardware and software such as execution time,
  138. software errors, and security vulnerabilities. For those interested
  139. in pursuing compiler construction, our goal is to provide a
  140. stepping-stone to advanced topics such as just-in-time compilation,
  141. program analysis, and program optimization. For those interested in
  142. designing and implementing programming languages, we connect
  143. language design choices to their impact on the compiler and the generated
  144. code.
  145. A compiler is typically organized as a sequence of stages that
  146. progressively translate a program to code that runs on hardware. We
  147. take this approach to the extreme by partitioning our compiler into a
  148. large number of \emph{nanopasses}, each of which performs a single
  149. task. This allows us to test the output of each pass in isolation, and
  150. furthermore, allows us to focus our attention which makes the compiler
  151. far easier to understand.
  152. The most familiar approach to describing compilers is with one pass
  153. per chapter. The problem with that approach is it obfuscates how
  154. language features motivate design choices in a compiler. We take an
  155. \emph{incremental} approach in which we build a complete compiler in
  156. each chapter, starting with a small input language that includes only
  157. arithmetic and variables and we add new language features in
  158. subsequent chapters.
  159. Our choice of language features is designed to elicit the fundamental
  160. concepts and algorithms used in compilers.
  161. \begin{itemize}
  162. \item We begin with integer arithmetic and local variables in
  163. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  164. the fundamental tools of compiler construction: \emph{abstract
  165. syntax trees} and \emph{recursive functions}.
  166. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  167. \emph{graph coloring} to assign variables to machine registers.
  168. \item Chapter~\ref{ch:Lif} adds \code{if} expressions, which motivates
  169. an elegant recursive algorithm for translating them into conditional
  170. \code{goto}'s.
  171. \item Chapter~\ref{ch:Lwhile} fleshes out support for imperative
  172. programming languages with the addition of loops\racket{ and mutable
  173. variables}. This elicits the need for \emph{dataflow
  174. analysis} in the register allocator.
  175. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  176. \emph{garbage collection}.
  177. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  178. but lack lexical scoping, similar to the C programming
  179. language~\citep{Kernighan:1988nx} except that we generate efficient
  180. tail calls. The reader learns about the procedure call stack,
  181. \emph{calling conventions}, and their interaction with register
  182. allocation and garbage collection.
  183. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  184. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  185. \emph{closure conversion}, in which lambdas are translated into a
  186. combination of functions and tuples.
  187. % Chapter about classes and objects?
  188. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  189. point the input languages are statically typed. The reader extends
  190. the statically typed language with an \code{Any} type which serves
  191. as a target for compiling the dynamically typed language.
  192. {\if\edition\pythonEd
  193. \item Chapter~\ref{ch:Robject} adds support for \emph{objects} and
  194. \emph{classes}.
  195. \fi}
  196. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  197. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  198. in which different regions of a program may be static or dynamically
  199. typed. The reader implements runtime support for \emph{proxies} that
  200. allow values to safely move between regions.
  201. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  202. leveraging the \code{Any} type and type casts developed in Chapters
  203. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  204. \end{itemize}
  205. There are many language features that we do not include. Our choices
  206. balance the incidental complexity of a feature versus the fundamental
  207. concepts that it exposes. For example, we include tuples and not
  208. records because they both elicit the study of heap allocation and
  209. garbage collection but records come with more incidental complexity.
  210. Since 2009 drafts of this book have served as the textbook for 16-week
  211. compiler courses for upper-level undergraduates and first-year
  212. graduate students at the University of Colorado and Indiana
  213. University.
  214. %
  215. Students come into the course having learned the basics of
  216. programming, data structures and algorithms, and discrete
  217. mathematics.
  218. %
  219. At the beginning of the course, students form groups of 2-4 people.
  220. The groups complete one chapter every two weeks, starting with
  221. Chapter~\ref{ch:Lvar}. Many chapters include a challenge problem that
  222. we assign to the graduate students. The last two weeks of the course
  223. involve a final project in which students design and implement a
  224. compiler extension of their choosing. Chapters~\ref{ch:Rgrad} and
  225. \ref{ch:Rpoly} can be used in support of these projects or they can
  226. replace some of the other chapters. For example, a course with an
  227. emphasis on statically-typed imperative languages could include
  228. Chapter~\ref{ch:Rpoly} but skip Chapter~\ref{ch:Rdyn}. For compiler
  229. courses at universities on the quarter system, with 10 weeks, we
  230. recommend completing up through Chapter~\ref{ch:Rfun}. (If pressed
  231. for time, one can skip Chapter~\ref{ch:Lvec} but still include
  232. Chapter~\ref{ch:Rfun} by limiting the number of parameters allowed in
  233. functions.) Figure~\ref{fig:chapter-dependences} depicts the
  234. dependencies between chapters.
  235. This book has also been used in compiler courses at California
  236. Polytechnic State University, Portland State University, Rose–Hulman
  237. Institute of Technology, University of Massachusetts Lowell, and the
  238. University of Vermont.
  239. \begin{figure}[tp]
  240. {\if\edition\racketEd
  241. \begin{tikzpicture}[baseline=(current bounding box.center)]
  242. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  243. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  244. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  245. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  246. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  247. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  248. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  249. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  250. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  251. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  252. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  253. \path[->] (C1) edge [above] node {} (C2);
  254. \path[->] (C2) edge [above] node {} (C3);
  255. \path[->] (C3) edge [above] node {} (C4);
  256. \path[->] (C4) edge [above] node {} (C5);
  257. \path[->] (C5) edge [above] node {} (C6);
  258. \path[->] (C6) edge [above] node {} (C7);
  259. \path[->] (C4) edge [above] node {} (C8);
  260. \path[->] (C4) edge [above] node {} (C9);
  261. \path[->] (C8) edge [above] node {} (C10);
  262. \path[->] (C10) edge [above] node {} (C11);
  263. \end{tikzpicture}
  264. \fi}
  265. {\if\edition\pythonEd
  266. \begin{tikzpicture}[baseline=(current bounding box.center)]
  267. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  268. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  269. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  270. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  271. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  272. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  273. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  274. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  275. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Robject} Objects};
  276. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  277. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual Typing};
  278. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  279. \path[->] (C1) edge [above] node {} (C2);
  280. \path[->] (C2) edge [above] node {} (C3);
  281. \path[->] (C3) edge [above] node {} (C4);
  282. \path[->] (C4) edge [above] node {} (C5);
  283. \path[->] (C5) edge [above] node {} (C6);
  284. \path[->] (C6) edge [above] node {} (C7);
  285. \path[->] (C4) edge [above] node {} (C8);
  286. \path[->] (C4) edge [above] node {} (C9);
  287. \path[->] (C8) edge [above] node {} (C10);
  288. \path[->] (C8) edge [above] node {} (CO);
  289. \path[->] (C10) edge [above] node {} (C11);
  290. \end{tikzpicture}
  291. \fi}
  292. \caption{Diagram of chapter dependencies.}
  293. \label{fig:chapter-dependences}
  294. \end{figure}
  295. \racket{
  296. We use the \href{https://racket-lang.org/}{Racket} language both for
  297. the implementation of the compiler and for the input language, so the
  298. reader should be proficient with Racket or Scheme. There are many
  299. excellent resources for learning Scheme and
  300. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  301. }
  302. \python{
  303. This edition of the book uses \href{https://www.python.org/}{Python}
  304. both for the implementation of the compiler and for the input language, so the
  305. reader should be proficient with Python. There are many
  306. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  307. }
  308. The support code for this book is in the github repository at
  309. the following URL:
  310. \if\edition\racketEd
  311. \begin{center}\small
  312. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  313. \end{center}
  314. \fi
  315. \if\edition\pythonEd
  316. \begin{center}\small
  317. \url{https://github.com/IUCompilerCourse/}
  318. \end{center}
  319. \fi
  320. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  321. is helpful but not necessary for the reader to have taken a computer
  322. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  323. of x86-64 assembly language that are needed.
  324. %
  325. We follow the System V calling
  326. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  327. that we generate works with the runtime system (written in C) when it
  328. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  329. operating systems on Intel hardware.
  330. %
  331. On the Windows operating system, \code{gcc} uses the Microsoft x64
  332. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  333. assembly code that we generate does \emph{not} work with the runtime
  334. system on Windows. One workaround is to use a virtual machine with
  335. Linux as the guest operating system.
  336. \section*{Acknowledgments}
  337. The tradition of compiler construction at Indiana University goes back
  338. to research and courses on programming languages by Daniel Friedman in
  339. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  340. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  341. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  342. the compiler course and continued the development of Chez Scheme.
  343. %
  344. The compiler course evolved to incorporate novel pedagogical ideas
  345. while also including elements of real-world compilers. One of
  346. Friedman's ideas was to split the compiler into many small
  347. passes. Another idea, called ``the game'', was to test the code
  348. generated by each pass using interpreters.
  349. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  350. developed infrastructure to support this approach and evolved the
  351. course to use even smaller
  352. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  353. design decisions in this book are inspired by the assignment
  354. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  355. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  356. organization of the course made it difficult for students to
  357. understand the rationale for the compiler design. Ghuloum proposed the
  358. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  359. on.
  360. We thank the many students who served as teaching assistants for the
  361. compiler course at IU and made suggestions for improving the book
  362. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  363. thank Andre Kuhlenschmidt for his work on the garbage collector,
  364. Michael Vollmer for his work on efficient tail calls, and Michael
  365. Vitousek for his help running the first offering of the incremental
  366. compiler course at IU.
  367. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  368. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  369. for teaching courses based on drafts of this book and for their
  370. invaluable feedback.
  371. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  372. course in the early 2000's and especially for finding the bug that
  373. sent our garbage collector on a wild goose chase!
  374. \mbox{}\\
  375. \noindent Jeremy G. Siek \\
  376. Bloomington, Indiana
  377. \mainmatter
  378. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  379. \chapter{Preliminaries}
  380. \label{ch:trees-recur}
  381. In this chapter we review the basic tools that are needed to implement
  382. a compiler. Programs are typically input by a programmer as text,
  383. i.e., a sequence of characters. The program-as-text representation is
  384. called \emph{concrete syntax}. We use concrete syntax to concisely
  385. write down and talk about programs. Inside the compiler, we use
  386. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  387. that efficiently supports the operations that the compiler needs to
  388. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  389. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  390. from concrete syntax to abstract syntax is a process called
  391. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  392. implementation of parsing in this book.
  393. %
  394. \racket{A parser is provided in the support code for translating from
  395. concrete to abstract syntax.}
  396. %
  397. \python{We use Python's \code{ast} module to translate from concrete
  398. to abstract syntax.}
  399. ASTs can be represented in many different ways inside the compiler,
  400. depending on the programming language used to write the compiler.
  401. %
  402. \racket{We use Racket's
  403. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  404. feature to represent ASTs (Section~\ref{sec:ast}).}
  405. %
  406. \python{We use Python classes and objects to represent ASTs, especially the
  407. classes defined in the standard \code{ast} module for the Python
  408. source language.}
  409. %
  410. We use grammars to define the abstract syntax of programming languages
  411. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  412. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  413. recursive functions to construct and deconstruct ASTs
  414. (Section~\ref{sec:recursion}). This chapter provides an brief
  415. introduction to these ideas.
  416. \racket{\index{subject}{struct}}
  417. \python{\index{subject}{class}\index{subject}{object}}
  418. \section{Abstract Syntax Trees}
  419. \label{sec:ast}
  420. Compilers use abstract syntax trees to represent programs because they
  421. often need to ask questions like: for a given part of a program, what
  422. kind of language feature is it? What are its sub-parts? Consider the
  423. program on the left and its AST on the right. This program is an
  424. addition operation and it has two sub-parts, a
  425. \racket{read}\python{input} operation and a negation. The negation has
  426. another sub-part, the integer constant \code{8}. By using a tree to
  427. represent the program, we can easily follow the links to go from one
  428. part of a program to its sub-parts.
  429. \begin{center}
  430. \begin{minipage}{0.4\textwidth}
  431. \if\edition\racketEd
  432. \begin{lstlisting}
  433. (+ (read) (- 8))
  434. \end{lstlisting}
  435. \fi
  436. \if\edition\pythonEd
  437. \begin{lstlisting}
  438. input_int() + -8
  439. \end{lstlisting}
  440. \fi
  441. \end{minipage}
  442. \begin{minipage}{0.4\textwidth}
  443. \begin{equation}
  444. \begin{tikzpicture}
  445. \node[draw] (plus) at (0 , 0) {\key{+}};
  446. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  447. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  448. \node[draw] (8) at (1 , -3) {\key{8}};
  449. \draw[->] (plus) to (read);
  450. \draw[->] (plus) to (minus);
  451. \draw[->] (minus) to (8);
  452. \end{tikzpicture}
  453. \label{eq:arith-prog}
  454. \end{equation}
  455. \end{minipage}
  456. \end{center}
  457. We use the standard terminology for trees to describe ASTs: each
  458. rectangle above is called a \emph{node}. The arrows connect a node to its
  459. \emph{children} (which are also nodes). The top-most node is the
  460. \emph{root}. Every node except for the root has a \emph{parent} (the
  461. node it is the child of). If a node has no children, it is a
  462. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  463. \index{subject}{node}
  464. \index{subject}{children}
  465. \index{subject}{root}
  466. \index{subject}{parent}
  467. \index{subject}{leaf}
  468. \index{subject}{internal node}
  469. %% Recall that an \emph{symbolic expression} (S-expression) is either
  470. %% \begin{enumerate}
  471. %% \item an atom, or
  472. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  473. %% where $e_1$ and $e_2$ are each an S-expression.
  474. %% \end{enumerate}
  475. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  476. %% null value \code{'()}, etc. We can create an S-expression in Racket
  477. %% simply by writing a backquote (called a quasi-quote in Racket)
  478. %% followed by the textual representation of the S-expression. It is
  479. %% quite common to use S-expressions to represent a list, such as $a, b
  480. %% ,c$ in the following way:
  481. %% \begin{lstlisting}
  482. %% `(a . (b . (c . ())))
  483. %% \end{lstlisting}
  484. %% Each element of the list is in the first slot of a pair, and the
  485. %% second slot is either the rest of the list or the null value, to mark
  486. %% the end of the list. Such lists are so common that Racket provides
  487. %% special notation for them that removes the need for the periods
  488. %% and so many parenthesis:
  489. %% \begin{lstlisting}
  490. %% `(a b c)
  491. %% \end{lstlisting}
  492. %% The following expression creates an S-expression that represents AST
  493. %% \eqref{eq:arith-prog}.
  494. %% \begin{lstlisting}
  495. %% `(+ (read) (- 8))
  496. %% \end{lstlisting}
  497. %% When using S-expressions to represent ASTs, the convention is to
  498. %% represent each AST node as a list and to put the operation symbol at
  499. %% the front of the list. The rest of the list contains the children. So
  500. %% in the above case, the root AST node has operation \code{`+} and its
  501. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  502. %% diagram \eqref{eq:arith-prog}.
  503. %% To build larger S-expressions one often needs to splice together
  504. %% several smaller S-expressions. Racket provides the comma operator to
  505. %% splice an S-expression into a larger one. For example, instead of
  506. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  507. %% we could have first created an S-expression for AST
  508. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  509. %% S-expression.
  510. %% \begin{lstlisting}
  511. %% (define ast1.4 `(- 8))
  512. %% (define ast1_1 `(+ (read) ,ast1.4))
  513. %% \end{lstlisting}
  514. %% In general, the Racket expression that follows the comma (splice)
  515. %% can be any expression that produces an S-expression.
  516. {\if\edition\racketEd
  517. We define a Racket \code{struct} for each kind of node. For this
  518. chapter we require just two kinds of nodes: one for integer constants
  519. and one for primitive operations. The following is the \code{struct}
  520. definition for integer constants.
  521. \begin{lstlisting}
  522. (struct Int (value))
  523. \end{lstlisting}
  524. An integer node includes just one thing: the integer value.
  525. To create an AST node for the integer $8$, we write \INT{8}.
  526. \begin{lstlisting}
  527. (define eight (Int 8))
  528. \end{lstlisting}
  529. We say that the value created by \INT{8} is an
  530. \emph{instance} of the
  531. \code{Int} structure.
  532. The following is the \code{struct} definition for primitive operations.
  533. \begin{lstlisting}
  534. (struct Prim (op args))
  535. \end{lstlisting}
  536. A primitive operation node includes an operator symbol \code{op} and a
  537. list of child \code{args}. For example, to create an AST that negates
  538. the number $8$, we write \code{(Prim '- (list eight))}.
  539. \begin{lstlisting}
  540. (define neg-eight (Prim '- (list eight)))
  541. \end{lstlisting}
  542. Primitive operations may have zero or more children. The \code{read}
  543. operator has zero children:
  544. \begin{lstlisting}
  545. (define rd (Prim 'read '()))
  546. \end{lstlisting}
  547. whereas the addition operator has two children:
  548. \begin{lstlisting}
  549. (define ast1_1 (Prim '+ (list rd neg-eight)))
  550. \end{lstlisting}
  551. We have made a design choice regarding the \code{Prim} structure.
  552. Instead of using one structure for many different operations
  553. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  554. structure for each operation, as follows.
  555. \begin{lstlisting}
  556. (struct Read ())
  557. (struct Add (left right))
  558. (struct Neg (value))
  559. \end{lstlisting}
  560. The reason we choose to use just one structure is that in many parts
  561. of the compiler the code for the different primitive operators is the
  562. same, so we might as well just write that code once, which is enabled
  563. by using a single structure.
  564. \fi}
  565. {\if\edition\pythonEd
  566. We use a Python \code{class} for each kind of node.
  567. The following is the class definition for constants.
  568. \begin{lstlisting}
  569. class Constant:
  570. def __init__(self, value):
  571. self.value = value
  572. \end{lstlisting}
  573. An integer constant node includes just one thing: the integer value.
  574. To create an AST node for the integer $8$, we write \INT{8}.
  575. \begin{lstlisting}
  576. eight = Constant(8)
  577. \end{lstlisting}
  578. We say that the value created by \INT{8} is an
  579. \emph{instance} of the \code{Constant} class.
  580. The following is the class definition for unary operators.
  581. \begin{lstlisting}
  582. class UnaryOp:
  583. def __init__(self, op, operand):
  584. self.op = op
  585. self.operand = operand
  586. \end{lstlisting}
  587. The specific operation is specified by the \code{op} parameter. For
  588. example, the class \code{USub} is for unary subtraction. (More unary
  589. operators are introduced in later chapters.) To create an AST that
  590. negates the number $8$, we write the following.
  591. \begin{lstlisting}
  592. neg_eight = UnaryOp(USub(), eight)
  593. \end{lstlisting}
  594. The call to the \code{input\_int} function is represented by the
  595. \code{Call} and \code{Name} classes.
  596. \begin{lstlisting}
  597. class Call:
  598. def __init__(self, func, args):
  599. self.func = func
  600. self.args = args
  601. class Name:
  602. def __init__(self, id):
  603. self.id = id
  604. \end{lstlisting}
  605. To create an AST node that calls \code{input\_int}, we write
  606. \begin{lstlisting}
  607. read = Call(Name('input_int'), [])
  608. \end{lstlisting}
  609. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  610. the \code{BinOp} class for binary operators.
  611. \begin{lstlisting}
  612. class BinOp:
  613. def __init__(self, left, op, right):
  614. self.op = op
  615. self.left = left
  616. self.right = right
  617. \end{lstlisting}
  618. Similar to \code{UnaryOp}, the specific operation is specified by the
  619. \code{op} parameter, which for now is just an instance of the
  620. \code{Add} class. So to create the AST node that adds negative eight
  621. to some user input, we write the following.
  622. \begin{lstlisting}
  623. ast1_1 = BinOp(read, Add(), neg_eight)
  624. \end{lstlisting}
  625. \fi}
  626. When compiling a program such as \eqref{eq:arith-prog}, we need to
  627. know that the operation associated with the root node is addition and
  628. we need to be able to access its two children. \racket{Racket}\python{Python}
  629. provides pattern matching to support these kinds of queries, as we see in
  630. Section~\ref{sec:pattern-matching}.
  631. In this book, we often write down the concrete syntax of a program
  632. even when we really have in mind the AST because the concrete syntax
  633. is more concise. We recommend that, in your mind, you always think of
  634. programs as abstract syntax trees.
  635. \section{Grammars}
  636. \label{sec:grammar}
  637. \index{subject}{integer}
  638. \index{subject}{literal}
  639. \index{subject}{constant}
  640. A programming language can be thought of as a \emph{set} of programs.
  641. The set is typically infinite (one can always create larger and larger
  642. programs), so one cannot simply describe a language by listing all of
  643. the programs in the language. Instead we write down a set of rules, a
  644. \emph{grammar}, for building programs. Grammars are often used to
  645. define the concrete syntax of a language, but they can also be used to
  646. describe the abstract syntax. We write our rules in a variant of
  647. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  648. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  649. As an example, we describe a small language, named \LangInt{}, that consists of
  650. integers and arithmetic operations.
  651. \index{subject}{grammar}
  652. The first grammar rule for the abstract syntax of \LangInt{} says that an
  653. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  654. \begin{equation}
  655. \Exp ::= \INT{\Int} \label{eq:arith-int}
  656. \end{equation}
  657. %
  658. Each rule has a left-hand-side and a right-hand-side.
  659. If you have an AST node that matches the
  660. right-hand-side, then you can categorize it according to the
  661. left-hand-side.
  662. %
  663. A name such as $\Exp$ that is defined by the grammar rules is a
  664. \emph{non-terminal}. \index{subject}{non-terminal}
  665. %
  666. The name $\Int$ is also a non-terminal, but instead of defining it
  667. with a grammar rule, we define it with the following explanation. An
  668. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  669. $-$ (for negative integers), such that the sequence of decimals
  670. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  671. the representation of integers using 63 bits, which simplifies several
  672. aspects of compilation. \racket{Thus, these integers corresponds to
  673. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  674. \python{In contrast, integers in Python have unlimited precision, but
  675. the techniques need to handle unlimited precision fall outside the
  676. scope of this book.}
  677. The second grammar rule is the \READOP{} operation that receives an
  678. input integer from the user of the program.
  679. \begin{equation}
  680. \Exp ::= \READ{} \label{eq:arith-read}
  681. \end{equation}
  682. The third rule says that, given an $\Exp$ node, the negation of that
  683. node is also an $\Exp$.
  684. \begin{equation}
  685. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  686. \end{equation}
  687. Symbols in typewriter font are \emph{terminal} symbols and must
  688. literally appear in the program for the rule to be applicable.
  689. \index{subject}{terminal}
  690. We can apply these rules to categorize the ASTs that are in the
  691. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  692. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  693. following AST is an $\Exp$.
  694. \begin{center}
  695. \begin{minipage}{0.5\textwidth}
  696. \NEG{\INT{\code{8}}}
  697. \end{minipage}
  698. \begin{minipage}{0.25\textwidth}
  699. \begin{equation}
  700. \begin{tikzpicture}
  701. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  702. \node[draw, circle] (8) at (0, -1.2) {$8$};
  703. \draw[->] (minus) to (8);
  704. \end{tikzpicture}
  705. \label{eq:arith-neg8}
  706. \end{equation}
  707. \end{minipage}
  708. \end{center}
  709. The next grammar rule is for addition expressions:
  710. \begin{equation}
  711. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  712. \end{equation}
  713. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  714. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  715. \eqref{eq:arith-read} and we have already categorized
  716. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  717. to show that
  718. \[
  719. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  720. \]
  721. is an $\Exp$ in the \LangInt{} language.
  722. If you have an AST for which the above rules do not apply, then the
  723. AST is not in \LangInt{}. For example, the program \racket{\code{(-
  724. (read) 8)}} \python{\code{input\_int() - 8}} is not in \LangInt{}
  725. because there are no rules for the \key{-} operator with two
  726. arguments. Whenever we define a language with a grammar, the language
  727. only includes those programs that are justified by the grammar rules.
  728. {\if\edition\pythonEd
  729. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  730. There is a statement for printing the value of an expression
  731. \[
  732. \Stmt{} ::= \PRINT{\Exp}
  733. \]
  734. and a statement that evaluates an expression but ignores the result.
  735. \[
  736. \Stmt{} ::= \EXPR{\Exp}
  737. \]
  738. \fi}
  739. {\if\edition\racketEd
  740. The last grammar rule for \LangInt{} states that there is a
  741. \code{Program} node to mark the top of the whole program:
  742. \[
  743. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  744. \]
  745. The \code{Program} structure is defined as follows
  746. \begin{lstlisting}
  747. (struct Program (info body))
  748. \end{lstlisting}
  749. where \code{body} is an expression. In later chapters, the \code{info}
  750. part will be used to store auxiliary information but for now it is
  751. just the empty list.
  752. \fi}
  753. {\if\edition\pythonEd
  754. The last grammar rule for \LangInt{} states that there is a
  755. \code{Module} node to mark the top of the whole program:
  756. \[
  757. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  758. \]
  759. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  760. this case, a list of statements.
  761. %
  762. The \code{Module} class is defined as follows
  763. \begin{lstlisting}
  764. class Module:
  765. def __init__(self, body):
  766. self.body = body
  767. \end{lstlisting}
  768. where \code{body} is a list of statements.
  769. \fi}
  770. It is common to have many grammar rules with the same left-hand side
  771. but different right-hand sides, such as the rules for $\Exp$ in the
  772. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  773. combine several right-hand-sides into a single rule.
  774. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  775. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  776. defined in Figure~\ref{fig:r0-concrete-syntax}.
  777. \racket{The \code{read-program} function provided in
  778. \code{utilities.rkt} of the support code reads a program in from a
  779. file (the sequence of characters in the concrete syntax of Racket)
  780. and parses it into an abstract syntax tree. See the description of
  781. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  782. details.}
  783. \python{The \code{parse} function in Python's \code{ast} module
  784. converts the concrete syntax (represented as a string) into an
  785. abstract syntax tree.}
  786. \begin{figure}[tp]
  787. \fbox{
  788. \begin{minipage}{0.96\textwidth}
  789. {\if\edition\racketEd
  790. \[
  791. \begin{array}{rcl}
  792. \Exp &::=& \Int \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp\;\Exp\RP\\
  793. \LangInt{} &::=& \Exp
  794. \end{array}
  795. \]
  796. \fi}
  797. {\if\edition\pythonEd
  798. \[
  799. \begin{array}{rcl}
  800. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp\\
  801. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp\\
  802. \LangInt{} &::=& \Stmt^{*}
  803. \end{array}
  804. \]
  805. \fi}
  806. \end{minipage}
  807. }
  808. \caption{The concrete syntax of \LangInt{}.}
  809. \label{fig:r0-concrete-syntax}
  810. \end{figure}
  811. \begin{figure}[tp]
  812. \fbox{
  813. \begin{minipage}{0.96\textwidth}
  814. {\if\edition\racketEd
  815. \[
  816. \begin{array}{rcl}
  817. \Exp &::=& \INT{\Int} \MID \READ{} \MID \NEG{\Exp} \\
  818. &\MID& \ADD{\Exp}{\Exp} \\
  819. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  820. \end{array}
  821. \]
  822. \fi}
  823. {\if\edition\pythonEd
  824. \[
  825. \begin{array}{rcl}
  826. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  827. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  828. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  829. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  830. \end{array}
  831. \]
  832. \fi}
  833. \end{minipage}
  834. }
  835. \caption{The abstract syntax of \LangInt{}.}
  836. \label{fig:r0-syntax}
  837. \end{figure}
  838. \section{Pattern Matching}
  839. \label{sec:pattern-matching}
  840. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  841. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  842. \texttt{match} feature to access the parts of a value.
  843. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  844. \begin{center}
  845. \begin{minipage}{0.5\textwidth}
  846. {\if\edition\racketEd
  847. \begin{lstlisting}
  848. (match ast1_1
  849. [(Prim op (list child1 child2))
  850. (print op)])
  851. \end{lstlisting}
  852. \fi}
  853. {\if\edition\pythonEd
  854. \begin{lstlisting}
  855. match ast1_1:
  856. case BinOp(child1, op, child2):
  857. print(op)
  858. \end{lstlisting}
  859. \fi}
  860. \end{minipage}
  861. \end{center}
  862. {\if\edition\racketEd
  863. %
  864. In the above example, the \texttt{match} form checks whether the AST
  865. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  866. three pattern variables \texttt{op}, \texttt{child1}, and
  867. \texttt{child2}, and then prints out the operator. In general, a match
  868. clause consists of a \emph{pattern} and a
  869. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  870. to be either a pattern variable, a structure name followed by a
  871. pattern for each of the structure's arguments, or an S-expression
  872. (symbols, lists, etc.). (See Chapter 12 of The Racket
  873. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  874. and Chapter 9 of The Racket
  875. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  876. for a complete description of \code{match}.)
  877. %
  878. The body of a match clause may contain arbitrary Racket code. The
  879. pattern variables can be used in the scope of the body, such as
  880. \code{op} in \code{(print op)}.
  881. %
  882. \fi}
  883. %
  884. %
  885. {\if\edition\pythonEd
  886. %
  887. In the above example, the \texttt{match} form checks whether the AST
  888. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  889. three pattern variables \texttt{child1}, \texttt{op}, and
  890. \texttt{child2}, and then prints out the operator. In general, each
  891. \code{case} consists of a \emph{pattern} and a
  892. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  893. to be either a pattern variable, a class name followed by a pattern
  894. for each of its constructor's arguments, or other literals such as
  895. strings, lists, etc.
  896. %
  897. The body of each \code{case} may contain arbitrary Python code. The
  898. pattern variables can be used in the body, such as \code{op} in
  899. \code{print(op)}.
  900. %
  901. \fi}
  902. A \code{match} form may contain several clauses, as in the following
  903. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  904. the AST. The \code{match} proceeds through the clauses in order,
  905. checking whether the pattern can match the input AST. The body of the
  906. first clause that matches is executed. The output of \code{leaf} for
  907. several ASTs is shown on the right.
  908. \begin{center}
  909. \begin{minipage}{0.6\textwidth}
  910. {\if\edition\racketEd
  911. \begin{lstlisting}
  912. (define (leaf arith)
  913. (match arith
  914. [(Int n) #t]
  915. [(Prim 'read '()) #t]
  916. [(Prim '- (list e1)) #f]
  917. [(Prim '+ (list e1 e2)) #f]))
  918. (leaf (Prim 'read '()))
  919. (leaf (Prim '- (list (Int 8))))
  920. (leaf (Int 8))
  921. \end{lstlisting}
  922. \fi}
  923. {\if\edition\pythonEd
  924. \begin{lstlisting}
  925. def leaf(arith):
  926. match arith:
  927. case Constant(n):
  928. return True
  929. case Call(Name('input_int'), []):
  930. return True
  931. case UnaryOp(USub(), e1):
  932. return False
  933. case BinOp(e1, Add(), e2):
  934. return False
  935. print(leaf(Call(Name('input_int'), [])))
  936. print(leaf(UnaryOp(USub(), eight)))
  937. print(leaf(Constant(8)))
  938. \end{lstlisting}
  939. \fi}
  940. \end{minipage}
  941. \vrule
  942. \begin{minipage}{0.25\textwidth}
  943. {\if\edition\racketEd
  944. \begin{lstlisting}
  945. #t
  946. #f
  947. #t
  948. \end{lstlisting}
  949. \fi}
  950. {\if\edition\pythonEd
  951. \begin{lstlisting}
  952. True
  953. False
  954. True
  955. \end{lstlisting}
  956. \fi}
  957. \end{minipage}
  958. \end{center}
  959. When writing a \code{match}, we refer to the grammar definition to
  960. identify which non-terminal we are expecting to match against, then we
  961. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  962. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  963. corresponding right-hand side of a grammar rule. For the \code{match}
  964. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  965. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  966. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  967. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  968. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  969. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  970. patterns, replace non-terminals such as $\Exp$ with pattern variables
  971. of your choice (e.g. \code{e1} and \code{e2}).
  972. \section{Recursive Functions}
  973. \label{sec:recursion}
  974. \index{subject}{recursive function}
  975. Programs are inherently recursive. For example, an expression is often
  976. made of smaller expressions. Thus, the natural way to process an
  977. entire program is with a recursive function. As a first example of
  978. such a recursive function, we define the function \code{exp} in
  979. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  980. determines whether or not it is an expression in \LangInt{}.
  981. %
  982. We say that a function is defined by \emph{structural recursion} when
  983. it is defined using a sequence of match \racket{clauses}\python{cases}
  984. that correspond to a grammar, and the body of each \racket{clause}\python{case}
  985. makes a recursive call on each
  986. child node.\footnote{This principle of structuring code according to
  987. the data definition is advocated in the book \emph{How to Design
  988. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  989. \python{We define a second function, named \code{stmt}, that recognizes
  990. whether a value is a \LangInt{} statement.}
  991. \python{Finally, }
  992. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{Lint}, which
  993. determines whether an AST is a program in \LangInt{}. In general we can
  994. expect to write one recursive function to handle each non-terminal in
  995. a grammar.\index{subject}{structural recursion}
  996. \begin{figure}[tp]
  997. {\if\edition\racketEd
  998. \begin{minipage}{0.7\textwidth}
  999. \begin{lstlisting}
  1000. (define (exp ast)
  1001. (match ast
  1002. [(Int n) #t]
  1003. [(Prim 'read '()) #t]
  1004. [(Prim '- (list e)) (exp e)]
  1005. [(Prim '+ (list e1 e2))
  1006. (and (exp e1) (exp e2))]
  1007. [else #f]))
  1008. (define (Lint ast)
  1009. (match ast
  1010. [(Program '() e) (exp e)]
  1011. [else #f]))
  1012. (Lint (Program '() ast1_1)
  1013. (Lint (Program '()
  1014. (Prim '- (list (Prim 'read '())
  1015. (Prim '+ (list (Num 8)))))))
  1016. \end{lstlisting}
  1017. \end{minipage}
  1018. \vrule
  1019. \begin{minipage}{0.25\textwidth}
  1020. \begin{lstlisting}
  1021. #t
  1022. #f
  1023. \end{lstlisting}
  1024. \end{minipage}
  1025. \fi}
  1026. {\if\edition\pythonEd
  1027. \begin{minipage}{0.7\textwidth}
  1028. \begin{lstlisting}
  1029. def exp(e):
  1030. match e:
  1031. case Constant(n):
  1032. return True
  1033. case Call(Name('input_int'), []):
  1034. return True
  1035. case UnaryOp(USub(), e1):
  1036. return exp(e1)
  1037. case BinOp(e1, Add(), e2):
  1038. return exp(e1) and exp(e2)
  1039. case _:
  1040. return False
  1041. def stmt(s):
  1042. match s:
  1043. case Call(Name('print'), [e]):
  1044. return exp(e)
  1045. case Expr(e):
  1046. return exp(e)
  1047. case _:
  1048. return False
  1049. def Lint(p):
  1050. match p:
  1051. case Module(body):
  1052. return all([stmt(s) for s in body])
  1053. case _:
  1054. return False
  1055. print(Lint(Module([Expr(ast1_1)])))
  1056. print(Lint(Module([Expr(BinOp(read, Sub(),
  1057. UnaryOp(Add(), Constant(8))))])))
  1058. \end{lstlisting}
  1059. \end{minipage}
  1060. \vrule
  1061. \begin{minipage}{0.25\textwidth}
  1062. \begin{lstlisting}
  1063. True
  1064. False
  1065. \end{lstlisting}
  1066. \end{minipage}
  1067. \fi}
  1068. \caption{Example of recursive functions for \LangInt{}. These functions
  1069. recognize whether an AST is in \LangInt{}.}
  1070. \label{fig:exp-predicate}
  1071. \end{figure}
  1072. %% You may be tempted to merge the two functions into one, like this:
  1073. %% \begin{center}
  1074. %% \begin{minipage}{0.5\textwidth}
  1075. %% \begin{lstlisting}
  1076. %% (define (Lint ast)
  1077. %% (match ast
  1078. %% [(Int n) #t]
  1079. %% [(Prim 'read '()) #t]
  1080. %% [(Prim '- (list e)) (Lint e)]
  1081. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1082. %% [(Program '() e) (Lint e)]
  1083. %% [else #f]))
  1084. %% \end{lstlisting}
  1085. %% \end{minipage}
  1086. %% \end{center}
  1087. %% %
  1088. %% Sometimes such a trick will save a few lines of code, especially when
  1089. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1090. %% \emph{not} recommended because it can get you into trouble.
  1091. %% %
  1092. %% For example, the above function is subtly wrong:
  1093. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1094. %% returns true when it should return false.
  1095. \section{Interpreters}
  1096. \label{sec:interp_Lint}
  1097. \index{subject}{interpreter}
  1098. The behavior of a program is defined by the specification of the
  1099. programming language.
  1100. %
  1101. \racket{For example, the Scheme language is defined in the report by
  1102. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1103. reference manual~\citep{plt-tr}.}
  1104. %
  1105. \python{For example, the Python language is defined in the Python
  1106. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1107. %
  1108. In this book we use interpreters
  1109. to specify each language that we consider. An interpreter that is
  1110. designated as the definition of a language is called a
  1111. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1112. \index{subject}{definitional interpreter} We warm up by creating a
  1113. definitional interpreter for the \LangInt{} language, which serves as
  1114. a second example of structural recursion. The \code{interp\_Lint}
  1115. function is defined in Figure~\ref{fig:interp_Lint}.
  1116. %
  1117. \racket{The body of the function is a match on the input program
  1118. followed by a call to the \lstinline{interp_exp} helper function,
  1119. which in turn has one match clause per grammar rule for \LangInt{}
  1120. expressions.}
  1121. %
  1122. \python{The body of the function matches on the \code{Module} AST node
  1123. and then invokes \code{interp\_stmt} on each statement in the
  1124. module. The \code{interp\_stmt} function includes a case for each
  1125. grammar rule of the \Stmt{} non-terminal and it calls
  1126. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1127. function includes a case for each grammar rule of the \Exp{}
  1128. non-terminal.}
  1129. \begin{figure}[tp]
  1130. {\if\edition\racketEd
  1131. \begin{lstlisting}
  1132. (define (interp_exp e)
  1133. (match e
  1134. [(Int n) n]
  1135. [(Prim 'read '())
  1136. (define r (read))
  1137. (cond [(fixnum? r) r]
  1138. [else (error 'interp_exp "read expected an integer" r)])]
  1139. [(Prim '- (list e))
  1140. (define v (interp_exp e))
  1141. (fx- 0 v)]
  1142. [(Prim '+ (list e1 e2))
  1143. (define v1 (interp_exp e1))
  1144. (define v2 (interp_exp e2))
  1145. (fx+ v1 v2)]))
  1146. (define (interp_Lint p)
  1147. (match p
  1148. [(Program '() e) (interp_exp e)]))
  1149. \end{lstlisting}
  1150. \fi}
  1151. {\if\edition\pythonEd
  1152. \begin{lstlisting}
  1153. def interp_exp(e):
  1154. match e:
  1155. case BinOp(left, Add(), right):
  1156. l = interp_exp(left)
  1157. r = interp_exp(right)
  1158. return l + r
  1159. case UnaryOp(USub(), v):
  1160. return - interp_exp(v)
  1161. case Constant(value):
  1162. return value
  1163. case Call(Name('input_int'), []):
  1164. return int(input())
  1165. def interp_stmt(s):
  1166. match s:
  1167. case Expr(Call(Name('print'), [arg])):
  1168. print(interp_exp(arg))
  1169. case Expr(value):
  1170. interp_exp(value)
  1171. def interp_Lint(p):
  1172. match p:
  1173. case Module(body):
  1174. for s in body:
  1175. interp_stmt(s)
  1176. \end{lstlisting}
  1177. \fi}
  1178. \caption{Interpreter for the \LangInt{} language.}
  1179. \label{fig:interp_Lint}
  1180. \end{figure}
  1181. Let us consider the result of interpreting a few \LangInt{} programs. The
  1182. following program adds two integers.
  1183. {\if\edition\racketEd
  1184. \begin{lstlisting}
  1185. (+ 10 32)
  1186. \end{lstlisting}
  1187. \fi}
  1188. {\if\edition\pythonEd
  1189. \begin{lstlisting}
  1190. print(10 + 32)
  1191. \end{lstlisting}
  1192. \fi}
  1193. The result is \key{42}, the answer to life, the universe, and
  1194. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1195. Galaxy} by Douglas Adams.}.
  1196. %
  1197. We wrote the above program in concrete syntax whereas the parsed
  1198. abstract syntax is:
  1199. {\if\edition\racketEd
  1200. \begin{lstlisting}
  1201. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1202. \end{lstlisting}
  1203. \fi}
  1204. {\if\edition\pythonEd
  1205. \begin{lstlisting}
  1206. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1207. \end{lstlisting}
  1208. \fi}
  1209. The next example demonstrates that expressions may be nested within
  1210. each other, in this case nesting several additions and negations.
  1211. {\if\edition\racketEd
  1212. \begin{lstlisting}
  1213. (+ 10 (- (+ 12 20)))
  1214. \end{lstlisting}
  1215. \fi}
  1216. {\if\edition\pythonEd
  1217. \begin{lstlisting}
  1218. print(10 + -(12 + 20))
  1219. \end{lstlisting}
  1220. \fi}
  1221. %
  1222. \noindent What is the result of the above program?
  1223. {\if\edition\racketEd
  1224. As mentioned previously, the \LangInt{} language does not support
  1225. arbitrarily-large integers, but only $63$-bit integers, so we
  1226. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1227. in Racket.
  1228. Suppose
  1229. \[
  1230. n = 999999999999999999
  1231. \]
  1232. which indeed fits in $63$-bits. What happens when we run the
  1233. following program in our interpreter?
  1234. \begin{lstlisting}
  1235. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1236. \end{lstlisting}
  1237. It produces an error:
  1238. \begin{lstlisting}
  1239. fx+: result is not a fixnum
  1240. \end{lstlisting}
  1241. We establish the convention that if running the definitional
  1242. interpreter on a program produces an error then the meaning of that
  1243. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1244. error is a \code{trapped-error}. A compiler for the language is under
  1245. no obligations regarding programs with unspecified behavior; it does
  1246. not have to produce an executable, and if it does, that executable can
  1247. do anything. On the other hand, if the error is a
  1248. \code{trapped-error}, then the compiler must produce an executable and
  1249. it is required to report that an error occurred. To signal an error,
  1250. exit with a return code of \code{255}. The interpreters in chapters
  1251. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1252. \code{trapped-error}.
  1253. \fi}
  1254. % TODO: how to deal with too-large integers in the Python interpreter?
  1255. %% This convention applies to the languages defined in this
  1256. %% book, as a way to simplify the student's task of implementing them,
  1257. %% but this convention is not applicable to all programming languages.
  1258. %%
  1259. Moving on to the last feature of the \LangInt{} language, the
  1260. \READOP{} operation prompts the user of the program for an integer.
  1261. Recall that program \eqref{eq:arith-prog} requests an integer input
  1262. and then subtracts \code{8}. So if we run
  1263. {\if\edition\racketEd
  1264. \begin{lstlisting}
  1265. (interp_Lint (Program '() ast1_1))
  1266. \end{lstlisting}
  1267. \fi}
  1268. {\if\edition\pythonEd
  1269. \begin{lstlisting}
  1270. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1271. \end{lstlisting}
  1272. \fi}
  1273. \noindent and if the input is \code{50}, the result is \code{42}.
  1274. We include the \READOP{} operation in \LangInt{} so a clever student
  1275. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1276. during compilation to obtain the output and then generates the trivial
  1277. code to produce the output.\footnote{Yes, a clever student did this in the
  1278. first instance of this course!}
  1279. The job of a compiler is to translate a program in one language into a
  1280. program in another language so that the output program behaves the
  1281. same way as the input program. This idea is depicted in the
  1282. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1283. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1284. Given a compiler that translates from language $\mathcal{L}_1$ to
  1285. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1286. compiler must translate it into some program $P_2$ such that
  1287. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1288. same input $i$ yields the same output $o$.
  1289. \begin{equation} \label{eq:compile-correct}
  1290. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1291. \node (p1) at (0, 0) {$P_1$};
  1292. \node (p2) at (3, 0) {$P_2$};
  1293. \node (o) at (3, -2.5) {$o$};
  1294. \path[->] (p1) edge [above] node {compile} (p2);
  1295. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1296. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1297. \end{tikzpicture}
  1298. \end{equation}
  1299. In the next section we see our first example of a compiler.
  1300. \section{Example Compiler: a Partial Evaluator}
  1301. \label{sec:partial-evaluation}
  1302. In this section we consider a compiler that translates \LangInt{}
  1303. programs into \LangInt{} programs that may be more efficient. The
  1304. compiler eagerly computes the parts of the program that do not depend
  1305. on any inputs, a process known as \emph{partial
  1306. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1307. For example, given the following program
  1308. {\if\edition\racketEd
  1309. \begin{lstlisting}
  1310. (+ (read) (- (+ 5 3)))
  1311. \end{lstlisting}
  1312. \fi}
  1313. {\if\edition\pythonEd
  1314. \begin{lstlisting}
  1315. print(input_int() + -(5 + 3) )
  1316. \end{lstlisting}
  1317. \fi}
  1318. \noindent our compiler translates it into the program
  1319. {\if\edition\racketEd
  1320. \begin{lstlisting}
  1321. (+ (read) -8)
  1322. \end{lstlisting}
  1323. \fi}
  1324. {\if\edition\pythonEd
  1325. \begin{lstlisting}
  1326. print(input_int() + -8)
  1327. \end{lstlisting}
  1328. \fi}
  1329. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1330. evaluator for the \LangInt{} language. The output of the partial evaluator
  1331. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1332. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1333. whereas the code for partially evaluating the negation and addition
  1334. operations is factored into two auxiliary functions:
  1335. \code{pe\_neg} and \code{pe\_add}. The input to these
  1336. functions is the output of partially evaluating the children.
  1337. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1338. arguments are integers and if they are, perform the appropriate
  1339. arithmetic. Otherwise, they create an AST node for the arithmetic
  1340. operation.
  1341. \begin{figure}[tp]
  1342. {\if\edition\racketEd
  1343. \begin{lstlisting}
  1344. (define (pe_neg r)
  1345. (match r
  1346. [(Int n) (Int (fx- 0 n))]
  1347. [else (Prim '- (list r))]))
  1348. (define (pe_add r1 r2)
  1349. (match* (r1 r2)
  1350. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1351. [(_ _) (Prim '+ (list r1 r2))]))
  1352. (define (pe_exp e)
  1353. (match e
  1354. [(Int n) (Int n)]
  1355. [(Prim 'read '()) (Prim 'read '())]
  1356. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1357. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1358. (define (pe_Lint p)
  1359. (match p
  1360. [(Program '() e) (Program '() (pe_exp e))]))
  1361. \end{lstlisting}
  1362. \fi}
  1363. {\if\edition\pythonEd
  1364. \begin{lstlisting}
  1365. def pe_neg(r):
  1366. match r:
  1367. case Constant(n):
  1368. return Constant(-n)
  1369. case _:
  1370. return UnaryOp(USub(), r)
  1371. def pe_add(r1, r2):
  1372. match (r1, r2):
  1373. case (Constant(n1), Constant(n2)):
  1374. return Constant(n1 + n2)
  1375. case _:
  1376. return BinOp(r1, Add(), r2)
  1377. def pe_exp(e):
  1378. match e:
  1379. case BinOp(left, Add(), right):
  1380. return pe_add(pe_exp(left), pe_exp(right))
  1381. case UnaryOp(USub(), v):
  1382. return pe_neg(pe_exp(v))
  1383. case Constant(value):
  1384. return e
  1385. case Call(Name('input_int'), []):
  1386. return e
  1387. def pe_stmt(s):
  1388. match s:
  1389. case Expr(Call(Name('print'), [arg])):
  1390. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1391. case Expr(value):
  1392. return Expr(pe_exp(value))
  1393. def pe_P_int(p):
  1394. match p:
  1395. case Module(body):
  1396. new_body = [pe_stmt(s) for s in body]
  1397. return Module(new_body)
  1398. \end{lstlisting}
  1399. \fi}
  1400. \caption{A partial evaluator for \LangInt{}.}
  1401. \label{fig:pe-arith}
  1402. \end{figure}
  1403. To gain some confidence that the partial evaluator is correct, we can
  1404. test whether it produces programs that get the same result as the
  1405. input programs. That is, we can test whether it satisfies Diagram
  1406. \ref{eq:compile-correct}.
  1407. %
  1408. {\if\edition\racketEd
  1409. The following code runs the partial evaluator on several examples and
  1410. tests the output program. The \texttt{parse-program} and
  1411. \texttt{assert} functions are defined in
  1412. Appendix~\ref{appendix:utilities}.\\
  1413. \begin{minipage}{1.0\textwidth}
  1414. \begin{lstlisting}
  1415. (define (test_pe p)
  1416. (assert "testing pe_Lint"
  1417. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1418. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1419. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1420. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1421. \end{lstlisting}
  1422. \end{minipage}
  1423. \fi}
  1424. % TODO: python version of testing the PE
  1425. \begin{exercise}\normalfont
  1426. Create three programs in the \LangInt{} language and test whether
  1427. partially evaluating them with \code{pe\_Lint} and then
  1428. interpreting them with \code{interp\_Lint} gives the same result
  1429. as directly interpreting them with \code{interp\_Lint}.
  1430. \end{exercise}
  1431. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1432. \chapter{Integers and Variables}
  1433. \label{ch:Lvar}
  1434. This chapter is about compiling a subset of
  1435. \racket{Racket}\python{Python} to x86-64 assembly
  1436. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1437. integer arithmetic and local variables. We often refer to x86-64
  1438. simply as x86. The chapter begins with a description of the
  1439. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1440. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1441. large so we discuss only the instructions needed for compiling
  1442. \LangVar{}. We introduce more x86 instructions in later chapters.
  1443. After introducing \LangVar{} and x86, we reflect on their differences
  1444. and come up with a plan to break down the translation from \LangVar{}
  1445. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1446. rest of the sections in this chapter give detailed hints regarding
  1447. each step. We hope to give enough hints that the well-prepared
  1448. reader, together with a few friends, can implement a compiler from
  1449. \LangVar{} to x86 in a couple weeks. To give the reader a feeling for
  1450. the scale of this first compiler, the instructor solution for the
  1451. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1452. code.
  1453. \section{The \LangVar{} Language}
  1454. \label{sec:s0}
  1455. \index{subject}{variable}
  1456. The \LangVar{} language extends the \LangInt{} language with
  1457. variables. The concrete syntax of the \LangVar{} language is defined
  1458. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1459. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1460. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1461. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1462. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1463. syntax of \LangVar{} includes the \racket{\key{Program}
  1464. struct}\python{\key{Module} instance} to mark the top of the
  1465. program.
  1466. %% The $\itm{info}$
  1467. %% field of the \key{Program} structure contains an \emph{association
  1468. %% list} (a list of key-value pairs) that is used to communicate
  1469. %% auxiliary data from one compiler pass the next.
  1470. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1471. exhibit several compilation techniques.
  1472. \begin{figure}[tp]
  1473. \centering
  1474. \fbox{
  1475. \begin{minipage}{0.96\textwidth}
  1476. {\if\edition\racketEd
  1477. \[
  1478. \begin{array}{rcl}
  1479. \Exp &::=& \Int{} \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}\\
  1480. &\MID& \Var{} \MID \CLET{\Var}{\Exp}{\Exp} \\
  1481. \LangVarM{} &::=& \Exp
  1482. \end{array}
  1483. \]
  1484. \fi}
  1485. {\if\edition\pythonEd
  1486. \[
  1487. \begin{array}{rcl}
  1488. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Var{} \\
  1489. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp\\
  1490. \LangVarM{} &::=& \Stmt^{*}
  1491. \end{array}
  1492. \]
  1493. \fi}
  1494. \end{minipage}
  1495. }
  1496. \caption{The concrete syntax of \LangVar{}.}
  1497. \label{fig:Lvar-concrete-syntax}
  1498. \end{figure}
  1499. \begin{figure}[tp]
  1500. \centering
  1501. \fbox{
  1502. \begin{minipage}{0.96\textwidth}
  1503. {\if\edition\racketEd
  1504. \[
  1505. \begin{array}{rcl}
  1506. \Exp &::=& \INT{\Int} \MID \READ{} \\
  1507. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  1508. &\MID& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  1509. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1510. \end{array}
  1511. \]
  1512. \fi}
  1513. {\if\edition\pythonEd
  1514. \[
  1515. \begin{array}{rcl}
  1516. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  1517. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \VAR{\Var{}} \\
  1518. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  1519. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  1520. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1521. \end{array}
  1522. \]
  1523. \fi}
  1524. \end{minipage}
  1525. }
  1526. \caption{The abstract syntax of \LangVar{}.}
  1527. \label{fig:Lvar-syntax}
  1528. \end{figure}
  1529. {\if\edition\racketEd
  1530. Let us dive further into the syntax and semantics of the \LangVar{}
  1531. language. The \key{let} feature defines a variable for use within its
  1532. body and initializes the variable with the value of an expression.
  1533. The abstract syntax for \key{let} is defined in
  1534. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1535. \begin{lstlisting}
  1536. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1537. \end{lstlisting}
  1538. For example, the following program initializes \code{x} to $32$ and then
  1539. evaluates the body \code{(+ 10 x)}, producing $42$.
  1540. \begin{lstlisting}
  1541. (let ([x (+ 12 20)]) (+ 10 x))
  1542. \end{lstlisting}
  1543. \fi}
  1544. %
  1545. {\if\edition\pythonEd
  1546. %
  1547. The \LangVar{} language includes assignment statements, which define a
  1548. variable for use in later statements and initializes the variable with
  1549. the value of an expression. The abstract syntax for assignment is
  1550. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1551. assignment is
  1552. \begin{lstlisting}
  1553. |$\itm{var}$| = |$\itm{exp}$|
  1554. \end{lstlisting}
  1555. For example, the following program initializes the variable \code{x}
  1556. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1557. \begin{lstlisting}
  1558. x = 12 + 20
  1559. print(10 + x)
  1560. \end{lstlisting}
  1561. \fi}
  1562. {\if\edition\racketEd
  1563. %
  1564. When there are multiple \key{let}'s for the same variable, the closest
  1565. enclosing \key{let} is used. That is, variable definitions overshadow
  1566. prior definitions. Consider the following program with two \key{let}'s
  1567. that define variables named \code{x}. Can you figure out the result?
  1568. \begin{lstlisting}
  1569. (let ([x 32]) (+ (let ([x 10]) x) x))
  1570. \end{lstlisting}
  1571. For the purposes of depicting which variable uses correspond to which
  1572. definitions, the following shows the \code{x}'s annotated with
  1573. subscripts to distinguish them. Double check that your answer for the
  1574. above is the same as your answer for this annotated version of the
  1575. program.
  1576. \begin{lstlisting}
  1577. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1578. \end{lstlisting}
  1579. The initializing expression is always evaluated before the body of the
  1580. \key{let}, so in the following, the \key{read} for \code{x} is
  1581. performed before the \key{read} for \code{y}. Given the input
  1582. $52$ then $10$, the following produces $42$ (not $-42$).
  1583. \begin{lstlisting}
  1584. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1585. \end{lstlisting}
  1586. \fi}
  1587. \subsection{Extensible Interpreters via Method Overriding}
  1588. \label{sec:extensible-interp}
  1589. To prepare for discussing the interpreter of \LangVar{}, we explain
  1590. why we implement it in an object-oriented style. Throughout this book
  1591. we define many interpreters, one for each of language that we
  1592. study. Because each language builds on the prior one, there is a lot
  1593. of commonality between these interpreters. We want to write down the
  1594. common parts just once instead of many times. A naive approach would
  1595. be for the interpreter of \LangVar{} to handle the
  1596. \racket{cases for variables and \code{let}}
  1597. \python{case for variables}
  1598. but dispatch to \LangInt{}
  1599. for the rest of the cases. The following code sketches this idea. (We
  1600. explain the \code{env} parameter soon, in
  1601. Section~\ref{sec:interp-Lvar}.)
  1602. \begin{center}
  1603. {\if\edition\racketEd
  1604. \begin{minipage}{0.45\textwidth}
  1605. \begin{lstlisting}
  1606. (define ((interp_Lint env) e)
  1607. (match e
  1608. [(Prim '- (list e1))
  1609. (fx- 0 ((interp_Lint env) e1))]
  1610. ...))
  1611. \end{lstlisting}
  1612. \end{minipage}
  1613. \begin{minipage}{0.45\textwidth}
  1614. \begin{lstlisting}
  1615. (define ((interp_Lvar env) e)
  1616. (match e
  1617. [(Var x)
  1618. (dict-ref env x)]
  1619. [(Let x e body)
  1620. (define v ((interp_exp env) e))
  1621. (define env^ (dict-set env x v))
  1622. ((interp_exp env^) body)]
  1623. [else ((interp_Lint env) e)]))
  1624. \end{lstlisting}
  1625. \end{minipage}
  1626. \fi}
  1627. {\if\edition\pythonEd
  1628. \begin{minipage}{0.45\textwidth}
  1629. \begin{lstlisting}
  1630. def interp_Lint(e, env):
  1631. match e:
  1632. case UnaryOp(USub(), e1):
  1633. return - interp_Lint(e1, env)
  1634. ...
  1635. \end{lstlisting}
  1636. \end{minipage}
  1637. \begin{minipage}{0.45\textwidth}
  1638. \begin{lstlisting}
  1639. def interp_Lvar(e, env):
  1640. match e:
  1641. case Name(id):
  1642. return env[id]
  1643. case _:
  1644. return interp_Lint(e, env)
  1645. \end{lstlisting}
  1646. \end{minipage}
  1647. \fi}
  1648. \end{center}
  1649. The problem with this approach is that it does not handle situations
  1650. in which an \LangVar{} feature, such as a variable, is nested inside
  1651. an \LangInt{} feature, like the \code{-} operator, as in the following
  1652. program.
  1653. %
  1654. {\if\edition\racketEd
  1655. \begin{lstlisting}
  1656. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1657. \end{lstlisting}
  1658. \fi}
  1659. {\if\edition\pythonEd
  1660. \begin{lstlisting}
  1661. y = 10
  1662. print(-y)
  1663. \end{lstlisting}
  1664. \fi}
  1665. %
  1666. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1667. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1668. then it recursively calls \code{interp\_Lint} again on its argument.
  1669. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1670. an error!
  1671. To make our interpreters extensible we need something called
  1672. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1673. recursive knot is delayed to when the functions are
  1674. composed. Object-oriented languages provide open recursion via
  1675. method overriding\index{subject}{method overriding}. The
  1676. following code uses method overriding to interpret \LangInt{} and
  1677. \LangVar{} using
  1678. %
  1679. \racket{the
  1680. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1681. \index{subject}{class} feature of Racket}
  1682. %
  1683. \python{a Python \code{class} definition}.
  1684. %
  1685. We define one class for each language and define a method for
  1686. interpreting expressions inside each class. The class for \LangVar{}
  1687. inherits from the class for \LangInt{} and the method
  1688. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1689. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1690. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1691. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1692. \code{interp\_exp} in \LangInt{}.
  1693. \begin{center}
  1694. \hspace{-20pt}
  1695. {\if\edition\racketEd
  1696. \begin{minipage}{0.45\textwidth}
  1697. \begin{lstlisting}
  1698. (define interp_Lint_class
  1699. (class object%
  1700. (define/public ((interp_exp env) e)
  1701. (match e
  1702. [(Prim '- (list e))
  1703. (fx- 0 ((interp_exp env) e))]
  1704. ...))
  1705. ...))
  1706. \end{lstlisting}
  1707. \end{minipage}
  1708. \begin{minipage}{0.45\textwidth}
  1709. \begin{lstlisting}
  1710. (define interp_Lvar_class
  1711. (class interp_Lint_class
  1712. (define/override ((interp_exp env) e)
  1713. (match e
  1714. [(Var x)
  1715. (dict-ref env x)]
  1716. [(Let x e body)
  1717. (define v ((interp_exp env) e))
  1718. (define env^ (dict-set env x v))
  1719. ((interp_exp env^) body)]
  1720. [else
  1721. (super (interp_exp env) e)]))
  1722. ...
  1723. ))
  1724. \end{lstlisting}
  1725. \end{minipage}
  1726. \fi}
  1727. {\if\edition\pythonEd
  1728. \begin{minipage}{0.45\textwidth}
  1729. \begin{lstlisting}
  1730. class InterpLint:
  1731. def interp_exp(e):
  1732. match e:
  1733. case UnaryOp(USub(), e1):
  1734. return -self.interp_exp(e1)
  1735. ...
  1736. ...
  1737. \end{lstlisting}
  1738. \end{minipage}
  1739. \begin{minipage}{0.45\textwidth}
  1740. \begin{lstlisting}
  1741. def InterpLvar(InterpLint):
  1742. def interp_exp(e):
  1743. match e:
  1744. case Name(id):
  1745. return env[id]
  1746. case _:
  1747. return super().interp_exp(e)
  1748. ...
  1749. \end{lstlisting}
  1750. \end{minipage}
  1751. \fi}
  1752. \end{center}
  1753. Getting back to the troublesome example, repeated here:
  1754. {\if\edition\racketEd
  1755. \begin{lstlisting}
  1756. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1757. \end{lstlisting}
  1758. \fi}
  1759. {\if\edition\pythonEd
  1760. \begin{lstlisting}
  1761. y = 10
  1762. print(-y)
  1763. \end{lstlisting}
  1764. \fi}
  1765. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1766. \racket{on this expression,}
  1767. \python{on the \code{-y} expression,}
  1768. %
  1769. call it \code{e0}, by creating an object of the \LangVar{} class
  1770. and calling the \code{interp\_exp} method.
  1771. {\if\edition\racketEd
  1772. \begin{lstlisting}
  1773. (send (new interp_Lvar_class) interp_exp e0)
  1774. \end{lstlisting}
  1775. \fi}
  1776. {\if\edition\pythonEd
  1777. \begin{lstlisting}
  1778. InterpLvar().interp_exp(e0)
  1779. \end{lstlisting}
  1780. \fi}
  1781. \noindent To process the \code{-} operator, the default case of
  1782. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1783. method in \LangInt{}. But then for the recursive method call, it
  1784. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1785. \code{Var} node is handled correctly. Thus, method overriding gives us
  1786. the open recursion that we need to implement our interpreters in an
  1787. extensible way.
  1788. \subsection{Definitional Interpreter for \LangVar{}}
  1789. \label{sec:interp-Lvar}
  1790. {\if\edition\racketEd
  1791. \begin{figure}[tp]
  1792. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1793. \small
  1794. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1795. An \emph{association list} (alist) is a list of key-value pairs.
  1796. For example, we can map people to their ages with an alist.
  1797. \index{subject}{alist}\index{subject}{association list}
  1798. \begin{lstlisting}[basicstyle=\ttfamily]
  1799. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1800. \end{lstlisting}
  1801. The \emph{dictionary} interface is for mapping keys to values.
  1802. Every alist implements this interface. \index{subject}{dictionary} The package
  1803. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1804. provides many functions for working with dictionaries. Here
  1805. are a few of them:
  1806. \begin{description}
  1807. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1808. returns the value associated with the given $\itm{key}$.
  1809. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1810. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1811. but otherwise is the same as $\itm{dict}$.
  1812. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1813. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1814. of keys and values in $\itm{dict}$. For example, the following
  1815. creates a new alist in which the ages are incremented.
  1816. \end{description}
  1817. \vspace{-10pt}
  1818. \begin{lstlisting}[basicstyle=\ttfamily]
  1819. (for/list ([(k v) (in-dict ages)])
  1820. (cons k (add1 v)))
  1821. \end{lstlisting}
  1822. \end{tcolorbox}
  1823. %\end{wrapfigure}
  1824. \caption{Association lists implement the dictionary interface.}
  1825. \label{fig:alist}
  1826. \end{figure}
  1827. \fi}
  1828. Having justified the use of classes and methods to implement
  1829. interpreters, we revisit the definitional interpreter for \LangInt{}
  1830. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1831. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1832. interpreter for \LangVar{} adds two new \key{match} cases for
  1833. variables and \racket{\key{let}}\python{assignment}. For
  1834. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1835. value bound to a variable to all the uses of the variable. To
  1836. accomplish this, we maintain a mapping from variables to values
  1837. called an \emph{environment}\index{subject}{environment}.
  1838. %
  1839. We use%
  1840. %
  1841. \racket{an association list (alist)}
  1842. %
  1843. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1844. %
  1845. to represent the environment.
  1846. %
  1847. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1848. and the \code{racket/dict} package.}
  1849. %
  1850. The \code{interp\_exp} function takes the current environment,
  1851. \code{env}, as an extra parameter. When the interpreter encounters a
  1852. variable, it looks up the corresponding value in the dictionary.
  1853. %
  1854. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1855. initializing expression, extends the environment with the result
  1856. value bound to the variable, using \code{dict-set}, then evaluates
  1857. the body of the \key{Let}.}
  1858. %
  1859. \python{When the interpreter encounters an assignment, it evaluates
  1860. the initializing expression and then associates the resulting value
  1861. with the variable in the environment.}
  1862. \begin{figure}[tp]
  1863. {\if\edition\racketEd
  1864. \begin{lstlisting}
  1865. (define interp_Lint_class
  1866. (class object%
  1867. (super-new)
  1868. (define/public ((interp_exp env) e)
  1869. (match e
  1870. [(Int n) n]
  1871. [(Prim 'read '())
  1872. (define r (read))
  1873. (cond [(fixnum? r) r]
  1874. [else (error 'interp_exp "expected an integer" r)])]
  1875. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1876. [(Prim '+ (list e1 e2))
  1877. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1878. (define/public (interp_program p)
  1879. (match p
  1880. [(Program '() e) ((interp_exp '()) e)]))
  1881. ))
  1882. \end{lstlisting}
  1883. \fi}
  1884. {\if\edition\pythonEd
  1885. \begin{lstlisting}
  1886. class InterpLint:
  1887. def interp_exp(self, e, env):
  1888. match e:
  1889. case BinOp(left, Add(), right):
  1890. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1891. case UnaryOp(USub(), v):
  1892. return - self.interp_exp(v, env)
  1893. case Constant(value):
  1894. return value
  1895. case Call(Name('input_int'), []):
  1896. return int(input())
  1897. def interp_stmts(self, ss, env):
  1898. if len(ss) == 0:
  1899. return
  1900. match ss[0]:
  1901. case Expr(Call(Name('print'), [arg])):
  1902. print(self.interp_exp(arg, env), end='')
  1903. return self.interp_stmts(ss[1:], env)
  1904. case Expr(value):
  1905. self.interp_exp(value, env)
  1906. return self.interp_stmts(ss[1:], env)
  1907. def interp(self, p):
  1908. match p:
  1909. case Module(body):
  1910. self.interp_stmts(body, {})
  1911. def interp_Lint(p):
  1912. return InterpLint().interp(p)
  1913. \end{lstlisting}
  1914. \fi}
  1915. \caption{Interpreter for \LangInt{} as a class.}
  1916. \label{fig:interp-Lint-class}
  1917. \end{figure}
  1918. \begin{figure}[tp]
  1919. {\if\edition\racketEd
  1920. \begin{lstlisting}
  1921. (define interp_Lvar_class
  1922. (class interp_Lint_class
  1923. (super-new)
  1924. (define/override ((interp_exp env) e)
  1925. (match e
  1926. [(Var x) (dict-ref env x)]
  1927. [(Let x e body)
  1928. (define new-env (dict-set env x ((interp_exp env) e)))
  1929. ((interp_exp new-env) body)]
  1930. [else ((super interp-exp env) e)]))
  1931. ))
  1932. (define (interp_Lvar p)
  1933. (send (new interp_Lvar_class) interp_program p))
  1934. \end{lstlisting}
  1935. \fi}
  1936. {\if\edition\pythonEd
  1937. \begin{lstlisting}
  1938. class InterpLvar(InterpLint):
  1939. def interp_exp(self, e, env):
  1940. match e:
  1941. case Name(id):
  1942. return env[id]
  1943. case _:
  1944. return super().interp_exp(e, env)
  1945. def interp_stmts(self, ss, env):
  1946. if len(ss) == 0:
  1947. return
  1948. match ss[0]:
  1949. case Assign([lhs], value):
  1950. env[lhs.id] = self.interp_exp(value, env)
  1951. return self.interp_stmts(ss[1:], env)
  1952. case _:
  1953. return super().interp_stmts(ss, env)
  1954. def interp_Lvar(p):
  1955. return InterpLvar().interp(p)
  1956. \end{lstlisting}
  1957. \fi}
  1958. \caption{Interpreter for the \LangVar{} language.}
  1959. \label{fig:interp-Lvar}
  1960. \end{figure}
  1961. The goal for this chapter is to implement a compiler that translates
  1962. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1963. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1964. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  1965. That is, they output the same integer $n$. We depict this correctness
  1966. criteria in the following diagram.
  1967. \[
  1968. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1969. \node (p1) at (0, 0) {$P_1$};
  1970. \node (p2) at (4, 0) {$P_2$};
  1971. \node (o) at (4, -2) {$n$};
  1972. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1973. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  1974. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  1975. \end{tikzpicture}
  1976. \]
  1977. In the next section we introduce the \LangXInt{} subset of x86 that
  1978. suffices for compiling \LangVar{}.
  1979. \section{The \LangXInt{} Assembly Language}
  1980. \label{sec:x86}
  1981. \index{subject}{x86}
  1982. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1983. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1984. assembler.
  1985. %
  1986. A program begins with a \code{main} label followed by a sequence of
  1987. instructions. The \key{globl} directive says that the \key{main}
  1988. procedure is externally visible, which is necessary so that the
  1989. operating system can call it.
  1990. %
  1991. An x86 program is stored in the computer's memory. For our purposes,
  1992. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1993. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1994. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1995. the address of the next instruction to be executed. For most
  1996. instructions, the program counter is incremented after the instruction
  1997. is executed, so it points to the next instruction in memory. Most x86
  1998. instructions take two operands, where each operand is either an
  1999. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2000. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2001. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2002. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2003. && \key{r8} \MID \key{r9} \MID \key{r10}
  2004. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2005. \MID \key{r14} \MID \key{r15}}
  2006. \begin{figure}[tp]
  2007. \fbox{
  2008. \begin{minipage}{0.96\textwidth}
  2009. {\if\edition\racketEd
  2010. \[
  2011. \begin{array}{lcl}
  2012. \Reg &::=& \allregisters{} \\
  2013. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2014. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2015. \key{subq} \; \Arg\key{,} \Arg \MID
  2016. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2017. && \key{callq} \; \mathit{label} \MID
  2018. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  2019. && \itm{label}\key{:}\; \Instr \\
  2020. \LangXIntM{} &::= & \key{.globl main}\\
  2021. & & \key{main:} \; \Instr\ldots
  2022. \end{array}
  2023. \]
  2024. \fi}
  2025. {\if\edition\pythonEd
  2026. \[
  2027. \begin{array}{lcl}
  2028. \Reg &::=& \allregisters{} \\
  2029. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2030. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2031. \key{subq} \; \Arg\key{,} \Arg \MID
  2032. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2033. && \key{callq} \; \mathit{label} \MID
  2034. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2035. \LangXIntM{} &::= & \key{.globl main}\\
  2036. & & \key{main:} \; \Instr^{*}
  2037. \end{array}
  2038. \]
  2039. \fi}
  2040. \end{minipage}
  2041. }
  2042. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2043. \label{fig:x86-int-concrete}
  2044. \end{figure}
  2045. A register is a special kind of variable that holds a 64-bit
  2046. value. There are 16 general-purpose registers in the computer and
  2047. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2048. is written with a \key{\%} followed by the register name, such as
  2049. \key{\%rax}.
  2050. An immediate value is written using the notation \key{\$}$n$ where $n$
  2051. is an integer.
  2052. %
  2053. %
  2054. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2055. which obtains the address stored in register $r$ and then adds $n$
  2056. bytes to the address. The resulting address is used to load or store
  2057. to memory depending on whether it occurs as a source or destination
  2058. argument of an instruction.
  2059. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2060. source $s$ and destination $d$, applies the arithmetic operation, then
  2061. writes the result back to the destination $d$. \index{subject}{instruction}
  2062. %
  2063. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2064. stores the result in $d$.
  2065. %
  2066. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2067. specified by the label and $\key{retq}$ returns from a procedure to
  2068. its caller.
  2069. %
  2070. We discuss procedure calls in more detail later in this chapter and in
  2071. Chapter~\ref{ch:Rfun}.
  2072. %
  2073. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2074. counter to the address of the instruction after the specified
  2075. label.}
  2076. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2077. all of the x86 instructions used in this book.
  2078. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2079. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2080. \lstinline{movq $10, %rax}
  2081. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2082. adds $32$ to the $10$ in \key{rax} and
  2083. puts the result, $42$, back into \key{rax}.
  2084. %
  2085. The last instruction, \key{retq}, finishes the \key{main} function by
  2086. returning the integer in \key{rax} to the operating system. The
  2087. operating system interprets this integer as the program's exit
  2088. code. By convention, an exit code of 0 indicates that a program
  2089. completed successfully, and all other exit codes indicate various
  2090. errors.
  2091. %
  2092. \racket{Nevertheless, in this book we return the result of the program
  2093. as the exit code.}
  2094. \begin{figure}[tbp]
  2095. \begin{lstlisting}
  2096. .globl main
  2097. main:
  2098. movq $10, %rax
  2099. addq $32, %rax
  2100. retq
  2101. \end{lstlisting}
  2102. \caption{An x86 program that computes
  2103. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2104. \label{fig:p0-x86}
  2105. \end{figure}
  2106. We exhibit the use of memory for storing intermediate results in the
  2107. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2108. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2109. uses a region of memory called the \emph{procedure call stack} (or
  2110. \emph{stack} for
  2111. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2112. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2113. for each procedure call. The memory layout for an individual frame is
  2114. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2115. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  2116. item at the top of the stack. The stack grows downward in memory, so
  2117. we increase the size of the stack by subtracting from the stack
  2118. pointer. In the context of a procedure call, the \emph{return
  2119. address}\index{subject}{return address} is the instruction after the
  2120. call instruction on the caller side. The function call instruction,
  2121. \code{callq}, pushes the return address onto the stack prior to
  2122. jumping to the procedure. The register \key{rbp} is the \emph{base
  2123. pointer}\index{subject}{base pointer} and is used to access variables
  2124. that are stored in the frame of the current procedure call. The base
  2125. pointer of the caller is store after the return address. In
  2126. Figure~\ref{fig:frame} we number the variables from $1$ to
  2127. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2128. at $-16\key{(\%rbp)}$, etc.
  2129. \begin{figure}[tbp]
  2130. {\if\edition\racketEd
  2131. \begin{lstlisting}
  2132. start:
  2133. movq $10, -8(%rbp)
  2134. negq -8(%rbp)
  2135. movq -8(%rbp), %rax
  2136. addq $52, %rax
  2137. jmp conclusion
  2138. .globl main
  2139. main:
  2140. pushq %rbp
  2141. movq %rsp, %rbp
  2142. subq $16, %rsp
  2143. jmp start
  2144. conclusion:
  2145. addq $16, %rsp
  2146. popq %rbp
  2147. retq
  2148. \end{lstlisting}
  2149. \fi}
  2150. {\if\edition\pythonEd
  2151. \begin{lstlisting}
  2152. .globl main
  2153. main:
  2154. pushq %rbp
  2155. movq %rsp, %rbp
  2156. subq $16, %rsp
  2157. movq $10, -8(%rbp)
  2158. negq -8(%rbp)
  2159. movq -8(%rbp), %rax
  2160. addq $52, %rax
  2161. addq $16, %rsp
  2162. popq %rbp
  2163. retq
  2164. \end{lstlisting}
  2165. \fi}
  2166. \caption{An x86 program that computes
  2167. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2168. \label{fig:p1-x86}
  2169. \end{figure}
  2170. \begin{figure}[tbp]
  2171. \centering
  2172. \begin{tabular}{|r|l|} \hline
  2173. Position & Contents \\ \hline
  2174. 8(\key{\%rbp}) & return address \\
  2175. 0(\key{\%rbp}) & old \key{rbp} \\
  2176. -8(\key{\%rbp}) & variable $1$ \\
  2177. -16(\key{\%rbp}) & variable $2$ \\
  2178. \ldots & \ldots \\
  2179. 0(\key{\%rsp}) & variable $n$\\ \hline
  2180. \end{tabular}
  2181. \caption{Memory layout of a frame.}
  2182. \label{fig:frame}
  2183. \end{figure}
  2184. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2185. control is transferred from the operating system to the \code{main}
  2186. function. The operating system issues a \code{callq main} instruction
  2187. which pushes its return address on the stack and then jumps to
  2188. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2189. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2190. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2191. alignment (because the \code{callq} pushed the return address). The
  2192. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2193. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2194. pointer for the caller onto the stack and subtracts $8$ from the stack
  2195. pointer. The next instruction \code{movq \%rsp, \%rbp} sets the
  2196. base pointer to the current stack pointer, which is pointing at the location
  2197. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2198. pointer down to make enough room for storing variables. This program
  2199. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2200. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2201. functions.
  2202. \racket{The last instruction of the prelude is \code{jmp start},
  2203. which transfers control to the instructions that were generated from
  2204. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2205. \racket{The first instruction under the \code{start} label is}
  2206. %
  2207. \python{The first instruction after the prelude is}
  2208. %
  2209. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2210. %
  2211. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2212. %
  2213. The next instruction moves the $-10$ from variable $1$ into the
  2214. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2215. the value in \code{rax}, updating its contents to $42$.
  2216. \racket{The three instructions under the label \code{conclusion} are the
  2217. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2218. %
  2219. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2220. \code{main} function consists of the last three instructions.}
  2221. %
  2222. The first two restore the \code{rsp} and \code{rbp} registers to the
  2223. state they were in at the beginning of the procedure. In particular,
  2224. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2225. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2226. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2227. \key{retq}, jumps back to the procedure that called this one and adds
  2228. $8$ to the stack pointer.
  2229. Our compiler needs a convenient representation for manipulating x86
  2230. programs, so we define an abstract syntax for x86 in
  2231. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2232. \LangXInt{}.
  2233. %
  2234. {\if\edition\racketEd
  2235. The main difference compared to the concrete syntax of \LangXInt{}
  2236. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2237. front of every instruction. Instead instructions are grouped into
  2238. \emph{blocks}\index{subject}{block} with a
  2239. label associated with every block, which is why the \key{X86Program}
  2240. struct includes an alist mapping labels to blocks. The reason for this
  2241. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2242. introduce conditional branching. The \code{Block} structure includes
  2243. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2244. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2245. $\itm{info}$ field should contain an empty list.
  2246. \fi}
  2247. %
  2248. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2249. node includes an integer for representing the arity of the function,
  2250. i.e., the number of arguments, which is helpful to know during
  2251. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2252. \begin{figure}[tp]
  2253. \fbox{
  2254. \begin{minipage}{0.98\textwidth}
  2255. \small
  2256. {\if\edition\racketEd
  2257. \[
  2258. \begin{array}{lcl}
  2259. \Reg &::=& \allregisters{} \\
  2260. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2261. \MID \DEREF{\Reg}{\Int} \\
  2262. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2263. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2264. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2265. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2266. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2267. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2268. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2269. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2270. \end{array}
  2271. \]
  2272. \fi}
  2273. {\if\edition\pythonEd
  2274. \[
  2275. \begin{array}{lcl}
  2276. \Reg &::=& \allregisters{} \\
  2277. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2278. \MID \DEREF{\Reg}{\Int} \\
  2279. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2280. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2281. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2282. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2283. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2284. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2285. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2286. \end{array}
  2287. \]
  2288. \fi}
  2289. \end{minipage}
  2290. }
  2291. \caption{The abstract syntax of \LangXInt{} assembly.}
  2292. \label{fig:x86-int-ast}
  2293. \end{figure}
  2294. \section{Planning the trip to x86}
  2295. \label{sec:plan-s0-x86}
  2296. To compile one language to another it helps to focus on the
  2297. differences between the two languages because the compiler will need
  2298. to bridge those differences. What are the differences between \LangVar{}
  2299. and x86 assembly? Here are some of the most important ones:
  2300. \begin{enumerate}
  2301. \item x86 arithmetic instructions typically have two arguments and
  2302. update the second argument in place. In contrast, \LangVar{}
  2303. arithmetic operations take two arguments and produce a new value.
  2304. An x86 instruction may have at most one memory-accessing argument.
  2305. Furthermore, some x86 instructions place special restrictions on
  2306. their arguments.
  2307. \item An argument of an \LangVar{} operator can be a deeply-nested
  2308. expression, whereas x86 instructions restrict their arguments to be
  2309. integer constants, registers, and memory locations.
  2310. {\if\edition\racketEd
  2311. \item The order of execution in x86 is explicit in the syntax: a
  2312. sequence of instructions and jumps to labeled positions, whereas in
  2313. \LangVar{} the order of evaluation is a left-to-right depth-first
  2314. traversal of the abstract syntax tree.
  2315. \fi}
  2316. \item A program in \LangVar{} can have any number of variables
  2317. whereas x86 has 16 registers and the procedure call stack.
  2318. {\if\edition\racketEd
  2319. \item Variables in \LangVar{} can shadow other variables with the
  2320. same name. In x86, registers have unique names and memory locations
  2321. have unique addresses.
  2322. \fi}
  2323. \end{enumerate}
  2324. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2325. down the problem into several steps, dealing with the above
  2326. differences one at a time. Each of these steps is called a \emph{pass}
  2327. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2328. %
  2329. This terminology comes from the way each step passes over, that is,
  2330. traverses the AST of the program.
  2331. %
  2332. Furthermore, we follow the nanopass approach, which means we strive
  2333. for each pass to accomplish one clear objective (not two or three at
  2334. the same time).
  2335. %
  2336. We begin by sketching how we might implement each pass, and give them
  2337. names. We then figure out an ordering of the passes and the
  2338. input/output language for each pass. The very first pass has
  2339. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2340. its output language. In between we can choose whichever language is
  2341. most convenient for expressing the output of each pass, whether that
  2342. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2343. our own design. Finally, to implement each pass we write one
  2344. recursive function per non-terminal in the grammar of the input
  2345. language of the pass. \index{subject}{intermediate language}
  2346. Our compiler for \LangVar{} consists of the following passes.
  2347. %
  2348. \begin{description}
  2349. {\if\edition\racketEd
  2350. \item[\key{uniquify}] deals with the shadowing of variables by
  2351. renaming every variable to a unique name.
  2352. \fi}
  2353. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2354. of a primitive operation or function call is a variable or integer,
  2355. that is, an \emph{atomic} expression. We refer to non-atomic
  2356. expressions as \emph{complex}. This pass introduces temporary
  2357. variables to hold the results of complex
  2358. subexpressions.\index{subject}{atomic
  2359. expression}\index{subject}{complex expression}%
  2360. {\if\edition\racketEd
  2361. \item[\key{explicate\_control}] makes the execution order of the
  2362. program explicit. It converts the abstract syntax tree representation
  2363. into a control-flow graph in which each node contains a sequence of
  2364. statements and the edges between nodes say which nodes contain jumps
  2365. to other nodes.
  2366. \fi}
  2367. \item[\key{select\_instructions}] handles the difference between
  2368. \LangVar{} operations and x86 instructions. This pass converts each
  2369. \LangVar{} operation to a short sequence of instructions that
  2370. accomplishes the same task.
  2371. \item[\key{assign\_homes}] replaces variables with registers or stack
  2372. locations.
  2373. \end{description}
  2374. %
  2375. {\if\edition\racketEd
  2376. %
  2377. Our treatment of \code{remove\_complex\_operands} and
  2378. \code{explicate\_control} as separate passes is an example of the
  2379. nanopass approach\footnote{For analogous decompositions of the
  2380. translation into continuation passing style, see the work of
  2381. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2382. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2383. %
  2384. \fi}
  2385. The next question is: in what order should we apply these passes? This
  2386. question can be challenging because it is difficult to know ahead of
  2387. time which orderings will be better (easier to implement, produce more
  2388. efficient code, etc.) so oftentimes trial-and-error is
  2389. involved. Nevertheless, we can try to plan ahead and make educated
  2390. choices regarding the ordering.
  2391. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2392. \key{uniquify}? The \key{uniquify} pass should come first because
  2393. \key{explicate\_control} changes all the \key{let}-bound variables to
  2394. become local variables whose scope is the entire program, which would
  2395. confuse variables with the same name.}
  2396. %
  2397. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2398. because the later removes the \key{let} form, but it is convenient to
  2399. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2400. %
  2401. \racket{The ordering of \key{uniquify} with respect to
  2402. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2403. \key{uniquify} to come first.}
  2404. The \key{select\_instructions} and \key{assign\_homes} passes are
  2405. intertwined.
  2406. %
  2407. In Chapter~\ref{ch:Rfun} we learn that, in x86, registers are used for
  2408. passing arguments to functions and it is preferable to assign
  2409. parameters to their corresponding registers. This suggests that it
  2410. would be better to start with the \key{select\_instructions} pass,
  2411. which generates the instructions for argument passing, before
  2412. performing register allocation.
  2413. %
  2414. On the other hand, by selecting instructions first we may run into a
  2415. dead end in \key{assign\_homes}. Recall that only one argument of an
  2416. x86 instruction may be a memory access but \key{assign\_homes} might
  2417. be forced to assign both arguments to memory locations.
  2418. %
  2419. A sophisticated approach is to iteratively repeat the two passes until
  2420. a solution is found. However, to reduce implementation complexity we
  2421. recommend placing \key{select\_instructions} first, followed by the
  2422. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2423. that uses a reserved register to fix outstanding problems.
  2424. \begin{figure}[tbp]
  2425. {\if\edition\racketEd
  2426. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2427. \node (Lvar) at (0,2) {\large \LangVar{}};
  2428. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2429. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2430. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2431. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2432. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2433. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2434. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2435. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2436. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2437. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2438. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2439. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2440. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2441. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2442. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2443. \end{tikzpicture}
  2444. \fi}
  2445. {\if\edition\pythonEd
  2446. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2447. \node (Lvar) at (0,2) {\large \LangVar{}};
  2448. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2449. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2450. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2451. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2452. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2453. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2454. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2455. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2456. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2457. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2458. \end{tikzpicture}
  2459. \fi}
  2460. \caption{Diagram of the passes for compiling \LangVar{}. }
  2461. \label{fig:Lvar-passes}
  2462. \end{figure}
  2463. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2464. passes and identifies the input and output language of each pass.
  2465. %
  2466. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2467. language, which extends \LangXInt{} with an unbounded number of
  2468. program-scope variables and removes the restrictions regarding
  2469. instruction arguments.
  2470. %
  2471. The last pass, \key{prelude\_and\_conclusion}, places the program
  2472. instructions inside a \code{main} function with instructions for the
  2473. prelude and conclusion.
  2474. %
  2475. \racket{In the following section we discuss the \LangCVar{}
  2476. intermediate language.}
  2477. %
  2478. The remainder of this chapter provides guidance on the implementation
  2479. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2480. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2481. %% are programs that are still in the \LangVar{} language, though the
  2482. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2483. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2484. %% %
  2485. %% The output of \code{explicate\_control} is in an intermediate language
  2486. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2487. %% syntax, which we introduce in the next section. The
  2488. %% \key{select-instruction} pass translates from \LangCVar{} to
  2489. %% \LangXVar{}. The \key{assign-homes} and
  2490. %% \key{patch-instructions}
  2491. %% passes input and output variants of x86 assembly.
  2492. {\if\edition\racketEd
  2493. \subsection{The \LangCVar{} Intermediate Language}
  2494. The output of \code{explicate\_control} is similar to the $C$
  2495. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2496. categories for expressions and statements, so we name it \LangCVar{}.
  2497. This style of intermediate language is also known as
  2498. \emph{three-address code}, to emphasize that the typical form of a
  2499. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2500. addresses~\citep{Aho:2006wb}.
  2501. The concrete syntax for \LangCVar{} is defined in
  2502. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2503. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2504. %
  2505. The \LangCVar{} language supports the same operators as \LangVar{} but
  2506. the arguments of operators are restricted to atomic
  2507. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2508. assignment statements which can be executed in sequence using the
  2509. \key{Seq} form. A sequence of statements always ends with
  2510. \key{Return}, a guarantee that is baked into the grammar rules for
  2511. \itm{tail}. The naming of this non-terminal comes from the term
  2512. \emph{tail position}\index{subject}{tail position}, which refers to an
  2513. expression that is the last one to execute within a function.
  2514. A \LangCVar{} program consists of an alist mapping labels to
  2515. tails. This is more general than necessary for the present chapter, as
  2516. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2517. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2518. there will be just one label, \key{start}, and the whole program is
  2519. its tail.
  2520. %
  2521. The $\itm{info}$ field of the \key{CProgram} form, after the
  2522. \code{explicate\_control} pass, contains a mapping from the symbol
  2523. \key{locals} to a list of variables, that is, a list of all the
  2524. variables used in the program. At the start of the program, these
  2525. variables are uninitialized; they become initialized on their first
  2526. assignment.
  2527. \begin{figure}[tbp]
  2528. \fbox{
  2529. \begin{minipage}{0.96\textwidth}
  2530. \[
  2531. \begin{array}{lcl}
  2532. \Atm &::=& \Int \MID \Var \\
  2533. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  2534. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  2535. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  2536. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2537. \end{array}
  2538. \]
  2539. \end{minipage}
  2540. }
  2541. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2542. \label{fig:c0-concrete-syntax}
  2543. \end{figure}
  2544. \begin{figure}[tbp]
  2545. \fbox{
  2546. \begin{minipage}{0.96\textwidth}
  2547. \[
  2548. \begin{array}{lcl}
  2549. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2550. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2551. &\MID& \ADD{\Atm}{\Atm}\\
  2552. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2553. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2554. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2555. \end{array}
  2556. \]
  2557. \end{minipage}
  2558. }
  2559. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2560. \label{fig:c0-syntax}
  2561. \end{figure}
  2562. The definitional interpreter for \LangCVar{} is in the support code,
  2563. in the file \code{interp-Cvar.rkt}.
  2564. \fi}
  2565. {\if\edition\racketEd
  2566. \section{Uniquify Variables}
  2567. \label{sec:uniquify-Lvar}
  2568. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2569. programs in which every \key{let} binds a unique variable name. For
  2570. example, the \code{uniquify} pass should translate the program on the
  2571. left into the program on the right.
  2572. \begin{transformation}
  2573. \begin{lstlisting}
  2574. (let ([x 32])
  2575. (+ (let ([x 10]) x) x))
  2576. \end{lstlisting}
  2577. \compilesto
  2578. \begin{lstlisting}
  2579. (let ([x.1 32])
  2580. (+ (let ([x.2 10]) x.2) x.1))
  2581. \end{lstlisting}
  2582. \end{transformation}
  2583. The following is another example translation, this time of a program
  2584. with a \key{let} nested inside the initializing expression of another
  2585. \key{let}.
  2586. \begin{transformation}
  2587. \begin{lstlisting}
  2588. (let ([x (let ([x 4])
  2589. (+ x 1))])
  2590. (+ x 2))
  2591. \end{lstlisting}
  2592. \compilesto
  2593. \begin{lstlisting}
  2594. (let ([x.2 (let ([x.1 4])
  2595. (+ x.1 1))])
  2596. (+ x.2 2))
  2597. \end{lstlisting}
  2598. \end{transformation}
  2599. We recommend implementing \code{uniquify} by creating a structurally
  2600. recursive function named \code{uniquify-exp} that mostly just copies
  2601. an expression. However, when encountering a \key{let}, it should
  2602. generate a unique name for the variable and associate the old name
  2603. with the new name in an alist.\footnote{The Racket function
  2604. \code{gensym} is handy for generating unique variable names.} The
  2605. \code{uniquify-exp} function needs to access this alist when it gets
  2606. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2607. for the alist.
  2608. The skeleton of the \code{uniquify-exp} function is shown in
  2609. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2610. convenient to partially apply it to an alist and then apply it to
  2611. different expressions, as in the last case for primitive operations in
  2612. Figure~\ref{fig:uniquify-Lvar}. The
  2613. %
  2614. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2615. %
  2616. form of Racket is useful for transforming each element of a list to
  2617. produce a new list.\index{subject}{for/list}
  2618. \begin{figure}[tbp]
  2619. \begin{lstlisting}
  2620. (define (uniquify-exp env)
  2621. (lambda (e)
  2622. (match e
  2623. [(Var x) ___]
  2624. [(Int n) (Int n)]
  2625. [(Let x e body) ___]
  2626. [(Prim op es)
  2627. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2628. (define (uniquify p)
  2629. (match p
  2630. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2631. \end{lstlisting}
  2632. \caption{Skeleton for the \key{uniquify} pass.}
  2633. \label{fig:uniquify-Lvar}
  2634. \end{figure}
  2635. \begin{exercise}
  2636. \normalfont % I don't like the italics for exercises. -Jeremy
  2637. Complete the \code{uniquify} pass by filling in the blanks in
  2638. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2639. variables and for the \key{let} form in the file \code{compiler.rkt}
  2640. in the support code.
  2641. \end{exercise}
  2642. \begin{exercise}
  2643. \normalfont % I don't like the italics for exercises. -Jeremy
  2644. \label{ex:Lvar}
  2645. Create five \LangVar{} programs that exercise the most interesting
  2646. parts of the \key{uniquify} pass, that is, the programs should include
  2647. \key{let} forms, variables, and variables that shadow each other.
  2648. The five programs should be placed in the subdirectory named
  2649. \key{tests} and the file names should start with \code{var\_test\_}
  2650. followed by a unique integer and end with the file extension
  2651. \key{.rkt}.
  2652. %
  2653. The \key{run-tests.rkt} script in the support code checks whether the
  2654. output programs produce the same result as the input programs. The
  2655. script uses the \key{interp-tests} function
  2656. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2657. your \key{uniquify} pass on the example programs. The \code{passes}
  2658. parameter of \key{interp-tests} is a list that should have one entry
  2659. for each pass in your compiler. For now, define \code{passes} to
  2660. contain just one entry for \code{uniquify} as shown below.
  2661. \begin{lstlisting}
  2662. (define passes
  2663. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2664. \end{lstlisting}
  2665. Run the \key{run-tests.rkt} script in the support code to check
  2666. whether the output programs produce the same result as the input
  2667. programs.
  2668. \end{exercise}
  2669. \fi}
  2670. \section{Remove Complex Operands}
  2671. \label{sec:remove-complex-opera-Lvar}
  2672. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2673. into a restricted form in which the arguments of operations are atomic
  2674. expressions. Put another way, this pass removes complex
  2675. operands\index{subject}{complex operand}, such as the expression
  2676. \racket{\code{(- 10)}}\python{\code{-10}}
  2677. in the program below. This is accomplished by introducing a new
  2678. temporary variable, assigning the complex operand to the new
  2679. variable, and then using the new variable in place of the complex
  2680. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2681. right.
  2682. {\if\edition\racketEd
  2683. \begin{transformation}
  2684. % var_test_19.rkt
  2685. \begin{lstlisting}
  2686. (let ([x (+ 42 (- 10))])
  2687. (+ x 10))
  2688. \end{lstlisting}
  2689. \compilesto
  2690. \begin{lstlisting}
  2691. (let ([x (let ([tmp.1 (- 10)])
  2692. (+ 42 tmp.1))])
  2693. (+ x 10))
  2694. \end{lstlisting}
  2695. \end{transformation}
  2696. \fi}
  2697. {\if\edition\pythonEd
  2698. \begin{transformation}
  2699. \begin{lstlisting}
  2700. x = 42 + -10
  2701. print(x + 10)
  2702. \end{lstlisting}
  2703. \compilesto
  2704. \begin{lstlisting}
  2705. tmp_0 = -10
  2706. x = 42 + tmp_0
  2707. tmp_1 = x + 10
  2708. print(tmp_1)
  2709. \end{lstlisting}
  2710. \end{transformation}
  2711. \fi}
  2712. \begin{figure}[tp]
  2713. \centering
  2714. \fbox{
  2715. \begin{minipage}{0.96\textwidth}
  2716. {\if\edition\racketEd
  2717. \[
  2718. \begin{array}{rcl}
  2719. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2720. \Exp &::=& \Atm \MID \READ{} \\
  2721. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2722. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2723. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2724. \end{array}
  2725. \]
  2726. \fi}
  2727. {\if\edition\pythonEd
  2728. \[
  2729. \begin{array}{rcl}
  2730. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2731. \Exp{} &::=& \Atm \MID \READ{} \\
  2732. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2733. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2734. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2735. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2736. \end{array}
  2737. \]
  2738. \fi}
  2739. \end{minipage}
  2740. }
  2741. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2742. atomic expressions.}
  2743. \label{fig:Lvar-anf-syntax}
  2744. \end{figure}
  2745. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2746. of this pass, the language \LangVarANF{}. The only difference is that
  2747. operator arguments are restricted to be atomic expressions that are
  2748. defined by the \Atm{} non-terminal. In particular, integer constants
  2749. and variables are atomic.
  2750. The atomic expressions are pure (they do not cause side-effects or
  2751. depend on them) whereas complex expressions may have side effects,
  2752. such as \READ{}. A language with this separation between pure versus
  2753. side-effecting expressions is said to be in monadic normal
  2754. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2755. in \LangVarANF{}. An important invariant of the
  2756. \code{remove\_complex\_operands} pass is that the relative ordering
  2757. among complex expressions is not changed, but the relative ordering
  2758. between atomic expressions and complex expressions can change and
  2759. often does. The reason that these changes are behaviour preserving is
  2760. that the atomic expressions are pure.
  2761. Another well-known form for intermediate languages is the
  2762. \emph{administrative normal form}
  2763. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2764. \index{subject}{administrative normal form} \index{subject}{ANF}
  2765. %
  2766. The \LangVarANF{} language is not quite in ANF because we allow the
  2767. right-hand side of a \code{let} to be a complex expression.
  2768. {\if\edition\racketEd
  2769. We recommend implementing this pass with two mutually recursive
  2770. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2771. \code{rco\_atom} to subexpressions that need to become atomic and to
  2772. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2773. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2774. returns an expression. The \code{rco\_atom} function returns two
  2775. things: an atomic expression and an alist mapping temporary variables to
  2776. complex subexpressions. You can return multiple things from a function
  2777. using Racket's \key{values} form and you can receive multiple things
  2778. from a function call using the \key{define-values} form.
  2779. Also, the
  2780. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2781. form is useful for applying a function to each element of a list, in
  2782. the case where the function returns multiple values.
  2783. \index{subject}{for/lists}
  2784. \fi}
  2785. %
  2786. {\if\edition\pythonEd
  2787. %
  2788. We recommend implementing this pass with an auxiliary method named
  2789. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2790. Boolean that specifies whether the expression needs to become atomic
  2791. or not. The \code{rco\_exp} method should return a pair consisting of
  2792. the new expression and a list of pairs, associating new temporary
  2793. variables with their initializing expressions.
  2794. %
  2795. \fi}
  2796. {\if\edition\racketEd
  2797. Returning to the example program with the expression \code{(+ 42 (-
  2798. 10))}, the subexpression \code{(- 10)} should be processed using the
  2799. \code{rco\_atom} function because it is an argument of the \code{+} and
  2800. therefore needs to become atomic. The output of \code{rco\_atom}
  2801. applied to \code{(- 10)} is as follows.
  2802. \begin{transformation}
  2803. \begin{lstlisting}
  2804. (- 10)
  2805. \end{lstlisting}
  2806. \compilesto
  2807. \begin{lstlisting}
  2808. tmp.1
  2809. ((tmp.1 . (- 10)))
  2810. \end{lstlisting}
  2811. \end{transformation}
  2812. \fi}
  2813. %
  2814. {\if\edition\pythonEd
  2815. %
  2816. Returning to the example program with the expression \code{42 + -10},
  2817. the subexpression \code{-10} should be processed using the
  2818. \code{rco\_exp} function with \code{True} as the second argument
  2819. because \code{-10} is an argument of the \code{+} operator and
  2820. therefore needs to become atomic. The output of \code{rco\_exp}
  2821. applied to \code{-10} is as follows.
  2822. \begin{transformation}
  2823. \begin{lstlisting}
  2824. -10
  2825. \end{lstlisting}
  2826. \compilesto
  2827. \begin{lstlisting}
  2828. tmp_1
  2829. [(tmp_1, -10)]
  2830. \end{lstlisting}
  2831. \end{transformation}
  2832. %
  2833. \fi}
  2834. Take special care of programs such as the following that
  2835. %
  2836. \racket{bind a variable to an atomic expression}
  2837. %
  2838. \python{assign an atomic expression to a variable}.
  2839. %
  2840. You should leave such \racket{variable bindings}\python{assignments}
  2841. unchanged, as shown in the program on the right\\
  2842. %
  2843. {\if\edition\racketEd
  2844. \begin{transformation}
  2845. % var_test_20.rkt
  2846. \begin{lstlisting}
  2847. (let ([a 42])
  2848. (let ([b a])
  2849. b))
  2850. \end{lstlisting}
  2851. \compilesto
  2852. \begin{lstlisting}
  2853. (let ([a 42])
  2854. (let ([b a])
  2855. b))
  2856. \end{lstlisting}
  2857. \end{transformation}
  2858. \fi}
  2859. {\if\edition\pythonEd
  2860. \begin{transformation}
  2861. \begin{lstlisting}
  2862. a = 42
  2863. b = a
  2864. print(b)
  2865. \end{lstlisting}
  2866. \compilesto
  2867. \begin{lstlisting}
  2868. a = 42
  2869. b = a
  2870. print(b)
  2871. \end{lstlisting}
  2872. \end{transformation}
  2873. \fi}
  2874. %
  2875. \noindent A careless implementation might produce the following output with
  2876. unnecessary temporary variables.
  2877. \begin{center}
  2878. \begin{minipage}{0.4\textwidth}
  2879. {\if\edition\racketEd
  2880. \begin{lstlisting}
  2881. (let ([tmp.1 42])
  2882. (let ([a tmp.1])
  2883. (let ([tmp.2 a])
  2884. (let ([b tmp.2])
  2885. b))))
  2886. \end{lstlisting}
  2887. \fi}
  2888. {\if\edition\pythonEd
  2889. \begin{lstlisting}
  2890. tmp_1 = 42
  2891. a = tmp_1
  2892. tmp_2 = a
  2893. b = tmp_2
  2894. print(b)
  2895. \end{lstlisting}
  2896. \fi}
  2897. \end{minipage}
  2898. \end{center}
  2899. \begin{exercise}
  2900. \normalfont
  2901. {\if\edition\racketEd
  2902. Implement the \code{remove\_complex\_operands} function in
  2903. \code{compiler.rkt}.
  2904. %
  2905. Create three new \LangVar{} programs that exercise the interesting
  2906. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  2907. regarding file names described in Exercise~\ref{ex:Lvar}.
  2908. %
  2909. In the \code{run-tests.rkt} script, add the following entry to the
  2910. list of \code{passes} and then run the script to test your compiler.
  2911. \begin{lstlisting}
  2912. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  2913. \end{lstlisting}
  2914. While debugging your compiler, it is often useful to see the
  2915. intermediate programs that are output from each pass. To print the
  2916. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2917. \code{interp-tests} in \code{run-tests.rkt}.
  2918. \fi}
  2919. %
  2920. {\if\edition\pythonEd
  2921. Implement the \code{remove\_complex\_operands} pass in
  2922. \code{compiler.py}, creating auxiliary functions for each
  2923. non-terminal in the grammar, i.e., \code{rco\_exp}
  2924. and \code{rco\_stmt}.
  2925. \fi}
  2926. \end{exercise}
  2927. {\if\edition\pythonEd
  2928. \begin{exercise}
  2929. \normalfont % I don't like the italics for exercises. -Jeremy
  2930. \label{ex:Lvar}
  2931. Create five \LangVar{} programs that exercise the most interesting
  2932. parts of the \code{remove\_complex\_operands} pass. The five programs
  2933. should be placed in the subdirectory named \key{tests} and the file
  2934. names should start with \code{var\_test\_} followed by a unique
  2935. integer and end with the file extension \key{.py}.
  2936. %% The \key{run-tests.rkt} script in the support code checks whether the
  2937. %% output programs produce the same result as the input programs. The
  2938. %% script uses the \key{interp-tests} function
  2939. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2940. %% your \key{uniquify} pass on the example programs. The \code{passes}
  2941. %% parameter of \key{interp-tests} is a list that should have one entry
  2942. %% for each pass in your compiler. For now, define \code{passes} to
  2943. %% contain just one entry for \code{uniquify} as shown below.
  2944. %% \begin{lstlisting}
  2945. %% (define passes
  2946. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2947. %% \end{lstlisting}
  2948. Run the \key{run-tests.py} script in the support code to check
  2949. whether the output programs produce the same result as the input
  2950. programs.
  2951. \end{exercise}
  2952. \fi}
  2953. {\if\edition\racketEd
  2954. \section{Explicate Control}
  2955. \label{sec:explicate-control-Lvar}
  2956. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  2957. programs that make the order of execution explicit in their
  2958. syntax. For now this amounts to flattening \key{let} constructs into a
  2959. sequence of assignment statements. For example, consider the following
  2960. \LangVar{} program.\\
  2961. % var_test_11.rkt
  2962. \begin{minipage}{0.96\textwidth}
  2963. \begin{lstlisting}
  2964. (let ([y (let ([x 20])
  2965. (+ x (let ([x 22]) x)))])
  2966. y)
  2967. \end{lstlisting}
  2968. \end{minipage}\\
  2969. %
  2970. The output of the previous pass and of \code{explicate\_control} is
  2971. shown below. Recall that the right-hand-side of a \key{let} executes
  2972. before its body, so the order of evaluation for this program is to
  2973. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2974. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2975. output of \code{explicate\_control} makes this ordering explicit.
  2976. \begin{transformation}
  2977. \begin{lstlisting}
  2978. (let ([y (let ([x.1 20])
  2979. (let ([x.2 22])
  2980. (+ x.1 x.2)))])
  2981. y)
  2982. \end{lstlisting}
  2983. \compilesto
  2984. \begin{lstlisting}[language=C]
  2985. start:
  2986. x.1 = 20;
  2987. x.2 = 22;
  2988. y = (+ x.1 x.2);
  2989. return y;
  2990. \end{lstlisting}
  2991. \end{transformation}
  2992. \begin{figure}[tbp]
  2993. \begin{lstlisting}
  2994. (define (explicate_tail e)
  2995. (match e
  2996. [(Var x) ___]
  2997. [(Int n) (Return (Int n))]
  2998. [(Let x rhs body) ___]
  2999. [(Prim op es) ___]
  3000. [else (error "explicate_tail unhandled case" e)]))
  3001. (define (explicate_assign e x cont)
  3002. (match e
  3003. [(Var x) ___]
  3004. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3005. [(Let y rhs body) ___]
  3006. [(Prim op es) ___]
  3007. [else (error "explicate_assign unhandled case" e)]))
  3008. (define (explicate_control p)
  3009. (match p
  3010. [(Program info body) ___]))
  3011. \end{lstlisting}
  3012. \caption{Skeleton for the \code{explicate\_control} pass.}
  3013. \label{fig:explicate-control-Lvar}
  3014. \end{figure}
  3015. The organization of this pass depends on the notion of tail position
  3016. that we have alluded to earlier.
  3017. \begin{definition}
  3018. The following rules define when an expression is in \textbf{\emph{tail
  3019. position}}\index{subject}{tail position} for the language \LangVar{}.
  3020. \begin{enumerate}
  3021. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3022. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3023. \end{enumerate}
  3024. \end{definition}
  3025. We recommend implementing \code{explicate\_control} using two mutually
  3026. recursive functions, \code{explicate\_tail} and
  3027. \code{explicate\_assign}, as suggested in the skeleton code in
  3028. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3029. function should be applied to expressions in tail position whereas the
  3030. \code{explicate\_assign} should be applied to expressions that occur on
  3031. the right-hand-side of a \key{let}.
  3032. %
  3033. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3034. input and produces a \Tail{} in \LangCVar{} (see
  3035. Figure~\ref{fig:c0-syntax}).
  3036. %
  3037. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3038. the variable that it is to be assigned to, and a \Tail{} in
  3039. \LangCVar{} for the code that comes after the assignment. The
  3040. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3041. The \code{explicate\_assign} function is in accumulator-passing style:
  3042. the \code{cont} parameter is used for accumulating the output. This
  3043. accumulator-passing style plays an important role in how we generate
  3044. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3045. \begin{exercise}\normalfont
  3046. %
  3047. Implement the \code{explicate\_control} function in
  3048. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3049. exercise the code in \code{explicate\_control}.
  3050. %
  3051. In the \code{run-tests.rkt} script, add the following entry to the
  3052. list of \code{passes} and then run the script to test your compiler.
  3053. \begin{lstlisting}
  3054. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3055. \end{lstlisting}
  3056. \end{exercise}
  3057. \fi}
  3058. \section{Select Instructions}
  3059. \label{sec:select-Lvar}
  3060. \index{subject}{instruction selection}
  3061. In the \code{select\_instructions} pass we begin the work of
  3062. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3063. language of this pass is a variant of x86 that still uses variables,
  3064. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3065. non-terminal of the \LangXInt{} abstract syntax
  3066. (Figure~\ref{fig:x86-int-ast}).
  3067. \racket{We recommend implementing the
  3068. \code{select\_instructions} with three auxiliary functions, one for
  3069. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3070. $\Tail$.}
  3071. \python{We recommend implementing an auxiliary function
  3072. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3073. \racket{
  3074. The cases for $\Atm$ are straightforward; variables stay
  3075. the same and integer constants change to immediates:
  3076. $\INT{n}$ changes to $\IMM{n}$.}
  3077. We consider the cases for the $\Stmt$ non-terminal, starting with
  3078. arithmetic operations. For example, consider the addition operation
  3079. below, on the left side. There is an \key{addq} instruction in x86,
  3080. but it performs an in-place update. So we could move $\Arg_1$
  3081. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3082. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3083. $\Atm_1$ and $\Atm_2$ respectively.
  3084. \begin{transformation}
  3085. {\if\edition\racketEd
  3086. \begin{lstlisting}
  3087. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3088. \end{lstlisting}
  3089. \fi}
  3090. {\if\edition\pythonEd
  3091. \begin{lstlisting}
  3092. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3093. \end{lstlisting}
  3094. \fi}
  3095. \compilesto
  3096. \begin{lstlisting}
  3097. movq |$\Arg_1$|, |$\itm{var}$|
  3098. addq |$\Arg_2$|, |$\itm{var}$|
  3099. \end{lstlisting}
  3100. \end{transformation}
  3101. There are also cases that require special care to avoid generating
  3102. needlessly complicated code. For example, if one of the arguments of
  3103. the addition is the same variable as the left-hand side of the
  3104. assignment, as shown below, then there is no need for the extra move
  3105. instruction. The assignment statement can be translated into a single
  3106. \key{addq} instruction as follows.
  3107. \begin{transformation}
  3108. {\if\edition\racketEd
  3109. \begin{lstlisting}
  3110. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3111. \end{lstlisting}
  3112. \fi}
  3113. {\if\edition\pythonEd
  3114. \begin{lstlisting}
  3115. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3116. \end{lstlisting}
  3117. \fi}
  3118. \compilesto
  3119. \begin{lstlisting}
  3120. addq |$\Arg_1$|, |$\itm{var}$|
  3121. \end{lstlisting}
  3122. \end{transformation}
  3123. The \READOP{} operation does not have a direct counterpart in x86
  3124. assembly, so we provide this functionality with the function
  3125. \code{read\_int} in the file \code{runtime.c}, written in
  3126. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3127. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3128. system}, or simply the \emph{runtime} for short. When compiling your
  3129. generated x86 assembly code, you need to compile \code{runtime.c} to
  3130. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3131. \code{-c}) and link it into the executable. For our purposes of code
  3132. generation, all you need to do is translate an assignment of
  3133. \READOP{} into a call to the \code{read\_int} function followed by a
  3134. move from \code{rax} to the left-hand-side variable. (Recall that the
  3135. return value of a function goes into \code{rax}.)
  3136. \begin{transformation}
  3137. {\if\edition\racketEd
  3138. \begin{lstlisting}
  3139. |$\itm{var}$| = (read);
  3140. \end{lstlisting}
  3141. \fi}
  3142. {\if\edition\pythonEd
  3143. \begin{lstlisting}
  3144. |$\itm{var}$| = input_int();
  3145. \end{lstlisting}
  3146. \fi}
  3147. \compilesto
  3148. \begin{lstlisting}
  3149. callq read_int
  3150. movq %rax, |$\itm{var}$|
  3151. \end{lstlisting}
  3152. \end{transformation}
  3153. {\if\edition\pythonEd
  3154. %
  3155. Similarly, we translate the \code{print} operation, shown below, into
  3156. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3157. In x86, the first six arguments to functions are passed in registers,
  3158. with the first argument passed in register \code{rdi}. So we move the
  3159. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3160. \code{callq} instruction.
  3161. \begin{transformation}
  3162. \begin{lstlisting}
  3163. print(|$\Atm$|)
  3164. \end{lstlisting}
  3165. \compilesto
  3166. \begin{lstlisting}
  3167. movq |$\Arg$|, %rdi
  3168. callq print_int
  3169. \end{lstlisting}
  3170. \end{transformation}
  3171. %
  3172. \fi}
  3173. {\if\edition\racketEd
  3174. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3175. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3176. assignment to the \key{rax} register followed by a jump to the
  3177. conclusion of the program (so the conclusion needs to be labeled).
  3178. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3179. recursively and then append the resulting instructions.
  3180. \fi}
  3181. \begin{exercise}
  3182. \normalfont
  3183. {\if\edition\racketEd
  3184. Implement the \code{select\_instructions} pass in
  3185. \code{compiler.rkt}. Create three new example programs that are
  3186. designed to exercise all of the interesting cases in this pass.
  3187. %
  3188. In the \code{run-tests.rkt} script, add the following entry to the
  3189. list of \code{passes} and then run the script to test your compiler.
  3190. \begin{lstlisting}
  3191. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3192. \end{lstlisting}
  3193. \fi}
  3194. {\if\edition\pythonEd
  3195. Implement the \key{select\_instructions} pass in
  3196. \code{compiler.py}. Create three new example programs that are
  3197. designed to exercise all of the interesting cases in this pass.
  3198. Run the \code{run-tests.py} script to to check
  3199. whether the output programs produce the same result as the input
  3200. programs.
  3201. \fi}
  3202. \end{exercise}
  3203. \section{Assign Homes}
  3204. \label{sec:assign-Lvar}
  3205. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3206. \LangXVar{} programs that no longer use program variables.
  3207. Thus, the \key{assign-homes} pass is responsible for placing all of
  3208. the program variables in registers or on the stack. For runtime
  3209. efficiency, it is better to place variables in registers, but as there
  3210. are only 16 registers, some programs must necessarily resort to
  3211. placing some variables on the stack. In this chapter we focus on the
  3212. mechanics of placing variables on the stack. We study an algorithm for
  3213. placing variables in registers in
  3214. Chapter~\ref{ch:register-allocation-Lvar}.
  3215. Consider again the following \LangVar{} program from
  3216. Section~\ref{sec:remove-complex-opera-Lvar}.
  3217. % var_test_20.rkt
  3218. {\if\edition\racketEd
  3219. \begin{lstlisting}
  3220. (let ([a 42])
  3221. (let ([b a])
  3222. b))
  3223. \end{lstlisting}
  3224. \fi}
  3225. {\if\edition\pythonEd
  3226. \begin{lstlisting}
  3227. a = 42
  3228. b = a
  3229. print(b)
  3230. \end{lstlisting}
  3231. \fi}
  3232. %
  3233. The output of \code{select\_instructions} is shown below, on the left,
  3234. and the output of \code{assign\_homes} is on the right. In this
  3235. example, we assign variable \code{a} to stack location
  3236. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3237. \begin{transformation}
  3238. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3239. movq $42, a
  3240. movq a, b
  3241. movq b, %rax
  3242. \end{lstlisting}
  3243. \compilesto
  3244. %stack-space: 16
  3245. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3246. movq $42, -8(%rbp)
  3247. movq -8(%rbp), -16(%rbp)
  3248. movq -16(%rbp), %rax
  3249. \end{lstlisting}
  3250. \end{transformation}
  3251. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3252. \code{X86Program} node is an alist mapping all the variables in the
  3253. program to their types (for now just \code{Integer}). The
  3254. \code{assign\_homes} pass should replace all uses of those variables
  3255. with stack locations. As an aside, the \code{locals-types} entry is
  3256. computed by \code{type-check-Cvar} in the support code, which
  3257. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3258. which should be propagated to the \code{X86Program} node.}
  3259. %
  3260. \python{The \code{assign\_homes} pass should replace all uses of
  3261. variables with stack locations.}
  3262. %
  3263. In the process of assigning variables to stack locations, it is
  3264. convenient for you to compute and store the size of the frame (in
  3265. bytes) in%
  3266. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3267. %
  3268. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3269. which is needed later to generate the conclusion of the \code{main}
  3270. procedure. The x86-64 standard requires the frame size to be a
  3271. multiple of 16 bytes.\index{subject}{frame}
  3272. % TODO: store the number of variables instead? -Jeremy
  3273. \begin{exercise}\normalfont
  3274. Implement the \key{assign\_homes} pass in
  3275. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3276. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3277. grammar. We recommend that the auxiliary functions take an extra
  3278. parameter that maps variable names to homes (stack locations for now).
  3279. %
  3280. {\if\edition\racketEd
  3281. In the \code{run-tests.rkt} script, add the following entry to the
  3282. list of \code{passes} and then run the script to test your compiler.
  3283. \begin{lstlisting}
  3284. (list "assign homes" assign-homes interp_x86-0)
  3285. \end{lstlisting}
  3286. \fi}
  3287. {\if\edition\pythonEd
  3288. Run the \code{run-tests.py} script to to check
  3289. whether the output programs produce the same result as the input
  3290. programs.
  3291. \fi}
  3292. \end{exercise}
  3293. \section{Patch Instructions}
  3294. \label{sec:patch-s0}
  3295. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3296. \LangXInt{} by making sure that each instruction adheres to the
  3297. restriction that at most one argument of an instruction may be a
  3298. memory reference.
  3299. We return to the following example.\\
  3300. \begin{minipage}{0.5\textwidth}
  3301. % var_test_20.rkt
  3302. {\if\edition\racketEd
  3303. \begin{lstlisting}
  3304. (let ([a 42])
  3305. (let ([b a])
  3306. b))
  3307. \end{lstlisting}
  3308. \fi}
  3309. {\if\edition\pythonEd
  3310. \begin{lstlisting}
  3311. a = 42
  3312. b = a
  3313. print(b)
  3314. \end{lstlisting}
  3315. \fi}
  3316. \end{minipage}\\
  3317. The \key{assign\_homes} pass produces the following translation. \\
  3318. \begin{minipage}{0.5\textwidth}
  3319. {\if\edition\racketEd
  3320. \begin{lstlisting}
  3321. movq $42, -8(%rbp)
  3322. movq -8(%rbp), -16(%rbp)
  3323. movq -16(%rbp), %rax
  3324. \end{lstlisting}
  3325. \fi}
  3326. {\if\edition\pythonEd
  3327. \begin{lstlisting}
  3328. movq 42, -8(%rbp)
  3329. movq -8(%rbp), -16(%rbp)
  3330. movq -16(%rbp), %rdi
  3331. callq print_int
  3332. \end{lstlisting}
  3333. \fi}
  3334. \end{minipage}\\
  3335. The second \key{movq} instruction is problematic because both
  3336. arguments are stack locations. We suggest fixing this problem by
  3337. moving from the source location to the register \key{rax} and then
  3338. from \key{rax} to the destination location, as follows.
  3339. \begin{lstlisting}
  3340. movq -8(%rbp), %rax
  3341. movq %rax, -16(%rbp)
  3342. \end{lstlisting}
  3343. \begin{exercise}
  3344. \normalfont Implement the \key{patch\_instructions} pass in
  3345. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3346. Create three new example programs that are
  3347. designed to exercise all of the interesting cases in this pass.
  3348. %
  3349. {\if\edition\racketEd
  3350. In the \code{run-tests.rkt} script, add the following entry to the
  3351. list of \code{passes} and then run the script to test your compiler.
  3352. \begin{lstlisting}
  3353. (list "patch instructions" patch_instructions interp_x86-0)
  3354. \end{lstlisting}
  3355. \fi}
  3356. {\if\edition\pythonEd
  3357. Run the \code{run-tests.py} script to to check
  3358. whether the output programs produce the same result as the input
  3359. programs.
  3360. \fi}
  3361. \end{exercise}
  3362. \section{Generate Prelude and Conclusion}
  3363. \label{sec:print-x86}
  3364. \index{subject}{prelude}\index{subject}{conclusion}
  3365. The last step of the compiler from \LangVar{} to x86 is to generate
  3366. the \code{main} function with a prelude and conclusion wrapped around
  3367. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3368. discussed in Section~\ref{sec:x86}.
  3369. When running on Mac OS X, your compiler should prefix an underscore to
  3370. all labels, e.g., changing \key{main} to \key{\_main}.
  3371. %
  3372. \racket{The Racket call \code{(system-type 'os)} is useful for
  3373. determining which operating system the compiler is running on. It
  3374. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3375. %
  3376. \python{The Python \code{platform} library includes a \code{system()}
  3377. function that returns \code{'Linux'}, \code{'Windows'}, or
  3378. \code{'Darwin'} (for Mac).}
  3379. \begin{exercise}\normalfont
  3380. %
  3381. Implement the \key{prelude\_and\_conclusion} pass in
  3382. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3383. %
  3384. {\if\edition\racketEd
  3385. In the \code{run-tests.rkt} script, add the following entry to the
  3386. list of \code{passes} and then run the script to test your compiler.
  3387. \begin{lstlisting}
  3388. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3389. \end{lstlisting}
  3390. %
  3391. Uncomment the call to the \key{compiler-tests} function
  3392. (Appendix~\ref{appendix:utilities}), which tests your complete
  3393. compiler by executing the generated x86 code. It translates the x86
  3394. AST that you produce into a string by invoking the \code{print-x86}
  3395. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3396. the provided \key{runtime.c} file to \key{runtime.o} using
  3397. \key{gcc}. Run the script to test your compiler.
  3398. %
  3399. \fi}
  3400. {\if\edition\pythonEd
  3401. %
  3402. Run the \code{run-tests.py} script to to check whether the output
  3403. programs produce the same result as the input programs. That script
  3404. translates the x86 AST that you produce into a string by invoking the
  3405. \code{repr} method that is implemented by the x86 AST classes in
  3406. \code{x86\_ast.py}.
  3407. %
  3408. \fi}
  3409. \end{exercise}
  3410. \section{Challenge: Partial Evaluator for \LangVar{}}
  3411. \label{sec:pe-Lvar}
  3412. \index{subject}{partial evaluation}
  3413. This section describes two optional challenge exercises that involve
  3414. adapting and improving the partial evaluator for \LangInt{} that was
  3415. introduced in Section~\ref{sec:partial-evaluation}.
  3416. \begin{exercise}\label{ex:pe-Lvar}
  3417. \normalfont
  3418. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3419. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3420. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3421. %
  3422. \racket{\key{let} binding}\python{assignment}
  3423. %
  3424. to the \LangInt{} language, so you will need to add cases for them in
  3425. the \code{pe\_exp}
  3426. %
  3427. \racket{function}
  3428. %
  3429. \python{and \code{pe\_stmt} functions}.
  3430. %
  3431. Once complete, add the partial evaluation pass to the front of your
  3432. compiler and make sure that your compiler still passes all of the
  3433. tests.
  3434. \end{exercise}
  3435. \begin{exercise}
  3436. \normalfont
  3437. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3438. \code{pe\_add} auxiliary functions with functions that know more about
  3439. arithmetic. For example, your partial evaluator should translate
  3440. {\if\edition\racketEd
  3441. \[
  3442. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3443. \code{(+ 2 (read))}
  3444. \]
  3445. \fi}
  3446. {\if\edition\pythonEd
  3447. \[
  3448. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3449. \code{2 + input\_int()}
  3450. \]
  3451. \fi}
  3452. To accomplish this, the \code{pe\_exp} function should produce output
  3453. in the form of the $\itm{residual}$ non-terminal of the following
  3454. grammar. The idea is that when processing an addition expression, we
  3455. can always produce either 1) an integer constant, 2) an addition
  3456. expression with an integer constant on the left-hand side but not the
  3457. right-hand side, or 3) or an addition expression in which neither
  3458. subexpression is a constant.
  3459. {\if\edition\racketEd
  3460. \[
  3461. \begin{array}{lcl}
  3462. \itm{inert} &::=& \Var
  3463. \MID \LP\key{read}\RP
  3464. \MID \LP\key{-} ~\Var\RP
  3465. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3466. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3467. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3468. \itm{residual} &::=& \Int
  3469. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3470. \MID \itm{inert}
  3471. \end{array}
  3472. \]
  3473. \fi}
  3474. {\if\edition\pythonEd
  3475. \[
  3476. \begin{array}{lcl}
  3477. \itm{inert} &::=& \Var
  3478. \MID \key{input\_int}\LP\RP
  3479. \MID \key{-} \Var
  3480. \MID \key{-} \key{input\_int}\LP\RP
  3481. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3482. \itm{residual} &::=& \Int
  3483. \MID \Int ~ \key{+} ~ \itm{inert}
  3484. \MID \itm{inert}
  3485. \end{array}
  3486. \]
  3487. \fi}
  3488. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3489. inputs are $\itm{residual}$ expressions and they should return
  3490. $\itm{residual}$ expressions. Once the improvements are complete,
  3491. make sure that your compiler still passes all of the tests. After
  3492. all, fast code is useless if it produces incorrect results!
  3493. \end{exercise}
  3494. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3495. \chapter{Register Allocation}
  3496. \label{ch:register-allocation-Lvar}
  3497. \index{subject}{register allocation}
  3498. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3499. stack. In this chapter we learn how to improve the performance of the
  3500. generated code by assigning some variables to registers. The CPU can
  3501. access a register in a single cycle, whereas accessing the stack can
  3502. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3503. serves as a running example. The source program is on the left and the
  3504. output of instruction selection is on the right. The program is almost
  3505. in the x86 assembly language but it still uses variables.
  3506. \begin{figure}
  3507. \begin{minipage}{0.45\textwidth}
  3508. Example \LangVar{} program:
  3509. % var_test_28.rkt
  3510. {\if\edition\racketEd
  3511. \begin{lstlisting}
  3512. (let ([v 1])
  3513. (let ([w 42])
  3514. (let ([x (+ v 7)])
  3515. (let ([y x])
  3516. (let ([z (+ x w)])
  3517. (+ z (- y)))))))
  3518. \end{lstlisting}
  3519. \fi}
  3520. {\if\edition\pythonEd
  3521. \begin{lstlisting}
  3522. v = 1
  3523. w = 42
  3524. x = v + 7
  3525. y = x
  3526. z = x + w
  3527. print(z + (- y))
  3528. \end{lstlisting}
  3529. \fi}
  3530. \end{minipage}
  3531. \begin{minipage}{0.45\textwidth}
  3532. After instruction selection:
  3533. {\if\edition\racketEd
  3534. \begin{lstlisting}
  3535. locals-types:
  3536. x : Integer, y : Integer,
  3537. z : Integer, t : Integer,
  3538. v : Integer, w : Integer
  3539. start:
  3540. movq $1, v
  3541. movq $42, w
  3542. movq v, x
  3543. addq $7, x
  3544. movq x, y
  3545. movq x, z
  3546. addq w, z
  3547. movq y, t
  3548. negq t
  3549. movq z, %rax
  3550. addq t, %rax
  3551. jmp conclusion
  3552. \end{lstlisting}
  3553. \fi}
  3554. {\if\edition\pythonEd
  3555. \begin{lstlisting}
  3556. movq $1, v
  3557. movq $42, w
  3558. movq v, x
  3559. addq $7, x
  3560. movq x, y
  3561. movq x, z
  3562. addq w, z
  3563. movq y, tmp_0
  3564. negq tmp_0
  3565. movq z, tmp_1
  3566. addq tmp_0, tmp_1
  3567. movq tmp_1, %rdi
  3568. callq print_int
  3569. \end{lstlisting}
  3570. \fi}
  3571. \end{minipage}
  3572. \caption{A running example for register allocation.}
  3573. \label{fig:reg-eg}
  3574. \end{figure}
  3575. The goal of register allocation is to fit as many variables into
  3576. registers as possible. Some programs have more variables than
  3577. registers so we cannot always map each variable to a different
  3578. register. Fortunately, it is common for different variables to be
  3579. needed during different periods of time during program execution, and
  3580. in such cases several variables can be mapped to the same register.
  3581. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3582. After the variable \code{x} is moved to \code{z} it is no longer
  3583. needed. Variable \code{z}, on the other hand, is used only after this
  3584. point, so \code{x} and \code{z} could share the same register. The
  3585. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3586. where a variable is needed. Once we have that information, we compute
  3587. which variables are needed at the same time, i.e., which ones
  3588. \emph{interfere} with each other, and represent this relation as an
  3589. undirected graph whose vertices are variables and edges indicate when
  3590. two variables interfere (Section~\ref{sec:build-interference}). We
  3591. then model register allocation as a graph coloring problem
  3592. (Section~\ref{sec:graph-coloring}).
  3593. If we run out of registers despite these efforts, we place the
  3594. remaining variables on the stack, similar to what we did in
  3595. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3596. assigning a variable to a stack location. The decision to spill a
  3597. variable is handled as part of the graph coloring process.
  3598. We make the simplifying assumption that each variable is assigned to
  3599. one location (a register or stack address). A more sophisticated
  3600. approach is to assign a variable to one or more locations in different
  3601. regions of the program. For example, if a variable is used many times
  3602. in short sequence and then only used again after many other
  3603. instructions, it could be more efficient to assign the variable to a
  3604. register during the initial sequence and then move it to the stack for
  3605. the rest of its lifetime. We refer the interested reader to
  3606. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3607. approach.
  3608. % discuss prioritizing variables based on how much they are used.
  3609. \section{Registers and Calling Conventions}
  3610. \label{sec:calling-conventions}
  3611. \index{subject}{calling conventions}
  3612. As we perform register allocation, we need to be aware of the
  3613. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3614. functions calls are performed in x86.
  3615. %
  3616. Even though \LangVar{} does not include programmer-defined functions,
  3617. our generated code includes a \code{main} function that is called by
  3618. the operating system and our generated code contains calls to the
  3619. \code{read\_int} function.
  3620. Function calls require coordination between two pieces of code that
  3621. may be written by different programmers or generated by different
  3622. compilers. Here we follow the System V calling conventions that are
  3623. used by the GNU C compiler on Linux and
  3624. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3625. %
  3626. The calling conventions include rules about how functions share the
  3627. use of registers. In particular, the caller is responsible for freeing
  3628. up some registers prior to the function call for use by the callee.
  3629. These are called the \emph{caller-saved registers}
  3630. \index{subject}{caller-saved registers}
  3631. and they are
  3632. \begin{lstlisting}
  3633. rax rcx rdx rsi rdi r8 r9 r10 r11
  3634. \end{lstlisting}
  3635. On the other hand, the callee is responsible for preserving the values
  3636. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3637. which are
  3638. \begin{lstlisting}
  3639. rsp rbp rbx r12 r13 r14 r15
  3640. \end{lstlisting}
  3641. We can think about this caller/callee convention from two points of
  3642. view, the caller view and the callee view:
  3643. \begin{itemize}
  3644. \item The caller should assume that all the caller-saved registers get
  3645. overwritten with arbitrary values by the callee. On the other hand,
  3646. the caller can safely assume that all the callee-saved registers
  3647. contain the same values after the call that they did before the
  3648. call.
  3649. \item The callee can freely use any of the caller-saved registers.
  3650. However, if the callee wants to use a callee-saved register, the
  3651. callee must arrange to put the original value back in the register
  3652. prior to returning to the caller. This can be accomplished by saving
  3653. the value to the stack in the prelude of the function and restoring
  3654. the value in the conclusion of the function.
  3655. \end{itemize}
  3656. In x86, registers are also used for passing arguments to a function
  3657. and for the return value. In particular, the first six arguments to a
  3658. function are passed in the following six registers, in this order.
  3659. \begin{lstlisting}
  3660. rdi rsi rdx rcx r8 r9
  3661. \end{lstlisting}
  3662. If there are more than six arguments, then the convention is to use
  3663. space on the frame of the caller for the rest of the
  3664. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3665. need more than six arguments.
  3666. %
  3667. \racket{For now, the only function we care about is \code{read\_int}
  3668. and it takes zero arguments.}
  3669. %
  3670. \python{For now, the only functions we care about are \code{read\_int}
  3671. and \code{print\_int}, which take zero and one argument, respectively.}
  3672. %
  3673. The register \code{rax} is used for the return value of a function.
  3674. The next question is how these calling conventions impact register
  3675. allocation. Consider the \LangVar{} program in
  3676. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3677. example from the caller point of view and then from the callee point
  3678. of view.
  3679. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3680. is in use during the second call to \READOP{}, so we need to make sure
  3681. that the value in \code{x} does not get accidentally wiped out by the
  3682. call to \READOP{}. One obvious approach is to save all the values in
  3683. caller-saved registers to the stack prior to each function call, and
  3684. restore them after each call. That way, if the register allocator
  3685. chooses to assign \code{x} to a caller-saved register, its value will
  3686. be preserved across the call to \READOP{}. However, saving and
  3687. restoring to the stack is relatively slow. If \code{x} is not used
  3688. many times, it may be better to assign \code{x} to a stack location in
  3689. the first place. Or better yet, if we can arrange for \code{x} to be
  3690. placed in a callee-saved register, then it won't need to be saved and
  3691. restored during function calls.
  3692. The approach that we recommend for variables that are in use during a
  3693. function call is to either assign them to callee-saved registers or to
  3694. spill them to the stack. On the other hand, for variables that are not
  3695. in use during a function call, we try the following alternatives in
  3696. order 1) look for an available caller-saved register (to leave room
  3697. for other variables in the callee-saved register), 2) look for a
  3698. callee-saved register, and 3) spill the variable to the stack.
  3699. It is straightforward to implement this approach in a graph coloring
  3700. register allocator. First, we know which variables are in use during
  3701. every function call because we compute that information for every
  3702. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3703. we build the interference graph
  3704. (Section~\ref{sec:build-interference}), we can place an edge between
  3705. each of these call-live variables and the caller-saved registers in
  3706. the interference graph. This will prevent the graph coloring algorithm
  3707. from assigning them to caller-saved registers.
  3708. Returning to the example in
  3709. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3710. generated x86 code on the right-hand side. Notice that variable
  3711. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3712. is already in a safe place during the second call to
  3713. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3714. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3715. live-after set of a \code{callq} instruction.
  3716. Next we analyze the example from the callee point of view, focusing on
  3717. the prelude and conclusion of the \code{main} function. As usual the
  3718. prelude begins with saving the \code{rbp} register to the stack and
  3719. setting the \code{rbp} to the current stack pointer. We now know why
  3720. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3721. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3722. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3723. (\code{x}). The other callee-saved registers are not saved in the
  3724. prelude because they are not used. The prelude subtracts 8 bytes from
  3725. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3726. conclusion, we see that \code{rbx} is restored from the stack with a
  3727. \code{popq} instruction.
  3728. \index{subject}{prelude}\index{subject}{conclusion}
  3729. \begin{figure}[tp]
  3730. \begin{minipage}{0.45\textwidth}
  3731. Example \LangVar{} program:
  3732. %var_test_14.rkt
  3733. {\if\edition\racketEd
  3734. \begin{lstlisting}
  3735. (let ([x (read)])
  3736. (let ([y (read)])
  3737. (+ (+ x y) 42)))
  3738. \end{lstlisting}
  3739. \fi}
  3740. {\if\edition\pythonEd
  3741. \begin{lstlisting}
  3742. x = input_int()
  3743. y = input_int()
  3744. print((x + y) + 42)
  3745. \end{lstlisting}
  3746. \fi}
  3747. \end{minipage}
  3748. \begin{minipage}{0.45\textwidth}
  3749. Generated x86 assembly:
  3750. {\if\edition\racketEd
  3751. \begin{lstlisting}
  3752. start:
  3753. callq read_int
  3754. movq %rax, %rbx
  3755. callq read_int
  3756. movq %rax, %rcx
  3757. addq %rcx, %rbx
  3758. movq %rbx, %rax
  3759. addq $42, %rax
  3760. jmp _conclusion
  3761. .globl main
  3762. main:
  3763. pushq %rbp
  3764. movq %rsp, %rbp
  3765. pushq %rbx
  3766. subq $8, %rsp
  3767. jmp start
  3768. conclusion:
  3769. addq $8, %rsp
  3770. popq %rbx
  3771. popq %rbp
  3772. retq
  3773. \end{lstlisting}
  3774. \fi}
  3775. {\if\edition\pythonEd
  3776. \begin{lstlisting}
  3777. .globl main
  3778. main:
  3779. pushq %rbp
  3780. movq %rsp, %rbp
  3781. pushq %rbx
  3782. subq $8, %rsp
  3783. callq read_int
  3784. movq %rax, %rbx
  3785. callq read_int
  3786. movq %rax, %rcx
  3787. movq %rbx, %rdx
  3788. addq %rcx, %rdx
  3789. movq %rdx, %rcx
  3790. addq $42, %rcx
  3791. movq %rcx, %rdi
  3792. callq print_int
  3793. addq $8, %rsp
  3794. popq %rbx
  3795. popq %rbp
  3796. retq
  3797. \end{lstlisting}
  3798. \fi}
  3799. \end{minipage}
  3800. \caption{An example with function calls.}
  3801. \label{fig:example-calling-conventions}
  3802. \end{figure}
  3803. %\clearpage
  3804. \section{Liveness Analysis}
  3805. \label{sec:liveness-analysis-Lvar}
  3806. \index{subject}{liveness analysis}
  3807. The \code{uncover\_live} \racket{pass}\python{function}
  3808. performs \emph{liveness analysis}, that
  3809. is, it discovers which variables are in-use in different regions of a
  3810. program.
  3811. %
  3812. A variable or register is \emph{live} at a program point if its
  3813. current value is used at some later point in the program. We refer to
  3814. variables, stack locations, and registers collectively as
  3815. \emph{locations}.
  3816. %
  3817. Consider the following code fragment in which there are two writes to
  3818. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3819. \begin{center}
  3820. \begin{minipage}{0.96\textwidth}
  3821. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3822. movq $5, a
  3823. movq $30, b
  3824. movq a, c
  3825. movq $10, b
  3826. addq b, c
  3827. \end{lstlisting}
  3828. \end{minipage}
  3829. \end{center}
  3830. The answer is no because \code{a} is live from line 1 to 3 and
  3831. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3832. line 2 is never used because it is overwritten (line 4) before the
  3833. next read (line 5).
  3834. The live locations can be computed by traversing the instruction
  3835. sequence back to front (i.e., backwards in execution order). Let
  3836. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3837. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3838. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3839. locations before instruction $I_k$.
  3840. \racket{We recommend representing these
  3841. sets with the Racket \code{set} data structure described in
  3842. Figure~\ref{fig:set}.}
  3843. \python{We recommend representing these sets with the Python
  3844. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3845. data structure.}
  3846. {\if\edition\racketEd
  3847. \begin{figure}[tp]
  3848. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3849. \small
  3850. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3851. A \emph{set} is an unordered collection of elements without duplicates.
  3852. Here are some of the operations defined on sets.
  3853. \index{subject}{set}
  3854. \begin{description}
  3855. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3856. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3857. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3858. difference of the two sets.
  3859. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3860. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3861. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3862. \end{description}
  3863. \end{tcolorbox}
  3864. %\end{wrapfigure}
  3865. \caption{The \code{set} data structure.}
  3866. \label{fig:set}
  3867. \end{figure}
  3868. \fi}
  3869. The live locations after an instruction are always the same as the
  3870. live locations before the next instruction.
  3871. \index{subject}{live-after} \index{subject}{live-before}
  3872. \begin{equation} \label{eq:live-after-before-next}
  3873. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3874. \end{equation}
  3875. To start things off, there are no live locations after the last
  3876. instruction, so
  3877. \begin{equation}\label{eq:live-last-empty}
  3878. L_{\mathsf{after}}(n) = \emptyset
  3879. \end{equation}
  3880. We then apply the following rule repeatedly, traversing the
  3881. instruction sequence back to front.
  3882. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3883. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3884. \end{equation}
  3885. where $W(k)$ are the locations written to by instruction $I_k$ and
  3886. $R(k)$ are the locations read by instruction $I_k$.
  3887. {\if\edition\racketEd
  3888. There is a special case for \code{jmp} instructions. The locations
  3889. that are live before a \code{jmp} should be the locations in
  3890. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3891. maintaining an alist named \code{label->live} that maps each label to
  3892. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3893. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3894. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3895. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3896. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3897. \fi}
  3898. Let us walk through the above example, applying these formulas
  3899. starting with the instruction on line 5. We collect the answers in
  3900. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3901. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3902. instruction (formula~\ref{eq:live-last-empty}). The
  3903. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3904. because it reads from variables \code{b} and \code{c}
  3905. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3906. \[
  3907. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3908. \]
  3909. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3910. the live-before set from line 5 to be the live-after set for this
  3911. instruction (formula~\ref{eq:live-after-before-next}).
  3912. \[
  3913. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3914. \]
  3915. This move instruction writes to \code{b} and does not read from any
  3916. variables, so we have the following live-before set
  3917. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3918. \[
  3919. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3920. \]
  3921. The live-before for instruction \code{movq a, c}
  3922. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3923. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3924. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3925. variable that is not live and does not read from a variable.
  3926. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3927. because it writes to variable \code{a}.
  3928. \begin{figure}[tbp]
  3929. \begin{minipage}{0.45\textwidth}
  3930. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3931. movq $5, a
  3932. movq $30, b
  3933. movq a, c
  3934. movq $10, b
  3935. addq b, c
  3936. \end{lstlisting}
  3937. \end{minipage}
  3938. \vrule\hspace{10pt}
  3939. \begin{minipage}{0.45\textwidth}
  3940. \begin{align*}
  3941. L_{\mathsf{before}}(1)= \emptyset,
  3942. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3943. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3944. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3945. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3946. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3947. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3948. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3949. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3950. L_{\mathsf{after}}(5)= \emptyset
  3951. \end{align*}
  3952. \end{minipage}
  3953. \caption{Example output of liveness analysis on a short example.}
  3954. \label{fig:liveness-example-0}
  3955. \end{figure}
  3956. \begin{exercise}\normalfont
  3957. Perform liveness analysis on the running example in
  3958. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3959. sets for each instruction. Compare your answers to the solution
  3960. shown in Figure~\ref{fig:live-eg}.
  3961. \end{exercise}
  3962. \begin{figure}[tp]
  3963. \hspace{20pt}
  3964. \begin{minipage}{0.45\textwidth}
  3965. {\if\edition\racketEd
  3966. \begin{lstlisting}
  3967. |$\{\ttm{rsp}\}$|
  3968. movq $1, v
  3969. |$\{\ttm{v},\ttm{rsp}\}$|
  3970. movq $42, w
  3971. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3972. movq v, x
  3973. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3974. addq $7, x
  3975. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3976. movq x, y
  3977. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3978. movq x, z
  3979. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3980. addq w, z
  3981. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3982. movq y, t
  3983. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3984. negq t
  3985. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3986. movq z, %rax
  3987. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3988. addq t, %rax
  3989. |$\{\ttm{rax},\ttm{rsp}\}$|
  3990. jmp conclusion
  3991. \end{lstlisting}
  3992. \fi}
  3993. {\if\edition\pythonEd
  3994. \begin{lstlisting}
  3995. movq $1, v
  3996. |$\{\ttm{v}\}$|
  3997. movq $42, w
  3998. |$\{\ttm{w}, \ttm{v}\}$|
  3999. movq v, x
  4000. |$\{\ttm{w}, \ttm{x}\}$|
  4001. addq $7, x
  4002. |$\{\ttm{w}, \ttm{x}\}$|
  4003. movq x, y
  4004. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4005. movq x, z
  4006. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4007. addq w, z
  4008. |$\{\ttm{y}, \ttm{z}\}$|
  4009. movq y, tmp_0
  4010. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4011. negq tmp_0
  4012. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4013. movq z, tmp_1
  4014. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4015. addq tmp_0, tmp_1
  4016. |$\{\ttm{tmp\_1}\}$|
  4017. movq tmp_1, %rdi
  4018. |$\{\ttm{rdi}\}$|
  4019. callq print_int
  4020. |$\{\}$|
  4021. \end{lstlisting}
  4022. \fi}
  4023. \end{minipage}
  4024. \caption{The running example annotated with live-after sets.}
  4025. \label{fig:live-eg}
  4026. \end{figure}
  4027. \begin{exercise}\normalfont
  4028. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4029. %
  4030. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4031. field of the \code{Block} structure.}
  4032. %
  4033. \python{Return a dictionary that maps each instruction to its
  4034. live-after set.}
  4035. %
  4036. \racket{We recommend creating an auxiliary function that takes a list
  4037. of instructions and an initial live-after set (typically empty) and
  4038. returns the list of live-after sets.}
  4039. %
  4040. We recommend creating auxiliary functions to 1) compute the set
  4041. of locations that appear in an \Arg{}, 2) compute the locations read
  4042. by an instruction (the $R$ function), and 3) the locations written by
  4043. an instruction (the $W$ function). The \code{callq} instruction should
  4044. include all of the caller-saved registers in its write-set $W$ because
  4045. the calling convention says that those registers may be written to
  4046. during the function call. Likewise, the \code{callq} instruction
  4047. should include the appropriate argument-passing registers in its
  4048. read-set $R$, depending on the arity of the function being
  4049. called. (This is why the abstract syntax for \code{callq} includes the
  4050. arity.)
  4051. \end{exercise}
  4052. %\clearpage
  4053. \section{Build the Interference Graph}
  4054. \label{sec:build-interference}
  4055. {\if\edition\racketEd
  4056. \begin{figure}[tp]
  4057. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4058. \small
  4059. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4060. A \emph{graph} is a collection of vertices and edges where each
  4061. edge connects two vertices. A graph is \emph{directed} if each
  4062. edge points from a source to a target. Otherwise the graph is
  4063. \emph{undirected}.
  4064. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4065. \begin{description}
  4066. %% We currently don't use directed graphs. We instead use
  4067. %% directed multi-graphs. -Jeremy
  4068. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4069. directed graph from a list of edges. Each edge is a list
  4070. containing the source and target vertex.
  4071. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4072. undirected graph from a list of edges. Each edge is represented by
  4073. a list containing two vertices.
  4074. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4075. inserts a vertex into the graph.
  4076. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4077. inserts an edge between the two vertices.
  4078. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4079. returns a sequence of vertices adjacent to the vertex.
  4080. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4081. returns a sequence of all vertices in the graph.
  4082. \end{description}
  4083. \end{tcolorbox}
  4084. %\end{wrapfigure}
  4085. \caption{The Racket \code{graph} package.}
  4086. \label{fig:graph}
  4087. \end{figure}
  4088. \fi}
  4089. Based on the liveness analysis, we know where each location is live.
  4090. However, during register allocation, we need to answer questions of
  4091. the specific form: are locations $u$ and $v$ live at the same time?
  4092. (And therefore cannot be assigned to the same register.) To make this
  4093. question more efficient to answer, we create an explicit data
  4094. structure, an \emph{interference graph}\index{subject}{interference
  4095. graph}. An interference graph is an undirected graph that has an
  4096. edge between two locations if they are live at the same time, that is,
  4097. if they interfere with each other.
  4098. %
  4099. \racket{We recommend using the Racket \code{graph} package
  4100. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4101. %
  4102. \python{We provide implementations of directed and undirected graph
  4103. data structures in the file \code{graph.py} of the support code.}
  4104. A straightforward way to compute the interference graph is to look at
  4105. the set of live locations between each instruction and add an edge to
  4106. the graph for every pair of variables in the same set. This approach
  4107. is less than ideal for two reasons. First, it can be expensive because
  4108. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4109. locations. Second, in the special case where two locations hold the
  4110. same value (because one was assigned to the other), they can be live
  4111. at the same time without interfering with each other.
  4112. A better way to compute the interference graph is to focus on
  4113. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4114. must not overwrite something in a live location. So for each
  4115. instruction, we create an edge between the locations being written to
  4116. and the live locations. (Except that one should not create self
  4117. edges.) Note that for the \key{callq} instruction, we consider all of
  4118. the caller-saved registers as being written to, so an edge is added
  4119. between every live variable and every caller-saved register. Also, for
  4120. \key{movq} there is the above-mentioned special case to deal with. If
  4121. a live variable $v$ is the same as the source of the \key{movq}, then
  4122. there is no need to add an edge between $v$ and the destination,
  4123. because they both hold the same value.
  4124. %
  4125. So we have the following two rules.
  4126. \begin{enumerate}
  4127. \item If instruction $I_k$ is a move instruction of the form
  4128. \key{movq} $s$\key{,} $d$, then for every $v \in
  4129. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4130. $(d,v)$.
  4131. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4132. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4133. $(d,v)$.
  4134. \end{enumerate}
  4135. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4136. the above rules to each instruction. We highlight a few of the
  4137. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4138. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4139. so \code{v} interferes with \code{rsp}.}
  4140. %
  4141. \python{The first instruction is \lstinline{movq $1, v} and the
  4142. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4143. no interference because $\ttm{v}$ is the destination of the move.}
  4144. %
  4145. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4146. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4147. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4148. %
  4149. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4150. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4151. $\ttm{x}$ interferes with \ttm{w}.}
  4152. %
  4153. \racket{The next instruction is \lstinline{movq x, y} and the
  4154. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4155. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4156. \ttm{x} because \ttm{x} is the source of the move and therefore
  4157. \ttm{x} and \ttm{y} hold the same value.}
  4158. %
  4159. \python{The next instruction is \lstinline{movq x, y} and the
  4160. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4161. applies, so \ttm{y} interferes with \ttm{w} but not
  4162. \ttm{x} because \ttm{x} is the source of the move and therefore
  4163. \ttm{x} and \ttm{y} hold the same value.}
  4164. %
  4165. Figure~\ref{fig:interference-results} lists the interference results
  4166. for all of the instructions and the resulting interference graph is
  4167. shown in Figure~\ref{fig:interfere}.
  4168. \begin{figure}[tbp]
  4169. \begin{quote}
  4170. {\if\edition\racketEd
  4171. \begin{tabular}{ll}
  4172. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4173. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4174. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4175. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4176. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4177. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4178. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4179. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4180. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4181. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4182. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4183. \lstinline!jmp conclusion!& no interference.
  4184. \end{tabular}
  4185. \fi}
  4186. {\if\edition\pythonEd
  4187. \begin{tabular}{ll}
  4188. \lstinline!movq $1, v!& no interference\\
  4189. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4190. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4191. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4192. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4193. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4194. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4195. \lstinline!movq y, tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4196. \lstinline!negq tmp_0!& \ttm{t} interferes with \ttm{z} \\
  4197. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4198. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4199. \lstinline!movq tmp_1, %rdi! & no interference \\
  4200. \lstinline!callq print_int!& no interference.
  4201. \end{tabular}
  4202. \fi}
  4203. \end{quote}
  4204. \caption{Interference results for the running example.}
  4205. \label{fig:interference-results}
  4206. \end{figure}
  4207. \begin{figure}[tbp]
  4208. \large
  4209. {\if\edition\racketEd
  4210. \[
  4211. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4212. \node (rax) at (0,0) {$\ttm{rax}$};
  4213. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4214. \node (t1) at (0,2) {$\ttm{t}$};
  4215. \node (z) at (3,2) {$\ttm{z}$};
  4216. \node (x) at (6,2) {$\ttm{x}$};
  4217. \node (y) at (3,0) {$\ttm{y}$};
  4218. \node (w) at (6,0) {$\ttm{w}$};
  4219. \node (v) at (9,0) {$\ttm{v}$};
  4220. \draw (t1) to (rax);
  4221. \draw (t1) to (z);
  4222. \draw (z) to (y);
  4223. \draw (z) to (w);
  4224. \draw (x) to (w);
  4225. \draw (y) to (w);
  4226. \draw (v) to (w);
  4227. \draw (v) to (rsp);
  4228. \draw (w) to (rsp);
  4229. \draw (x) to (rsp);
  4230. \draw (y) to (rsp);
  4231. \path[-.,bend left=15] (z) edge node {} (rsp);
  4232. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4233. \draw (rax) to (rsp);
  4234. \end{tikzpicture}
  4235. \]
  4236. \fi}
  4237. {\if\edition\pythonEd
  4238. \[
  4239. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4240. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4241. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4242. \node (z) at (3,2) {$\ttm{z}$};
  4243. \node (x) at (6,2) {$\ttm{x}$};
  4244. \node (y) at (3,0) {$\ttm{y}$};
  4245. \node (w) at (6,0) {$\ttm{w}$};
  4246. \node (v) at (9,0) {$\ttm{v}$};
  4247. \draw (t0) to (t1);
  4248. \draw (t0) to (z);
  4249. \draw (z) to (y);
  4250. \draw (z) to (w);
  4251. \draw (x) to (w);
  4252. \draw (y) to (w);
  4253. \draw (v) to (w);
  4254. \end{tikzpicture}
  4255. \]
  4256. \fi}
  4257. \caption{The interference graph of the example program.}
  4258. \label{fig:interfere}
  4259. \end{figure}
  4260. %% Our next concern is to choose a data structure for representing the
  4261. %% interference graph. There are many choices for how to represent a
  4262. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4263. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4264. %% data structure is to study the algorithm that uses the data structure,
  4265. %% determine what operations need to be performed, and then choose the
  4266. %% data structure that provide the most efficient implementations of
  4267. %% those operations. Often times the choice of data structure can have an
  4268. %% effect on the time complexity of the algorithm, as it does here. If
  4269. %% you skim the next section, you will see that the register allocation
  4270. %% algorithm needs to ask the graph for all of its vertices and, given a
  4271. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4272. %% correct choice of graph representation is that of an adjacency
  4273. %% list. There are helper functions in \code{utilities.rkt} for
  4274. %% representing graphs using the adjacency list representation:
  4275. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4276. %% (Appendix~\ref{appendix:utilities}).
  4277. %% %
  4278. %% \margincomment{\footnotesize To do: change to use the
  4279. %% Racket graph library. \\ --Jeremy}
  4280. %% %
  4281. %% In particular, those functions use a hash table to map each vertex to
  4282. %% the set of adjacent vertices, and the sets are represented using
  4283. %% Racket's \key{set}, which is also a hash table.
  4284. \begin{exercise}\normalfont
  4285. \racket{Implement the compiler pass named \code{build\_interference} according
  4286. to the algorithm suggested above. We recommend using the Racket
  4287. \code{graph} package to create and inspect the interference graph.
  4288. The output graph of this pass should be stored in the $\itm{info}$ field of
  4289. the program, under the key \code{conflicts}.}
  4290. %
  4291. \python{Implement a function named \code{build\_interference}
  4292. according to the algorithm suggested above that
  4293. returns the interference graph.}
  4294. \end{exercise}
  4295. \section{Graph Coloring via Sudoku}
  4296. \label{sec:graph-coloring}
  4297. \index{subject}{graph coloring}
  4298. \index{subject}{Sudoku}
  4299. \index{subject}{color}
  4300. We come to the main event, mapping variables to registers and stack
  4301. locations. Variables that interfere with each other must be mapped to
  4302. different locations. In terms of the interference graph, this means
  4303. that adjacent vertices must be mapped to different locations. If we
  4304. think of locations as colors, the register allocation problem becomes
  4305. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4306. The reader may be more familiar with the graph coloring problem than he
  4307. or she realizes; the popular game of Sudoku is an instance of the
  4308. graph coloring problem. The following describes how to build a graph
  4309. out of an initial Sudoku board.
  4310. \begin{itemize}
  4311. \item There is one vertex in the graph for each Sudoku square.
  4312. \item There is an edge between two vertices if the corresponding squares
  4313. are in the same row, in the same column, or if the squares are in
  4314. the same $3\times 3$ region.
  4315. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4316. \item Based on the initial assignment of numbers to squares in the
  4317. Sudoku board, assign the corresponding colors to the corresponding
  4318. vertices in the graph.
  4319. \end{itemize}
  4320. If you can color the remaining vertices in the graph with the nine
  4321. colors, then you have also solved the corresponding game of Sudoku.
  4322. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4323. the corresponding graph with colored vertices. We map the Sudoku
  4324. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4325. sampling of the vertices (the colored ones) because showing edges for
  4326. all of the vertices would make the graph unreadable.
  4327. \begin{figure}[tbp]
  4328. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4329. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4330. \caption{A Sudoku game board and the corresponding colored graph.}
  4331. \label{fig:sudoku-graph}
  4332. \end{figure}
  4333. Some techniques for playing Sudoku correspond to heuristics used in
  4334. graph coloring algorithms. For example, one of the basic techniques
  4335. for Sudoku is called Pencil Marks. The idea is to use a process of
  4336. elimination to determine what numbers are no longer available for a
  4337. square and write down those numbers in the square (writing very
  4338. small). For example, if the number $1$ is assigned to a square, then
  4339. write the pencil mark $1$ in all the squares in the same row, column,
  4340. and region to indicate that $1$ is no longer an option for those other
  4341. squares.
  4342. %
  4343. The Pencil Marks technique corresponds to the notion of
  4344. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4345. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4346. are no longer available. In graph terminology, we have the following
  4347. definition:
  4348. \begin{equation*}
  4349. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4350. \text{ and } \mathrm{color}(v) = c \}
  4351. \end{equation*}
  4352. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4353. edge with $u$.
  4354. The Pencil Marks technique leads to a simple strategy for filling in
  4355. numbers: if there is a square with only one possible number left, then
  4356. choose that number! But what if there are no squares with only one
  4357. possibility left? One brute-force approach is to try them all: choose
  4358. the first one and if that ultimately leads to a solution, great. If
  4359. not, backtrack and choose the next possibility. One good thing about
  4360. Pencil Marks is that it reduces the degree of branching in the search
  4361. tree. Nevertheless, backtracking can be terribly time consuming. One
  4362. way to reduce the amount of backtracking is to use the
  4363. most-constrained-first heuristic (aka. minimum remaining
  4364. values)~\citep{Russell2003}. That is, when choosing a square, always
  4365. choose one with the fewest possibilities left (the vertex with the
  4366. highest saturation). The idea is that choosing highly constrained
  4367. squares earlier rather than later is better because later on there may
  4368. not be any possibilities left in the highly saturated squares.
  4369. However, register allocation is easier than Sudoku because the
  4370. register allocator can fall back to assigning variables to stack
  4371. locations when the registers run out. Thus, it makes sense to replace
  4372. backtracking with greedy search: make the best choice at the time and
  4373. keep going. We still wish to minimize the number of colors needed, so
  4374. we use the most-constrained-first heuristic in the greedy search.
  4375. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4376. algorithm for register allocation based on saturation and the
  4377. most-constrained-first heuristic. It is roughly equivalent to the
  4378. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4379. %,Gebremedhin:1999fk,Omari:2006uq
  4380. Just as in Sudoku, the algorithm represents colors with integers. The
  4381. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4382. for register allocation. The integers $k$ and larger correspond to
  4383. stack locations. The registers that are not used for register
  4384. allocation, such as \code{rax}, are assigned to negative integers. In
  4385. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4386. %% One might wonder why we include registers at all in the liveness
  4387. %% analysis and interference graph. For example, we never allocate a
  4388. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4389. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4390. %% to use register for passing arguments to functions, it will be
  4391. %% necessary for those registers to appear in the interference graph
  4392. %% because those registers will also be assigned to variables, and we
  4393. %% don't want those two uses to encroach on each other. Regarding
  4394. %% registers such as \code{rax} and \code{rsp} that are not used for
  4395. %% variables, we could omit them from the interference graph but that
  4396. %% would require adding special cases to our algorithm, which would
  4397. %% complicate the logic for little gain.
  4398. \begin{figure}[btp]
  4399. \centering
  4400. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4401. Algorithm: DSATUR
  4402. Input: a graph |$G$|
  4403. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4404. |$W \gets \mathrm{vertices}(G)$|
  4405. while |$W \neq \emptyset$| do
  4406. pick a vertex |$u$| from |$W$| with the highest saturation,
  4407. breaking ties randomly
  4408. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4409. |$\mathrm{color}[u] \gets c$|
  4410. |$W \gets W - \{u\}$|
  4411. \end{lstlisting}
  4412. \caption{The saturation-based greedy graph coloring algorithm.}
  4413. \label{fig:satur-algo}
  4414. \end{figure}
  4415. {\if\edition\racketEd
  4416. With the DSATUR algorithm in hand, let us return to the running
  4417. example and consider how to color the interference graph in
  4418. Figure~\ref{fig:interfere}.
  4419. %
  4420. We start by assigning the register nodes to their own color. For
  4421. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4422. assigned $-2$. The variables are not yet colored, so they are
  4423. annotated with a dash. We then update the saturation for vertices that
  4424. are adjacent to a register, obtaining the following annotated
  4425. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4426. it interferes with both \code{rax} and \code{rsp}.
  4427. \[
  4428. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4429. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4430. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4431. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4432. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4433. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4434. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4435. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4436. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4437. \draw (t1) to (rax);
  4438. \draw (t1) to (z);
  4439. \draw (z) to (y);
  4440. \draw (z) to (w);
  4441. \draw (x) to (w);
  4442. \draw (y) to (w);
  4443. \draw (v) to (w);
  4444. \draw (v) to (rsp);
  4445. \draw (w) to (rsp);
  4446. \draw (x) to (rsp);
  4447. \draw (y) to (rsp);
  4448. \path[-.,bend left=15] (z) edge node {} (rsp);
  4449. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4450. \draw (rax) to (rsp);
  4451. \end{tikzpicture}
  4452. \]
  4453. The algorithm says to select a maximally saturated vertex. So we pick
  4454. $\ttm{t}$ and color it with the first available integer, which is
  4455. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4456. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4457. \[
  4458. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4459. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4460. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4461. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4462. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4463. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4464. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4465. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4466. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4467. \draw (t1) to (rax);
  4468. \draw (t1) to (z);
  4469. \draw (z) to (y);
  4470. \draw (z) to (w);
  4471. \draw (x) to (w);
  4472. \draw (y) to (w);
  4473. \draw (v) to (w);
  4474. \draw (v) to (rsp);
  4475. \draw (w) to (rsp);
  4476. \draw (x) to (rsp);
  4477. \draw (y) to (rsp);
  4478. \path[-.,bend left=15] (z) edge node {} (rsp);
  4479. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4480. \draw (rax) to (rsp);
  4481. \end{tikzpicture}
  4482. \]
  4483. We repeat the process, selecting a maximally saturated vertex,
  4484. choosing is \code{z}, and color it with the first available number, which
  4485. is $1$. We add $1$ to the saturation for the neighboring vertices
  4486. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4487. \[
  4488. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4489. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4490. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4491. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4492. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4493. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4494. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4495. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4496. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4497. \draw (t1) to (rax);
  4498. \draw (t1) to (z);
  4499. \draw (z) to (y);
  4500. \draw (z) to (w);
  4501. \draw (x) to (w);
  4502. \draw (y) to (w);
  4503. \draw (v) to (w);
  4504. \draw (v) to (rsp);
  4505. \draw (w) to (rsp);
  4506. \draw (x) to (rsp);
  4507. \draw (y) to (rsp);
  4508. \path[-.,bend left=15] (z) edge node {} (rsp);
  4509. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4510. \draw (rax) to (rsp);
  4511. \end{tikzpicture}
  4512. \]
  4513. The most saturated vertices are now \code{w} and \code{y}. We color
  4514. \code{w} with the first available color, which is $0$.
  4515. \[
  4516. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4517. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4518. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4519. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4520. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4521. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4522. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4523. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4524. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4525. \draw (t1) to (rax);
  4526. \draw (t1) to (z);
  4527. \draw (z) to (y);
  4528. \draw (z) to (w);
  4529. \draw (x) to (w);
  4530. \draw (y) to (w);
  4531. \draw (v) to (w);
  4532. \draw (v) to (rsp);
  4533. \draw (w) to (rsp);
  4534. \draw (x) to (rsp);
  4535. \draw (y) to (rsp);
  4536. \path[-.,bend left=15] (z) edge node {} (rsp);
  4537. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4538. \draw (rax) to (rsp);
  4539. \end{tikzpicture}
  4540. \]
  4541. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4542. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4543. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4544. and \code{z}, whose colors are $0$ and $1$ respectively.
  4545. \[
  4546. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4547. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4548. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4549. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4550. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4551. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4552. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4553. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4554. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4555. \draw (t1) to (rax);
  4556. \draw (t1) to (z);
  4557. \draw (z) to (y);
  4558. \draw (z) to (w);
  4559. \draw (x) to (w);
  4560. \draw (y) to (w);
  4561. \draw (v) to (w);
  4562. \draw (v) to (rsp);
  4563. \draw (w) to (rsp);
  4564. \draw (x) to (rsp);
  4565. \draw (y) to (rsp);
  4566. \path[-.,bend left=15] (z) edge node {} (rsp);
  4567. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4568. \draw (rax) to (rsp);
  4569. \end{tikzpicture}
  4570. \]
  4571. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4572. \[
  4573. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4574. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4575. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4576. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4577. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4578. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4579. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4580. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4581. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4582. \draw (t1) to (rax);
  4583. \draw (t1) to (z);
  4584. \draw (z) to (y);
  4585. \draw (z) to (w);
  4586. \draw (x) to (w);
  4587. \draw (y) to (w);
  4588. \draw (v) to (w);
  4589. \draw (v) to (rsp);
  4590. \draw (w) to (rsp);
  4591. \draw (x) to (rsp);
  4592. \draw (y) to (rsp);
  4593. \path[-.,bend left=15] (z) edge node {} (rsp);
  4594. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4595. \draw (rax) to (rsp);
  4596. \end{tikzpicture}
  4597. \]
  4598. In the last step of the algorithm, we color \code{x} with $1$.
  4599. \[
  4600. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4601. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4602. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4603. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4604. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4605. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4606. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4607. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4608. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4609. \draw (t1) to (rax);
  4610. \draw (t1) to (z);
  4611. \draw (z) to (y);
  4612. \draw (z) to (w);
  4613. \draw (x) to (w);
  4614. \draw (y) to (w);
  4615. \draw (v) to (w);
  4616. \draw (v) to (rsp);
  4617. \draw (w) to (rsp);
  4618. \draw (x) to (rsp);
  4619. \draw (y) to (rsp);
  4620. \path[-.,bend left=15] (z) edge node {} (rsp);
  4621. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4622. \draw (rax) to (rsp);
  4623. \end{tikzpicture}
  4624. \]
  4625. So we obtain the following coloring:
  4626. \[
  4627. \{
  4628. \ttm{rax} \mapsto -1,
  4629. \ttm{rsp} \mapsto -2,
  4630. \ttm{t} \mapsto 0,
  4631. \ttm{z} \mapsto 1,
  4632. \ttm{x} \mapsto 1,
  4633. \ttm{y} \mapsto 2,
  4634. \ttm{w} \mapsto 0,
  4635. \ttm{v} \mapsto 1
  4636. \}
  4637. \]
  4638. \fi}
  4639. %
  4640. {\if\edition\pythonEd
  4641. %
  4642. With the DSATUR algorithm in hand, let us return to the running
  4643. example and consider how to color the interference graph in
  4644. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4645. to indicate that it has not yet been assigned a color. The saturation
  4646. sets are also shown for each node; all of them start as the empty set.
  4647. (We do not include the register nodes in the graph below because there
  4648. were no interference edges involving registers in this program, but in
  4649. general there can be.)
  4650. %
  4651. \[
  4652. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4653. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4654. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4655. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4656. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4657. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4658. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4659. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4660. \draw (t0) to (t1);
  4661. \draw (t0) to (z);
  4662. \draw (z) to (y);
  4663. \draw (z) to (w);
  4664. \draw (x) to (w);
  4665. \draw (y) to (w);
  4666. \draw (v) to (w);
  4667. \end{tikzpicture}
  4668. \]
  4669. The algorithm says to select a maximally saturated vertex, but they
  4670. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4671. then color it with the first available integer, which is $0$. We mark
  4672. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4673. they interfere with $\ttm{tmp\_0}$.
  4674. \[
  4675. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4676. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4677. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4678. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4679. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4680. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4681. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4682. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4683. \draw (t0) to (t1);
  4684. \draw (t0) to (z);
  4685. \draw (z) to (y);
  4686. \draw (z) to (w);
  4687. \draw (x) to (w);
  4688. \draw (y) to (w);
  4689. \draw (v) to (w);
  4690. \end{tikzpicture}
  4691. \]
  4692. We repeat the process. The most saturated vertices are \code{z} and
  4693. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4694. available number, which is $1$. We add $1$ to the saturation for the
  4695. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4696. \[
  4697. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4698. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4699. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4700. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4701. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4702. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4703. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4704. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4705. \draw (t0) to (t1);
  4706. \draw (t0) to (z);
  4707. \draw (z) to (y);
  4708. \draw (z) to (w);
  4709. \draw (x) to (w);
  4710. \draw (y) to (w);
  4711. \draw (v) to (w);
  4712. \end{tikzpicture}
  4713. \]
  4714. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4715. \code{y}. We color \code{w} with the first available color, which
  4716. is $0$.
  4717. \[
  4718. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4719. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4720. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4721. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4722. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4723. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4724. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4725. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4726. \draw (t0) to (t1);
  4727. \draw (t0) to (z);
  4728. \draw (z) to (y);
  4729. \draw (z) to (w);
  4730. \draw (x) to (w);
  4731. \draw (y) to (w);
  4732. \draw (v) to (w);
  4733. \end{tikzpicture}
  4734. \]
  4735. Now \code{y} is the most saturated, so we color it with $2$.
  4736. \[
  4737. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4738. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4739. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4740. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4741. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4742. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4743. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4744. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4745. \draw (t0) to (t1);
  4746. \draw (t0) to (z);
  4747. \draw (z) to (y);
  4748. \draw (z) to (w);
  4749. \draw (x) to (w);
  4750. \draw (y) to (w);
  4751. \draw (v) to (w);
  4752. \end{tikzpicture}
  4753. \]
  4754. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4755. We choose to color \code{v} with $1$.
  4756. \[
  4757. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4758. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4759. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4760. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4761. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4762. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4763. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4764. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4765. \draw (t0) to (t1);
  4766. \draw (t0) to (z);
  4767. \draw (z) to (y);
  4768. \draw (z) to (w);
  4769. \draw (x) to (w);
  4770. \draw (y) to (w);
  4771. \draw (v) to (w);
  4772. \end{tikzpicture}
  4773. \]
  4774. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4775. \[
  4776. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4777. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4778. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4779. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4780. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4781. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4782. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4783. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4784. \draw (t0) to (t1);
  4785. \draw (t0) to (z);
  4786. \draw (z) to (y);
  4787. \draw (z) to (w);
  4788. \draw (x) to (w);
  4789. \draw (y) to (w);
  4790. \draw (v) to (w);
  4791. \end{tikzpicture}
  4792. \]
  4793. So we obtain the following coloring:
  4794. \[
  4795. \{ \ttm{tmp\_0} \mapsto 0,
  4796. \ttm{tmp\_1} \mapsto 1,
  4797. \ttm{z} \mapsto 1,
  4798. \ttm{x} \mapsto 1,
  4799. \ttm{y} \mapsto 2,
  4800. \ttm{w} \mapsto 0,
  4801. \ttm{v} \mapsto 1 \}
  4802. \]
  4803. \fi}
  4804. We recommend creating an auxiliary function named \code{color\_graph}
  4805. that takes an interference graph and a list of all the variables in
  4806. the program. This function should return a mapping of variables to
  4807. their colors (represented as natural numbers). By creating this helper
  4808. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4809. when we add support for functions.
  4810. To prioritize the processing of highly saturated nodes inside the
  4811. \code{color\_graph} function, we recommend using the priority queue
  4812. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4813. addition, you will need to maintain a mapping from variables to their
  4814. ``handles'' in the priority queue so that you can notify the priority
  4815. queue when their saturation changes.}
  4816. {\if\edition\racketEd
  4817. \begin{figure}[tp]
  4818. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4819. \small
  4820. \begin{tcolorbox}[title=Priority Queue]
  4821. A \emph{priority queue} is a collection of items in which the
  4822. removal of items is governed by priority. In a ``min'' queue,
  4823. lower priority items are removed first. An implementation is in
  4824. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4825. queue} \index{subject}{minimum priority queue}
  4826. \begin{description}
  4827. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4828. priority queue that uses the $\itm{cmp}$ predicate to determine
  4829. whether its first argument has lower or equal priority to its
  4830. second argument.
  4831. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4832. items in the queue.
  4833. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4834. the item into the queue and returns a handle for the item in the
  4835. queue.
  4836. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4837. the lowest priority.
  4838. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4839. notifies the queue that the priority has decreased for the item
  4840. associated with the given handle.
  4841. \end{description}
  4842. \end{tcolorbox}
  4843. %\end{wrapfigure}
  4844. \caption{The priority queue data structure.}
  4845. \label{fig:priority-queue}
  4846. \end{figure}
  4847. \fi}
  4848. With the coloring complete, we finalize the assignment of variables to
  4849. registers and stack locations. We map the first $k$ colors to the $k$
  4850. registers and the rest of the colors to stack locations. Suppose for
  4851. the moment that we have just one register to use for register
  4852. allocation, \key{rcx}. Then we have the following map from colors to
  4853. locations.
  4854. \[
  4855. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4856. \]
  4857. Composing this mapping with the coloring, we arrive at the following
  4858. assignment of variables to locations.
  4859. {\if\edition\racketEd
  4860. \begin{gather*}
  4861. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4862. \ttm{w} \mapsto \key{\%rcx}, \,
  4863. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4864. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4865. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4866. \ttm{t} \mapsto \key{\%rcx} \}
  4867. \end{gather*}
  4868. \fi}
  4869. {\if\edition\pythonEd
  4870. \begin{gather*}
  4871. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4872. \ttm{w} \mapsto \key{\%rcx}, \,
  4873. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4874. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4875. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4876. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  4877. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  4878. \end{gather*}
  4879. \fi}
  4880. Adapt the code from the \code{assign\_homes} pass
  4881. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  4882. assigned location. Applying the above assignment to our running
  4883. example, on the left, yields the program on the right.
  4884. % why frame size of 32? -JGS
  4885. \begin{center}
  4886. {\if\edition\racketEd
  4887. \begin{minipage}{0.3\textwidth}
  4888. \begin{lstlisting}
  4889. movq $1, v
  4890. movq $42, w
  4891. movq v, x
  4892. addq $7, x
  4893. movq x, y
  4894. movq x, z
  4895. addq w, z
  4896. movq y, t
  4897. negq t
  4898. movq z, %rax
  4899. addq t, %rax
  4900. jmp conclusion
  4901. \end{lstlisting}
  4902. \end{minipage}
  4903. $\Rightarrow\qquad$
  4904. \begin{minipage}{0.45\textwidth}
  4905. \begin{lstlisting}
  4906. movq $1, -8(%rbp)
  4907. movq $42, %rcx
  4908. movq -8(%rbp), -8(%rbp)
  4909. addq $7, -8(%rbp)
  4910. movq -8(%rbp), -16(%rbp)
  4911. movq -8(%rbp), -8(%rbp)
  4912. addq %rcx, -8(%rbp)
  4913. movq -16(%rbp), %rcx
  4914. negq %rcx
  4915. movq -8(%rbp), %rax
  4916. addq %rcx, %rax
  4917. jmp conclusion
  4918. \end{lstlisting}
  4919. \end{minipage}
  4920. \fi}
  4921. {\if\edition\pythonEd
  4922. \begin{minipage}{0.3\textwidth}
  4923. \begin{lstlisting}
  4924. movq $1, v
  4925. movq $42, w
  4926. movq v, x
  4927. addq $7, x
  4928. movq x, y
  4929. movq x, z
  4930. addq w, z
  4931. movq y, tmp_0
  4932. negq tmp_0
  4933. movq z, tmp_1
  4934. addq tmp_0, tmp_1
  4935. movq tmp_1, %rdi
  4936. callq print_int
  4937. \end{lstlisting}
  4938. \end{minipage}
  4939. $\Rightarrow\qquad$
  4940. \begin{minipage}{0.45\textwidth}
  4941. \begin{lstlisting}
  4942. movq $1, -8(%rbp)
  4943. movq $42, %rcx
  4944. movq -8(%rbp), -8(%rbp)
  4945. addq $7, -8(%rbp)
  4946. movq -8(%rbp), -16(%rbp)
  4947. movq -8(%rbp), -8(%rbp)
  4948. addq %rcx, -8(%rbp)
  4949. movq -16(%rbp), %rcx
  4950. negq %rcx
  4951. movq -8(%rbp), -8(%rbp)
  4952. addq %rcx, -8(%rbp)
  4953. movq -8(%rbp), %rdi
  4954. callq print_int
  4955. \end{lstlisting}
  4956. \end{minipage}
  4957. \fi}
  4958. \end{center}
  4959. \begin{exercise}\normalfont
  4960. %
  4961. Implement the compiler pass \code{allocate\_registers}.
  4962. %
  4963. Create five programs that exercise all aspects of the register
  4964. allocation algorithm, including spilling variables to the stack.
  4965. %
  4966. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  4967. \code{run-tests.rkt} script with the three new passes:
  4968. \code{uncover\_live}, \code{build\_interference}, and
  4969. \code{allocate\_registers}.
  4970. %
  4971. Temporarily remove the \code{print\_x86} pass from the list of passes
  4972. and the call to \code{compiler-tests}.
  4973. Run the script to test the register allocator.
  4974. }
  4975. %
  4976. \python{Run the \code{run-tests.py} script to to check whether the
  4977. output programs produce the same result as the input programs.}
  4978. \end{exercise}
  4979. \section{Patch Instructions}
  4980. \label{sec:patch-instructions}
  4981. The remaining step in the compilation to x86 is to ensure that the
  4982. instructions have at most one argument that is a memory access.
  4983. %
  4984. In the running example, the instruction \code{movq -8(\%rbp),
  4985. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  4986. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  4987. then move \code{rax} into \code{-16(\%rbp)}.
  4988. %
  4989. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4990. problematic, but they can simply be deleted. In general, we recommend
  4991. deleting all the trivial moves whose source and destination are the
  4992. same location.
  4993. %
  4994. The following is the output of \code{patch\_instructions} on the
  4995. running example.
  4996. \begin{center}
  4997. {\if\edition\racketEd
  4998. \begin{minipage}{0.4\textwidth}
  4999. \begin{lstlisting}
  5000. movq $1, -8(%rbp)
  5001. movq $42, %rcx
  5002. movq -8(%rbp), -8(%rbp)
  5003. addq $7, -8(%rbp)
  5004. movq -8(%rbp), -16(%rbp)
  5005. movq -8(%rbp), -8(%rbp)
  5006. addq %rcx, -8(%rbp)
  5007. movq -16(%rbp), %rcx
  5008. negq %rcx
  5009. movq -8(%rbp), %rax
  5010. addq %rcx, %rax
  5011. jmp conclusion
  5012. \end{lstlisting}
  5013. \end{minipage}
  5014. $\Rightarrow\qquad$
  5015. \begin{minipage}{0.45\textwidth}
  5016. \begin{lstlisting}
  5017. movq $1, -8(%rbp)
  5018. movq $42, %rcx
  5019. addq $7, -8(%rbp)
  5020. movq -8(%rbp), %rax
  5021. movq %rax, -16(%rbp)
  5022. addq %rcx, -8(%rbp)
  5023. movq -16(%rbp), %rcx
  5024. negq %rcx
  5025. movq -8(%rbp), %rax
  5026. addq %rcx, %rax
  5027. jmp conclusion
  5028. \end{lstlisting}
  5029. \end{minipage}
  5030. \fi}
  5031. {\if\edition\pythonEd
  5032. \begin{minipage}{0.4\textwidth}
  5033. \begin{lstlisting}
  5034. movq $1, -8(%rbp)
  5035. movq $42, %rcx
  5036. movq -8(%rbp), -8(%rbp)
  5037. addq $7, -8(%rbp)
  5038. movq -8(%rbp), -16(%rbp)
  5039. movq -8(%rbp), -8(%rbp)
  5040. addq %rcx, -8(%rbp)
  5041. movq -16(%rbp), %rcx
  5042. negq %rcx
  5043. movq -8(%rbp), -8(%rbp)
  5044. addq %rcx, -8(%rbp)
  5045. movq -8(%rbp), %rdi
  5046. callq print_int
  5047. \end{lstlisting}
  5048. \end{minipage}
  5049. $\Rightarrow\qquad$
  5050. \begin{minipage}{0.45\textwidth}
  5051. \begin{lstlisting}
  5052. movq $1, -8(%rbp)
  5053. movq $42, %rcx
  5054. addq $7, -8(%rbp)
  5055. movq -8(%rbp), %rax
  5056. movq %rax, -16(%rbp)
  5057. addq %rcx, -8(%rbp)
  5058. movq -16(%rbp), %rcx
  5059. negq %rcx
  5060. addq %rcx, -8(%rbp)
  5061. movq -8(%rbp), %rdi
  5062. callq print_int
  5063. \end{lstlisting}
  5064. \end{minipage}
  5065. \fi}
  5066. \end{center}
  5067. \begin{exercise}\normalfont
  5068. %
  5069. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5070. %
  5071. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5072. %in the \code{run-tests.rkt} script.
  5073. %
  5074. Run the script to test the \code{patch\_instructions} pass.
  5075. \end{exercise}
  5076. \section{Prelude and Conclusion}
  5077. \label{sec:print-x86-reg-alloc}
  5078. \index{subject}{calling conventions}
  5079. \index{subject}{prelude}\index{subject}{conclusion}
  5080. Recall that this pass generates the prelude and conclusion
  5081. instructions to satisfy the x86 calling conventions
  5082. (Section~\ref{sec:calling-conventions}). With the addition of the
  5083. register allocator, the callee-saved registers used by the register
  5084. allocator must be saved in the prelude and restored in the conclusion.
  5085. In the \code{allocate\_registers} pass,
  5086. %
  5087. \racket{add an entry to the \itm{info}
  5088. of \code{X86Program} named \code{used\_callee}}
  5089. %
  5090. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5091. %
  5092. that stores the set of callee-saved registers that were assigned to
  5093. variables. The \code{prelude\_and\_conclusion} pass can then access
  5094. this information to decide which callee-saved registers need to be
  5095. saved and restored.
  5096. %
  5097. When calculating the size of the frame to adjust the \code{rsp} in the
  5098. prelude, make sure to take into account the space used for saving the
  5099. callee-saved registers. Also, don't forget that the frame needs to be
  5100. a multiple of 16 bytes!
  5101. \racket{An overview of all of the passes involved in register
  5102. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5103. {\if\edition\racketEd
  5104. \begin{figure}[tbp]
  5105. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5106. \node (Lvar) at (0,2) {\large \LangVar{}};
  5107. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5108. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5109. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5110. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5111. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5112. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5113. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5114. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5115. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5116. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5117. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5118. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5119. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5120. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5121. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5122. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5123. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5124. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5125. \end{tikzpicture}
  5126. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5127. \label{fig:reg-alloc-passes}
  5128. \end{figure}
  5129. \fi}
  5130. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5131. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5132. use of registers and the stack, we limit the register allocator for
  5133. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5134. the prelude\index{subject}{prelude} of the \code{main} function, we
  5135. push \code{rbx} onto the stack because it is a callee-saved register
  5136. and it was assigned to variable by the register allocator. We
  5137. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5138. reserve space for the one spilled variable. After that subtraction,
  5139. the \code{rsp} is aligned to 16 bytes.
  5140. Moving on to the program proper, we see how the registers were
  5141. allocated.
  5142. %
  5143. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5144. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5145. %
  5146. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5147. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5148. were assigned to \code{rbx}.}
  5149. %
  5150. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5151. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5152. callee-save register \code{rbx} onto the stack. The spilled variables
  5153. must be placed lower on the stack than the saved callee-save
  5154. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5155. \code{-16(\%rbp)}.
  5156. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5157. done in the prelude. We move the stack pointer up by \code{8} bytes
  5158. (the room for spilled variables), then we pop the old values of
  5159. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5160. \code{retq} to return control to the operating system.
  5161. \begin{figure}[tbp]
  5162. % var_test_28.rkt
  5163. % (use-minimal-set-of-registers! #t)
  5164. % and only rbx rcx
  5165. % tmp 0 rbx
  5166. % z 1 rcx
  5167. % y 0 rbx
  5168. % w 2 16(%rbp)
  5169. % v 0 rbx
  5170. % x 0 rbx
  5171. {\if\edition\racketEd
  5172. \begin{lstlisting}
  5173. start:
  5174. movq $1, %rbx
  5175. movq $42, -16(%rbp)
  5176. addq $7, %rbx
  5177. movq %rbx, %rcx
  5178. addq -16(%rbp), %rcx
  5179. negq %rbx
  5180. movq %rcx, %rax
  5181. addq %rbx, %rax
  5182. jmp conclusion
  5183. .globl main
  5184. main:
  5185. pushq %rbp
  5186. movq %rsp, %rbp
  5187. pushq %rbx
  5188. subq $8, %rsp
  5189. jmp start
  5190. conclusion:
  5191. addq $8, %rsp
  5192. popq %rbx
  5193. popq %rbp
  5194. retq
  5195. \end{lstlisting}
  5196. \fi}
  5197. {\if\edition\pythonEd
  5198. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5199. \begin{lstlisting}
  5200. .globl main
  5201. main:
  5202. pushq %rbp
  5203. movq %rsp, %rbp
  5204. pushq %rbx
  5205. subq $8, %rsp
  5206. movq $1, %rcx
  5207. movq $42, %rbx
  5208. addq $7, %rcx
  5209. movq %rcx, -16(%rbp)
  5210. addq %rbx, -16(%rbp)
  5211. negq %rcx
  5212. movq -16(%rbp), %rbx
  5213. addq %rcx, %rbx
  5214. movq %rbx, %rdi
  5215. callq print_int
  5216. addq $8, %rsp
  5217. popq %rbx
  5218. popq %rbp
  5219. retq
  5220. \end{lstlisting}
  5221. \fi}
  5222. \caption{The x86 output from the running example
  5223. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5224. and \code{rcx}.}
  5225. \label{fig:running-example-x86}
  5226. \end{figure}
  5227. \begin{exercise}\normalfont
  5228. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5229. %
  5230. \racket{
  5231. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5232. list of passes and the call to \code{compiler-tests}.}
  5233. %
  5234. Run the script to test the complete compiler for \LangVar{} that
  5235. performs register allocation.
  5236. \end{exercise}
  5237. \section{Challenge: Move Biasing}
  5238. \label{sec:move-biasing}
  5239. \index{subject}{move biasing}
  5240. This section describes an enhancement to the register allocator,
  5241. called move biasing, for students who are looking for an extra
  5242. challenge.
  5243. {\if\edition\racketEd
  5244. To motivate the need for move biasing we return to the running example
  5245. but this time use all of the general purpose registers. So we have
  5246. the following mapping of color numbers to registers.
  5247. \[
  5248. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5249. \]
  5250. Using the same assignment of variables to color numbers that was
  5251. produced by the register allocator described in the last section, we
  5252. get the following program.
  5253. \begin{center}
  5254. \begin{minipage}{0.3\textwidth}
  5255. \begin{lstlisting}
  5256. movq $1, v
  5257. movq $42, w
  5258. movq v, x
  5259. addq $7, x
  5260. movq x, y
  5261. movq x, z
  5262. addq w, z
  5263. movq y, t
  5264. negq t
  5265. movq z, %rax
  5266. addq t, %rax
  5267. jmp conclusion
  5268. \end{lstlisting}
  5269. \end{minipage}
  5270. $\Rightarrow\qquad$
  5271. \begin{minipage}{0.45\textwidth}
  5272. \begin{lstlisting}
  5273. movq $1, %rdx
  5274. movq $42, %rcx
  5275. movq %rdx, %rdx
  5276. addq $7, %rdx
  5277. movq %rdx, %rsi
  5278. movq %rdx, %rdx
  5279. addq %rcx, %rdx
  5280. movq %rsi, %rcx
  5281. negq %rcx
  5282. movq %rdx, %rax
  5283. addq %rcx, %rax
  5284. jmp conclusion
  5285. \end{lstlisting}
  5286. \end{minipage}
  5287. \end{center}
  5288. In the above output code there are two \key{movq} instructions that
  5289. can be removed because their source and target are the same. However,
  5290. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5291. register, we could instead remove three \key{movq} instructions. We
  5292. can accomplish this by taking into account which variables appear in
  5293. \key{movq} instructions with which other variables.
  5294. \fi}
  5295. {\if\edition\pythonEd
  5296. %
  5297. To motivate the need for move biasing we return to the running example
  5298. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5299. remove three trivial move instructions from the running
  5300. example. However, we could remove another trivial move if we were able
  5301. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5302. We say that two variables $p$ and $q$ are \emph{move
  5303. related}\index{subject}{move related} if they participate together in
  5304. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5305. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5306. when there are multiple variables with the same saturation, prefer
  5307. variables that can be assigned to a color that is the same as the
  5308. color of a move related variable. Furthermore, when the register
  5309. allocator chooses a color for a variable, it should prefer a color
  5310. that has already been used for a move-related variable (assuming that
  5311. they do not interfere). Of course, this preference should not override
  5312. the preference for registers over stack locations. So this preference
  5313. should be used as a tie breaker when choosing between registers or
  5314. when choosing between stack locations.
  5315. We recommend representing the move relationships in a graph, similar
  5316. to how we represented interference. The following is the \emph{move
  5317. graph} for our running example.
  5318. {\if\edition\racketEd
  5319. \[
  5320. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5321. \node (rax) at (0,0) {$\ttm{rax}$};
  5322. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5323. \node (t) at (0,2) {$\ttm{t}$};
  5324. \node (z) at (3,2) {$\ttm{z}$};
  5325. \node (x) at (6,2) {$\ttm{x}$};
  5326. \node (y) at (3,0) {$\ttm{y}$};
  5327. \node (w) at (6,0) {$\ttm{w}$};
  5328. \node (v) at (9,0) {$\ttm{v}$};
  5329. \draw (v) to (x);
  5330. \draw (x) to (y);
  5331. \draw (x) to (z);
  5332. \draw (y) to (t);
  5333. \end{tikzpicture}
  5334. \]
  5335. \fi}
  5336. %
  5337. {\if\edition\pythonEd
  5338. \[
  5339. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5340. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5341. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5342. \node (z) at (3,2) {$\ttm{z}$};
  5343. \node (x) at (6,2) {$\ttm{x}$};
  5344. \node (y) at (3,0) {$\ttm{y}$};
  5345. \node (w) at (6,0) {$\ttm{w}$};
  5346. \node (v) at (9,0) {$\ttm{v}$};
  5347. \draw (y) to (t0);
  5348. \draw (z) to (x);
  5349. \draw (z) to (t1);
  5350. \draw (x) to (y);
  5351. \draw (x) to (v);
  5352. \end{tikzpicture}
  5353. \]
  5354. \fi}
  5355. {\if\edition\racketEd
  5356. Now we replay the graph coloring, pausing to see the coloring of
  5357. \code{y}. Recall the following configuration. The most saturated vertices
  5358. were \code{w} and \code{y}.
  5359. \[
  5360. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5361. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5362. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5363. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5364. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5365. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5366. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5367. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5368. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5369. \draw (t1) to (rax);
  5370. \draw (t1) to (z);
  5371. \draw (z) to (y);
  5372. \draw (z) to (w);
  5373. \draw (x) to (w);
  5374. \draw (y) to (w);
  5375. \draw (v) to (w);
  5376. \draw (v) to (rsp);
  5377. \draw (w) to (rsp);
  5378. \draw (x) to (rsp);
  5379. \draw (y) to (rsp);
  5380. \path[-.,bend left=15] (z) edge node {} (rsp);
  5381. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5382. \draw (rax) to (rsp);
  5383. \end{tikzpicture}
  5384. \]
  5385. %
  5386. Last time we chose to color \code{w} with $0$. But this time we see
  5387. that \code{w} is not move related to any vertex, but \code{y} is move
  5388. related to \code{t}. So we choose to color \code{y} the same color as
  5389. \code{t}, $0$.
  5390. \[
  5391. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5392. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5393. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5394. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5395. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5396. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5397. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5398. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5399. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5400. \draw (t1) to (rax);
  5401. \draw (t1) to (z);
  5402. \draw (z) to (y);
  5403. \draw (z) to (w);
  5404. \draw (x) to (w);
  5405. \draw (y) to (w);
  5406. \draw (v) to (w);
  5407. \draw (v) to (rsp);
  5408. \draw (w) to (rsp);
  5409. \draw (x) to (rsp);
  5410. \draw (y) to (rsp);
  5411. \path[-.,bend left=15] (z) edge node {} (rsp);
  5412. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5413. \draw (rax) to (rsp);
  5414. \end{tikzpicture}
  5415. \]
  5416. Now \code{w} is the most saturated, so we color it $2$.
  5417. \[
  5418. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5419. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5420. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5421. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5422. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5423. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5424. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5425. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5426. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5427. \draw (t1) to (rax);
  5428. \draw (t1) to (z);
  5429. \draw (z) to (y);
  5430. \draw (z) to (w);
  5431. \draw (x) to (w);
  5432. \draw (y) to (w);
  5433. \draw (v) to (w);
  5434. \draw (v) to (rsp);
  5435. \draw (w) to (rsp);
  5436. \draw (x) to (rsp);
  5437. \draw (y) to (rsp);
  5438. \path[-.,bend left=15] (z) edge node {} (rsp);
  5439. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5440. \draw (rax) to (rsp);
  5441. \end{tikzpicture}
  5442. \]
  5443. At this point, vertices \code{x} and \code{v} are most saturated, but
  5444. \code{x} is move related to \code{y} and \code{z}, so we color
  5445. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5446. \[
  5447. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5448. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5449. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5450. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5451. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5452. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5453. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5454. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5455. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5456. \draw (t1) to (rax);
  5457. \draw (t) to (z);
  5458. \draw (z) to (y);
  5459. \draw (z) to (w);
  5460. \draw (x) to (w);
  5461. \draw (y) to (w);
  5462. \draw (v) to (w);
  5463. \draw (v) to (rsp);
  5464. \draw (w) to (rsp);
  5465. \draw (x) to (rsp);
  5466. \draw (y) to (rsp);
  5467. \path[-.,bend left=15] (z) edge node {} (rsp);
  5468. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5469. \draw (rax) to (rsp);
  5470. \end{tikzpicture}
  5471. \]
  5472. \fi}
  5473. %
  5474. {\if\edition\pythonEd
  5475. Now we replay the graph coloring, pausing before the coloring of
  5476. \code{w}. Recall the following configuration. The most saturated vertices
  5477. were \code{tmp\_1}, \code{w}, and \code{y}.
  5478. \[
  5479. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5480. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5481. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5482. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5483. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5484. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5485. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5486. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5487. \draw (t0) to (t1);
  5488. \draw (t0) to (z);
  5489. \draw (z) to (y);
  5490. \draw (z) to (w);
  5491. \draw (x) to (w);
  5492. \draw (y) to (w);
  5493. \draw (v) to (w);
  5494. \end{tikzpicture}
  5495. \]
  5496. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5497. or \code{y}, but note that \code{w} is not move related to any
  5498. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5499. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5500. \code{y} and color it $0$, we can delete another move instruction.
  5501. \[
  5502. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5503. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5504. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5505. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5506. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5507. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5508. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5509. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5510. \draw (t0) to (t1);
  5511. \draw (t0) to (z);
  5512. \draw (z) to (y);
  5513. \draw (z) to (w);
  5514. \draw (x) to (w);
  5515. \draw (y) to (w);
  5516. \draw (v) to (w);
  5517. \end{tikzpicture}
  5518. \]
  5519. Now \code{w} is the most saturated, so we color it $2$.
  5520. \[
  5521. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5522. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5523. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5524. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5525. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5526. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5527. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5528. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5529. \draw (t0) to (t1);
  5530. \draw (t0) to (z);
  5531. \draw (z) to (y);
  5532. \draw (z) to (w);
  5533. \draw (x) to (w);
  5534. \draw (y) to (w);
  5535. \draw (v) to (w);
  5536. \end{tikzpicture}
  5537. \]
  5538. To finish the coloring, \code{x} and \code{v} get $0$ and
  5539. \code{tmp\_1} gets $1$.
  5540. \[
  5541. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5542. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5543. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5544. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5545. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5546. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5547. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5548. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5549. \draw (t0) to (t1);
  5550. \draw (t0) to (z);
  5551. \draw (z) to (y);
  5552. \draw (z) to (w);
  5553. \draw (x) to (w);
  5554. \draw (y) to (w);
  5555. \draw (v) to (w);
  5556. \end{tikzpicture}
  5557. \]
  5558. \fi}
  5559. So we have the following assignment of variables to registers.
  5560. {\if\edition\racketEd
  5561. \begin{gather*}
  5562. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5563. \ttm{w} \mapsto \key{\%rsi}, \,
  5564. \ttm{x} \mapsto \key{\%rcx}, \,
  5565. \ttm{y} \mapsto \key{\%rcx}, \,
  5566. \ttm{z} \mapsto \key{\%rdx}, \,
  5567. \ttm{t} \mapsto \key{\%rcx} \}
  5568. \end{gather*}
  5569. \fi}
  5570. {\if\edition\pythonEd
  5571. \begin{gather*}
  5572. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5573. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5574. \ttm{x} \mapsto \key{\%rcx}, \,
  5575. \ttm{y} \mapsto \key{\%rcx}, \\
  5576. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5577. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5578. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5579. \end{gather*}
  5580. \fi}
  5581. We apply this register assignment to the running example, on the left,
  5582. to obtain the code in the middle. The \code{patch\_instructions} then
  5583. deletes the trivial moves to obtain the code on the right.
  5584. {\if\edition\racketEd
  5585. \begin{minipage}{0.25\textwidth}
  5586. \begin{lstlisting}
  5587. movq $1, v
  5588. movq $42, w
  5589. movq v, x
  5590. addq $7, x
  5591. movq x, y
  5592. movq x, z
  5593. addq w, z
  5594. movq y, t
  5595. negq t
  5596. movq z, %rax
  5597. addq t, %rax
  5598. jmp conclusion
  5599. \end{lstlisting}
  5600. \end{minipage}
  5601. $\Rightarrow\qquad$
  5602. \begin{minipage}{0.25\textwidth}
  5603. \begin{lstlisting}
  5604. movq $1, %rcx
  5605. movq $42, %rsi
  5606. movq %rcx, %rcx
  5607. addq $7, %rcx
  5608. movq %rcx, %rcx
  5609. movq %rcx, %rdx
  5610. addq %rsi, %rdx
  5611. movq %rcx, %rcx
  5612. negq %rcx
  5613. movq %rdx, %rax
  5614. addq %rcx, %rax
  5615. jmp conclusion
  5616. \end{lstlisting}
  5617. \end{minipage}
  5618. $\Rightarrow\qquad$
  5619. \begin{minipage}{0.25\textwidth}
  5620. \begin{lstlisting}
  5621. movq $1, %rcx
  5622. movq $42, %rsi
  5623. addq $7, %rcx
  5624. movq %rcx, %rdx
  5625. addq %rsi, %rdx
  5626. negq %rcx
  5627. movq %rdx, %rax
  5628. addq %rcx, %rax
  5629. jmp conclusion
  5630. \end{lstlisting}
  5631. \end{minipage}
  5632. \fi}
  5633. {\if\edition\pythonEd
  5634. \begin{minipage}{0.20\textwidth}
  5635. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5636. movq $1, v
  5637. movq $42, w
  5638. movq v, x
  5639. addq $7, x
  5640. movq x, y
  5641. movq x, z
  5642. addq w, z
  5643. movq y, tmp_0
  5644. negq tmp_0
  5645. movq z, tmp_1
  5646. addq tmp_0, tmp_1
  5647. movq tmp_1, %rdi
  5648. callq _print_int
  5649. \end{lstlisting}
  5650. \end{minipage}
  5651. ${\Rightarrow\qquad}$
  5652. \begin{minipage}{0.30\textwidth}
  5653. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5654. movq $1, %rcx
  5655. movq $42, -16(%rbp)
  5656. movq %rcx, %rcx
  5657. addq $7, %rcx
  5658. movq %rcx, %rcx
  5659. movq %rcx, -8(%rbp)
  5660. addq -16(%rbp), -8(%rbp)
  5661. movq %rcx, %rcx
  5662. negq %rcx
  5663. movq -8(%rbp), -8(%rbp)
  5664. addq %rcx, -8(%rbp)
  5665. movq -8(%rbp), %rdi
  5666. callq _print_int
  5667. \end{lstlisting}
  5668. \end{minipage}
  5669. ${\Rightarrow\qquad}$
  5670. \begin{minipage}{0.20\textwidth}
  5671. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5672. movq $1, %rcx
  5673. movq $42, -16(%rbp)
  5674. addq $7, %rcx
  5675. movq %rcx, -8(%rbp)
  5676. movq -16(%rbp), %rax
  5677. addq %rax, -8(%rbp)
  5678. negq %rcx
  5679. addq %rcx, -8(%rbp)
  5680. movq -8(%rbp), %rdi
  5681. callq print_int
  5682. \end{lstlisting}
  5683. \end{minipage}
  5684. \fi}
  5685. \begin{exercise}\normalfont
  5686. Change your implementation of \code{allocate\_registers} to take move
  5687. biasing into account. Create two new tests that include at least one
  5688. opportunity for move biasing and visually inspect the output x86
  5689. programs to make sure that your move biasing is working properly. Make
  5690. sure that your compiler still passes all of the tests.
  5691. \end{exercise}
  5692. %To do: another neat challenge would be to do
  5693. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5694. %% \subsection{Output of the Running Example}
  5695. %% \label{sec:reg-alloc-output}
  5696. % challenge: prioritize variables based on execution frequencies
  5697. % and the number of uses of a variable
  5698. % challenge: enhance the coloring algorithm using Chaitin's
  5699. % approach of prioritizing high-degree variables
  5700. % by removing low-degree variables (coloring them later)
  5701. % from the interference graph
  5702. \section{Further Reading}
  5703. \label{sec:register-allocation-further-reading}
  5704. Early register allocation algorithms were developed for Fortran
  5705. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5706. of graph coloring began in the late 1970s and early 1980s with the
  5707. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5708. algorithm is based on the following observation of
  5709. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5710. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5711. $v$ removed is also $k$ colorable. To see why, suppose that the
  5712. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5713. different colors, but since there are less than $k$ neighbors, there
  5714. will be one or more colors left over to use for coloring $v$ in $G$.
  5715. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5716. less than $k$ from the graph and recursively colors the rest of the
  5717. graph. Upon returning from the recursion, it colors $v$ with one of
  5718. the available colors and returns. \citet{Chaitin:1982vn} augments
  5719. this algorithm to handle spilling as follows. If there are no vertices
  5720. of degree lower than $k$ then pick a vertex at random, spill it,
  5721. remove it from the graph, and proceed recursively to color the rest of
  5722. the graph.
  5723. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5724. move-related and that don't interfere with each other, a process
  5725. called \emph{coalescing}. While coalescing decreases the number of
  5726. moves, it can make the graph more difficult to
  5727. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5728. which two variables are merged only if they have fewer than $k$
  5729. neighbors of high degree. \citet{George:1996aa} observe that
  5730. conservative coalescing is sometimes too conservative and make it more
  5731. aggressive by iterating the coalescing with the removal of low-degree
  5732. vertices.
  5733. %
  5734. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5735. also propose \emph{biased coloring} in which a variable is assigned to
  5736. the same color as another move-related variable if possible, as
  5737. discussed in Section~\ref{sec:move-biasing}.
  5738. %
  5739. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5740. performs coalescing, graph coloring, and spill code insertion until
  5741. all variables have been assigned a location.
  5742. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5743. spills variables that don't have to be: a high-degree variable can be
  5744. colorable if many of its neighbors are assigned the same color.
  5745. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5746. high-degree vertex is not immediately spilled. Instead the decision is
  5747. deferred until after the recursive call, at which point it is apparent
  5748. whether there is actually an available color or not. We observe that
  5749. this algorithm is equivalent to the smallest-last ordering
  5750. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5751. be registers and the rest to be stack locations.
  5752. %% biased coloring
  5753. Earlier editions of the compiler course at Indiana University
  5754. \citep{Dybvig:2010aa} were based on the algorithm of
  5755. \citet{Briggs:1994kx}.
  5756. The smallest-last ordering algorithm is one of many \emph{greedy}
  5757. coloring algorithms. A greedy coloring algorithm visits all the
  5758. vertices in a particular order and assigns each one the first
  5759. available color. An \emph{offline} greedy algorithm chooses the
  5760. ordering up-front, prior to assigning colors. The algorithm of
  5761. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5762. ordering does not depend on the colors assigned. Other orderings are
  5763. possible. For example, \citet{Chow:1984ys} order variables according
  5764. to an estimate of runtime cost.
  5765. An \emph{online} greedy coloring algorithm uses information about the
  5766. current assignment of colors to influence the order in which the
  5767. remaining vertices are colored. The saturation-based algorithm
  5768. described in this chapter is one such algorithm. We choose to use
  5769. saturation-based coloring because it is fun to introduce graph
  5770. coloring via Sudoku!
  5771. A register allocator may choose to map each variable to just one
  5772. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5773. variable to one or more locations. The later can be achieved by
  5774. \emph{live range splitting}, where a variable is replaced by several
  5775. variables that each handle part of its live
  5776. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5777. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5778. %% replacement algorithm, bottom-up local
  5779. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5780. %% Cooper: top-down (priority bassed), bottom-up
  5781. %% top-down
  5782. %% order variables by priority (estimated cost)
  5783. %% caveat: split variables into two groups:
  5784. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5785. %% color the constrained ones first
  5786. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5787. %% cite J. Cocke for an algorithm that colors variables
  5788. %% in a high-degree first ordering
  5789. %Register Allocation via Usage Counts, Freiburghouse CACM
  5790. \citet{Palsberg:2007si} observe that many of the interference graphs
  5791. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5792. that is, every cycle with four or more edges has an edge which is not
  5793. part of the cycle but which connects two vertices on the cycle. Such
  5794. graphs can be optimally colored by the greedy algorithm with a vertex
  5795. ordering determined by maximum cardinality search.
  5796. In situations where compile time is of utmost importance, such as in
  5797. just-in-time compilers, graph coloring algorithms can be too expensive
  5798. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5799. appropriate.
  5800. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5801. \chapter{Booleans and Conditionals}
  5802. \label{ch:Lif}
  5803. \index{subject}{Boolean}
  5804. \index{subject}{control flow}
  5805. \index{subject}{conditional expression}
  5806. The \LangInt{} and \LangVar{} languages only have a single kind of
  5807. value, the integers. In this chapter we add a second kind of value,
  5808. the Booleans, to create the \LangIf{} language. The Boolean values
  5809. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5810. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5811. language includes several operations that involve Booleans (\key{and},
  5812. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5813. \key{if} expression \python{and statement}. With the addition of
  5814. \key{if}, programs can have non-trivial control flow which
  5815. %
  5816. \racket{impacts \code{explicate\_control} and liveness analysis}
  5817. %
  5818. \python{impacts liveness analysis and motivates a new pass named
  5819. \code{explicate\_control}}.
  5820. %
  5821. Also, because we now have two kinds of values, we need to handle
  5822. programs that apply an operation to the wrong kind of value, such as
  5823. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5824. There are two language design options for such situations. One option
  5825. is to signal an error and the other is to provide a wider
  5826. interpretation of the operation. \racket{The Racket
  5827. language}\python{Python} uses a mixture of these two options,
  5828. depending on the operation and the kind of value. For example, the
  5829. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5830. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5831. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5832. %
  5833. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5834. in Racket because \code{car} expects a pair.}
  5835. %
  5836. \python{On the other hand, \code{1[0]} results in a run-time error
  5837. in Python because an ``\code{int} object is not subscriptable''.}
  5838. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5839. design choices as \racket{Racket}\python{Python}, except much of the
  5840. error detection happens at compile time instead of run
  5841. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5842. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5843. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5844. Racket}\python{MyPy} reports a compile-time error
  5845. %
  5846. \racket{because Racket expects the type of the argument to be of the form
  5847. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5848. %
  5849. \python{stating that a ``value of type \code{int} is not indexable''.}
  5850. The \LangIf{} language performs type checking during compilation like
  5851. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Rdyn} we study the
  5852. alternative choice, that is, a dynamically typed language like
  5853. \racket{Racket}\python{Python}.
  5854. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5855. for some operations we are more restrictive, for example, rejecting
  5856. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5857. This chapter is organized as follows. We begin by defining the syntax
  5858. and interpreter for the \LangIf{} language
  5859. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5860. checking and define a type checker for \LangIf{}
  5861. (Section~\ref{sec:type-check-Lif}).
  5862. %
  5863. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5864. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5865. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5866. %
  5867. The remaining sections of this chapter discuss how the addition of
  5868. Booleans and conditional control flow to the language requires changes
  5869. to the existing compiler passes and the addition of new ones. In
  5870. particular, we introduce the \code{shrink} pass to translates some
  5871. operators into others, thereby reducing the number of operators that
  5872. need to be handled in later passes.
  5873. %
  5874. The main event of this chapter is the \code{explicate\_control} pass
  5875. that is responsible for translating \code{if}'s into conditional
  5876. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  5877. %
  5878. Regarding register allocation, there is the interesting question of
  5879. how to handle conditional \code{goto}'s during liveness analysis.
  5880. \section{The \LangIf{} Language}
  5881. \label{sec:lang-if}
  5882. The concrete syntax of the \LangIf{} language is defined in
  5883. Figure~\ref{fig:Lif-concrete-syntax} and the abstract syntax is defined
  5884. in Figure~\ref{fig:Lif-syntax}. The \LangIf{} language includes all of
  5885. \LangVar{}\racket{(shown in gray)}, the Boolean literals \TRUE{} and
  5886. \FALSE{}, and the \code{if} expression \python{and statement}. We expand the
  5887. operators to include
  5888. \begin{enumerate}
  5889. \item subtraction on integers,
  5890. \item the logical operators \key{and}, \key{or}, and \key{not},
  5891. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  5892. for comparing integers or Booleans for equality, and
  5893. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  5894. comparing integers.
  5895. \end{enumerate}
  5896. \racket{We reorganize the abstract syntax for the primitive
  5897. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  5898. rule for all of them. This means that the grammar no longer checks
  5899. whether the arity of an operators matches the number of
  5900. arguments. That responsibility is moved to the type checker for
  5901. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  5902. \begin{figure}[tp]
  5903. \centering
  5904. \fbox{
  5905. \begin{minipage}{0.96\textwidth}
  5906. {\if\edition\racketEd
  5907. \[
  5908. \begin{array}{lcl}
  5909. \itm{bool} &::=& \TRUE \MID \FALSE \\
  5910. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5911. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} } \MID \CSUB{\Exp}{\Exp} \\
  5912. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} } \\
  5913. &\MID& \itm{bool}
  5914. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  5915. \MID (\key{not}\;\Exp) \\
  5916. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5917. \LangIfM{} &::=& \Exp
  5918. \end{array}
  5919. \]
  5920. \fi}
  5921. {\if\edition\pythonEd
  5922. \[
  5923. \begin{array}{rcl}
  5924. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{and} \MID \key{or} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  5925. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  5926. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \CUNIOP{\itm{uniop}}{\Exp} \MID \CBINOP{\itm{binop}}{\Exp}{\Exp} \MID \Var{} \\
  5927. &\MID& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  5928. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \CASSIGN{\Var}{\Exp}
  5929. \MID \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}\\
  5930. \LangIfM{} &::=& \Stmt^{*}
  5931. \end{array}
  5932. \]
  5933. \fi}
  5934. \end{minipage}
  5935. }
  5936. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  5937. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  5938. \label{fig:Lif-concrete-syntax}
  5939. \end{figure}
  5940. \begin{figure}[tp]
  5941. \centering
  5942. \fbox{
  5943. \begin{minipage}{0.96\textwidth}
  5944. {\if\edition\racketEd
  5945. \[
  5946. \begin{array}{lcl}
  5947. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  5948. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  5949. \itm{op} &::= & \itm{cmp} \MID \code{read} \MID \code{+} \MID \code{-}
  5950. \MID \code{and} \MID \code{or} \MID \code{not} \\
  5951. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  5952. &\MID& \PRIM{\itm{op}}{\Exp\ldots}\\
  5953. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5954. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  5955. \end{array}
  5956. \]
  5957. \fi}
  5958. {\if\edition\pythonEd
  5959. \[
  5960. \begin{array}{lcl}
  5961. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  5962. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  5963. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  5964. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  5965. \itm{bool} &::=& \code{True} \MID \code{False} \\
  5966. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  5967. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  5968. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  5969. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  5970. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  5971. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5972. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  5973. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  5974. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  5975. \end{array}
  5976. \]
  5977. \fi}
  5978. \end{minipage}
  5979. }
  5980. \caption{The abstract syntax of \LangIf{}.}
  5981. \label{fig:Lif-syntax}
  5982. \end{figure}
  5983. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  5984. which inherits from the interpreter for \LangVar{}
  5985. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  5986. evaluate to the corresponding Boolean values. The conditional
  5987. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  5988. and then either evaluates $e_2$ or $e_3$ depending on whether
  5989. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  5990. \code{and}, \code{or}, and \code{not} behave according to propositional logic,
  5991. but note that the \code{and} and \code{or} operations are
  5992. short-circuiting.
  5993. %
  5994. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  5995. is not evaluated if $e_1$ evaluates to \FALSE{}.
  5996. %
  5997. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  5998. evaluated if $e_1$ evaluates to \TRUE{}.
  5999. \racket{With the increase in the number of primitive operations, the
  6000. interpreter would become repetitive without some care. We refactor
  6001. the case for \code{Prim}, moving the code that differs with each
  6002. operation into the \code{interp\_op} method shown in in
  6003. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6004. \code{or} operations separately because of their short-circuiting
  6005. behavior.}
  6006. \begin{figure}[tbp]
  6007. {\if\edition\racketEd
  6008. \begin{lstlisting}
  6009. (define interp_Lif_class
  6010. (class interp_Lvar_class
  6011. (super-new)
  6012. (define/public (interp_op op) ...)
  6013. (define/override ((interp_exp env) e)
  6014. (define recur (interp_exp env))
  6015. (match e
  6016. [(Bool b) b]
  6017. [(If cnd thn els)
  6018. (match (recur cnd)
  6019. [#t (recur thn)]
  6020. [#f (recur els)])]
  6021. [(Prim 'and (list e1 e2))
  6022. (match (recur e1)
  6023. [#t (match (recur e2) [#t #t] [#f #f])]
  6024. [#f #f])]
  6025. [(Prim 'or (list e1 e2))
  6026. (define v1 (recur e1))
  6027. (match v1
  6028. [#t #t]
  6029. [#f (match (recur e2) [#t #t] [#f #f])])]
  6030. [(Prim op args)
  6031. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6032. [else ((super interp_exp env) e)]))
  6033. ))
  6034. (define (interp_Lif p)
  6035. (send (new interp_Lif_class) interp_program p))
  6036. \end{lstlisting}
  6037. \fi}
  6038. {\if\edition\pythonEd
  6039. \begin{lstlisting}
  6040. class InterpLif(InterpLvar):
  6041. def interp_exp(self, e, env):
  6042. match e:
  6043. case IfExp(test, body, orelse):
  6044. if self.interp_exp(test, env):
  6045. return self.interp_exp(body, env)
  6046. else:
  6047. return self.interp_exp(orelse, env)
  6048. case BinOp(left, Sub(), right):
  6049. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6050. case UnaryOp(Not(), v):
  6051. return not self.interp_exp(v, env)
  6052. case BoolOp(And(), values):
  6053. if self.interp_exp(values[0], env):
  6054. return self.interp_exp(values[1], env)
  6055. else:
  6056. return False
  6057. case BoolOp(Or(), values):
  6058. if self.interp_exp(values[0], env):
  6059. return True
  6060. else:
  6061. return self.interp_exp(values[1], env)
  6062. case Compare(left, [cmp], [right]):
  6063. l = self.interp_exp(left, env)
  6064. r = self.interp_exp(right, env)
  6065. return self.interp_cmp(cmp)(l, r)
  6066. case _:
  6067. return super().interp_exp(e, env)
  6068. def interp_stmts(self, ss, env):
  6069. if len(ss) == 0:
  6070. return
  6071. match ss[0]:
  6072. case If(test, body, orelse):
  6073. if self.interp_exp(test, env):
  6074. return self.interp_stmts(body + ss[1:], env)
  6075. else:
  6076. return self.interp_stmts(orelse + ss[1:], env)
  6077. case _:
  6078. return super().interp_stmts(ss, env)
  6079. ...
  6080. \end{lstlisting}
  6081. \fi}
  6082. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6083. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6084. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6085. \label{fig:interp-Lif}
  6086. \end{figure}
  6087. {\if\edition\racketEd
  6088. \begin{figure}[tbp]
  6089. \begin{lstlisting}
  6090. (define/public (interp_op op)
  6091. (match op
  6092. ['+ fx+]
  6093. ['- fx-]
  6094. ['read read-fixnum]
  6095. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6096. ['eq? (lambda (v1 v2)
  6097. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6098. (and (boolean? v1) (boolean? v2))
  6099. (and (vector? v1) (vector? v2)))
  6100. (eq? v1 v2)]))]
  6101. ['< (lambda (v1 v2)
  6102. (cond [(and (fixnum? v1) (fixnum? v2))
  6103. (< v1 v2)]))]
  6104. ['<= (lambda (v1 v2)
  6105. (cond [(and (fixnum? v1) (fixnum? v2))
  6106. (<= v1 v2)]))]
  6107. ['> (lambda (v1 v2)
  6108. (cond [(and (fixnum? v1) (fixnum? v2))
  6109. (> v1 v2)]))]
  6110. ['>= (lambda (v1 v2)
  6111. (cond [(and (fixnum? v1) (fixnum? v2))
  6112. (>= v1 v2)]))]
  6113. [else (error 'interp_op "unknown operator")]))
  6114. \end{lstlisting}
  6115. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6116. \label{fig:interp-op-Lif}
  6117. \end{figure}
  6118. \fi}
  6119. {\if\edition\pythonEd
  6120. \begin{figure}
  6121. \begin{lstlisting}
  6122. class InterpLif(InterpLvar):
  6123. ...
  6124. def interp_cmp(self, cmp):
  6125. match cmp:
  6126. case Lt():
  6127. return lambda x, y: x < y
  6128. case LtE():
  6129. return lambda x, y: x <= y
  6130. case Gt():
  6131. return lambda x, y: x > y
  6132. case GtE():
  6133. return lambda x, y: x >= y
  6134. case Eq():
  6135. return lambda x, y: x == y
  6136. case NotEq():
  6137. return lambda x, y: x != y
  6138. \end{lstlisting}
  6139. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6140. \label{fig:interp-cmp-Lif}
  6141. \end{figure}
  6142. \fi}
  6143. \section{Type Checking \LangIf{} Programs}
  6144. \label{sec:type-check-Lif}
  6145. \index{subject}{type checking}
  6146. \index{subject}{semantic analysis}
  6147. It is helpful to think about type checking in two complementary
  6148. ways. A type checker predicts the type of value that will be produced
  6149. by each expression in the program. For \LangIf{}, we have just two types,
  6150. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6151. {\if\edition\racketEd
  6152. \begin{lstlisting}
  6153. (+ 10 (- (+ 12 20)))
  6154. \end{lstlisting}
  6155. \fi}
  6156. {\if\edition\pythonEd
  6157. \begin{lstlisting}
  6158. 10 + -(12 + 20)
  6159. \end{lstlisting}
  6160. \fi}
  6161. \noindent produces a value of type \INTTY{} while
  6162. {\if\edition\racketEd
  6163. \begin{lstlisting}
  6164. (and (not #f) #t)
  6165. \end{lstlisting}
  6166. \fi}
  6167. {\if\edition\pythonEd
  6168. \begin{lstlisting}
  6169. (not False) and True
  6170. \end{lstlisting}
  6171. \fi}
  6172. \noindent produces a value of type \BOOLTY{}.
  6173. A second way to think about type checking is that it enforces a set of
  6174. rules about which operators can be applied to which kinds of
  6175. values. For example, our type checker for \LangIf{} signals an error
  6176. for the below expression {\if\edition\racketEd
  6177. \begin{lstlisting}
  6178. (not (+ 10 (- (+ 12 20))))
  6179. \end{lstlisting}
  6180. \fi}
  6181. {\if\edition\pythonEd
  6182. \begin{lstlisting}
  6183. not (10 + -(12 + 20))
  6184. \end{lstlisting}
  6185. \fi}
  6186. The subexpression
  6187. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6188. has type \INTTY{} but the type checker enforces the rule that the argument of
  6189. \code{not} must be an expression of type \BOOLTY{}.
  6190. We implement type checking using classes and methods because they
  6191. provide the open recursion needed to reuse code as we extend the type
  6192. checker in later chapters, analogous to the use of classes and methods
  6193. for the interpreters (Section~\ref{sec:extensible-interp}).
  6194. We separate the type checker for the \LangVar{} subset into its own
  6195. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6196. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6197. from the type checker for \LangVar{}. These type checkers are in the
  6198. files
  6199. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6200. and
  6201. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6202. of the support code.
  6203. %
  6204. Each type checker is a structurally recursive function over the AST.
  6205. Given an input expression \code{e}, the type checker either signals an
  6206. error or returns \racket{an expression and} its type (\INTTY{} or
  6207. \BOOLTY{}).
  6208. %
  6209. \racket{It returns an expression because there are situations in which
  6210. we want to change or update the expression.}
  6211. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6212. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6213. \INTTY{}. To handle variables, the type checker uses the environment
  6214. \code{env} to map variables to types.
  6215. %
  6216. \racket{Consider the case for \key{let}. We type check the
  6217. initializing expression to obtain its type \key{T} and then
  6218. associate type \code{T} with the variable \code{x} in the
  6219. environment used to type check the body of the \key{let}. Thus,
  6220. when the type checker encounters a use of variable \code{x}, it can
  6221. find its type in the environment.}
  6222. %
  6223. \python{Consider the case for assignment. We type check the
  6224. initializing expression to obtain its type \key{t}. If the variable
  6225. \code{lhs.id} is already in the environment because there was a
  6226. prior assignment, we check that this initializer has the same type
  6227. as the prior one. If this is the first assignment to the variable,
  6228. we associate type \code{t} with the variable \code{lhs.id} in the
  6229. environment. Thus, when the type checker encounters a use of
  6230. variable \code{x}, it can find its type in the environment.}
  6231. %
  6232. \racket{Regarding primitive operators, we recursively analyze the
  6233. arguments and then invoke \code{type\_check\_op} to check whether
  6234. the argument types are allowed.}
  6235. %
  6236. \python{Regarding addition and negation, we recursively analyze the
  6237. arguments, check that they have type \INT{}, and return \INT{}.}
  6238. \racket{Several auxiliary methods are used in the type checker. The
  6239. method \code{operator-types} defines a dictionary that maps the
  6240. operator names to their parameter and return types. The
  6241. \code{type-equal?} method determines whether two types are equal,
  6242. which for now simply dispatches to \code{equal?} (deep
  6243. equality). The \code{check-type-equal?} method triggers an error if
  6244. the two types are not equal. The \code{type-check-op} method looks
  6245. up the operator in the \code{operator-types} dictionary and then
  6246. checks whether the argument types are equal to the parameter types.
  6247. The result is the return type of the operator.}
  6248. %
  6249. \python{The auxiliary method \code{check\_type\_equal} method triggers
  6250. an error if the two types are not equal.}
  6251. \begin{figure}[tbp]
  6252. {\if\edition\racketEd
  6253. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6254. (define type-check-Lvar_class
  6255. (class object%
  6256. (super-new)
  6257. (define/public (operator-types)
  6258. '((+ . ((Integer Integer) . Integer))
  6259. (- . ((Integer) . Integer))
  6260. (read . (() . Integer))))
  6261. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6262. (define/public (check-type-equal? t1 t2 e)
  6263. (unless (type-equal? t1 t2)
  6264. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6265. (define/public (type-check-op op arg-types e)
  6266. (match (dict-ref (operator-types) op)
  6267. [`(,param-types . ,return-type)
  6268. (for ([at arg-types] [pt param-types])
  6269. (check-type-equal? at pt e))
  6270. return-type]
  6271. [else (error 'type-check-op "unrecognized ~a" op)]))
  6272. (define/public (type-check-exp env)
  6273. (lambda (e)
  6274. (match e
  6275. [(Int n) (values (Int n) 'Integer)]
  6276. [(Var x) (values (Var x) (dict-ref env x))]
  6277. [(Let x e body)
  6278. (define-values (e^ Te) ((type-check-exp env) e))
  6279. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6280. (values (Let x e^ b) Tb)]
  6281. [(Prim op es)
  6282. (define-values (new-es ts)
  6283. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6284. (values (Prim op new-es) (type-check-op op ts e))]
  6285. [else (error 'type-check-exp "couldn't match" e)])))
  6286. (define/public (type-check-program e)
  6287. (match e
  6288. [(Program info body)
  6289. (define-values (body^ Tb) ((type-check-exp '()) body))
  6290. (check-type-equal? Tb 'Integer body)
  6291. (Program info body^)]
  6292. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6293. ))
  6294. (define (type-check-Lvar p)
  6295. (send (new type-check-Lvar_class) type-check-program p))
  6296. \end{lstlisting}
  6297. \fi}
  6298. {\if\edition\pythonEd
  6299. \begin{lstlisting}
  6300. class TypeCheckLvar:
  6301. def check_type_equal(self, t1, t2, e):
  6302. if t1 != t2:
  6303. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6304. raise Exception(msg)
  6305. def type_check_exp(self, e, env):
  6306. match e:
  6307. case BinOp(left, Add(), right):
  6308. l = self.type_check_exp(left, env)
  6309. check_type_equal(l, int, left)
  6310. r = self.type_check_exp(right, env)
  6311. check_type_equal(r, int, right)
  6312. return int
  6313. case UnaryOp(USub(), v):
  6314. t = self.type_check_exp(v, env)
  6315. check_type_equal(t, int, v)
  6316. return int
  6317. case Name(id):
  6318. return env[id]
  6319. case Constant(value) if isinstance(value, int):
  6320. return int
  6321. case Call(Name('input_int'), []):
  6322. return int
  6323. def type_check_stmts(self, ss, env):
  6324. if len(ss) == 0:
  6325. return
  6326. match ss[0]:
  6327. case Assign([lhs], value):
  6328. t = self.type_check_exp(value, env)
  6329. if lhs.id in env:
  6330. check_type_equal(env[lhs.id], t, value)
  6331. else:
  6332. env[lhs.id] = t
  6333. return self.type_check_stmts(ss[1:], env)
  6334. case Expr(Call(Name('print'), [arg])):
  6335. t = self.type_check_exp(arg, env)
  6336. check_type_equal(t, int, arg)
  6337. return self.type_check_stmts(ss[1:], env)
  6338. case Expr(value):
  6339. self.type_check_exp(value, env)
  6340. return self.type_check_stmts(ss[1:], env)
  6341. def type_check_P(self, p):
  6342. match p:
  6343. case Module(body):
  6344. self.type_check_stmts(body, {})
  6345. \end{lstlisting}
  6346. \fi}
  6347. \caption{Type checker for the \LangVar{} language.}
  6348. \label{fig:type-check-Lvar}
  6349. \end{figure}
  6350. \begin{figure}[tbp]
  6351. {\if\edition\racketEd
  6352. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6353. (define type-check-Lif_class
  6354. (class type-check-Lvar_class
  6355. (super-new)
  6356. (inherit check-type-equal?)
  6357. (define/override (operator-types)
  6358. (append '((- . ((Integer Integer) . Integer))
  6359. (and . ((Boolean Boolean) . Boolean))
  6360. (or . ((Boolean Boolean) . Boolean))
  6361. (< . ((Integer Integer) . Boolean))
  6362. (<= . ((Integer Integer) . Boolean))
  6363. (> . ((Integer Integer) . Boolean))
  6364. (>= . ((Integer Integer) . Boolean))
  6365. (not . ((Boolean) . Boolean))
  6366. )
  6367. (super operator-types)))
  6368. (define/override (type-check-exp env)
  6369. (lambda (e)
  6370. (match e
  6371. [(Bool b) (values (Bool b) 'Boolean)]
  6372. [(Prim 'eq? (list e1 e2))
  6373. (define-values (e1^ T1) ((type-check-exp env) e1))
  6374. (define-values (e2^ T2) ((type-check-exp env) e2))
  6375. (check-type-equal? T1 T2 e)
  6376. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6377. [(If cnd thn els)
  6378. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6379. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6380. (define-values (els^ Te) ((type-check-exp env) els))
  6381. (check-type-equal? Tc 'Boolean e)
  6382. (check-type-equal? Tt Te e)
  6383. (values (If cnd^ thn^ els^) Te)]
  6384. [else ((super type-check-exp env) e)])))
  6385. ))
  6386. (define (type-check-Lif p)
  6387. (send (new type-check-Lif_class) type-check-program p))
  6388. \end{lstlisting}
  6389. \fi}
  6390. {\if\edition\pythonEd
  6391. \begin{lstlisting}
  6392. class TypeCheckLif(TypeCheckLvar):
  6393. def type_check_exp(self, e, env):
  6394. match e:
  6395. case Constant(value) if isinstance(value, bool):
  6396. return bool
  6397. case BinOp(left, Sub(), right):
  6398. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6399. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6400. return int
  6401. case UnaryOp(Not(), v):
  6402. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6403. return bool
  6404. case BoolOp(op, values):
  6405. left = values[0] ; right = values[1]
  6406. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6407. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6408. return bool
  6409. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6410. or isinstance(cmp, NotEq):
  6411. l = self.type_check_exp(left, env)
  6412. r = self.type_check_exp(right, env)
  6413. check_type_equal(l, r, e)
  6414. return bool
  6415. case Compare(left, [cmp], [right]):
  6416. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6417. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6418. return bool
  6419. case IfExp(test, body, orelse):
  6420. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6421. b = self.type_check_exp(body, env)
  6422. o = self.type_check_exp(orelse, env)
  6423. check_type_equal(b, o, e)
  6424. return b
  6425. case _:
  6426. return super().type_check_exp(e, env)
  6427. def type_check_stmts(self, ss, env):
  6428. if len(ss) == 0:
  6429. return
  6430. match ss[0]:
  6431. case If(test, body, orelse):
  6432. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6433. b = self.type_check_stmts(body, env)
  6434. o = self.type_check_stmts(orelse, env)
  6435. check_type_equal(b, o, ss[0])
  6436. return self.type_check_stmts(ss[1:], env)
  6437. case _:
  6438. return super().type_check_stmts(ss, env)
  6439. \end{lstlisting}
  6440. \fi}
  6441. \caption{Type checker for the \LangIf{} language.}
  6442. \label{fig:type-check-Lif}
  6443. \end{figure}
  6444. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6445. checker for \LangIf{}.
  6446. %
  6447. The type of a Boolean constant is \BOOLTY{}.
  6448. %
  6449. \racket{The \code{operator-types} function adds dictionary entries for
  6450. the other new operators.}
  6451. %
  6452. \python{Subtraction requires its arguments to be of type \INTTY{} and produces
  6453. an \INTTY{}. Negation requires its argument to be a \BOOLTY{} and
  6454. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6455. %
  6456. The equality operators requires the two arguments to have the same
  6457. type.
  6458. %
  6459. \python{The other comparisons (less-than, etc.) require their
  6460. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6461. %
  6462. The condition of an \code{if} must
  6463. be of \BOOLTY{} type and the two branches must have the same type.
  6464. \begin{exercise}\normalfont
  6465. Create 10 new test programs in \LangIf{}. Half of the programs should
  6466. have a type error. For those programs, create an empty file with the
  6467. same base name but with file extension \code{.tyerr}. For example, if
  6468. the test
  6469. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6470. is expected to error, then create
  6471. an empty file named \code{cond\_test\_14.tyerr}.
  6472. %
  6473. \racket{This indicates to \code{interp-tests} and
  6474. \code{compiler-tests} that a type error is expected. }
  6475. %
  6476. \racket{This indicates to the \code{run-tests.rkt} scripts that a type
  6477. error is expected.}
  6478. %
  6479. The other half of the test programs should not have type errors.
  6480. %
  6481. \racket{In the \code{run-tests.rkt} script, change the second argument
  6482. of \code{interp-tests} and \code{compiler-tests} to
  6483. \code{type-check-Lif}, which causes the type checker to run prior to
  6484. the compiler passes. Temporarily change the \code{passes} to an
  6485. empty list and run the script, thereby checking that the new test
  6486. programs either type check or not as intended.}
  6487. %
  6488. Run the test script to check that these test programs type check as
  6489. expected.
  6490. \end{exercise}
  6491. \clearpage
  6492. \section{The \LangCIf{} Intermediate Language}
  6493. \label{sec:Cif}
  6494. {\if\edition\racketEd
  6495. %
  6496. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6497. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6498. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6499. language adds logical and comparison operators to the \Exp{}
  6500. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6501. non-terminal.
  6502. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6503. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6504. statement is a comparison operation and the branches are \code{goto}
  6505. statements, making it straightforward to compile \code{if} statements
  6506. to x86.
  6507. %
  6508. \fi}
  6509. %
  6510. {\if\edition\pythonEd
  6511. %
  6512. The output of \key{explicate\_control} is a language similar to the
  6513. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6514. \code{goto} statements, so we name it \LangCIf{}. The
  6515. concrete syntax for \LangCIf{} is defined in
  6516. Figure~\ref{fig:c1-concrete-syntax}
  6517. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6518. %
  6519. The \LangCIf{} language supports the same operators as \LangIf{} but
  6520. the arguments of operators are restricted to atomic expressions. The
  6521. \LangCIf{} language does not include \code{if} expressions but it does
  6522. include a restricted form of \code{if} statment. The condition must be
  6523. a comparison and the two branches may only contain \code{goto}
  6524. statements. These restrictions make it easier to translate \code{if}
  6525. statements to x86.
  6526. %
  6527. \fi}
  6528. %
  6529. The \key{CProgram} construct contains
  6530. %
  6531. \racket{an alist}\python{a dictionary}
  6532. %
  6533. mapping labels to $\Tail$ expressions, which can be return statements,
  6534. an assignment statement followed by a $\Tail$ expression, a
  6535. \code{goto}, or a conditional \code{goto}.
  6536. \begin{figure}[tbp]
  6537. \fbox{
  6538. \begin{minipage}{0.96\textwidth}
  6539. \small
  6540. \[
  6541. \begin{array}{lcl}
  6542. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  6543. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6544. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} \MID \key{(-}~\Atm~\Atm\key{)} } \\
  6545. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6546. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  6547. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  6548. \MID \key{goto}~\itm{label}\key{;}\\
  6549. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  6550. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  6551. \end{array}
  6552. \]
  6553. \end{minipage}
  6554. }
  6555. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6556. \label{fig:c1-concrete-syntax}
  6557. \end{figure}
  6558. \begin{figure}[tp]
  6559. \fbox{
  6560. \begin{minipage}{0.96\textwidth}
  6561. \small
  6562. {\if\edition\racketEd
  6563. \[
  6564. \begin{array}{lcl}
  6565. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  6566. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6567. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  6568. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6569. &\MID& \UNIOP{\key{'not}}{\Atm}
  6570. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6571. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  6572. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  6573. \MID \GOTO{\itm{label}} \\
  6574. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  6575. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  6576. \end{array}
  6577. \]
  6578. \fi}
  6579. {\if\edition\pythonEd
  6580. \[
  6581. \begin{array}{lcl}
  6582. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6583. \Exp &::= & \Atm \MID \READ{} \\
  6584. &\MID& \BINOP{\Atm}{\itm{binop}}{\Atm}
  6585. \MID \UNIOP{\itm{uniop}}{\Atm} \\
  6586. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  6587. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  6588. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6589. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6590. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6591. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  6592. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{*}, \ldots \RC}
  6593. \end{array}
  6594. \]
  6595. \fi}
  6596. \end{minipage}
  6597. }
  6598. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6599. (Figure~\ref{fig:c0-syntax})}.}
  6600. \label{fig:c1-syntax}
  6601. \end{figure}
  6602. \section{The \LangXIf{} Language}
  6603. \label{sec:x86-if}
  6604. \index{subject}{x86} To implement the new logical operations, the comparison
  6605. operations, and the \key{if} expression, we need to delve further into
  6606. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6607. define the concrete and abstract syntax for the \LangXIf{} subset
  6608. of x86, which includes instructions for logical operations,
  6609. comparisons, and \racket{conditional} jumps.
  6610. One challenge is that x86 does not provide an instruction that
  6611. directly implements logical negation (\code{not} in \LangIf{} and
  6612. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6613. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6614. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6615. bit of its arguments, and writes the results into its second argument.
  6616. Recall the truth table for exclusive-or:
  6617. \begin{center}
  6618. \begin{tabular}{l|cc}
  6619. & 0 & 1 \\ \hline
  6620. 0 & 0 & 1 \\
  6621. 1 & 1 & 0
  6622. \end{tabular}
  6623. \end{center}
  6624. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6625. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6626. for the bit $1$, the result is the opposite of the second bit. Thus,
  6627. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6628. the first argument as follows, where $\Arg$ is the translation of
  6629. $\Atm$.
  6630. \[
  6631. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6632. \qquad\Rightarrow\qquad
  6633. \begin{array}{l}
  6634. \key{movq}~ \Arg\key{,} \Var\\
  6635. \key{xorq}~ \key{\$1,} \Var
  6636. \end{array}
  6637. \]
  6638. \begin{figure}[tp]
  6639. \fbox{
  6640. \begin{minipage}{0.96\textwidth}
  6641. \[
  6642. \begin{array}{lcl}
  6643. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6644. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6645. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6646. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6647. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6648. \key{subq} \; \Arg\key{,} \Arg \MID
  6649. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6650. && \gray{ \key{callq} \; \itm{label} \MID
  6651. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6652. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6653. \MID \key{xorq}~\Arg\key{,}~\Arg
  6654. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6655. && \key{set}cc~\Arg
  6656. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6657. \MID \key{j}cc~\itm{label}
  6658. \\
  6659. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6660. & & \gray{ \key{main:} \; \Instr\ldots }
  6661. \end{array}
  6662. \]
  6663. \end{minipage}
  6664. }
  6665. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6666. \label{fig:x86-1-concrete}
  6667. \end{figure}
  6668. \begin{figure}[tp]
  6669. \fbox{
  6670. \begin{minipage}{0.98\textwidth}
  6671. \small
  6672. {\if\edition\racketEd
  6673. \[
  6674. \begin{array}{lcl}
  6675. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6676. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6677. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6678. \MID \BYTEREG{\itm{bytereg}} \\
  6679. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6680. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6681. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6682. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6683. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6684. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6685. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6686. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6687. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6688. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6689. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6690. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6691. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6692. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6693. \end{array}
  6694. \]
  6695. \fi}
  6696. %
  6697. {\if\edition\pythonEd
  6698. \[
  6699. \begin{array}{lcl}
  6700. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6701. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6702. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6703. \MID \BYTEREG{\itm{bytereg}} \\
  6704. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6705. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6706. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6707. &\MID& \gray{ \BININSTR{\code{movq}}{\Arg}{\Arg}
  6708. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6709. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6710. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6711. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6712. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6713. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6714. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6715. &\MID& \JMPIF{\key{'}\itm{cc}\key{'}}{\itm{label}} \\
  6716. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6717. \end{array}
  6718. \]
  6719. \fi}
  6720. \end{minipage}
  6721. }
  6722. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6723. \label{fig:x86-1}
  6724. \end{figure}
  6725. Next we consider the x86 instructions that are relevant for compiling
  6726. the comparison operations. The \key{cmpq} instruction compares its two
  6727. arguments to determine whether one argument is less than, equal, or
  6728. greater than the other argument. The \key{cmpq} instruction is unusual
  6729. regarding the order of its arguments and where the result is
  6730. placed. The argument order is backwards: if you want to test whether
  6731. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6732. \key{cmpq} is placed in the special EFLAGS register. This register
  6733. cannot be accessed directly but it can be queried by a number of
  6734. instructions, including the \key{set} instruction. The instruction
  6735. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6736. depending on whether the comparison comes out according to the
  6737. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6738. for less-or-equal, \key{g} for greater, \key{ge} for
  6739. greater-or-equal). The \key{set} instruction has a quirk in
  6740. that its destination argument must be single byte register, such as
  6741. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6742. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6743. instruction can be used to move from a single byte register to a
  6744. normal 64-bit register. The abstract syntax for the \code{set}
  6745. instruction differs from the concrete syntax in that it separates the
  6746. instruction name from the condition code.
  6747. \python{The x86 instructions for jumping are relevant to the
  6748. compilation of \key{if} expressions.}
  6749. %
  6750. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6751. counter to the address of the instruction after the specified
  6752. label.}
  6753. %
  6754. \racket{The x86 instruction for conditional jump is relevant to the
  6755. compilation of \key{if} expressions.}
  6756. %
  6757. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6758. counter to point to the instruction after \itm{label} depending on
  6759. whether the result in the EFLAGS register matches the condition code
  6760. \itm{cc}, otherwise the jump instruction falls through to the next
  6761. instruction. Like the abstract syntax for \code{set}, the abstract
  6762. syntax for conditional jump separates the instruction name from the
  6763. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6764. to \code{jle foo}. Because the conditional jump instruction relies on
  6765. the EFLAGS register, it is common for it to be immediately preceded by
  6766. a \key{cmpq} instruction to set the EFLAGS register.
  6767. \section{Shrink the \LangIf{} Language}
  6768. \label{sec:shrink-Lif}
  6769. The \LangIf{} language includes several features that are easily
  6770. expressible with other features. For example, \code{and} and \code{or}
  6771. are expressible using \code{if} as follows.
  6772. \begin{align*}
  6773. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6774. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6775. \end{align*}
  6776. By performing these translations in the front-end of the compiler, the
  6777. later passes of the compiler do not need to deal with these features,
  6778. making the passes shorter.
  6779. %% For example, subtraction is
  6780. %% expressible using addition and negation.
  6781. %% \[
  6782. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6783. %% \]
  6784. %% Several of the comparison operations are expressible using less-than
  6785. %% and logical negation.
  6786. %% \[
  6787. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6788. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6789. %% \]
  6790. %% The \key{let} is needed in the above translation to ensure that
  6791. %% expression $e_1$ is evaluated before $e_2$.
  6792. On the other hand, sometimes translations reduce the efficiency of the
  6793. generated code by increasing the number of instructions. For example,
  6794. expressing subtraction in terms of negation
  6795. \[
  6796. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  6797. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  6798. \]
  6799. produces code with two x86 instructions (\code{negq} and \code{addq})
  6800. instead of just one (\code{subq}).
  6801. %% However,
  6802. %% these differences typically do not affect the number of accesses to
  6803. %% memory, which is the primary factor that determines execution time on
  6804. %% modern computer architectures.
  6805. \begin{exercise}\normalfont
  6806. %
  6807. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  6808. the language by translating them to \code{if} expressions in \LangIf{}.
  6809. %
  6810. Create four test programs that involve these operators.
  6811. %
  6812. {\if\edition\racketEd
  6813. In the \code{run-tests.rkt} script, add the following entry for
  6814. \code{shrink} to the list of passes (it should be the only pass at
  6815. this point).
  6816. \begin{lstlisting}
  6817. (list "shrink" shrink interp_Lif type-check-Lif)
  6818. \end{lstlisting}
  6819. This instructs \code{interp-tests} to run the intepreter
  6820. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  6821. output of \code{shrink}.
  6822. \fi}
  6823. %
  6824. Run the script to test your compiler on all the test programs.
  6825. \end{exercise}
  6826. {\if\edition\racketEd
  6827. \section{Uniquify Variables}
  6828. \label{sec:uniquify-Lif}
  6829. Add cases to \code{uniquify-exp} to handle Boolean constants and
  6830. \code{if} expressions.
  6831. \begin{exercise}\normalfont
  6832. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  6833. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  6834. \begin{lstlisting}
  6835. (list "uniquify" uniquify interp_Lif type_check_Lif)
  6836. \end{lstlisting}
  6837. Run the script to test your compiler.
  6838. \end{exercise}
  6839. \fi}
  6840. \section{Remove Complex Operands}
  6841. \label{sec:remove-complex-opera-Lif}
  6842. The output language of \code{remove\_complex\_operands} is
  6843. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  6844. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  6845. but the \code{if} expression is not. All three sub-expressions of an
  6846. \code{if} are allowed to be complex expressions but the operands of
  6847. \code{not} and the comparisons must be atomic.
  6848. %
  6849. \python{We add a new language form, the \code{Let} expression, to aid
  6850. in the translation of \code{if} expressions. When we recursively
  6851. process the two branches of the \code{if}, we generate temporary
  6852. variables and their initializing expressions. However, these
  6853. expressions may contain side effects and should only be executed
  6854. when the condition of the \code{if} is true (for the ``then''
  6855. branch) or false (for the ``else'' branch). The \code{Let} provides
  6856. a way to initialize the temporary variables within the two branches
  6857. of the \code{if} expression. In general, the $\LET{x}{e_1}{e_2}$
  6858. form assigns the result of $e_1$ to the variable $x$, an then
  6859. evaluates $e_2$, which may reference $x$.}
  6860. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  6861. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  6862. according to whether the output needs to be \Exp{} or \Atm{} as
  6863. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  6864. particularly important to \textbf{not} replace its condition with a
  6865. temporary variable because that would interfere with the generation of
  6866. high-quality output in the \code{explicate\_control} pass.
  6867. \begin{figure}[tp]
  6868. \centering
  6869. \fbox{
  6870. \begin{minipage}{0.96\textwidth}
  6871. {\if\edition\racketEd
  6872. \[
  6873. \begin{array}{rcl}
  6874. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  6875. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6876. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6877. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6878. &\MID& \UNIOP{\key{not}}{\Atm} \\
  6879. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6880. R^{\mathsf{ANF}}_{\mathsf{if}} &::=& \PROGRAM{\code{()}}{\Exp}
  6881. \end{array}
  6882. \]
  6883. \fi}
  6884. {\if\edition\pythonEd
  6885. \[
  6886. \begin{array}{rcl}
  6887. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  6888. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6889. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  6890. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6891. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  6892. \Exp &::=& \Atm \MID \READ{} \\
  6893. &\MID& \BINOP{\itm{binop}}{\Atm}{\Atm} \MID \UNIOP{\key{uniop}}{\Atm} \\
  6894. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6895. &\MID& \LET{\Var}{\Exp}{\Exp}\\
  6896. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6897. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}\\
  6898. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  6899. \end{array}
  6900. \]
  6901. \fi}
  6902. \end{minipage}
  6903. }
  6904. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  6905. \label{fig:Lif-anf-syntax}
  6906. \end{figure}
  6907. \begin{exercise}\normalfont
  6908. %
  6909. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  6910. and \code{rco\_exp} functions in \code{compiler.rkt}.
  6911. %
  6912. Create three new \LangIf{} programs that exercise the interesting
  6913. code in this pass.
  6914. %
  6915. {\if\edition\racketEd
  6916. In the \code{run-tests.rkt} script, add the following entry to the
  6917. list of \code{passes} and then run the script to test your compiler.
  6918. \begin{lstlisting}
  6919. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  6920. \end{lstlisting}
  6921. \fi}
  6922. \end{exercise}
  6923. \section{Explicate Control}
  6924. \label{sec:explicate-control-Lif}
  6925. \racket{Recall that the purpose of \code{explicate\_control} is to
  6926. make the order of evaluation explicit in the syntax of the program.
  6927. With the addition of \key{if} this get more interesting.}
  6928. %
  6929. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  6930. %
  6931. The main challenge to overcome is that the condition of an \key{if}
  6932. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  6933. condition must be a comparison.
  6934. As a motivating example, consider the following program that has an
  6935. \key{if} expression nested in the condition of another \key{if}.%
  6936. \python{\footnote{Programmers rarely write nested \code{if}
  6937. expressions, but it is not uncommon for the condition of an
  6938. \code{if} statement to be a call of a function that also contains an
  6939. \code{if} statement. When such a function is inlined, the result is
  6940. a nested \code{if} that requires the techniques discussed in this
  6941. section.}}
  6942. % cond_test_41.rkt, if_lt_eq.py
  6943. \begin{center}
  6944. \begin{minipage}{0.96\textwidth}
  6945. {\if\edition\racketEd
  6946. \begin{lstlisting}
  6947. (let ([x (read)])
  6948. (let ([y (read)])
  6949. (if (if (< x 1) (eq? x 0) (eq? x 2))
  6950. (+ y 2)
  6951. (+ y 10))))
  6952. \end{lstlisting}
  6953. \fi}
  6954. {\if\edition\pythonEd
  6955. \begin{lstlisting}
  6956. x = input_int()
  6957. y = input_int()
  6958. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  6959. \end{lstlisting}
  6960. \fi}
  6961. \end{minipage}
  6962. \end{center}
  6963. %
  6964. The naive way to compile \key{if} and the comparison operations would
  6965. be to handle each of them in isolation, regardless of their context.
  6966. Each comparison would be translated into a \key{cmpq} instruction
  6967. followed by a couple instructions to move the result from the EFLAGS
  6968. register into a general purpose register or stack location. Each
  6969. \key{if} would be translated into a \key{cmpq} instruction followed by
  6970. a conditional jump. The generated code for the inner \key{if} in the
  6971. above example would be as follows.
  6972. \begin{center}
  6973. \begin{minipage}{0.96\textwidth}
  6974. \begin{lstlisting}
  6975. cmpq $1, x
  6976. setl %al
  6977. movzbq %al, tmp
  6978. cmpq $1, tmp
  6979. je then_branch_1
  6980. jmp else_branch_1
  6981. \end{lstlisting}
  6982. \end{minipage}
  6983. \end{center}
  6984. However, if we take context into account we can do better and reduce
  6985. the use of \key{cmpq} instructions for accessing the EFLAG register.
  6986. Our goal will be to compile \key{if} expressions so that the relevant
  6987. comparison instruction appears directly before the conditional jump.
  6988. For example, we want to generate the following code for the inner
  6989. \code{if}.
  6990. \begin{center}
  6991. \begin{minipage}{0.96\textwidth}
  6992. \begin{lstlisting}
  6993. cmpq $1, x
  6994. jl then_branch_1
  6995. jmp else_branch_1
  6996. \end{lstlisting}
  6997. \end{minipage}
  6998. \end{center}
  6999. One way to achieve this is to reorganize the code at the level of
  7000. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7001. the following code.
  7002. \begin{center}
  7003. \begin{minipage}{0.96\textwidth}
  7004. {\if\edition\racketEd
  7005. \begin{lstlisting}
  7006. (let ([x (read)])
  7007. (let ([y (read)])
  7008. (if (< x 1)
  7009. (if (eq? x 0)
  7010. (+ y 2)
  7011. (+ y 10))
  7012. (if (eq? x 2)
  7013. (+ y 2)
  7014. (+ y 10)))))
  7015. \end{lstlisting}
  7016. \fi}
  7017. {\if\edition\pythonEd
  7018. \begin{lstlisting}
  7019. x = input_int()
  7020. y = intput_int()
  7021. print(((y + 2) if x == 0 else (y + 10)) \
  7022. if (x < 1) \
  7023. else ((y + 2) if (x == 2) else (y + 10)))
  7024. \end{lstlisting}
  7025. \fi}
  7026. \end{minipage}
  7027. \end{center}
  7028. Unfortunately, this approach duplicates the two branches from the
  7029. outer \code{if} and a compiler must never duplicate code! After all,
  7030. the two branches could have been very large expressions.
  7031. We need a way to perform the above transformation but without
  7032. duplicating code. That is, we need a way for different parts of a
  7033. program to refer to the same piece of code.
  7034. %
  7035. Put another way, we need to move away from abstract syntax
  7036. \emph{trees} and instead use \emph{graphs}.
  7037. %
  7038. At the level of x86 assembly this is straightforward because we can
  7039. label the code for each branch and insert jumps in all the places that
  7040. need to execute the branch.
  7041. %
  7042. Likewise, our language \LangCIf{} provides the ability to label a
  7043. sequence of code and to jump to a label via \code{goto}.
  7044. %
  7045. %% In particular, we use a standard program representation called a
  7046. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7047. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7048. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7049. %% edge represents a jump to another block.
  7050. %
  7051. %% The nice thing about the output of \code{explicate\_control} is that
  7052. %% there are no unnecessary comparisons and every comparison is part of a
  7053. %% conditional jump.
  7054. %% The down-side of this output is that it includes
  7055. %% trivial blocks, such as the blocks labeled \code{block92} through
  7056. %% \code{block95}, that only jump to another block. We discuss a solution
  7057. %% to this problem in Section~\ref{sec:opt-jumps}.
  7058. {\if\edition\racketEd
  7059. %
  7060. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7061. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7062. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7063. former function translates expressions in tail position whereas the
  7064. later function translates expressions on the right-hand-side of a
  7065. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7066. have a new kind of position to deal with: the predicate position of
  7067. the \key{if}. We need another function, \code{explicate\_pred}, that
  7068. decides how to compile an \key{if} by analyzing its predicate. So
  7069. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7070. tails for the then-branch and else-branch and outputs a tail. In the
  7071. following paragraphs we discuss specific cases in the
  7072. \code{explicate\_tail}, \code{explicate\_assign}, and
  7073. \code{explicate\_pred} functions.
  7074. %
  7075. \fi}
  7076. %
  7077. {\if\edition\pythonEd
  7078. %
  7079. We recommend implementing \code{explicate\_control} using the
  7080. following four auxiliary functions.
  7081. \begin{description}
  7082. \item[\code{explicate\_effect}] generates code for expressions as
  7083. statements, so their result is ignored and only their side effects
  7084. matter.
  7085. \item[\code{explicate\_assign}] generates code for expressions
  7086. on the right-hand side of an assignment.
  7087. \item[\code{explicate\_pred}] generates code for an \code{if}
  7088. expression or statement by analyzing the condition expression.
  7089. \item[\code{explicate\_stmt}] generates code for statements.
  7090. \end{description}
  7091. These four functions should build the dictionary of basic blocks. The
  7092. following auxiliary function can be used to create a new basic block
  7093. from a list of statements. It returns a \code{goto} statement that
  7094. jumps to the new basic block.
  7095. \begin{center}
  7096. \begin{minipage}{\textwidth}
  7097. \begin{lstlisting}
  7098. def create_block(stmts, basic_blocks):
  7099. label = label_name(generate_name('block'))
  7100. basic_blocks[label] = stmts
  7101. return Goto(label)
  7102. \end{lstlisting}
  7103. \end{minipage}
  7104. \end{center}
  7105. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7106. \code{explicate\_control} pass.
  7107. The \code{explicate\_effect} function has three parameters: 1) the
  7108. expression to be compiled, 2) the already-compiled code for this
  7109. expression's \emph{continuation}, that is, the list of statements that
  7110. should execute after this expression, and 3) the dictionary of
  7111. generated basic blocks. The \code{explicate\_effect} function returns
  7112. a list of \LangCIf{} statements and it may add to the dictionary of
  7113. basic blocks.
  7114. %
  7115. Let's consider a few of the cases for the expression to be compiled.
  7116. If the expression to be compiled is a constant, then it can be
  7117. discarded because it has no side effects. If it's a \CREAD{}, then it
  7118. has a side-effect and should be preserved. So the exprssion should be
  7119. translated into a statement using the \code{Expr} AST class. If the
  7120. expression to be compiled is an \code{if} expression, we translate the
  7121. two branches using \code{explicate\_effect} and then translate the
  7122. condition expression using \code{explicate\_pred}, which generates
  7123. code for the entire \code{if}.
  7124. The \code{explicate\_assign} function has four parameters: 1) the
  7125. right-hand-side of the assignment, 2) the left-hand-side of the
  7126. assignment (the variable), 3) the continuation, and 4) the dictionary
  7127. of basic blocks. The \code{explicate\_assign} function returns a list
  7128. of \LangCIf{} statements and it may add to the dictionary of basic
  7129. blocks.
  7130. When the right-hand-side is an \code{if} expression, there is some
  7131. work to do. In particular, the two branches should be translated using
  7132. \code{explicate\_assign} and the condition expression should be
  7133. translated using \code{explicate\_pred}. Otherwise we can simply
  7134. generate an assignment statement, with the given left and right-hand
  7135. sides, concatenated with its continuation.
  7136. \begin{figure}[tbp]
  7137. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7138. def explicate_effect(e, cont, basic_blocks):
  7139. match e:
  7140. case IfExp(test, body, orelse):
  7141. ...
  7142. case Call(func, args):
  7143. ...
  7144. case Let(var, rhs, body):
  7145. ...
  7146. case _:
  7147. ...
  7148. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7149. match rhs:
  7150. case IfExp(test, body, orelse):
  7151. ...
  7152. case Let(var, rhs, body):
  7153. ...
  7154. case _:
  7155. return [Assign([lhs], rhs)] + cont
  7156. def explicate_pred(cnd, thn, els, basic_blocks):
  7157. match cnd:
  7158. case Compare(left, [op], [right]):
  7159. goto_thn = create_block(thn, basic_blocks)
  7160. goto_els = create_block(els, basic_blocks)
  7161. return [If(cnd, [goto_thn], [goto_els])]
  7162. case Constant(True):
  7163. return thn;
  7164. case Constant(False):
  7165. return els;
  7166. case UnaryOp(Not(), operand):
  7167. ...
  7168. case IfExp(test, body, orelse):
  7169. ...
  7170. case Let(var, rhs, body):
  7171. ...
  7172. case _:
  7173. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7174. [create_block(els, basic_blocks)],
  7175. [create_block(thn, basic_blocks)])]
  7176. def explicate_stmt(s, cont, basic_blocks):
  7177. match s:
  7178. case Assign([lhs], rhs):
  7179. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7180. case Expr(value):
  7181. return explicate_effect(value, cont, basic_blocks)
  7182. case If(test, body, orelse):
  7183. ...
  7184. def explicate_control(p):
  7185. match p:
  7186. case Module(body):
  7187. new_body = [Return(Constant(0))]
  7188. basic_blocks = {}
  7189. for s in reversed(body):
  7190. new_body = explicate_stmt(s, new_body, basic_blocks)
  7191. basic_blocks[label_name('start')] = new_body
  7192. return CProgram(basic_blocks)
  7193. \end{lstlisting}
  7194. \caption{Skeleton for the \code{explicate\_control} pass.}
  7195. \label{fig:explicate-control-Lif}
  7196. \end{figure}
  7197. \fi}
  7198. {\if\edition\racketEd
  7199. %
  7200. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7201. additional cases for Boolean constants and \key{if}. The cases for
  7202. \code{if} should recursively compile the two branches using either
  7203. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7204. cases should then invoke \code{explicate\_pred} on the condition
  7205. expression, passing in the generated code for the two branches. For
  7206. example, consider the following program with an \code{if} in tail
  7207. position.
  7208. \begin{lstlisting}
  7209. (let ([x (read)])
  7210. (if (eq? x 0) 42 777))
  7211. \end{lstlisting}
  7212. The two branches are recursively compiled to \code{return 42;} and
  7213. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7214. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7215. used as the result for \code{explicate\_tail}.
  7216. Next let us consider a program with an \code{if} on the right-hand
  7217. side of a \code{let}.
  7218. \begin{lstlisting}
  7219. (let ([y (read)])
  7220. (let ([x (if (eq? y 0) 40 777)])
  7221. (+ x 2)))
  7222. \end{lstlisting}
  7223. Note that the body of the inner \code{let} will have already been
  7224. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7225. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7226. to recursively process both branches of the \code{if}, so we generate
  7227. the following block using an auxiliary function named \code{create\_block}.
  7228. \begin{lstlisting}
  7229. block_6:
  7230. return (+ x 2)
  7231. \end{lstlisting}
  7232. and use \code{goto block\_6;} as the \code{cont} argument for
  7233. compiling the branches. So the two branches compile to
  7234. \begin{lstlisting}
  7235. x = 40;
  7236. goto block_6;
  7237. \end{lstlisting}
  7238. and
  7239. \begin{lstlisting}
  7240. x = 777;
  7241. goto block_6;
  7242. \end{lstlisting}
  7243. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7244. 0)} and the above code for the branches.
  7245. \fi}
  7246. {\if\edition\racketEd
  7247. \begin{figure}[tbp]
  7248. \begin{lstlisting}
  7249. (define (explicate_pred cnd thn els)
  7250. (match cnd
  7251. [(Var x) ___]
  7252. [(Let x rhs body) ___]
  7253. [(Prim 'not (list e)) ___]
  7254. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7255. (IfStmt (Prim op es) (create_block thn)
  7256. (create_block els))]
  7257. [(Bool b) (if b thn els)]
  7258. [(If cnd^ thn^ els^) ___]
  7259. [else (error "explicate_pred unhandled case" cnd)]))
  7260. \end{lstlisting}
  7261. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7262. \label{fig:explicate-pred}
  7263. \end{figure}
  7264. \fi}
  7265. \racket{The skeleton for the \code{explicate\_pred} function is given
  7266. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7267. 1) \code{cnd}, the condition expression of the \code{if},
  7268. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7269. and 3) \code{els}, the code generated by
  7270. explicate for the ``else'' branch. The \code{explicate\_pred}
  7271. function should match on \code{cnd} with a case for
  7272. every kind of expression that can have type \code{Boolean}.}
  7273. %
  7274. \python{The \code{explicate\_pred} function has four parameters: 1)
  7275. the condition expession, 2) the generated statements for the
  7276. ``then'' branch, 3) the generated statements for the ``else''
  7277. branch, and 4) the dictionary of basic blocks. The
  7278. \code{explicate\_pred} function returns a list of \LangCIf{}
  7279. statements and it may add to the dictionary of basic blocks.}
  7280. Consider the case for comparison operators. We translate the
  7281. comparison to an \code{if} statement whose branches are \code{goto}
  7282. statements created by applying \code{create\_block} to the code
  7283. generated for the \code{thn} and \code{els} branches. Let us
  7284. illustrate this translation with an example. Returning
  7285. to the program with an \code{if} expression in tail position,
  7286. we invoke \code{explicate\_pred} on its condition \code{(eq? x 0)}
  7287. which happens to be a comparison operator.
  7288. \begin{lstlisting}
  7289. (let ([x (read)])
  7290. (if (eq? x 0) 42 777))
  7291. \end{lstlisting}
  7292. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7293. statements, from which we now create the following blocks.
  7294. \begin{center}
  7295. \begin{minipage}{\textwidth}
  7296. \begin{lstlisting}
  7297. block_1:
  7298. return 42;
  7299. block_2:
  7300. return 777;
  7301. \end{lstlisting}
  7302. \end{minipage}
  7303. \end{center}
  7304. %
  7305. So \code{explicate\_pred} compiles the comparison \code{(eq? x 0)}
  7306. to the following \code{if} statement.
  7307. %
  7308. \begin{center}
  7309. \begin{minipage}{\textwidth}
  7310. \begin{lstlisting}
  7311. if (eq? x 0)
  7312. goto block_1;
  7313. else
  7314. goto block_2;
  7315. \end{lstlisting}
  7316. \end{minipage}
  7317. \end{center}
  7318. Next consider the case for Boolean constants. We perform a kind of
  7319. partial evaluation\index{subject}{partial evaluation} and output
  7320. either the \code{thn} or \code{els} branch depending on whether the
  7321. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7322. following program.
  7323. \begin{center}
  7324. \begin{minipage}{\textwidth}
  7325. \begin{lstlisting}
  7326. (if #t 42 777)
  7327. \end{lstlisting}
  7328. \end{minipage}
  7329. \end{center}
  7330. %
  7331. Again, the two branches \code{42} and \code{777} were compiled to
  7332. \code{return} statements, so \code{explicate\_pred} compiles the
  7333. constant \code{\#t} to the code for the ``then'' branch.
  7334. \begin{center}
  7335. \begin{minipage}{\textwidth}
  7336. \begin{lstlisting}
  7337. return 42;
  7338. \end{lstlisting}
  7339. \end{minipage}
  7340. \end{center}
  7341. %
  7342. This case demonstrates that we sometimes discard the \code{thn} or
  7343. \code{els} blocks that are input to \code{explicate\_pred}.
  7344. The case for \key{if} expressions in \code{explicate\_pred} is
  7345. particularly illuminating because it deals with the challenges we
  7346. discussed above regarding nested \key{if} expressions
  7347. (Figure~\ref{fig:explicate-control-s1-38}). The
  7348. \racket{\lstinline{thn^}}\python{\code{body}} and
  7349. \racket{\lstinline{els^}}\python{\code{orlese}} branches of the
  7350. \key{if} inherit their context from the current one, that is,
  7351. predicate context. So you should recursively apply
  7352. \code{explicate\_pred} to the
  7353. \racket{\lstinline{thn^}}\python{\code{body}} and
  7354. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7355. those recursive calls, pass \code{thn} and \code{els} as the extra
  7356. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7357. inside each recursive call. As discussed above, to avoid duplicating
  7358. code, we need to add them to the dictionary of basic blocks so that we
  7359. can instead refer to them by name and execute them with a \key{goto}.
  7360. {\if\edition\pythonEd
  7361. %
  7362. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7363. three parameters: 1) the statement to be compiled, 2) the code for its
  7364. continuation, and 3) the dictionary of basic blocks. The
  7365. \code{explicate\_stmt} returns a list of statements and it may add to
  7366. the dictionary of basic blocks. The cases for assignment and an
  7367. expression-statement are given in full in the skeleton code: they
  7368. simply dispatch to \code{explicate\_assign} and
  7369. \code{explicate\_effect}, respectively. The case for \code{if}
  7370. statements is not given, and is similar to the case for \code{if}
  7371. expressions.
  7372. The \code{explicate\_control} function itself is given in
  7373. Figure~\ref{fig:explicate-control-Lif}. It applies
  7374. \code{explicate\_stmt} to each statement in the program, from back to
  7375. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7376. used as the continuation parameter in the next call to
  7377. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7378. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7379. the dictionary of basic blocks, labeling it as the ``start'' block.
  7380. %
  7381. \fi}
  7382. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7383. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7384. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7385. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7386. %% results from the two recursive calls. We complete the case for
  7387. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7388. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7389. %% the result $B_5$.
  7390. %% \[
  7391. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7392. %% \quad\Rightarrow\quad
  7393. %% B_5
  7394. %% \]
  7395. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7396. %% inherit the current context, so they are in tail position. Thus, the
  7397. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7398. %% \code{explicate\_tail}.
  7399. %% %
  7400. %% We need to pass $B_0$ as the accumulator argument for both of these
  7401. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7402. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7403. %% to the control-flow graph and obtain a promised goto $G_0$.
  7404. %% %
  7405. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7406. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7407. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7408. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7409. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7410. %% \[
  7411. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7412. %% \]
  7413. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7414. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7415. %% should not be confused with the labels for the blocks that appear in
  7416. %% the generated code. We initially construct unlabeled blocks; we only
  7417. %% attach labels to blocks when we add them to the control-flow graph, as
  7418. %% we see in the next case.
  7419. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7420. %% function. The context of the \key{if} is an assignment to some
  7421. %% variable $x$ and then the control continues to some promised block
  7422. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7423. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7424. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7425. %% branches of the \key{if} inherit the current context, so they are in
  7426. %% assignment positions. Let $B_2$ be the result of applying
  7427. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7428. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7429. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7430. %% the result of applying \code{explicate\_pred} to the predicate
  7431. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7432. %% translates to the promise $B_4$.
  7433. %% \[
  7434. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7435. %% \]
  7436. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7437. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7438. \code{remove\_complex\_operands} pass and then the
  7439. \code{explicate\_control} pass on the example program. We walk through
  7440. the output program.
  7441. %
  7442. Following the order of evaluation in the output of
  7443. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7444. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7445. in the predicate of the inner \key{if}. In the output of
  7446. \code{explicate\_control}, in the
  7447. block labeled \code{start}, are two assignment statements followed by a
  7448. \code{if} statement that branches to \code{block\_8} or
  7449. \code{block\_9}. The blocks associated with those labels contain the
  7450. translations of the code
  7451. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7452. and
  7453. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7454. respectively. In particular, we start \code{block\_8} with the
  7455. comparison
  7456. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7457. and then branch to \code{block\_4} or \code{block\_5}.
  7458. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7459. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7460. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7461. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7462. and go directly to \code{block\_2} and \code{block\_3},
  7463. which we investigate in Section~\ref{sec:opt-jumps}.
  7464. Getting back to the example, \code{block\_2} and \code{block\_3},
  7465. corresponds to the two branches of the outer \key{if}, i.e.,
  7466. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7467. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7468. %
  7469. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7470. %
  7471. \python{The \code{block\_1} corresponds to the \code{print} statment
  7472. at the end of the program.}
  7473. \begin{figure}[tbp]
  7474. {\if\edition\racketEd
  7475. \begin{tabular}{lll}
  7476. \begin{minipage}{0.4\textwidth}
  7477. % cond_test_41.rkt
  7478. \begin{lstlisting}
  7479. (let ([x (read)])
  7480. (let ([y (read)])
  7481. (if (if (< x 1)
  7482. (eq? x 0)
  7483. (eq? x 2))
  7484. (+ y 2)
  7485. (+ y 10))))
  7486. \end{lstlisting}
  7487. \end{minipage}
  7488. &
  7489. $\Rightarrow$
  7490. &
  7491. \begin{minipage}{0.55\textwidth}
  7492. \begin{lstlisting}
  7493. start:
  7494. x = (read);
  7495. y = (read);
  7496. if (< x 1)
  7497. goto block_8;
  7498. else
  7499. goto block_9;
  7500. block_8:
  7501. if (eq? x 0)
  7502. goto block_4;
  7503. else
  7504. goto block_5;
  7505. block_9:
  7506. if (eq? x 2)
  7507. goto block_6;
  7508. else
  7509. goto block_7;
  7510. block_4:
  7511. goto block_2;
  7512. block_5:
  7513. goto block_3;
  7514. block_6:
  7515. goto block_2;
  7516. block_7:
  7517. goto block_3;
  7518. block_2:
  7519. return (+ y 2);
  7520. block_3:
  7521. return (+ y 10);
  7522. \end{lstlisting}
  7523. \end{minipage}
  7524. \end{tabular}
  7525. \fi}
  7526. {\if\edition\pythonEd
  7527. \begin{tabular}{lll}
  7528. \begin{minipage}{0.4\textwidth}
  7529. % cond_test_41.rkt
  7530. \begin{lstlisting}
  7531. x = input_int()
  7532. y = input_int()
  7533. print(y + 2 \
  7534. if (x == 0 \
  7535. if x < 1 \
  7536. else x == 2) \
  7537. else y + 10)
  7538. \end{lstlisting}
  7539. \end{minipage}
  7540. &
  7541. $\Rightarrow$
  7542. &
  7543. \begin{minipage}{0.55\textwidth}
  7544. \begin{lstlisting}
  7545. start:
  7546. x = input_int()
  7547. y = input_int()
  7548. if x < 1:
  7549. goto block_8
  7550. else:
  7551. goto block_9
  7552. block_8:
  7553. if x == 0:
  7554. goto block_4
  7555. else:
  7556. goto block_5
  7557. block_9:
  7558. if x == 2:
  7559. goto block_6
  7560. else:
  7561. goto block_7
  7562. block_4:
  7563. goto block_2
  7564. block_5:
  7565. goto block_3
  7566. block_6:
  7567. goto block_2
  7568. block_7:
  7569. goto block_3
  7570. block_2:
  7571. tmp_0 = y + 2
  7572. goto block_1
  7573. block_3:
  7574. tmp_0 = y + 10
  7575. goto block_1
  7576. block_1:
  7577. print(tmp_0)
  7578. return 0
  7579. \end{lstlisting}
  7580. \end{minipage}
  7581. \end{tabular}
  7582. \fi}
  7583. \caption{Translation from \LangIf{} to \LangCIf{}
  7584. via the \code{explicate\_control}.}
  7585. \label{fig:explicate-control-s1-38}
  7586. \end{figure}
  7587. {\if\edition\racketEd
  7588. The way in which the \code{shrink} pass transforms logical operations
  7589. such as \code{and} and \code{or} can impact the quality of code
  7590. generated by \code{explicate\_control}. For example, consider the
  7591. following program.
  7592. % cond_test_21.rkt, and_eq_input.py
  7593. \begin{lstlisting}
  7594. (if (and (eq? (read) 0) (eq? (read) 1))
  7595. 0
  7596. 42)
  7597. \end{lstlisting}
  7598. The \code{and} operation should transform into something that the
  7599. \code{explicate\_pred} function can still analyze and descend through to
  7600. reach the underlying \code{eq?} conditions. Ideally, your
  7601. \code{explicate\_control} pass should generate code similar to the
  7602. following for the above program.
  7603. \begin{center}
  7604. \begin{lstlisting}
  7605. start:
  7606. tmp1 = (read);
  7607. if (eq? tmp1 0) goto block40;
  7608. else goto block39;
  7609. block40:
  7610. tmp2 = (read);
  7611. if (eq? tmp2 1) goto block38;
  7612. else goto block39;
  7613. block38:
  7614. return 0;
  7615. block39:
  7616. return 42;
  7617. \end{lstlisting}
  7618. \end{center}
  7619. \fi}
  7620. \begin{exercise}\normalfont
  7621. \racket{
  7622. Implement the pass \code{explicate\_control} by adding the cases for
  7623. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7624. \code{explicate\_assign} functions. Implement the auxiliary function
  7625. \code{explicate\_pred} for predicate contexts.}
  7626. \python{Implement \code{explicate\_control} pass with its
  7627. four auxiliary functions.}
  7628. %
  7629. Create test cases that exercise all of the new cases in the code for
  7630. this pass.
  7631. %
  7632. {\if\edition\racketEd
  7633. Add the following entry to the list of \code{passes} in
  7634. \code{run-tests.rkt} and then run this script to test your compiler.
  7635. \begin{lstlisting}
  7636. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7637. \end{lstlisting}
  7638. \fi}
  7639. \end{exercise}
  7640. \clearpage
  7641. \section{Select Instructions}
  7642. \label{sec:select-Lif}
  7643. \index{subject}{instruction selection}
  7644. The \code{select\_instructions} pass translates \LangCIf{} to
  7645. \LangXIfVar{}.
  7646. %
  7647. \racket{Recall that we implement this pass using three auxiliary
  7648. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7649. $\Tail$.}
  7650. %
  7651. \racket{For $\Atm$, we have new cases for the Booleans.}
  7652. %
  7653. \python{We begin with the Boolean constants.}
  7654. We take the usual approach of encoding them as integers.
  7655. \[
  7656. \TRUE{} \quad\Rightarrow\quad \key{1}
  7657. \qquad\qquad
  7658. \FALSE{} \quad\Rightarrow\quad \key{0}
  7659. \]
  7660. For translating statements, we discuss a couple cases. The \code{not}
  7661. operation can be implemented in terms of \code{xorq} as we discussed
  7662. at the beginning of this section. Given an assignment, if the
  7663. left-hand side variable is the same as the argument of \code{not},
  7664. then just the \code{xorq} instruction suffices.
  7665. \[
  7666. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7667. \quad\Rightarrow\quad
  7668. \key{xorq}~\key{\$}1\key{,}~\Var
  7669. \]
  7670. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7671. semantics of x86. In the following translation, let $\Arg$ be the
  7672. result of translating $\Atm$ to x86.
  7673. \[
  7674. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7675. \quad\Rightarrow\quad
  7676. \begin{array}{l}
  7677. \key{movq}~\Arg\key{,}~\Var\\
  7678. \key{xorq}~\key{\$}1\key{,}~\Var
  7679. \end{array}
  7680. \]
  7681. Next consider the cases for equality. Translating this operation to
  7682. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7683. instruction discussed above. We recommend translating an assignment
  7684. with an equality on the right-hand side into a sequence of three
  7685. instructions. \\
  7686. \begin{tabular}{lll}
  7687. \begin{minipage}{0.4\textwidth}
  7688. \begin{lstlisting}
  7689. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7690. \end{lstlisting}
  7691. \end{minipage}
  7692. &
  7693. $\Rightarrow$
  7694. &
  7695. \begin{minipage}{0.4\textwidth}
  7696. \begin{lstlisting}
  7697. cmpq |$\Arg_2$|, |$\Arg_1$|
  7698. sete %al
  7699. movzbq %al, |$\Var$|
  7700. \end{lstlisting}
  7701. \end{minipage}
  7702. \end{tabular} \\
  7703. The translations for the other comparison operators are similar to the
  7704. above but use different suffixes for the \code{set} instruction.
  7705. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7706. \key{goto} and \key{if} statements. Both are straightforward to
  7707. translate to x86.}
  7708. %
  7709. A \key{goto} statement becomes a jump instruction.
  7710. \[
  7711. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7712. \]
  7713. %
  7714. An \key{if} statement becomes a compare instruction followed by a
  7715. conditional jump (for the ``then'' branch) and the fall-through is to
  7716. a regular jump (for the ``else'' branch).\\
  7717. \begin{tabular}{lll}
  7718. \begin{minipage}{0.4\textwidth}
  7719. \begin{lstlisting}
  7720. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7721. goto |$\ell_1$||$\racket{\key{;}}$|
  7722. else|$\python{\key{:}}$|
  7723. goto |$\ell_2$||$\racket{\key{;}}$|
  7724. \end{lstlisting}
  7725. \end{minipage}
  7726. &
  7727. $\Rightarrow$
  7728. &
  7729. \begin{minipage}{0.4\textwidth}
  7730. \begin{lstlisting}
  7731. cmpq |$\Arg_2$|, |$\Arg_1$|
  7732. je |$\ell_1$|
  7733. jmp |$\ell_2$|
  7734. \end{lstlisting}
  7735. \end{minipage}
  7736. \end{tabular} \\
  7737. Again, the translations for the other comparison operators are similar to the
  7738. above but use different suffixes for the conditional jump instruction.
  7739. \python{Regarding the \key{return} statement, we recommend treating it
  7740. as an assignment to the \key{rax} register followed by a jump to the
  7741. conclusion of the \code{main} function.}
  7742. \begin{exercise}\normalfont
  7743. Expand your \code{select\_instructions} pass to handle the new
  7744. features of the \LangIf{} language.
  7745. %
  7746. {\if\edition\racketEd
  7747. Add the following entry to the list of \code{passes} in
  7748. \code{run-tests.rkt}
  7749. \begin{lstlisting}
  7750. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  7751. \end{lstlisting}
  7752. \fi}
  7753. %
  7754. Run the script to test your compiler on all the test programs.
  7755. \end{exercise}
  7756. \section{Register Allocation}
  7757. \label{sec:register-allocation-Lif}
  7758. \index{subject}{register allocation}
  7759. The changes required for \LangIf{} affect liveness analysis, building the
  7760. interference graph, and assigning homes, but the graph coloring
  7761. algorithm itself does not change.
  7762. \subsection{Liveness Analysis}
  7763. \label{sec:liveness-analysis-Lif}
  7764. \index{subject}{liveness analysis}
  7765. Recall that for \LangVar{} we implemented liveness analysis for a
  7766. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  7767. the addition of \key{if} expressions to \LangIf{},
  7768. \code{explicate\_control} produces many basic blocks.
  7769. %% We recommend that you create a new auxiliary function named
  7770. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  7771. %% control-flow graph.
  7772. The first question is: what order should we process the basic blocks?
  7773. Recall that to perform liveness analysis on a basic block we need to
  7774. know the live-after set for the last instruction in the block. If a
  7775. basic block has no successors (i.e. contains no jumps to other
  7776. blocks), then it has an empty live-after set and we can immediately
  7777. apply liveness analysis to it. If a basic block has some successors,
  7778. then we need to complete liveness analysis on those blocks
  7779. first. These ordering contraints are the reverse of a
  7780. \emph{topological order}\index{subject}{topological order} on a graph
  7781. representation of the program. In particular, the \emph{control flow
  7782. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  7783. of a program has a node for each basic block and an edge for each jump
  7784. from one block to another. It is straightforward to generate a CFG
  7785. from the dictionary of basic blocks. One then transposes the CFG and
  7786. applies the topological sort algorithm.
  7787. %
  7788. %
  7789. \racket{We recommend using the \code{tsort} and \code{transpose}
  7790. functions of the Racket \code{graph} package to accomplish this.}
  7791. %
  7792. \python{We provide implementations of \code{topological\_sort} and
  7793. \code{transpose} in the file \code{graph.py} of the support code.}
  7794. %
  7795. As an aside, a topological ordering is only guaranteed to exist if the
  7796. graph does not contain any cycles. This is the case for the
  7797. control-flow graphs that we generate from \LangIf{} programs.
  7798. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  7799. and learn how to handle cycles in the control-flow graph.
  7800. \racket{You'll need to construct a directed graph to represent the
  7801. control-flow graph. Do not use the \code{directed-graph} of the
  7802. \code{graph} package because that only allows at most one edge
  7803. between each pair of vertices, but a control-flow graph may have
  7804. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  7805. file in the support code implements a graph representation that
  7806. allows multiple edges between a pair of vertices.}
  7807. {\if\edition\racketEd
  7808. The next question is how to analyze jump instructions. Recall that in
  7809. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  7810. \code{label->live} that maps each label to the set of live locations
  7811. at the beginning of its block. We use \code{label->live} to determine
  7812. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  7813. that we have many basic blocks, \code{label->live} needs to be updated
  7814. as we process the blocks. In particular, after performing liveness
  7815. analysis on a block, we take the live-before set of its first
  7816. instruction and associate that with the block's label in the
  7817. \code{label->live}.
  7818. \fi}
  7819. %
  7820. {\if\edition\pythonEd
  7821. %
  7822. The next question is how to analyze jump instructions. The locations
  7823. that are live before a \code{jmp} should be the locations in
  7824. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  7825. maintaining a dictionary named \code{live\_before\_block} that maps each
  7826. label to the $L_{\mathtt{before}}$ for the first instruction in its
  7827. block. After performing liveness analysis on each block, we take the
  7828. live-before set of its first instruction and associate that with the
  7829. block's label in the \code{live\_before\_block} dictionary.
  7830. %
  7831. \fi}
  7832. In \LangXIfVar{} we also have the conditional jump
  7833. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  7834. this instruction is particularly interesting because, during
  7835. compilation, we do not know which way a conditional jump will go. So
  7836. we do not know whether to use the live-before set for the following
  7837. instruction or the live-before set for the block associated with the
  7838. $\itm{label}$. However, there is no harm to the correctness of the
  7839. generated code if we classify more locations as live than the ones
  7840. that are truly live during one particular execution of the
  7841. instruction. Thus, we can take the union of the live-before sets from
  7842. the following instruction and from the mapping for $\itm{label}$ in
  7843. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  7844. The auxiliary functions for computing the variables in an
  7845. instruction's argument and for computing the variables read-from ($R$)
  7846. or written-to ($W$) by an instruction need to be updated to handle the
  7847. new kinds of arguments and instructions in \LangXIfVar{}.
  7848. \begin{exercise}\normalfont
  7849. {\if\edition\racketEd
  7850. %
  7851. Update the \code{uncover\_live} pass to apply liveness analysis to
  7852. every basic block in the program.
  7853. %
  7854. Add the following entry to the list of \code{passes} in the
  7855. \code{run-tests.rkt} script.
  7856. \begin{lstlisting}
  7857. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  7858. \end{lstlisting}
  7859. \fi}
  7860. {\if\edition\pythonEd
  7861. %
  7862. Update the \code{uncover\_live} function to perform liveness analysis,
  7863. in reverse topological order, on all of the basic blocks in the
  7864. program.
  7865. %
  7866. \fi}
  7867. % Check that the live-after sets that you generate for
  7868. % example X matches the following... -Jeremy
  7869. \end{exercise}
  7870. \subsection{Build the Interference Graph}
  7871. \label{sec:build-interference-Lif}
  7872. Many of the new instructions in \LangXIfVar{} can be handled in the
  7873. same way as the instructions in \LangXVar{}. Thus, if your code was
  7874. already quite general, it will not need to be changed to handle the
  7875. new instructions. If you code is not general enough, we recommend that
  7876. you change your code to be more general. For example, you can factor
  7877. out the computing of the the read and write sets for each kind of
  7878. instruction into auxiliary functions.
  7879. Note that the \key{movzbq} instruction requires some special care,
  7880. similar to the \key{movq} instruction. See rule number 1 in
  7881. Section~\ref{sec:build-interference}.
  7882. \begin{exercise}\normalfont
  7883. Update the \code{build\_interference} pass for \LangXIfVar{}.
  7884. {\if\edition\racketEd
  7885. Add the following entries to the list of \code{passes} in the
  7886. \code{run-tests.rkt} script.
  7887. \begin{lstlisting}
  7888. (list "build_interference" build_interference interp-pseudo-x86-1)
  7889. (list "allocate_registers" allocate_registers interp-x86-1)
  7890. \end{lstlisting}
  7891. \fi}
  7892. % Check that the interference graph that you generate for
  7893. % example X matches the following graph G... -Jeremy
  7894. \end{exercise}
  7895. \section{Patch Instructions}
  7896. The new instructions \key{cmpq} and \key{movzbq} have some special
  7897. restrictions that need to be handled in the \code{patch\_instructions}
  7898. pass.
  7899. %
  7900. The second argument of the \key{cmpq} instruction must not be an
  7901. immediate value (such as an integer). So if you are comparing two
  7902. immediates, we recommend inserting a \key{movq} instruction to put the
  7903. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  7904. one memory reference.
  7905. %
  7906. The second argument of the \key{movzbq} must be a register.
  7907. \begin{exercise}\normalfont
  7908. %
  7909. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  7910. %
  7911. {\if\edition\racketEd
  7912. Add the following entry to the list of \code{passes} in
  7913. \code{run-tests.rkt} and then run this script to test your compiler.
  7914. \begin{lstlisting}
  7915. (list "patch_instructions" patch_instructions interp-x86-1)
  7916. \end{lstlisting}
  7917. \fi}
  7918. \end{exercise}
  7919. {\if\edition\pythonEd
  7920. \section{Prelude and Conclusion}
  7921. \label{sec:prelude-conclusion-cond}
  7922. The generation of the \code{main} function with its prelude and
  7923. conclusion must change to accomodate how the program now consists of
  7924. one or more basic blocks. After the prelude in \code{main}, jump to
  7925. the \code{start} block. Place the conclusion in a basic block labelled
  7926. with \code{conclusion}.
  7927. \fi}
  7928. Figure~\ref{fig:if-example-x86} shows a simple example program in
  7929. \LangIf{} translated to x86, showing the results of
  7930. \code{explicate\_control}, \code{select\_instructions}, and the final
  7931. x86 assembly.
  7932. \begin{figure}[tbp]
  7933. {\if\edition\racketEd
  7934. \begin{tabular}{lll}
  7935. \begin{minipage}{0.4\textwidth}
  7936. % cond_test_20.rkt, eq_input.py
  7937. \begin{lstlisting}
  7938. (if (eq? (read) 1) 42 0)
  7939. \end{lstlisting}
  7940. $\Downarrow$
  7941. \begin{lstlisting}
  7942. start:
  7943. tmp7951 = (read);
  7944. if (eq? tmp7951 1)
  7945. goto block7952;
  7946. else
  7947. goto block7953;
  7948. block7952:
  7949. return 42;
  7950. block7953:
  7951. return 0;
  7952. \end{lstlisting}
  7953. $\Downarrow$
  7954. \begin{lstlisting}
  7955. start:
  7956. callq read_int
  7957. movq %rax, tmp7951
  7958. cmpq $1, tmp7951
  7959. je block7952
  7960. jmp block7953
  7961. block7953:
  7962. movq $0, %rax
  7963. jmp conclusion
  7964. block7952:
  7965. movq $42, %rax
  7966. jmp conclusion
  7967. \end{lstlisting}
  7968. \end{minipage}
  7969. &
  7970. $\Rightarrow\qquad$
  7971. \begin{minipage}{0.4\textwidth}
  7972. \begin{lstlisting}
  7973. start:
  7974. callq read_int
  7975. movq %rax, %rcx
  7976. cmpq $1, %rcx
  7977. je block7952
  7978. jmp block7953
  7979. block7953:
  7980. movq $0, %rax
  7981. jmp conclusion
  7982. block7952:
  7983. movq $42, %rax
  7984. jmp conclusion
  7985. .globl main
  7986. main:
  7987. pushq %rbp
  7988. movq %rsp, %rbp
  7989. pushq %r13
  7990. pushq %r12
  7991. pushq %rbx
  7992. pushq %r14
  7993. subq $0, %rsp
  7994. jmp start
  7995. conclusion:
  7996. addq $0, %rsp
  7997. popq %r14
  7998. popq %rbx
  7999. popq %r12
  8000. popq %r13
  8001. popq %rbp
  8002. retq
  8003. \end{lstlisting}
  8004. \end{minipage}
  8005. \end{tabular}
  8006. \fi}
  8007. {\if\edition\pythonEd
  8008. \begin{tabular}{lll}
  8009. \begin{minipage}{0.4\textwidth}
  8010. % cond_test_20.rkt, eq_input.py
  8011. \begin{lstlisting}
  8012. print(42 if input_int() == 1 else 0)
  8013. \end{lstlisting}
  8014. $\Downarrow$
  8015. \begin{lstlisting}
  8016. start:
  8017. tmp_0 = input_int()
  8018. if tmp_0 == 1:
  8019. goto block_3
  8020. else:
  8021. goto block_4
  8022. block_3:
  8023. tmp_1 = 42
  8024. goto block_2
  8025. block_4:
  8026. tmp_1 = 0
  8027. goto block_2
  8028. block_2:
  8029. print(tmp_1)
  8030. return 0
  8031. \end{lstlisting}
  8032. $\Downarrow$
  8033. \begin{lstlisting}
  8034. start:
  8035. callq read_int
  8036. movq %rax, tmp_0
  8037. cmpq 1, tmp_0
  8038. je block_3
  8039. jmp block_4
  8040. block_3:
  8041. movq 42, tmp_1
  8042. jmp block_2
  8043. block_4:
  8044. movq 0, tmp_1
  8045. jmp block_2
  8046. block_2:
  8047. movq tmp_1, %rdi
  8048. callq print_int
  8049. movq 0, %rax
  8050. jmp conclusion
  8051. \end{lstlisting}
  8052. \end{minipage}
  8053. &
  8054. $\Rightarrow\qquad$
  8055. \begin{minipage}{0.4\textwidth}
  8056. \begin{lstlisting}
  8057. .globl main
  8058. main:
  8059. pushq %rbp
  8060. movq %rsp, %rbp
  8061. subq $0, %rsp
  8062. jmp start
  8063. start:
  8064. callq read_int
  8065. movq %rax, %rcx
  8066. cmpq $1, %rcx
  8067. je block_3
  8068. jmp block_4
  8069. block_3:
  8070. movq $42, %rcx
  8071. jmp block_2
  8072. block_4:
  8073. movq $0, %rcx
  8074. jmp block_2
  8075. block_2:
  8076. movq %rcx, %rdi
  8077. callq print_int
  8078. movq $0, %rax
  8079. jmp conclusion
  8080. conclusion:
  8081. addq $0, %rsp
  8082. popq %rbp
  8083. retq
  8084. \end{lstlisting}
  8085. \end{minipage}
  8086. \end{tabular}
  8087. \fi}
  8088. \caption{Example compilation of an \key{if} expression to x86, showing
  8089. the results of \code{explicate\_control},
  8090. \code{select\_instructions}, and the final x86 assembly code. }
  8091. \label{fig:if-example-x86}
  8092. \end{figure}
  8093. \begin{figure}[tbp]
  8094. {\if\edition\racketEd
  8095. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8096. \node (Lif) at (0,2) {\large \LangIf{}};
  8097. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8098. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8099. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8100. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8101. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8102. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8103. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8104. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8105. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8106. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8107. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8108. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8109. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8110. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8111. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8112. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8113. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8114. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8115. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8116. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8117. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8118. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8119. \end{tikzpicture}
  8120. \fi}
  8121. {\if\edition\pythonEd
  8122. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8123. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8124. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8125. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8126. \node (C-1) at (3,0) {\large \LangCIf{}};
  8127. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8128. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8129. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8130. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8131. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8132. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8133. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8134. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8135. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8136. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8137. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8138. \end{tikzpicture}
  8139. \fi}
  8140. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8141. \label{fig:Lif-passes}
  8142. \end{figure}
  8143. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8144. compilation of \LangIf{}.
  8145. \section{Challenge: Optimize Blocks and Remove Jumps}
  8146. \label{sec:opt-jumps}
  8147. We discuss two optional challenges that involve optimizing the
  8148. control-flow of the program.
  8149. \subsection{Optimize Blocks}
  8150. The algorithm for \code{explicate\_control} that we discussed in
  8151. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8152. blocks. It does so in two different ways.
  8153. %
  8154. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8155. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8156. a new basic block from a single \code{goto} statement, whereas we
  8157. could have simply returned the \code{goto} statement. We can solve
  8158. this problem by modifying the \code{create\_block} function to
  8159. recognize this situation.
  8160. Second, \code{explicate\_control} creates a basic block whenever a
  8161. continuation \emph{might} get used more than once (wheneven a
  8162. continuation is passed into two or more recursive calls). However,
  8163. just because a continuation might get used more than once, doesn't
  8164. mean it will. In fact, some continuation parameters may not be used
  8165. at all because we sometimes ignore them. For example, consider the
  8166. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8167. discard the \code{els} branch. So the question is how can we decide
  8168. whether to create a basic block?
  8169. The solution to this conundrum is to use \emph{lazy
  8170. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8171. to delay creating a basic block until the point in time where we know
  8172. it will be used.
  8173. %
  8174. {\if\edition\racketEd
  8175. %
  8176. Racket provides support for
  8177. lazy evaluation with the
  8178. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8179. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8180. \index{subject}{delay} creates a
  8181. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8182. expressions is postponed. When \key{(force}
  8183. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8184. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8185. result of $e_n$ is cached in the promise and returned. If \code{force}
  8186. is applied again to the same promise, then the cached result is
  8187. returned. If \code{force} is applied to an argument that is not a
  8188. promise, \code{force} simply returns the argument.
  8189. %
  8190. \fi}
  8191. %
  8192. {\if\edition\pythonEd
  8193. %
  8194. While Python does not provide direct support for lazy evaluation, it
  8195. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8196. by wrapping it inside a function with no parameters. We can
  8197. \emph{force} its evaluation by calling the function. However, in some
  8198. cases of \code{explicate\_pred}, etc., we will return a list of
  8199. statements and in other cases we will return a function that computes
  8200. a list of statements. We use the term \emph{promise} to refer to a
  8201. value that may or may not be delayed. To uniformly deal with
  8202. promises, we define the following \code{force} function that checks
  8203. whether its input is delayed (i.e. whether it is a function) and then
  8204. either 1) calls the function, or 2) returns the input.
  8205. \begin{lstlisting}
  8206. def force(promise):
  8207. if isinstance(promise, types.FunctionType):
  8208. return promise()
  8209. else:
  8210. return promise
  8211. \end{lstlisting}
  8212. %
  8213. \fi}
  8214. We use promises for the input and output of the functions
  8215. \code{explicate\_pred}, \code{explicate\_assign},
  8216. %
  8217. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8218. %
  8219. So instead of taking and returning lists of statments, they take and
  8220. return promises. Furthermore, when we come to a situation in which a
  8221. continuation might be used more than once, as in the case for
  8222. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8223. that creates a basic block for each continuation (if there is not
  8224. already one) and then returns a \code{goto} statement to that basic
  8225. block.
  8226. %
  8227. {\if\edition\racketEd
  8228. %
  8229. The following auxiliary function named \code{create\_block} accomplishes
  8230. this task. It begins with \code{delay} to create a promise. When
  8231. forced, this promise will force the original promise. If that returns
  8232. a \code{goto} (because the block was already added to the control-flow
  8233. graph), then we return the \code{goto}. Otherwise we add the block to
  8234. the control-flow graph with another auxiliary function named
  8235. \code{add-node}. That function returns the label for the new block,
  8236. which we use to create a \code{goto}.
  8237. \begin{lstlisting}
  8238. (define (create_block tail)
  8239. (delay
  8240. (define t (force tail))
  8241. (match t
  8242. [(Goto label) (Goto label)]
  8243. [else (Goto (add-node t))])))
  8244. \end{lstlisting}
  8245. \fi}
  8246. {\if\edition\pythonEd
  8247. %
  8248. Here's the new version of the \code{create\_block} auxiliary function
  8249. that works on promises and that checks whether the block consists of a
  8250. solitary \code{goto} statement.\\
  8251. \begin{minipage}{\textwidth}
  8252. \begin{lstlisting}
  8253. def create_block(promise, basic_blocks):
  8254. stmts = force(promise)
  8255. match stmts:
  8256. case [Goto(l)]:
  8257. return Goto(l)
  8258. case _:
  8259. label = label_name(generate_name('block'))
  8260. basic_blocks[label] = stmts
  8261. return Goto(label)
  8262. \end{lstlisting}
  8263. \end{minipage}
  8264. \fi}
  8265. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8266. \code{explicate\_control} on the example of the nested \code{if}
  8267. expressions with the two improvements discussed above. As you can
  8268. see, the number of basic blocks has been reduced from 10 blocks (see
  8269. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8270. \begin{figure}[tbp]
  8271. {\if\edition\racketEd
  8272. \begin{tabular}{lll}
  8273. \begin{minipage}{0.4\textwidth}
  8274. % cond_test_41.rkt
  8275. \begin{lstlisting}
  8276. (let ([x (read)])
  8277. (let ([y (read)])
  8278. (if (if (< x 1)
  8279. (eq? x 0)
  8280. (eq? x 2))
  8281. (+ y 2)
  8282. (+ y 10))))
  8283. \end{lstlisting}
  8284. \end{minipage}
  8285. &
  8286. $\Rightarrow$
  8287. &
  8288. \begin{minipage}{0.55\textwidth}
  8289. \begin{lstlisting}
  8290. start:
  8291. x = (read);
  8292. y = (read);
  8293. if (< x 1) goto block40;
  8294. else goto block41;
  8295. block40:
  8296. if (eq? x 0) goto block38;
  8297. else goto block39;
  8298. block41:
  8299. if (eq? x 2) goto block38;
  8300. else goto block39;
  8301. block38:
  8302. return (+ y 2);
  8303. block39:
  8304. return (+ y 10);
  8305. \end{lstlisting}
  8306. \end{minipage}
  8307. \end{tabular}
  8308. \fi}
  8309. {\if\edition\pythonEd
  8310. \begin{tabular}{lll}
  8311. \begin{minipage}{0.4\textwidth}
  8312. % cond_test_41.rkt
  8313. \begin{lstlisting}
  8314. x = input_int()
  8315. y = input_int()
  8316. print(y + 2 \
  8317. if (x == 0 \
  8318. if x < 1 \
  8319. else x == 2) \
  8320. else y + 10)
  8321. \end{lstlisting}
  8322. \end{minipage}
  8323. &
  8324. $\Rightarrow$
  8325. &
  8326. \begin{minipage}{0.55\textwidth}
  8327. \begin{lstlisting}
  8328. start:
  8329. x = input_int()
  8330. y = input_int()
  8331. if x < 1:
  8332. goto block_4
  8333. else:
  8334. goto block_5
  8335. block_4:
  8336. if x == 0:
  8337. goto block_2
  8338. else:
  8339. goto block_3
  8340. block_5:
  8341. if x == 2:
  8342. goto block_2
  8343. else:
  8344. goto block_3
  8345. block_2:
  8346. tmp_0 = y + 2
  8347. goto block_1
  8348. block_3:
  8349. tmp_0 = y + 10
  8350. goto block_1
  8351. block_1:
  8352. print(tmp_0)
  8353. return 0
  8354. \end{lstlisting}
  8355. \end{minipage}
  8356. \end{tabular}
  8357. \fi}
  8358. \caption{Translation from \LangIf{} to \LangCIf{}
  8359. via the improved \code{explicate\_control}.}
  8360. \label{fig:explicate-control-challenge}
  8361. \end{figure}
  8362. %% Recall that in the example output of \code{explicate\_control} in
  8363. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8364. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8365. %% block. The first goal of this challenge assignment is to remove those
  8366. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8367. %% \code{explicate\_control} on the left and shows the result of bypassing
  8368. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8369. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8370. %% \code{block55}. The optimized code on the right of
  8371. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8372. %% \code{then} branch jumping directly to \code{block55}. The story is
  8373. %% similar for the \code{else} branch, as well as for the two branches in
  8374. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8375. %% have been optimized in this way, there are no longer any jumps to
  8376. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8377. %% \begin{figure}[tbp]
  8378. %% \begin{tabular}{lll}
  8379. %% \begin{minipage}{0.4\textwidth}
  8380. %% \begin{lstlisting}
  8381. %% block62:
  8382. %% tmp54 = (read);
  8383. %% if (eq? tmp54 2) then
  8384. %% goto block59;
  8385. %% else
  8386. %% goto block60;
  8387. %% block61:
  8388. %% tmp53 = (read);
  8389. %% if (eq? tmp53 0) then
  8390. %% goto block57;
  8391. %% else
  8392. %% goto block58;
  8393. %% block60:
  8394. %% goto block56;
  8395. %% block59:
  8396. %% goto block55;
  8397. %% block58:
  8398. %% goto block56;
  8399. %% block57:
  8400. %% goto block55;
  8401. %% block56:
  8402. %% return (+ 700 77);
  8403. %% block55:
  8404. %% return (+ 10 32);
  8405. %% start:
  8406. %% tmp52 = (read);
  8407. %% if (eq? tmp52 1) then
  8408. %% goto block61;
  8409. %% else
  8410. %% goto block62;
  8411. %% \end{lstlisting}
  8412. %% \end{minipage}
  8413. %% &
  8414. %% $\Rightarrow$
  8415. %% &
  8416. %% \begin{minipage}{0.55\textwidth}
  8417. %% \begin{lstlisting}
  8418. %% block62:
  8419. %% tmp54 = (read);
  8420. %% if (eq? tmp54 2) then
  8421. %% goto block55;
  8422. %% else
  8423. %% goto block56;
  8424. %% block61:
  8425. %% tmp53 = (read);
  8426. %% if (eq? tmp53 0) then
  8427. %% goto block55;
  8428. %% else
  8429. %% goto block56;
  8430. %% block56:
  8431. %% return (+ 700 77);
  8432. %% block55:
  8433. %% return (+ 10 32);
  8434. %% start:
  8435. %% tmp52 = (read);
  8436. %% if (eq? tmp52 1) then
  8437. %% goto block61;
  8438. %% else
  8439. %% goto block62;
  8440. %% \end{lstlisting}
  8441. %% \end{minipage}
  8442. %% \end{tabular}
  8443. %% \caption{Optimize jumps by removing trivial blocks.}
  8444. %% \label{fig:optimize-jumps}
  8445. %% \end{figure}
  8446. %% The name of this pass is \code{optimize-jumps}. We recommend
  8447. %% implementing this pass in two phases. The first phrase builds a hash
  8448. %% table that maps labels to possibly improved labels. The second phase
  8449. %% changes the target of each \code{goto} to use the improved label. If
  8450. %% the label is for a trivial block, then the hash table should map the
  8451. %% label to the first non-trivial block that can be reached from this
  8452. %% label by jumping through trivial blocks. If the label is for a
  8453. %% non-trivial block, then the hash table should map the label to itself;
  8454. %% we do not want to change jumps to non-trivial blocks.
  8455. %% The first phase can be accomplished by constructing an empty hash
  8456. %% table, call it \code{short-cut}, and then iterating over the control
  8457. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8458. %% then update the hash table, mapping the block's source to the target
  8459. %% of the \code{goto}. Also, the hash table may already have mapped some
  8460. %% labels to the block's source, to you must iterate through the hash
  8461. %% table and update all of those so that they instead map to the target
  8462. %% of the \code{goto}.
  8463. %% For the second phase, we recommend iterating through the $\Tail$ of
  8464. %% each block in the program, updating the target of every \code{goto}
  8465. %% according to the mapping in \code{short-cut}.
  8466. \begin{exercise}\normalfont
  8467. Implement the improvements to the \code{explicate\_control} pass.
  8468. Check that it removes trivial blocks in a few example programs. Then
  8469. check that your compiler still passes all of your tests.
  8470. \end{exercise}
  8471. \subsection{Remove Jumps}
  8472. There is an opportunity for removing jumps that is apparent in the
  8473. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8474. ends with a jump to \code{block\_4} and there are no other jumps to
  8475. \code{block\_4} in the rest of the program. In this situation we can
  8476. avoid the runtime overhead of this jump by merging \code{block\_4}
  8477. into the preceding block, in this case the \code{start} block.
  8478. Figure~\ref{fig:remove-jumps} shows the output of
  8479. \code{select\_instructions} on the left and the result of this
  8480. optimization on the right.
  8481. \begin{figure}[tbp]
  8482. {\if\edition\racketEd
  8483. \begin{tabular}{lll}
  8484. \begin{minipage}{0.5\textwidth}
  8485. % cond_test_20.rkt
  8486. \begin{lstlisting}
  8487. start:
  8488. callq read_int
  8489. movq %rax, tmp7951
  8490. cmpq $1, tmp7951
  8491. je block7952
  8492. jmp block7953
  8493. block7953:
  8494. movq $0, %rax
  8495. jmp conclusion
  8496. block7952:
  8497. movq $42, %rax
  8498. jmp conclusion
  8499. \end{lstlisting}
  8500. \end{minipage}
  8501. &
  8502. $\Rightarrow\qquad$
  8503. \begin{minipage}{0.4\textwidth}
  8504. \begin{lstlisting}
  8505. start:
  8506. callq read_int
  8507. movq %rax, tmp7951
  8508. cmpq $1, tmp7951
  8509. je block7952
  8510. movq $0, %rax
  8511. jmp conclusion
  8512. block7952:
  8513. movq $42, %rax
  8514. jmp conclusion
  8515. \end{lstlisting}
  8516. \end{minipage}
  8517. \end{tabular}
  8518. \fi}
  8519. {\if\edition\pythonEd
  8520. \begin{tabular}{lll}
  8521. \begin{minipage}{0.5\textwidth}
  8522. % cond_test_20.rkt
  8523. \begin{lstlisting}
  8524. start:
  8525. callq read_int
  8526. movq %rax, tmp_0
  8527. cmpq 1, tmp_0
  8528. je block_3
  8529. jmp block_4
  8530. block_3:
  8531. movq 42, tmp_1
  8532. jmp block_2
  8533. block_4:
  8534. movq 0, tmp_1
  8535. jmp block_2
  8536. block_2:
  8537. movq tmp_1, %rdi
  8538. callq print_int
  8539. movq 0, %rax
  8540. jmp conclusion
  8541. \end{lstlisting}
  8542. \end{minipage}
  8543. &
  8544. $\Rightarrow\qquad$
  8545. \begin{minipage}{0.4\textwidth}
  8546. \begin{lstlisting}
  8547. start:
  8548. callq read_int
  8549. movq %rax, tmp_0
  8550. cmpq 1, tmp_0
  8551. je block_3
  8552. movq 0, tmp_1
  8553. jmp block_2
  8554. block_3:
  8555. movq 42, tmp_1
  8556. jmp block_2
  8557. block_2:
  8558. movq tmp_1, %rdi
  8559. callq print_int
  8560. movq 0, %rax
  8561. jmp conclusion
  8562. \end{lstlisting}
  8563. \end{minipage}
  8564. \end{tabular}
  8565. \fi}
  8566. \caption{Merging basic blocks by removing unnecessary jumps.}
  8567. \label{fig:remove-jumps}
  8568. \end{figure}
  8569. \begin{exercise}\normalfont
  8570. %
  8571. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8572. into their preceding basic block, when there is only one preceding
  8573. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8574. %
  8575. {\if\edition\racketEd
  8576. In the \code{run-tests.rkt} script, add the following entry to the
  8577. list of \code{passes} between \code{allocate\_registers}
  8578. and \code{patch\_instructions}.
  8579. \begin{lstlisting}
  8580. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8581. \end{lstlisting}
  8582. \fi}
  8583. %
  8584. Run the script to test your compiler.
  8585. %
  8586. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8587. blocks on several test programs.
  8588. \end{exercise}
  8589. \section{Further Reading}
  8590. \label{sec:cond-further-reading}
  8591. The algorithm for the \code{explicate\_control} pass is based on the
  8592. the \code{explose-basic-blocks} pass in the course notes of
  8593. \citet{Dybvig:2010aa}.
  8594. %
  8595. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8596. \citet{Appel:2003fk}, and is related to translations into continuation
  8597. passing
  8598. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8599. %
  8600. The treatment of conditionals in the \code{explicate\_control} pass is
  8601. similar to short-cut boolean
  8602. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8603. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8604. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8605. \chapter{Loops and Dataflow Analysis}
  8606. \label{ch:Lwhile}
  8607. % TODO: define R'_8
  8608. % TODO: multi-graph
  8609. {\if\edition\racketEd
  8610. %
  8611. In this chapter we study two features that are the hallmarks of
  8612. imperative programming languages: loops and assignments to local
  8613. variables. The following example demonstrates these new features by
  8614. computing the sum of the first five positive integers.
  8615. % similar to loop_test_1.rkt
  8616. \begin{lstlisting}
  8617. (let ([sum 0])
  8618. (let ([i 5])
  8619. (begin
  8620. (while (> i 0)
  8621. (begin
  8622. (set! sum (+ sum i))
  8623. (set! i (- i 1))))
  8624. sum)))
  8625. \end{lstlisting}
  8626. The \code{while} loop consists of a condition and a
  8627. body\footnote{The \code{while} loop in particular is not a built-in
  8628. feature of the Racket language, but Racket includes many looping
  8629. constructs and it is straightforward to define \code{while} as a
  8630. macro.}. The body is evaluated repeatedly so long as the condition
  8631. remains true.
  8632. %
  8633. The \code{set!} consists of a variable and a right-hand-side
  8634. expression. The \code{set!} updates value of the variable to the
  8635. value of the right-hand-side.
  8636. %
  8637. The primary purpose of both the \code{while} loop and \code{set!} is
  8638. to cause side effects, so they do not have a meaningful result
  8639. value. Instead their result is the \code{\#<void>} value. The
  8640. expression \code{(void)} is an explicit way to create the
  8641. \code{\#<void>} value and it has type \code{Void}. The
  8642. \code{\#<void>} value can be passed around just like other values
  8643. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8644. compared for equality with another \code{\#<void>} value. However,
  8645. there are no other operations specific to the the \code{\#<void>}
  8646. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8647. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8648. \code{\#f} otherwise.
  8649. %
  8650. \footnote{Racket's \code{Void} type corresponds to what is called the
  8651. \code{Unit} type in the programming languages literature. Racket's
  8652. \code{Void} type is inhabited by a single value \code{\#<void>}
  8653. which corresponds to \code{unit} or \code{()} in the
  8654. literature~\citep{Pierce:2002hj}.}.
  8655. %
  8656. With the addition of side-effecting features such as \code{while} loop
  8657. and \code{set!}, it is helpful to also include in a language feature
  8658. for sequencing side effects: the \code{begin} expression. It consists
  8659. of one or more subexpressions that are evaluated left-to-right.
  8660. %
  8661. \fi}
  8662. {\if\edition\pythonEd
  8663. %
  8664. In this chapter we study loops, one of the hallmarks of imperative
  8665. programming languages. The following example demonstrates the
  8666. \code{while} loop by computing the sum of the first five positive
  8667. integers.
  8668. \begin{lstlisting}
  8669. sum = 0
  8670. i = 5
  8671. while i > 0:
  8672. sum = sum + i
  8673. i = i - 1
  8674. print(sum)
  8675. \end{lstlisting}
  8676. The \code{while} loop consists of a condition expression and a body (a
  8677. sequence of statements). The body is evaluated repeatedly so long as
  8678. the condition remains true.
  8679. %
  8680. \fi}
  8681. \section{The \LangLoop{} Language}
  8682. \begin{figure}[tp]
  8683. \centering
  8684. \fbox{
  8685. \begin{minipage}{0.96\textwidth}
  8686. \small
  8687. {\if\edition\racketEd
  8688. \[
  8689. \begin{array}{lcl}
  8690. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  8691. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  8692. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  8693. &\MID& \gray{\itm{bool}
  8694. \MID (\key{and}\;\Exp\;\Exp)
  8695. \MID (\key{or}\;\Exp\;\Exp)
  8696. \MID (\key{not}\;\Exp) } \\
  8697. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  8698. &\MID& \CSETBANG{\Var}{\Exp}
  8699. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8700. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP \\
  8701. \LangLoopM{} &::=& \gray{\Exp}
  8702. \end{array}
  8703. \]
  8704. \fi}
  8705. {\if\edition\pythonEd
  8706. \[
  8707. \begin{array}{rcl}
  8708. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{and} \MID \key{or} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  8709. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  8710. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \CUNIOP{\itm{uniop}}{\Exp} \MID \CBINOP{\itm{binop}}{\Exp}{\Exp} \MID \Var{} \\
  8711. &\MID& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  8712. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \CASSIGN{\Var}{\Exp}
  8713. \MID \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}\\
  8714. &\MID& \key{while}~ \Exp \key{:}~ \Stmt^{+}\\
  8715. \LangLoopM{} &::=& \Stmt^{*}
  8716. \end{array}
  8717. \]
  8718. \fi}
  8719. \end{minipage}
  8720. }
  8721. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8722. \label{fig:Lwhile-concrete-syntax}
  8723. \end{figure}
  8724. \begin{figure}[tp]
  8725. \centering
  8726. \fbox{
  8727. \begin{minipage}{0.96\textwidth}
  8728. \small
  8729. {\if\edition\racketEd
  8730. \[
  8731. \begin{array}{lcl}
  8732. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  8733. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8734. &\MID& \gray{ \BOOL{\itm{bool}}
  8735. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  8736. &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  8737. \MID \WHILE{\Exp}{\Exp} \\
  8738. &\MID& \VOID{} \\
  8739. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  8740. \end{array}
  8741. \]
  8742. \fi}
  8743. {\if\edition\pythonEd
  8744. \[
  8745. \begin{array}{lcl}
  8746. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  8747. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  8748. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8749. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  8750. \itm{bool} &::=& \code{True} \MID \code{False} \\
  8751. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  8752. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  8753. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  8754. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  8755. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  8756. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8757. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  8758. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  8759. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}\\
  8760. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  8761. \end{array}
  8762. \]
  8763. \fi}
  8764. \end{minipage}
  8765. }
  8766. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  8767. \label{fig:Lwhile-syntax}
  8768. \end{figure}
  8769. The concrete syntax of \LangLoop{} is defined in
  8770. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  8771. in Figure~\ref{fig:Lwhile-syntax}.
  8772. %
  8773. The definitional interpreter for \LangLoop{} is shown in
  8774. Figure~\ref{fig:interp-Rwhile}.
  8775. %
  8776. {\if\edition\racketEd
  8777. %
  8778. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  8779. and \code{Void} and we make changes to the cases for \code{Var},
  8780. \code{Let}, and \code{Apply} regarding variables. To support
  8781. assignment to variables and to make their lifetimes indefinite (see
  8782. the second example in Section~\ref{sec:assignment-scoping}), we box
  8783. the value that is bound to each variable (in \code{Let}) and function
  8784. parameter (in \code{Apply}). The case for \code{Var} unboxes the
  8785. value.
  8786. %
  8787. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8788. variable in the environment to obtain a boxed value and then we change
  8789. it using \code{set-box!} to the result of evaluating the right-hand
  8790. side. The result value of a \code{SetBang} is \code{void}.
  8791. %
  8792. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8793. if the result is true, 2) evaluate the body.
  8794. The result value of a \code{while} loop is also \code{void}.
  8795. %
  8796. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8797. subexpressions \itm{es} for their effects and then evaluates
  8798. and returns the result from \itm{body}.
  8799. %
  8800. The $\VOID{}$ expression produces the \code{void} value.
  8801. %
  8802. \fi}
  8803. {\if\edition\pythonEd
  8804. %
  8805. We add a new case for \code{While} in the \code{interp\_stmts}
  8806. function, where we repeatedly interpret the \code{body} so long as the
  8807. \code{test} expression remains true.
  8808. %
  8809. \fi}
  8810. \begin{figure}[tbp]
  8811. {\if\edition\racketEd
  8812. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8813. (define interp-Rwhile_class
  8814. (class interp-Rany_class
  8815. (super-new)
  8816. (define/override ((interp-exp env) e)
  8817. (define recur (interp-exp env))
  8818. (match e
  8819. [(SetBang x rhs)
  8820. (set-box! (lookup x env) (recur rhs))]
  8821. [(WhileLoop cnd body)
  8822. (define (loop)
  8823. (cond [(recur cnd) (recur body) (loop)]
  8824. [else (void)]))
  8825. (loop)]
  8826. [(Begin es body)
  8827. (for ([e es]) (recur e))
  8828. (recur body)]
  8829. [(Void) (void)]
  8830. [else ((super interp-exp env) e)]))
  8831. ))
  8832. (define (interp-Rwhile p)
  8833. (send (new interp-Rwhile_class) interp-program p))
  8834. \end{lstlisting}
  8835. \fi}
  8836. {\if\edition\pythonEd
  8837. \begin{lstlisting}
  8838. class InterpLwhile(InterpLif):
  8839. def interp_stmts(self, ss, env):
  8840. if len(ss) == 0:
  8841. return
  8842. match ss[0]:
  8843. case While(test, body, []):
  8844. while self.interp_exp(test, env):
  8845. self.interp_stmts(body, env)
  8846. return self.interp_stmts(ss[1:], env)
  8847. case _:
  8848. return super().interp_stmts(ss, env)
  8849. \end{lstlisting}
  8850. \fi}
  8851. \caption{Interpreter for \LangLoop{}.}
  8852. \label{fig:interp-Rwhile}
  8853. \end{figure}
  8854. The type checker for \LangLoop{} is defined in
  8855. Figure~\ref{fig:type-check-Rwhile}.
  8856. %
  8857. {\if\edition\racketEd
  8858. %
  8859. For \LangLoop{} we add a type named \code{Void} and the only value of
  8860. this type is the \code{void} value.
  8861. %
  8862. The type checking of the \code{SetBang} expression requires the type of
  8863. the variable and the right-hand-side to agree. The result type is
  8864. \code{Void}. For \code{while}, the condition must be a
  8865. \code{Boolean}. The result type is also \code{Void}. For
  8866. \code{Begin}, the result type is the type of its last subexpression.
  8867. %
  8868. \fi}
  8869. %
  8870. {\if\edition\pythonEd
  8871. %
  8872. A \code{while} loop is well typed if the type of the \code{test}
  8873. expression is \code{bool} and the statements in the \code{body} are
  8874. well typed.
  8875. %
  8876. \fi}
  8877. \begin{figure}[tbp]
  8878. {\if\edition\racketEd
  8879. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8880. (define type-check-Rwhile_class
  8881. (class type-check-Rany_class
  8882. (super-new)
  8883. (inherit check-type-equal?)
  8884. (define/override (type-check-exp env)
  8885. (lambda (e)
  8886. (define recur (type-check-exp env))
  8887. (match e
  8888. [(SetBang x rhs)
  8889. (define-values (rhs^ rhsT) (recur rhs))
  8890. (define varT (dict-ref env x))
  8891. (check-type-equal? rhsT varT e)
  8892. (values (SetBang x rhs^) 'Void)]
  8893. [(WhileLoop cnd body)
  8894. (define-values (cnd^ Tc) (recur cnd))
  8895. (check-type-equal? Tc 'Boolean e)
  8896. (define-values (body^ Tbody) ((type-check-exp env) body))
  8897. (values (WhileLoop cnd^ body^) 'Void)]
  8898. [(Begin es body)
  8899. (define-values (es^ ts)
  8900. (for/lists (l1 l2) ([e es]) (recur e)))
  8901. (define-values (body^ Tbody) (recur body))
  8902. (values (Begin es^ body^) Tbody)]
  8903. [else ((super type-check-exp env) e)])))
  8904. ))
  8905. (define (type-check-Rwhile p)
  8906. (send (new type-check-Rwhile_class) type-check-program p))
  8907. \end{lstlisting}
  8908. \fi}
  8909. {\if\edition\pythonEd
  8910. \begin{lstlisting}
  8911. class TypeCheckLwhile(TypeCheckLif):
  8912. def type_check_stmts(self, ss, env):
  8913. if len(ss) == 0:
  8914. return
  8915. match ss[0]:
  8916. case While(test, body, []):
  8917. test_t = self.type_check_exp(test, env)
  8918. check_type_equal(bool, test_t, test)
  8919. body_t = self.type_check_stmts(body, env)
  8920. return self.type_check_stmts(ss[1:], env)
  8921. case _:
  8922. return super().type_check_stmts(ss, env)
  8923. \end{lstlisting}
  8924. \fi}
  8925. \caption{Type checker for the \LangLoop{} language.}
  8926. \label{fig:type-check-Rwhile}
  8927. \end{figure}
  8928. {\if\edition\racketEd
  8929. %
  8930. At first glance, the translation of these language features to x86
  8931. seems straightforward because the \LangCIf{} intermediate language
  8932. already supports all of the ingredients that we need: assignment,
  8933. \code{goto}, conditional branching, and sequencing. However, there are
  8934. complications that arise which we discuss in the next section. After
  8935. that we introduce the changes necessary to the existing passes.
  8936. %
  8937. \fi}
  8938. {\if\edition\pythonEd
  8939. %
  8940. At first glance, the translation of \code{while} loops to x86 seems
  8941. straightforward because the \LangCIf{} intermediate language already
  8942. supports \code{goto} and conditional branching. However, there are
  8943. complications that arise which we discuss in the next section. After
  8944. that we introduce the changes necessary to the existing passes.
  8945. %
  8946. \fi}
  8947. \section{Cyclic Control Flow and Dataflow Analysis}
  8948. \label{sec:dataflow-analysis}
  8949. Up until this point the control-flow graphs of the programs generated
  8950. in \code{explicate\_control} were guaranteed to be acyclic. However,
  8951. each \code{while} loop introduces a cycle in the control-flow graph.
  8952. But does that matter?
  8953. %
  8954. Indeed it does. Recall that for register allocation, the compiler
  8955. performs liveness analysis to determine which variables can share the
  8956. same register. To accomplish this we analyzed the control-flow graph
  8957. in reverse topological order
  8958. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  8959. only well-defined for acyclic graphs.
  8960. Let us return to the example of computing the sum of the first five
  8961. positive integers. Here is the program after instruction selection but
  8962. before register allocation.
  8963. \begin{center}
  8964. {\if\edition\racketEd
  8965. \begin{minipage}{0.45\textwidth}
  8966. \begin{lstlisting}
  8967. (define (main) : Integer
  8968. mainstart:
  8969. movq $0, sum
  8970. movq $5, i
  8971. jmp block5
  8972. block5:
  8973. movq i, tmp3
  8974. cmpq tmp3, $0
  8975. jl block7
  8976. jmp block8
  8977. \end{lstlisting}
  8978. \end{minipage}
  8979. \begin{minipage}{0.45\textwidth}
  8980. \begin{lstlisting}
  8981. block7:
  8982. addq i, sum
  8983. movq $1, tmp4
  8984. negq tmp4
  8985. addq tmp4, i
  8986. jmp block5
  8987. block8:
  8988. movq $27, %rax
  8989. addq sum, %rax
  8990. jmp mainconclusion
  8991. )
  8992. \end{lstlisting}
  8993. \end{minipage}
  8994. \fi}
  8995. {\if\edition\pythonEd
  8996. \begin{minipage}{0.45\textwidth}
  8997. \begin{lstlisting}
  8998. mainstart:
  8999. movq $0, sum
  9000. movq $5, i
  9001. jmp block5
  9002. block5:
  9003. cmpq $0, i
  9004. jg block7
  9005. jmp block8
  9006. \end{lstlisting}
  9007. \end{minipage}
  9008. \begin{minipage}{0.45\textwidth}
  9009. \begin{lstlisting}
  9010. block7:
  9011. addq i, sum
  9012. subq $1, i
  9013. jmp block5
  9014. block8:
  9015. movq sum, %rdi
  9016. callq print_int
  9017. movq $0, %rax
  9018. jmp mainconclusion
  9019. \end{lstlisting}
  9020. \end{minipage}
  9021. \fi}
  9022. \end{center}
  9023. Recall that liveness analysis works backwards, starting at the end
  9024. of each function. For this example we could start with \code{block8}
  9025. because we know what is live at the beginning of the conclusion,
  9026. just \code{rax} and \code{rsp}. So the live-before set
  9027. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9028. %
  9029. Next we might try to analyze \code{block5} or \code{block7}, but
  9030. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9031. we are stuck.
  9032. The way out of this impasse is to realize that we can compute an
  9033. under-approximation of the live-before set by starting with empty
  9034. live-after sets. By \emph{under-approximation}, we mean that the set
  9035. only contains variables that are live for some execution of the
  9036. program, but the set may be missing some variables. Next, the
  9037. under-approximations for each block can be improved by 1) updating the
  9038. live-after set for each block using the approximate live-before sets
  9039. from the other blocks and 2) perform liveness analysis again on each
  9040. block. In fact, by iterating this process, the under-approximations
  9041. eventually become the correct solutions!
  9042. %
  9043. This approach of iteratively analyzing a control-flow graph is
  9044. applicable to many static analysis problems and goes by the name
  9045. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9046. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9047. Washington.
  9048. Let us apply this approach to the above example. We use the empty set
  9049. for the initial live-before set for each block. Let $m_0$ be the
  9050. following mapping from label names to sets of locations (variables and
  9051. registers).
  9052. \begin{center}
  9053. \begin{lstlisting}
  9054. mainstart: {}, block5: {}, block7: {}, block8: {}
  9055. \end{lstlisting}
  9056. \end{center}
  9057. Using the above live-before approximations, we determine the
  9058. live-after for each block and then apply liveness analysis to each
  9059. block. This produces our next approximation $m_1$ of the live-before
  9060. sets.
  9061. \begin{center}
  9062. \begin{lstlisting}
  9063. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9064. \end{lstlisting}
  9065. \end{center}
  9066. For the second round, the live-after for \code{mainstart} is the
  9067. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9068. liveness analysis for \code{mainstart} computes the empty set. The
  9069. live-after for \code{block5} is the union of the live-before sets for
  9070. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9071. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9072. sum\}}. The live-after for \code{block7} is the live-before for
  9073. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9074. So the liveness analysis for \code{block7} remains \code{\{i,
  9075. sum\}}. Together these yield the following approximation $m_2$ of
  9076. the live-before sets.
  9077. \begin{center}
  9078. \begin{lstlisting}
  9079. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9080. \end{lstlisting}
  9081. \end{center}
  9082. In the preceding iteration, only \code{block5} changed, so we can
  9083. limit our attention to \code{mainstart} and \code{block7}, the two
  9084. blocks that jump to \code{block5}. As a result, the live-before sets
  9085. for \code{mainstart} and \code{block7} are updated to include
  9086. \code{rsp}, yielding the following approximation $m_3$.
  9087. \begin{center}
  9088. \begin{lstlisting}
  9089. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9090. \end{lstlisting}
  9091. \end{center}
  9092. Because \code{block7} changed, we analyze \code{block5} once more, but
  9093. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9094. our approximations have converged, so $m_3$ is the solution.
  9095. This iteration process is guaranteed to converge to a solution by the
  9096. Kleene Fixed-Point Theorem, a general theorem about functions on
  9097. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9098. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9099. elements, a least element $\bot$ (pronounced bottom), and a join
  9100. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9101. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9102. working with join semi-lattices.} When two elements are ordered $m_i
  9103. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9104. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9105. approximation than $m_i$. The bottom element $\bot$ represents the
  9106. complete lack of information, i.e., the worst approximation. The join
  9107. operator takes two lattice elements and combines their information,
  9108. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9109. bound}
  9110. A dataflow analysis typically involves two lattices: one lattice to
  9111. represent abstract states and another lattice that aggregates the
  9112. abstract states of all the blocks in the control-flow graph. For
  9113. liveness analysis, an abstract state is a set of locations. We form
  9114. the lattice $L$ by taking its elements to be sets of locations, the
  9115. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9116. set, and the join operator to be set union.
  9117. %
  9118. We form a second lattice $M$ by taking its elements to be mappings
  9119. from the block labels to sets of locations (elements of $L$). We
  9120. order the mappings point-wise, using the ordering of $L$. So given any
  9121. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9122. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9123. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9124. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9125. We can think of one iteration of liveness analysis applied to the
  9126. whole program as being a function $f$ on the lattice $M$. It takes a
  9127. mapping as input and computes a new mapping.
  9128. \[
  9129. f(m_i) = m_{i+1}
  9130. \]
  9131. Next let us think for a moment about what a final solution $m_s$
  9132. should look like. If we perform liveness analysis using the solution
  9133. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9134. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9135. \[
  9136. f(m_s) = m_s
  9137. \]
  9138. Furthermore, the solution should only include locations that are
  9139. forced to be there by performing liveness analysis on the program, so
  9140. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9141. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9142. monotone (better inputs produce better outputs), then the least fixed
  9143. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9144. chain} obtained by starting at $\bot$ and iterating $f$ as
  9145. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9146. \[
  9147. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9148. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9149. \]
  9150. When a lattice contains only finitely-long ascending chains, then
  9151. every Kleene chain tops out at some fixed point after some number of
  9152. iterations of $f$.
  9153. \[
  9154. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9155. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9156. \]
  9157. The liveness analysis is indeed a monotone function and the lattice
  9158. $M$ only has finitely-long ascending chains because there are only a
  9159. finite number of variables and blocks in the program. Thus we are
  9160. guaranteed that iteratively applying liveness analysis to all blocks
  9161. in the program will eventually produce the least fixed point solution.
  9162. Next let us consider dataflow analysis in general and discuss the
  9163. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9164. %
  9165. The algorithm has four parameters: the control-flow graph \code{G}, a
  9166. function \code{transfer} that applies the analysis to one block, the
  9167. \code{bottom} and \code{join} operator for the lattice of abstract
  9168. states. The algorithm begins by creating the bottom mapping,
  9169. represented by a hash table. It then pushes all of the nodes in the
  9170. control-flow graph onto the work list (a queue). The algorithm repeats
  9171. the \code{while} loop as long as there are items in the work list. In
  9172. each iteration, a node is popped from the work list and processed. The
  9173. \code{input} for the node is computed by taking the join of the
  9174. abstract states of all the predecessor nodes. The \code{transfer}
  9175. function is then applied to obtain the \code{output} abstract
  9176. state. If the output differs from the previous state for this block,
  9177. the mapping for this block is updated and its successor nodes are
  9178. pushed onto the work list.
  9179. Note that the \code{analyze\_dataflow} function is formulated as a
  9180. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9181. function come from the predecessor nodes in the control-flow
  9182. graph. However, liveness analysis is a \emph{backward} dataflow
  9183. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9184. function with the transpose of the control-flow graph.
  9185. \begin{figure}[tb]
  9186. {\if\edition\racketEd
  9187. \begin{lstlisting}
  9188. (define (analyze_dataflow G transfer bottom join)
  9189. (define mapping (make-hash))
  9190. (for ([v (in-vertices G)])
  9191. (dict-set! mapping v bottom))
  9192. (define worklist (make-queue))
  9193. (for ([v (in-vertices G)])
  9194. (enqueue! worklist v))
  9195. (define trans-G (transpose G))
  9196. (while (not (queue-empty? worklist))
  9197. (define node (dequeue! worklist))
  9198. (define input (for/fold ([state bottom])
  9199. ([pred (in-neighbors trans-G node)])
  9200. (join state (dict-ref mapping pred))))
  9201. (define output (transfer node input))
  9202. (cond [(not (equal? output (dict-ref mapping node)))
  9203. (dict-set! mapping node output)
  9204. (for ([v (in-neighbors G node)])
  9205. (enqueue! worklist v))]))
  9206. mapping)
  9207. \end{lstlisting}
  9208. \fi}
  9209. {\if\edition\pythonEd
  9210. \begin{lstlisting}
  9211. def analyze_dataflow(G, transfer, bottom, join):
  9212. trans_G = transpose(G)
  9213. mapping = {}
  9214. for v in G.vertices():
  9215. mapping[v] = bottom
  9216. worklist = deque()
  9217. for v in G.vertices():
  9218. worklist.append(v)
  9219. while worklist:
  9220. node = worklist.pop()
  9221. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9222. output = transfer(node, input)
  9223. if output != mapping[node]:
  9224. mapping[node] = output
  9225. for v in G.adjacent(node):
  9226. worklist.append(v)
  9227. \end{lstlisting}
  9228. \fi}
  9229. \caption{Generic work list algorithm for dataflow analysis}
  9230. \label{fig:generic-dataflow}
  9231. \end{figure}
  9232. {\if\edition\racketEd
  9233. \section{Mutable Variables \& Remove Complex Operands}
  9234. There is a subtle interaction between the addition of \code{set!}, the
  9235. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9236. evaluation of Racket. Consider the following example.
  9237. \begin{lstlisting}
  9238. (let ([x 2])
  9239. (+ x (begin (set! x 40) x)))
  9240. \end{lstlisting}
  9241. The result of this program is \code{42} because the first read from
  9242. \code{x} produces \code{2} and the second produces \code{40}. However,
  9243. if we naively apply the \code{remove\_complex\_operands} pass to this
  9244. example we obtain the following program whose result is \code{80}!
  9245. \begin{lstlisting}
  9246. (let ([x 2])
  9247. (let ([tmp (begin (set! x 40) x)])
  9248. (+ x tmp)))
  9249. \end{lstlisting}
  9250. The problem is that, with mutable variables, the ordering between
  9251. reads and writes is important, and the
  9252. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9253. before the first read of \code{x}.
  9254. We recommend solving this problem by giving special treatment to reads
  9255. from mutable variables, that is, variables that occur on the left-hand
  9256. side of a \code{set!}. We mark each read from a mutable variable with
  9257. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9258. that the read operation is effectful in that it can produce different
  9259. results at different points in time. Let's apply this idea to the
  9260. following variation that also involves a variable that is not mutated.
  9261. % loop_test_24.rkt
  9262. \begin{lstlisting}
  9263. (let ([x 2])
  9264. (let ([y 0])
  9265. (+ y (+ x (begin (set! x 40) x)))))
  9266. \end{lstlisting}
  9267. We analyze the above program to discover that variable \code{x} is
  9268. mutable but \code{y} is not. We then transform the program as follows,
  9269. replacing each occurence of \code{x} with \code{(get! x)}.
  9270. \begin{lstlisting}
  9271. (let ([x 2])
  9272. (let ([y 0])
  9273. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9274. \end{lstlisting}
  9275. Now that we have a clear distinction between reads from mutable and
  9276. immutable variables, we can apply the \code{remove\_complex\_operands}
  9277. pass, where reads from immutable variables are still classified as
  9278. atomic expressions but reads from mutable variables are classified as
  9279. complex. Thus, \code{remove\_complex\_operands} yields the following
  9280. program.
  9281. \begin{lstlisting}
  9282. (let ([x 2])
  9283. (let ([y 0])
  9284. (+ y (let ([t1 (get! x)])
  9285. (let ([t2 (begin (set! x 40) (get! x))])
  9286. (+ t1 t2))))))
  9287. \end{lstlisting}
  9288. The temporary variable \code{t1} gets the value of \code{x} before the
  9289. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9290. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9291. do not generate a temporary variable for the occurence of \code{y}
  9292. because it's an immutable variable. We want to avoid such unnecessary
  9293. extra temporaries because they would needless increase the number of
  9294. variables, making it more likely for some of them to be spilled. The
  9295. result of this program is \code{42}, the same as the result prior to
  9296. \code{remove\_complex\_operands}.
  9297. The approach that we've sketched above requires only a small
  9298. modification to \code{remove\_complex\_operands} to handle
  9299. \code{get!}. However, it requires a new pass, called
  9300. \code{uncover-get!}, that we discuss in
  9301. Section~\ref{sec:uncover-get-bang}.
  9302. As an aside, this problematic interaction between \code{set!} and the
  9303. pass \code{remove\_complex\_operands} is particular to Racket and not
  9304. its predecessor, the Scheme language. The key difference is that
  9305. Scheme does not specify an order of evaluation for the arguments of an
  9306. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9307. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9308. would be correct results for the example program. Interestingly,
  9309. Racket is implemented on top of the Chez Scheme
  9310. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9311. presented in this section (using extra \code{let} bindings to control
  9312. the order of evaluation) is used in the translation from Racket to
  9313. Scheme~\citep{Flatt:2019tb}.
  9314. \fi} % racket
  9315. Having discussed the complications that arise from adding support for
  9316. assignment and loops, we turn to discussing the individual compilation
  9317. passes.
  9318. {\if\edition\racketEd
  9319. \section{Uncover \texttt{get!}}
  9320. \label{sec:uncover-get-bang}
  9321. The goal of this pass it to mark uses of mutable variables so that
  9322. \code{remove\_complex\_operands} can treat them as complex expressions
  9323. and thereby preserve their ordering relative to the side-effects in
  9324. other operands. So the first step is to collect all the mutable
  9325. variables. We recommend creating an auxilliary function for this,
  9326. named \code{collect-set!}, that recursively traverses expressions,
  9327. returning a set of all variables that occur on the left-hand side of a
  9328. \code{set!}. Here's an exerpt of its implementation.
  9329. \begin{center}
  9330. \begin{minipage}{\textwidth}
  9331. \begin{lstlisting}
  9332. (define (collect-set! e)
  9333. (match e
  9334. [(Var x) (set)]
  9335. [(Int n) (set)]
  9336. [(Let x rhs body)
  9337. (set-union (collect-set! rhs) (collect-set! body))]
  9338. [(SetBang var rhs)
  9339. (set-union (set var) (collect-set! rhs))]
  9340. ...))
  9341. \end{lstlisting}
  9342. \end{minipage}
  9343. \end{center}
  9344. By placing this pass after \code{uniquify}, we need not worry about
  9345. variable shadowing and our logic for \code{let} can remain simple, as
  9346. in the exerpt above.
  9347. The second step is to mark the occurences of the mutable variables
  9348. with the new \code{GetBang} AST node (\code{get!} in concrete
  9349. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9350. function, which takes two parameters: the set of mutable varaibles
  9351. \code{set!-vars}, and the expression \code{e} to be processed. The
  9352. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9353. mutable variable or leaves it alone if not.
  9354. \begin{center}
  9355. \begin{minipage}{\textwidth}
  9356. \begin{lstlisting}
  9357. (define ((uncover-get!-exp set!-vars) e)
  9358. (match e
  9359. [(Var x)
  9360. (if (set-member? set!-vars x)
  9361. (GetBang x)
  9362. (Var x))]
  9363. ...))
  9364. \end{lstlisting}
  9365. \end{minipage}
  9366. \end{center}
  9367. To wrap things up, define the \code{uncover-get!} function for
  9368. processing a whole program, using \code{collect-set!} to obtain the
  9369. set of mutable variables and then \code{uncover-get!-exp} to replace
  9370. their occurences with \code{GetBang}.
  9371. \fi}
  9372. \section{Remove Complex Operands}
  9373. \label{sec:rco-loop}
  9374. {\if\edition\racketEd
  9375. %
  9376. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9377. \code{while} are all complex expressions. The subexpressions of
  9378. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9379. %
  9380. \fi}
  9381. {\if\edition\pythonEd
  9382. %
  9383. The change needed for this pass is to add a case for the \code{while}
  9384. statement. The condition of a \code{while} loop is allowed to be a
  9385. complex expression, just like the condition of the \code{if}
  9386. statement.
  9387. %
  9388. \fi}
  9389. %
  9390. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9391. \LangLoopANF{} of this pass.
  9392. \begin{figure}[tp]
  9393. \centering
  9394. \fbox{
  9395. \begin{minipage}{0.96\textwidth}
  9396. \small
  9397. {\if\edition\racketEd
  9398. \[
  9399. \begin{array}{rcl}
  9400. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  9401. \MID \VOID{} } \\
  9402. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9403. &\MID& \GETBANG{\Var}
  9404. \MID \SETBANG{\Var}{\Exp} \\
  9405. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9406. \MID \WHILE{\Exp}{\Exp} \\
  9407. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9408. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9409. \end{array}
  9410. \]
  9411. \fi}
  9412. {\if\edition\pythonEd
  9413. \[
  9414. \begin{array}{rcl}
  9415. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9416. \Exp &::=& \Atm \MID \READ{} \\
  9417. &\MID& \BINOP{\itm{binop}}{\Atm}{\Atm} \MID \UNIOP{\key{uniop}}{\Atm} \\
  9418. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9419. % &\MID& \LET{\Var}{\Exp}{\Exp}\\
  9420. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9421. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9422. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9423. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9424. \end{array}
  9425. \]
  9426. \fi}
  9427. \end{minipage}
  9428. }
  9429. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9430. \label{fig:Rwhile-anf-syntax}
  9431. \end{figure}
  9432. {\if\edition\racketEd
  9433. As usual, when a complex expression appears in a grammar position that
  9434. needs to be atomic, such as the argument of a primitive operator, we
  9435. must introduce a temporary variable and bind it to the complex
  9436. expression. This approach applies, unchanged, to handle the new
  9437. language forms. For example, in the following code there are two
  9438. \code{begin} expressions appearing as arguments to \code{+}. The
  9439. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9440. expressions have been bound to temporary variables. Recall that
  9441. \code{let} expressions in \LangLoopANF{} are allowed to have
  9442. arbitrary expressions in their right-hand-side expression, so it is
  9443. fine to place \code{begin} there.
  9444. \begin{center}
  9445. \begin{minipage}{\textwidth}
  9446. \begin{lstlisting}
  9447. (let ([x0 10])
  9448. (let ([y1 0])
  9449. (+ (+ (begin (set! y1 (read)) x0)
  9450. (begin (set! x0 (read)) y1))
  9451. x0)))
  9452. |$\Rightarrow$|
  9453. (let ([x0 10])
  9454. (let ([y1 0])
  9455. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9456. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9457. (let ([tmp4 (+ tmp2 tmp3)])
  9458. (+ tmp4 x0))))))
  9459. \end{lstlisting}
  9460. \end{minipage}
  9461. \end{center}
  9462. \fi}
  9463. \section{Explicate Control \racket{and \LangCLoop{}}}
  9464. \label{sec:explicate-loop}
  9465. {\if\edition\racketEd
  9466. Recall that in the \code{explicate\_control} pass we define one helper
  9467. function for each kind of position in the program. For the \LangVar{}
  9468. language of integers and variables we needed kinds of positions:
  9469. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9470. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9471. yet another kind of position: effect position. Except for the last
  9472. subexpression, the subexpressions inside a \code{begin} are evaluated
  9473. only for their effect. Their result values are discarded. We can
  9474. generate better code by taking this fact into account.
  9475. The output language of \code{explicate\_control} is \LangCLoop{}
  9476. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9477. \LangCLam{}. The only syntactic difference is that \code{Call} and
  9478. \code{read} may also appear as statements. The most significant
  9479. difference between \LangCLam{} and \LangCLoop{} is that the
  9480. control-flow graphs of the later may contain cycles.
  9481. \begin{figure}[tp]
  9482. \fbox{
  9483. \begin{minipage}{0.96\textwidth}
  9484. \small
  9485. \[
  9486. \begin{array}{lcl}
  9487. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9488. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  9489. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  9490. % &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9491. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9492. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9493. \end{array}
  9494. \]
  9495. \end{minipage}
  9496. }
  9497. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9498. \label{fig:c7-syntax}
  9499. \end{figure}
  9500. The new auxiliary function \code{explicate\_effect} takes an
  9501. expression (in an effect position) and a continuation. The function
  9502. returns a $\Tail$ that includes the generated code for the input
  9503. expression followed by the continuation. If the expression is
  9504. obviously pure, that is, never causes side effects, then the
  9505. expression can be removed, so the result is just the continuation.
  9506. %
  9507. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9508. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9509. the loop. Recursively process the \itm{body} (in effect position)
  9510. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9511. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9512. \itm{body'} as the then-branch and the continuation block as the
  9513. else-branch. The result should be added to the control-flow graph with
  9514. the label \itm{loop}. The result for the whole \code{while} loop is a
  9515. \code{goto} to the \itm{loop} label.
  9516. The auxiliary functions for tail, assignment, and predicate positions
  9517. need to be updated. The three new language forms, \code{while},
  9518. \code{set!}, and \code{begin}, can appear in assignment and tail
  9519. positions. Only \code{begin} may appear in predicate positions; the
  9520. other two have result type \code{Void}.
  9521. \fi}
  9522. %
  9523. {\if\edition\pythonEd
  9524. %
  9525. The output of this pass is the language \LangCIf{}. No new language
  9526. features are needed in the output because a \code{while} loop can be
  9527. expressed in terms of \code{goto} and \code{if} statements, which are
  9528. already in \LangCIf{}.
  9529. %
  9530. Add a case for the \code{while} statement to the
  9531. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9532. the condition expression.
  9533. %
  9534. \fi}
  9535. {\if\edition\racketEd
  9536. \section{Select Instructions}
  9537. \label{sec:select-instructions-loop}
  9538. Only three small additions are needed in the
  9539. \code{select\_instructions} pass to handle the changes to
  9540. \LangCLoop{}. That is, a \code{Call} to \code{read} may now appear as a
  9541. stand-alone statement instead of only appearing on the right-hand
  9542. side of an assignment statement. The code generation is nearly
  9543. identical; just leave off the instruction for moving the result into
  9544. the left-hand side.
  9545. \fi}
  9546. \section{Register Allocation}
  9547. \label{sec:register-allocation-loop}
  9548. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9549. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9550. which complicates the liveness analysis needed for register
  9551. allocation.
  9552. \subsection{Liveness Analysis}
  9553. \label{sec:liveness-analysis-r8}
  9554. We recommend using the generic \code{analyze\_dataflow} function that
  9555. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9556. perform liveness analysis, replacing the code in
  9557. \code{uncover\_live} that processed the basic blocks in topological
  9558. order (Section~\ref{sec:liveness-analysis-Lif}).
  9559. The \code{analyze\_dataflow} function has four parameters.
  9560. \begin{enumerate}
  9561. \item The first parameter \code{G} should be a directed graph from the
  9562. \racket{
  9563. \code{racket/graph} package (see the sidebar in
  9564. Section~\ref{sec:build-interference})}
  9565. \python{\code{graph.py} file in the support code}
  9566. that represents the
  9567. control-flow graph.
  9568. \item The second parameter \code{transfer} is a function that applies
  9569. liveness analysis to a basic block. It takes two parameters: the
  9570. label for the block to analyze and the live-after set for that
  9571. block. The transfer function should return the live-before set for
  9572. the block.
  9573. %
  9574. \racket{Also, as a side-effect, it should update the block's
  9575. $\itm{info}$ with the liveness information for each instruction.}
  9576. %
  9577. \python{Also, as a side-effect, it should update the live-before and
  9578. live-after sets for each instruction.}
  9579. %
  9580. To implement the \code{transfer} function, you should be able to
  9581. reuse the code you already have for analyzing basic blocks.
  9582. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9583. \code{bottom} and \code{join} for the lattice of abstract states,
  9584. i.e. sets of locations. The bottom of the lattice is the empty set
  9585. and the join operator is set union.
  9586. \end{enumerate}
  9587. \begin{figure}[p]
  9588. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9589. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9590. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9591. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9592. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9593. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9594. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9595. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9596. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9597. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9598. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9599. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9600. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9601. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9602. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9603. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9604. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9605. %% \path[->,bend left=15] (Rfun) edge [above] node
  9606. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9607. \path[->,bend left=15] (Rfun) edge [above] node
  9608. {\ttfamily\footnotesize shrink} (Rfun-2);
  9609. \path[->,bend left=15] (Rfun-2) edge [above] node
  9610. {\ttfamily\footnotesize uniquify} (F1-4);
  9611. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9612. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9613. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9614. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9615. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9616. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9617. %% \path[->,bend right=15] (F1-2) edge [above] node
  9618. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9619. %% \path[->,bend right=15] (F1-3) edge [above] node
  9620. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9621. \path[->,bend left=15] (F1-4) edge [above] node
  9622. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9623. \path[->,bend left=15] (F1-5) edge [right] node
  9624. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9625. \path[->,bend left=15] (C3-2) edge [left] node
  9626. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9627. \path[->,bend right=15] (x86-2) edge [left] node
  9628. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9629. \path[->,bend right=15] (x86-2-1) edge [below] node
  9630. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9631. \path[->,bend right=15] (x86-2-2) edge [left] node
  9632. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9633. \path[->,bend left=15] (x86-3) edge [above] node
  9634. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9635. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9636. \end{tikzpicture}
  9637. \caption{Diagram of the passes for \LangLoop{}.}
  9638. \label{fig:Rwhile-passes}
  9639. \end{figure}
  9640. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9641. for the compilation of \LangLoop{}.
  9642. % Further Reading: dataflow analysis
  9643. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9644. \chapter{Tuples and Garbage Collection}
  9645. \label{ch:Lvec}
  9646. \index{subject}{tuple}
  9647. \index{subject}{vector}
  9648. \index{subject}{allocate}
  9649. \index{subject}{heap allocate}
  9650. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9651. %% all the IR grammars are spelled out! \\ --Jeremy}
  9652. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9653. %% the root stack. \\ --Jeremy}
  9654. In this chapter we study the implementation of
  9655. tuples\racket{, called vectors in Racket}.
  9656. %
  9657. This language feature is the first of ours to use the computer's
  9658. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9659. indefinite, that is, a tuple lives forever from the programmer's
  9660. viewpoint. Of course, from an implementer's viewpoint, it is important
  9661. to reclaim the space associated with a tuple when it is no longer
  9662. needed, which is why we also study \emph{garbage collection}
  9663. \index{garbage collection} techniques in this chapter.
  9664. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9665. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9666. language of Chapter~\ref{ch:Lwhile} with tuples.
  9667. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9668. copying live objects back and forth between two halves of the
  9669. heap. The garbage collector requires coordination with the compiler so
  9670. that it can see all of the \emph{root} pointers, that is, pointers in
  9671. registers or on the procedure call stack.
  9672. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9673. discuss all the necessary changes and additions to the compiler
  9674. passes, including a new compiler pass named \code{expose\_allocation}.
  9675. \section{The \LangVec{} Language}
  9676. \label{sec:r3}
  9677. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9678. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9679. %
  9680. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9681. creating a tuple, \code{vector-ref} for reading an element of a
  9682. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9683. \code{vector-length} for obtaining the number of elements of a
  9684. tuple.}
  9685. %
  9686. \python{The \LangVec{} language adds 1) tuple creation via a
  9687. comma-separated list of expressions, 2) accessing an element of a
  9688. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9689. the nth element of the tuple \code{t}, 3) the \code{is} comparison
  9690. operator, and 4) obtaining the number of elements (the length) of a
  9691. tuple.}
  9692. %
  9693. The program below shows an example use of tuples. It creates a 3-tuple
  9694. \code{t} and a 1-tuple that is stored at index $2$ of the 3-tuple,
  9695. demonstrating that tuples are first-class values. The element at
  9696. index $1$ of \code{t} is \racket{\code{\#t}}\python{\code{True}}, so the
  9697. ``then'' branch of the \key{if} is taken. The element at index $0$ of
  9698. \code{t} is \code{40}, to which we add \code{2}, the element at index
  9699. $0$ of the 1-tuple. So the result of the program is \code{42}.
  9700. %
  9701. {\if\edition\racketEd
  9702. \begin{lstlisting}
  9703. (let ([t (vector 40 #t (vector 2))])
  9704. (if (vector-ref t 1)
  9705. (+ (vector-ref t 0)
  9706. (vector-ref (vector-ref t 2) 0))
  9707. 44))
  9708. \end{lstlisting}
  9709. \fi}
  9710. {\if\edition\pythonEd
  9711. \begin{lstlisting}
  9712. t = 40, True, (2,)
  9713. print( t[0] + t[2][0] if t[1] else 44 )
  9714. \end{lstlisting}
  9715. \fi}
  9716. \begin{figure}[tbp]
  9717. \centering
  9718. \fbox{
  9719. \begin{minipage}{0.96\textwidth}
  9720. {\if\edition\racketEd
  9721. \[
  9722. \begin{array}{lcl}
  9723. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  9724. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  9725. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  9726. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  9727. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  9728. \MID \LP\key{and}\;\Exp\;\Exp\RP
  9729. \MID \LP\key{or}\;\Exp\;\Exp\RP
  9730. \MID \LP\key{not}\;\Exp\RP } \\
  9731. &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  9732. \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  9733. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  9734. \MID \CBEGIN{\Exp\ldots}{\Exp}
  9735. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP } \\
  9736. &\MID& \LP\key{vector}\;\Exp\ldots\RP
  9737. \MID \LP\key{vector-length}\;\Exp\RP \\
  9738. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  9739. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  9740. &\MID& \LP\key{has-type}~\Exp~\Type\RP\\
  9741. \LangVecM{} &::=& \Exp
  9742. \end{array}
  9743. \]
  9744. \fi}
  9745. {\if\edition\pythonEd
  9746. \[
  9747. \begin{array}{rcl}
  9748. \itm{binop} &::= & \key{+} \MID \key{-} \MID \key{and} \MID \key{or} \MID \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  9749. \itm{uniop} &::= & \key{-} \MID \key{not} \\
  9750. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \CUNIOP{\itm{uniop}}{\Exp} \MID \CBINOP{\itm{binop}}{\Exp}{\Exp} \MID \Var{} \\
  9751. &\MID& \TRUE \MID \FALSE \MID \CIF{\Exp}{\Exp}{\Exp} \\
  9752. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp} \MID \CLEN{\Exp} \\
  9753. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \CASSIGN{\Var}{\Exp}
  9754. \MID \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}\\
  9755. &\MID& \key{while}~ \Exp \key{:}~ \Stmt^{+}\\
  9756. \LangVecM{} &::=& \Stmt^{*}
  9757. \end{array}
  9758. \]
  9759. \fi}
  9760. \end{minipage}
  9761. }
  9762. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  9763. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  9764. \label{fig:Lvec-concrete-syntax}
  9765. \end{figure}
  9766. \begin{figure}[tp]
  9767. \centering
  9768. \fbox{
  9769. \begin{minipage}{0.96\textwidth}
  9770. {\if\edition\racketEd
  9771. \[
  9772. \begin{array}{lcl}
  9773. \itm{op} &::=& \ldots \MID \code{vector} \MID \code{vector-length} \\
  9774. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  9775. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  9776. \MID \BOOL{\itm{bool}}
  9777. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  9778. &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  9779. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  9780. &\MID& \LP\key{HasType}~\Exp~\Type \RP \\
  9781. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  9782. \end{array}
  9783. \]
  9784. \fi}
  9785. {\if\edition\pythonEd
  9786. \[
  9787. \begin{array}{lcl}
  9788. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  9789. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  9790. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  9791. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  9792. \itm{bool} &::=& \code{True} \MID \code{False} \\
  9793. \Exp &::=& \INT{\Int} \MID \READ{} \MID \VAR{\Var} \\
  9794. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  9795. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  9796. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  9797. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  9798. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9799. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  9800. &\MID& \LEN{\Exp}\\
  9801. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  9802. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9803. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}\\
  9804. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9805. \end{array}
  9806. \]
  9807. \fi}
  9808. \end{minipage}
  9809. }
  9810. \caption{The abstract syntax of \LangVec{}.}
  9811. \label{fig:Lvec-syntax}
  9812. \end{figure}
  9813. Tuples raises several interesting new issues. First, variable binding
  9814. performs a shallow-copy when dealing with tuples, which means that
  9815. different variables can refer to the same tuple, that is, two
  9816. variables can be \emph{aliases}\index{subject}{alias} for the same
  9817. entity. Consider the following example in which both \code{t1} and
  9818. \code{t2} refer to the same tuple value but \code{t3} refers to a
  9819. different tuple value but with equal elements. The result of the
  9820. program is \code{42}.
  9821. \begin{center}
  9822. \begin{minipage}{0.96\textwidth}
  9823. {\if\edition\racketEd
  9824. \begin{lstlisting}
  9825. (let ([t1 (vector 3 7)])
  9826. (let ([t2 t1])
  9827. (let ([t3 (vector 3 7)])
  9828. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  9829. 42
  9830. 0))))
  9831. \end{lstlisting}
  9832. \fi}
  9833. {\if\edition\pythonEd
  9834. \begin{lstlisting}
  9835. t1 = 3, 7
  9836. t2 = t1
  9837. t3 = 3, 7
  9838. print( 42 if (t1 is t2) and not (t1 is t3) else 0)
  9839. \end{lstlisting}
  9840. \fi}
  9841. \end{minipage}
  9842. \end{center}
  9843. {\if\edition\racketEd
  9844. Whether two variables are aliased or not affects what happens
  9845. when the underlying tuple is mutated\index{subject}{mutation}.
  9846. Consider the following example in which \code{t1} and \code{t2}
  9847. again refer to the same tuple value.
  9848. \begin{center}
  9849. \begin{minipage}{0.96\textwidth}
  9850. \begin{lstlisting}
  9851. (let ([t1 (vector 3 7)])
  9852. (let ([t2 t1])
  9853. (let ([_ (vector-set! t2 0 42)])
  9854. (vector-ref t1 0))))
  9855. \end{lstlisting}
  9856. \end{minipage}
  9857. \end{center}
  9858. The mutation through \code{t2} is visible when referencing the tuple
  9859. from \code{t1}, so the result of this program is \code{42}.
  9860. \fi}
  9861. The next issue concerns the lifetime of tuples. When does their
  9862. lifetime end? Notice that \LangVec{} does not include an operation
  9863. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  9864. to any notion of static scoping.
  9865. %
  9866. {\if\edition\racketEd
  9867. %
  9868. For example, the following program returns \code{42} even though the
  9869. variable \code{w} goes out of scope prior to the \code{vector-ref}
  9870. that reads from the vector it was bound to.
  9871. \begin{center}
  9872. \begin{minipage}{0.96\textwidth}
  9873. \begin{lstlisting}
  9874. (let ([v (vector (vector 44))])
  9875. (let ([x (let ([w (vector 42)])
  9876. (let ([_ (vector-set! v 0 w)])
  9877. 0))])
  9878. (+ x (vector-ref (vector-ref v 0) 0))))
  9879. \end{lstlisting}
  9880. \end{minipage}
  9881. \end{center}
  9882. \fi}
  9883. %
  9884. {\if\edition\pythonEd
  9885. %
  9886. For example, the following program returns \code{42} even though the
  9887. variable \code{x} goes out of scope when the function returns, prior
  9888. to reading the tuple element at index zero. (We study the compilation
  9889. of functions in Chapter~\ref{ch:Rfun}.)
  9890. %
  9891. \begin{center}
  9892. \begin{minipage}{0.96\textwidth}
  9893. \begin{lstlisting}
  9894. def f():
  9895. x = 42, 43
  9896. return x
  9897. t = f()
  9898. print( t[0] )
  9899. \end{lstlisting}
  9900. \end{minipage}
  9901. \end{center}
  9902. \fi}
  9903. %
  9904. From the perspective of programmer-observable behavior, tuples live
  9905. forever. Of course, if they really lived forever then many programs
  9906. would run out of memory. The language's runtime system must therefore
  9907. perform automatic garbage collection.
  9908. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  9909. \LangVec{} language.
  9910. %
  9911. \racket{We define the \code{vector}, \code{vector-ref},
  9912. \code{vector-set!}, and \code{vector-length} operations for
  9913. \LangVec{} in terms of the corresponding operations in Racket. One
  9914. subtle point is that the \code{vector-set!} operation returns the
  9915. \code{\#<void>} value.}
  9916. %
  9917. \python{We define tuple creation, element access, and the \code{len}
  9918. operator for \LangVec{} in terms of the corresponding operations in
  9919. Python.}
  9920. \begin{figure}[tbp]
  9921. {\if\edition\racketEd
  9922. \begin{lstlisting}
  9923. (define interp-Lvec_class
  9924. (class interp-Lif_class
  9925. (super-new)
  9926. (define/override (interp-op op)
  9927. (match op
  9928. ['eq? (lambda (v1 v2)
  9929. (cond [(or (and (fixnum? v1) (fixnum? v2))
  9930. (and (boolean? v1) (boolean? v2))
  9931. (and (vector? v1) (vector? v2))
  9932. (and (void? v1) (void? v2)))
  9933. (eq? v1 v2)]))]
  9934. ['vector vector]
  9935. ['vector-length vector-length]
  9936. ['vector-ref vector-ref]
  9937. ['vector-set! vector-set!]
  9938. [else (super interp-op op)]
  9939. ))
  9940. (define/override ((interp-exp env) e)
  9941. (define recur (interp-exp env))
  9942. (match e
  9943. [(HasType e t) (recur e)]
  9944. [(Void) (void)]
  9945. [else ((super interp-exp env) e)]
  9946. ))
  9947. ))
  9948. (define (interp-Lvec p)
  9949. (send (new interp-Lvec_class) interp-program p))
  9950. \end{lstlisting}
  9951. \fi}
  9952. %
  9953. {\if\edition\pythonEd
  9954. \begin{lstlisting}
  9955. class InterpLtup(InterpLwhile):
  9956. def interp_cmp(self, cmp):
  9957. match cmp:
  9958. case Is():
  9959. return lambda x, y: x is y
  9960. case _:
  9961. return super().interp_cmp(cmp)
  9962. def interp_exp(self, e, env):
  9963. match e:
  9964. case Tuple(es, Load()):
  9965. return tuple([self.interp_exp(e, env) for e in es])
  9966. case Subscript(tup, index, Load()):
  9967. t = self.interp_exp(tup, env)
  9968. n = self.interp_exp(index, env)
  9969. return t[n]
  9970. case _:
  9971. return super().interp_exp(e, env)
  9972. \end{lstlisting}
  9973. \fi}
  9974. \caption{Interpreter for the \LangVec{} language.}
  9975. \label{fig:interp-Lvec}
  9976. \end{figure}
  9977. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  9978. \LangVec{}, which deserves some explanation. When allocating a tuple,
  9979. we need to know which elements of the tuple are pointers (i.e. are
  9980. also tuple) for garbage collection purposes. We can obtain this
  9981. information during type checking. The type checker in
  9982. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  9983. expression, it also
  9984. %
  9985. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  9986. where $T$ is the vector's type.
  9987. To create the s-expression for the \code{Vector} type in
  9988. Figure~\ref{fig:type-check-Lvec}, we use the
  9989. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  9990. operator} \code{,@} to insert the list \code{t*} without its usual
  9991. start and end parentheses. \index{subject}{unquote-slicing}}
  9992. %
  9993. \python{records the type of each tuple expression in a new field
  9994. named \code{has\_type}.}
  9995. \begin{figure}[tp]
  9996. {\if\edition\racketEd
  9997. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  9998. (define type-check-Lvec_class
  9999. (class type-check-Lif_class
  10000. (super-new)
  10001. (inherit check-type-equal?)
  10002. (define/override (type-check-exp env)
  10003. (lambda (e)
  10004. (define recur (type-check-exp env))
  10005. (match e
  10006. [(Void) (values (Void) 'Void)]
  10007. [(Prim 'vector es)
  10008. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10009. (define t `(Vector ,@t*))
  10010. (values (HasType (Prim 'vector e*) t) t)]
  10011. [(Prim 'vector-ref (list e1 (Int i)))
  10012. (define-values (e1^ t) (recur e1))
  10013. (match t
  10014. [`(Vector ,ts ...)
  10015. (unless (and (0 . <= . i) (i . < . (length ts)))
  10016. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10017. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10018. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10019. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10020. (define-values (e-vec t-vec) (recur e1))
  10021. (define-values (e-arg^ t-arg) (recur arg))
  10022. (match t-vec
  10023. [`(Vector ,ts ...)
  10024. (unless (and (0 . <= . i) (i . < . (length ts)))
  10025. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10026. (check-type-equal? (list-ref ts i) t-arg e)
  10027. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10028. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10029. [(Prim 'vector-length (list e))
  10030. (define-values (e^ t) (recur e))
  10031. (match t
  10032. [`(Vector ,ts ...)
  10033. (values (Prim 'vector-length (list e^)) 'Integer)]
  10034. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10035. [(Prim 'eq? (list arg1 arg2))
  10036. (define-values (e1 t1) (recur arg1))
  10037. (define-values (e2 t2) (recur arg2))
  10038. (match* (t1 t2)
  10039. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10040. [(other wise) (check-type-equal? t1 t2 e)])
  10041. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10042. [(HasType (Prim 'vector es) t)
  10043. ((type-check-exp env) (Prim 'vector es))]
  10044. [(HasType e1 t)
  10045. (define-values (e1^ t^) (recur e1))
  10046. (check-type-equal? t t^ e)
  10047. (values (HasType e1^ t) t)]
  10048. [else ((super type-check-exp env) e)]
  10049. )))
  10050. ))
  10051. (define (type-check-Lvec p)
  10052. (send (new type-check-Lvec_class) type-check-program p))
  10053. \end{lstlisting}
  10054. \fi}
  10055. {\if\edition\pythonEd
  10056. \begin{lstlisting}
  10057. class TypeCheckLtup(TypeCheckLwhile):
  10058. def type_check_exp(self, e, env):
  10059. match e:
  10060. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10061. l = self.type_check_exp(left, env)
  10062. r = self.type_check_exp(right, env)
  10063. check_type_equal(l, r, e)
  10064. return bool
  10065. case Tuple(es, Load()):
  10066. ts = [self.type_check_exp(e, env) for e in es]
  10067. e.has_type = tuple(ts)
  10068. return e.has_type
  10069. case Subscript(tup, Constant(index), Load()):
  10070. tup_ty = self.type_check_exp(tup, env)
  10071. index_ty = self.type_check_exp(Constant(index), env)
  10072. check_type_equal(index_ty, int, index)
  10073. match tup_ty:
  10074. case tuple(ts):
  10075. return ts[index]
  10076. case _:
  10077. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10078. case _:
  10079. return super().type_check_exp(e, env)
  10080. \end{lstlisting}
  10081. \fi}
  10082. \caption{Type checker for the \LangVec{} language.}
  10083. \label{fig:type-check-Lvec}
  10084. \end{figure}
  10085. \section{Garbage Collection}
  10086. \label{sec:GC}
  10087. Here we study a relatively simple algorithm for garbage collection
  10088. that is the basis of state-of-the-art garbage
  10089. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10090. particular, we describe a two-space copying
  10091. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10092. perform the
  10093. copy~\citep{Cheney:1970aa}.
  10094. \index{subject}{copying collector}
  10095. \index{subject}{two-space copying collector}
  10096. Figure~\ref{fig:copying-collector} gives a
  10097. coarse-grained depiction of what happens in a two-space collector,
  10098. showing two time steps, prior to garbage collection (on the top) and
  10099. after garbage collection (on the bottom). In a two-space collector,
  10100. the heap is divided into two parts named the FromSpace and the
  10101. ToSpace. Initially, all allocations go to the FromSpace until there is
  10102. not enough room for the next allocation request. At that point, the
  10103. garbage collector goes to work to make more room.
  10104. \index{subject}{ToSpace}
  10105. \index{subject}{FromSpace}
  10106. The garbage collector must be careful not to reclaim tuples that will
  10107. be used by the program in the future. Of course, it is impossible in
  10108. general to predict what a program will do, but we can over approximate
  10109. the will-be-used tuples by preserving all tuples that could be
  10110. accessed by \emph{any} program given the current computer state. A
  10111. program could access any tuple whose address is in a register or on
  10112. the procedure call stack. These addresses are called the \emph{root
  10113. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  10114. transitively reachable from the root set. Thus, it is safe for the
  10115. garbage collector to reclaim the tuples that are not reachable in this
  10116. way.
  10117. So the goal of the garbage collector is twofold:
  10118. \begin{enumerate}
  10119. \item preserve all tuple that are reachable from the root set via a
  10120. path of pointers, that is, the \emph{live} tuples, and
  10121. \item reclaim the memory of everything else, that is, the
  10122. \emph{garbage}.
  10123. \end{enumerate}
  10124. A copying collector accomplishes this by copying all of the live
  10125. objects from the FromSpace into the ToSpace and then performs a sleight
  10126. of hand, treating the ToSpace as the new FromSpace and the old
  10127. FromSpace as the new ToSpace. In the example of
  10128. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10129. root set, one in a register and two on the stack. All of the live
  10130. objects have been copied to the ToSpace (the right-hand side of
  10131. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10132. pointer relationships. For example, the pointer in the register still
  10133. points to a 2-tuple whose first element is a 3-tuple and whose second
  10134. element is a 2-tuple. There are four tuples that are not reachable
  10135. from the root set and therefore do not get copied into the ToSpace.
  10136. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10137. created by a well-typed program in \LangVec{} because it contains a
  10138. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  10139. We design the garbage collector to deal with cycles to begin with so
  10140. we will not need to revisit this issue.
  10141. \begin{figure}[tbp]
  10142. \centering
  10143. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  10144. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  10145. \caption{A copying collector in action.}
  10146. \label{fig:copying-collector}
  10147. \end{figure}
  10148. There are many alternatives to copying collectors (and their bigger
  10149. siblings, the generational collectors) when its comes to garbage
  10150. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  10151. reference counting~\citep{Collins:1960aa}. The strengths of copying
  10152. collectors are that allocation is fast (just a comparison and pointer
  10153. increment), there is no fragmentation, cyclic garbage is collected,
  10154. and the time complexity of collection only depends on the amount of
  10155. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  10156. main disadvantages of a two-space copying collector is that it uses a
  10157. lot of space and takes a long time to perform the copy, though these
  10158. problems are ameliorated in generational collectors. Racket and
  10159. Scheme programs tend to allocate many small objects and generate a lot
  10160. of garbage, so copying and generational collectors are a good fit.
  10161. Garbage collection is an active research topic, especially concurrent
  10162. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  10163. developing new techniques and revisiting old
  10164. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  10165. meet every year at the International Symposium on Memory Management to
  10166. present these findings.
  10167. \subsection{Graph Copying via Cheney's Algorithm}
  10168. \label{sec:cheney}
  10169. \index{subject}{Cheney's algorithm}
  10170. Let us take a closer look at the copying of the live objects. The
  10171. allocated objects and pointers can be viewed as a graph and we need to
  10172. copy the part of the graph that is reachable from the root set. To
  10173. make sure we copy all of the reachable vertices in the graph, we need
  10174. an exhaustive graph traversal algorithm, such as depth-first search or
  10175. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10176. such algorithms take into account the possibility of cycles by marking
  10177. which vertices have already been visited, so as to ensure termination
  10178. of the algorithm. These search algorithms also use a data structure
  10179. such as a stack or queue as a to-do list to keep track of the vertices
  10180. that need to be visited. We use breadth-first search and a trick
  10181. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10182. and copying tuples into the ToSpace.
  10183. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10184. copy progresses. The queue is represented by a chunk of contiguous
  10185. memory at the beginning of the ToSpace, using two pointers to track
  10186. the front and the back of the queue. The algorithm starts by copying
  10187. all tuples that are immediately reachable from the root set into the
  10188. ToSpace to form the initial queue. When we copy a tuple, we mark the
  10189. old tuple to indicate that it has been visited. We discuss how this
  10190. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  10191. pointers inside the copied tuples in the queue still point back to the
  10192. FromSpace. Once the initial queue has been created, the algorithm
  10193. enters a loop in which it repeatedly processes the tuple at the front
  10194. of the queue and pops it off the queue. To process a tuple, the
  10195. algorithm copies all the tuple that are directly reachable from it to
  10196. the ToSpace, placing them at the back of the queue. The algorithm then
  10197. updates the pointers in the popped tuple so they point to the newly
  10198. copied tuples.
  10199. \begin{figure}[tbp]
  10200. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  10201. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10202. \label{fig:cheney}
  10203. \end{figure}
  10204. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10205. tuple whose second element is $42$ to the back of the queue. The other
  10206. pointer goes to a tuple that has already been copied, so we do not
  10207. need to copy it again, but we do need to update the pointer to the new
  10208. location. This can be accomplished by storing a \emph{forwarding
  10209. pointer} to the new location in the old tuple, back when we initially
  10210. copied the tuple into the ToSpace. This completes one step of the
  10211. algorithm. The algorithm continues in this way until the front of the
  10212. queue is empty, that is, until the front catches up with the back.
  10213. \subsection{Data Representation}
  10214. \label{sec:data-rep-gc}
  10215. The garbage collector places some requirements on the data
  10216. representations used by our compiler. First, the garbage collector
  10217. needs to distinguish between pointers and other kinds of data. There
  10218. are several ways to accomplish this.
  10219. \begin{enumerate}
  10220. \item Attached a tag to each object that identifies what type of
  10221. object it is~\citep{McCarthy:1960dz}.
  10222. \item Store different types of objects in different
  10223. regions~\citep{Steele:1977ab}.
  10224. \item Use type information from the program to either generate
  10225. type-specific code for collecting or to generate tables that can
  10226. guide the
  10227. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10228. \end{enumerate}
  10229. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10230. need to tag objects anyways, so option 1 is a natural choice for those
  10231. languages. However, \LangVec{} is a statically typed language, so it
  10232. would be unfortunate to require tags on every object, especially small
  10233. and pervasive objects like integers and Booleans. Option 3 is the
  10234. best-performing choice for statically typed languages, but comes with
  10235. a relatively high implementation complexity. To keep this chapter
  10236. within a 2-week time budget, we recommend a combination of options 1
  10237. and 2, using separate strategies for the stack and the heap.
  10238. Regarding the stack, we recommend using a separate stack for pointers,
  10239. which we call a \emph{root stack}\index{subject}{root stack}
  10240. (a.k.a. ``shadow
  10241. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10242. is, when a local variable needs to be spilled and is of type
  10243. \racket{\code{Vector}}\python{\code{tuple}}, then we put it on the
  10244. root stack instead of the normal procedure call stack. Furthermore, we
  10245. always spill tuple-typed variables if they are live during a call to
  10246. the collector, thereby ensuring that no pointers are in registers
  10247. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  10248. example from Figure~\ref{fig:copying-collector} and contrasts it with
  10249. the data layout using a root stack. The root stack contains the two
  10250. pointers from the regular stack and also the pointer in the second
  10251. register.
  10252. \begin{figure}[tbp]
  10253. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  10254. \caption{Maintaining a root stack to facilitate garbage collection.}
  10255. \label{fig:shadow-stack}
  10256. \end{figure}
  10257. The problem of distinguishing between pointers and other kinds of data
  10258. also arises inside of each tuple on the heap. We solve this problem by
  10259. attaching a tag, an extra 64-bits, to each
  10260. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10261. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10262. that we have drawn the bits in a big-endian way, from right-to-left,
  10263. with bit location 0 (the least significant bit) on the far right,
  10264. which corresponds to the direction of the x86 shifting instructions
  10265. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10266. is dedicated to specifying which elements of the tuple are pointers,
  10267. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10268. indicates there is a pointer and a 0 bit indicates some other kind of
  10269. data. The pointer mask starts at bit location 7. We have limited
  10270. tuples to a maximum size of 50 elements, so we just need 50 bits for
  10271. the pointer mask. The tag also contains two other pieces of
  10272. information. The length of the tuple (number of elements) is stored in
  10273. bits location 1 through 6. Finally, the bit at location 0 indicates
  10274. whether the tuple has yet to be copied to the ToSpace. If the bit has
  10275. value 1, then this tuple has not yet been copied. If the bit has
  10276. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  10277. of a pointer are always zero anyways because our tuples are 8-byte
  10278. aligned.)
  10279. \begin{figure}[tbp]
  10280. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10281. \caption{Representation of tuples in the heap.}
  10282. \label{fig:tuple-rep}
  10283. \end{figure}
  10284. \subsection{Implementation of the Garbage Collector}
  10285. \label{sec:organize-gz}
  10286. \index{subject}{prelude}
  10287. An implementation of the copying collector is provided in the
  10288. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10289. interface to the garbage collector that is used by the compiler. The
  10290. \code{initialize} function creates the FromSpace, ToSpace, and root
  10291. stack and should be called in the prelude of the \code{main}
  10292. function. The arguments of \code{initialize} are the root stack size
  10293. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10294. good choice for both. The \code{initialize} function puts the address
  10295. of the beginning of the FromSpace into the global variable
  10296. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10297. the address that is 1-past the last element of the FromSpace. (We use
  10298. half-open intervals to represent chunks of
  10299. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10300. points to the first element of the root stack.
  10301. As long as there is room left in the FromSpace, your generated code
  10302. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10303. %
  10304. The amount of room left in FromSpace is the difference between the
  10305. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10306. function should be called when there is not enough room left in the
  10307. FromSpace for the next allocation. The \code{collect} function takes
  10308. a pointer to the current top of the root stack (one past the last item
  10309. that was pushed) and the number of bytes that need to be
  10310. allocated. The \code{collect} function performs the copying collection
  10311. and leaves the heap in a state such that the next allocation will
  10312. succeed.
  10313. \begin{figure}[tbp]
  10314. \begin{lstlisting}
  10315. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10316. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10317. int64_t* free_ptr;
  10318. int64_t* fromspace_begin;
  10319. int64_t* fromspace_end;
  10320. int64_t** rootstack_begin;
  10321. \end{lstlisting}
  10322. \caption{The compiler's interface to the garbage collector.}
  10323. \label{fig:gc-header}
  10324. \end{figure}
  10325. %% \begin{exercise}
  10326. %% In the file \code{runtime.c} you will find the implementation of
  10327. %% \code{initialize} and a partial implementation of \code{collect}.
  10328. %% The \code{collect} function calls another function, \code{cheney},
  10329. %% to perform the actual copy, and that function is left to the reader
  10330. %% to implement. The following is the prototype for \code{cheney}.
  10331. %% \begin{lstlisting}
  10332. %% static void cheney(int64_t** rootstack_ptr);
  10333. %% \end{lstlisting}
  10334. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10335. %% rootstack (which is an array of pointers). The \code{cheney} function
  10336. %% also communicates with \code{collect} through the global
  10337. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10338. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10339. %% the ToSpace:
  10340. %% \begin{lstlisting}
  10341. %% static int64_t* tospace_begin;
  10342. %% static int64_t* tospace_end;
  10343. %% \end{lstlisting}
  10344. %% The job of the \code{cheney} function is to copy all the live
  10345. %% objects (reachable from the root stack) into the ToSpace, update
  10346. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10347. %% update the root stack so that it points to the objects in the
  10348. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10349. %% and ToSpace.
  10350. %% \end{exercise}
  10351. %% \section{Compiler Passes}
  10352. %% \label{sec:code-generation-gc}
  10353. The introduction of garbage collection has a non-trivial impact on our
  10354. compiler passes. We introduce a new compiler pass named
  10355. \code{expose-allocation}. We make
  10356. significant changes to \code{select\_instructions},
  10357. \code{build\_interference}, \code{allocate\_registers}, and
  10358. \code{print\_x86} and make minor changes in several more passes. The
  10359. following program will serve as our running example. It creates two
  10360. tuples, one nested inside the other. Both tuples have length one. The
  10361. program accesses the element in the inner tuple tuple.
  10362. % tests/vectors_test_17.rkt
  10363. {\if\edition\racketEd
  10364. \begin{lstlisting}
  10365. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10366. \end{lstlisting}
  10367. \fi}
  10368. {\if\edition\pythonEd
  10369. \begin{lstlisting}
  10370. print( ((42,),)[0][0] )
  10371. \end{lstlisting}
  10372. \fi}
  10373. {\if\edition\racketEd
  10374. \section{Shrink}
  10375. \label{sec:shrink-Lvec}
  10376. Recall that the \code{shrink} pass translates the primitives operators
  10377. into a smaller set of primitives. Because this pass comes after type
  10378. checking, but before the passes that require the type information in
  10379. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  10380. to wrap \code{HasType} around each AST node that it generates.
  10381. \fi}
  10382. \section{Expose Allocation}
  10383. \label{sec:expose-allocation}
  10384. The pass \code{expose\_allocation} lowers tuple creation
  10385. into a conditional call to the collector followed by the
  10386. allocation. We choose to place the \code{expose\_allocation} pass
  10387. before \code{remove\_complex\_operands} because the code generated by
  10388. \code{expose\_allocation} contains complex operands.
  10389. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10390. that extends \LangVec{} with new forms that we use in the translation
  10391. of tuple creation.
  10392. %
  10393. {\if\edition\racketEd
  10394. \[
  10395. \begin{array}{lcl}
  10396. \Exp &::=& \cdots
  10397. \MID (\key{collect} \,\itm{int})
  10398. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10399. \MID (\key{global-value} \,\itm{name})
  10400. \end{array}
  10401. \]
  10402. \fi}
  10403. {\if\edition\pythonEd
  10404. \[
  10405. \begin{array}{lcl}
  10406. \Exp &::=& \cdots\\
  10407. &\MID& \key{collect}(\itm{int})
  10408. \MID \key{allocate}(\itm{int},\itm{type})
  10409. \MID \key{global\_value}(\itm{name}) \\
  10410. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp
  10411. \end{array}
  10412. \]
  10413. \fi}
  10414. The \CCOLLECT{$n$} form runs the garbage collector, requesting $n$
  10415. bytes. During instruction selection, it will become a call to the
  10416. \code{collect} function in \code{runtime.c}. The \CALLOCATE{$n$}{$T$}
  10417. form creates a tuple with space for $n$ elements, but they are not
  10418. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10419. of the tuple:
  10420. %
  10421. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10422. %
  10423. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10424. \CGLOBAL{\itm{name}} form reads the value of a global variable, such
  10425. as \code{free\_ptr}.
  10426. %
  10427. \python{The \code{begin} form is an expression that executes a
  10428. sequence of statements and then produces the value of the expression
  10429. at the end.}
  10430. The following shows the transformation of tuple creation into 1) a
  10431. sequence of temporary variables bindings for the initializing
  10432. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10433. \code{allocate}, and 4) the initialization of the vector. The
  10434. \itm{len} placeholder refers to the length of the vector and
  10435. \itm{bytes} is how many total bytes need to be allocated for the
  10436. vector, which is 8 for the tag plus \itm{len} times 8.
  10437. %
  10438. \python{The \itm{type} needed for the second argument of the
  10439. \code{allocate} form can be obtained from the \code{has\_type} field
  10440. of the tuple expression, which is stored there by running the type
  10441. checker for \LangVec{} immediately before this pass.}
  10442. %
  10443. {\if\edition\racketEd
  10444. \begin{lstlisting}
  10445. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10446. |$\Longrightarrow$|
  10447. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10448. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10449. (global-value fromspace_end))
  10450. (void)
  10451. (collect |\itm{bytes}|))])
  10452. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10453. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10454. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10455. |$v$|) ... )))) ...)
  10456. \end{lstlisting}
  10457. \fi}
  10458. {\if\edition\pythonEd
  10459. \begin{lstlisting}
  10460. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10461. |$\Longrightarrow$|
  10462. begin:
  10463. |$x_0$| = |$e_0$|
  10464. |$\vdots$|
  10465. |$x_{n-1}$| = |$e_{n-1}$|
  10466. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10467. 0
  10468. else:
  10469. collect(|\itm{bytes}|)
  10470. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10471. |$v$|[0] = |$x_0$|
  10472. |$\vdots$|
  10473. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10474. |$v$|
  10475. \end{lstlisting}
  10476. \fi}
  10477. %
  10478. \noindent The placement of the initializing expressions
  10479. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10480. those expressions may trigger garbage collection and we cannot have an
  10481. allocated but uninitialized tuple on the heap during a collection.
  10482. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10483. \code{expose\_allocation} pass on our running example.
  10484. \begin{figure}[tbp]
  10485. % tests/s2_17.rkt
  10486. {\if\edition\racketEd
  10487. \begin{lstlisting}
  10488. (vector-ref
  10489. (vector-ref
  10490. (let ([vecinit7976
  10491. (let ([vecinit7972 42])
  10492. (let ([collectret7974
  10493. (if (< (+ (global-value free_ptr) 16)
  10494. (global-value fromspace_end))
  10495. (void)
  10496. (collect 16)
  10497. )])
  10498. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10499. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10500. alloc7971))))])
  10501. (let ([collectret7978
  10502. (if (< (+ (global-value free_ptr) 16)
  10503. (global-value fromspace_end))
  10504. (void)
  10505. (collect 16)
  10506. )])
  10507. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10508. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10509. alloc7975))))
  10510. 0)
  10511. 0)
  10512. \end{lstlisting}
  10513. \fi}
  10514. {\if\edition\pythonEd
  10515. \begin{lstlisting}
  10516. print( |$T_1$|[0][0] )
  10517. \end{lstlisting}
  10518. where $T_1$ is
  10519. \begin{lstlisting}
  10520. begin:
  10521. tmp.1 = |$T_2$|
  10522. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10523. 0
  10524. else:
  10525. collect(16)
  10526. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10527. tmp.2[0] = tmp.1
  10528. tmp.2
  10529. \end{lstlisting}
  10530. and $T_2$ is
  10531. \begin{lstlisting}
  10532. begin:
  10533. tmp.3 = 42
  10534. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10535. 0
  10536. else:
  10537. collect(16)
  10538. tmp.4 = allocate(1, TupleType([int]))
  10539. tmp.4[0] = tmp.3
  10540. tmp.4
  10541. \end{lstlisting}
  10542. \fi}
  10543. \caption{Output of the \code{expose\_allocation} pass.}
  10544. \label{fig:expose-alloc-output}
  10545. \end{figure}
  10546. \section{Remove Complex Operands}
  10547. \label{sec:remove-complex-opera-Lvec}
  10548. {\if\edition\racketEd
  10549. %
  10550. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10551. should be treated as complex operands.
  10552. %
  10553. \fi}
  10554. %
  10555. {\if\edition\pythonEd
  10556. %
  10557. The expressions \code{Allocate}, \code{GlobalValue}, \code{Begin}, and
  10558. \code{Subscript} should be treated as complex operands. The
  10559. sub-expressions of \code{Subscript} must be atomic.
  10560. %
  10561. \fi}
  10562. %% A new case for
  10563. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10564. %% handled carefully to prevent the \code{Prim} node from being separated
  10565. %% from its enclosing \code{HasType}.
  10566. Figure~\ref{fig:Lvec-anf-syntax}
  10567. shows the grammar for the output language \LangVecANF{} of this
  10568. pass, which is \LangVec{} in monadic normal form.
  10569. \begin{figure}[tp]
  10570. \centering
  10571. \fbox{
  10572. \begin{minipage}{0.96\textwidth}
  10573. \small
  10574. {\if\edition\racketEd
  10575. \[
  10576. \begin{array}{rcl}
  10577. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10578. \MID \VOID{} } \\
  10579. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10580. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10581. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10582. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10583. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10584. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10585. \MID \GLOBALVALUE{\Var}\\
  10586. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10587. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10588. \end{array}
  10589. \]
  10590. \fi}
  10591. {\if\edition\pythonEd
  10592. \[
  10593. \begin{array}{lcl}
  10594. \itm{binop} &::=& \code{Add()} \MID \code{Sub()} \\
  10595. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10596. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10597. \itm{uniop} &::=& \code{USub()} \MID \code{Not()} \\
  10598. \itm{bool} &::=& \code{True} \MID \code{False} \\
  10599. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10600. \Exp &::=& \Atm \MID \READ{} \MID \\
  10601. &\MID& \BINOP{\Exp}{\itm{binop}}{\Exp}
  10602. \MID \UNIOP{\itm{uniop}}{\Exp}\\
  10603. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp}
  10604. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  10605. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10606. &\MID& \GET{\Atm}{\Atm} \\
  10607. &\MID& \LEN{\Exp}\\
  10608. &\MID& \ALLOCATE{\Int}{\Type}
  10609. \MID \GLOBALVALUE{\Var}\RP\\
  10610. &\MID& \BEGIN{\Stmt^{*}}{\Exp} \\
  10611. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10612. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10613. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10614. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10615. &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10616. \MID \COLLECT{\Int} \\
  10617. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10618. \end{array}
  10619. \]
  10620. \fi}
  10621. \end{minipage}
  10622. }
  10623. \caption{\LangVecANF{} is \LangVec{} in monadic normal form.}
  10624. \label{fig:Lvec-anf-syntax}
  10625. \end{figure}
  10626. \section{Explicate Control and the \LangCVec{} language}
  10627. \label{sec:explicate-control-r3}
  10628. \begin{figure}[tp]
  10629. \fbox{
  10630. \begin{minipage}{0.96\textwidth}
  10631. \small
  10632. {\if\edition\racketEd
  10633. \[
  10634. \begin{array}{lcl}
  10635. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  10636. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  10637. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  10638. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  10639. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  10640. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10641. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  10642. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  10643. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  10644. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  10645. \MID \LP\key{Collect} \,\itm{int}\RP \\
  10646. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  10647. \MID \GOTO{\itm{label}} } \\
  10648. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10649. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  10650. \end{array}
  10651. \]
  10652. \fi}
  10653. {\if\edition\pythonEd
  10654. \[
  10655. \begin{array}{lcl}
  10656. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10657. \Exp &::= & \Atm \MID \READ{} \\
  10658. &\MID& \BINOP{\Atm}{\itm{binop}}{\Atm}
  10659. \MID \UNIOP{\itm{uniop}}{\Atm} \\
  10660. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm}
  10661. \MID \BOOLOP{\itm{boolop}}{\Atm}{\Atm} \\
  10662. &\MID& \GET{\Atm}{\Atm}
  10663. \MID \ALLOCATE{\Int}{\Type} \MID \GLOBALVALUE{\Var}\RP\\
  10664. &\MID& \LEN{\Atm} \\
  10665. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  10666. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  10667. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  10668. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS} \\
  10669. &\MID& \COLLECT{\Int} \\
  10670. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  10671. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\,\key{:}\,\Stmt^{*}, \ldots \RC}
  10672. \end{array}
  10673. \]
  10674. \fi}
  10675. \end{minipage}
  10676. }
  10677. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  10678. (Figure~\ref{fig:c1-syntax}).}
  10679. \label{fig:c2-syntax}
  10680. \end{figure}
  10681. The output of \code{explicate\_control} is a program in the
  10682. intermediate language \LangCVec{}, whose abstract syntax is defined in
  10683. Figure~\ref{fig:c2-syntax}. \racket{(The concrete syntax is defined
  10684. in Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)} The new
  10685. expressions of \LangCVec{} include \key{allocate},
  10686. %
  10687. \racket{\key{vector-ref}, and \key{vector-set!},}
  10688. %
  10689. \python{accessing tuple elements,}
  10690. %
  10691. and \key{global\_value}.
  10692. %
  10693. \python{It also includes the \code{collect} statment and
  10694. assignment to a tuple element.}
  10695. %
  10696. \racket{It also includes the new \code{collect} statement.}
  10697. %
  10698. The \code{explicate\_control} pass can treat these new forms much like
  10699. the other forms that we've already encoutered.
  10700. \section{Select Instructions and the \LangXGlobal{} Language}
  10701. \label{sec:select-instructions-gc}
  10702. \index{subject}{instruction selection}
  10703. %% void (rep as zero)
  10704. %% allocate
  10705. %% collect (callq collect)
  10706. %% vector-ref
  10707. %% vector-set!
  10708. %% global (postpone)
  10709. In this pass we generate x86 code for most of the new operations that
  10710. were needed to compile tuples, including \code{Allocate},
  10711. \code{Collect}, and accessing tuple elements.
  10712. %
  10713. We compile \code{GlobalValue} to \code{Global} because the later has a
  10714. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  10715. \ref{fig:x86-2}). \index{subject}{x86}
  10716. The tuple read and write forms translate into \code{movq}
  10717. instructions. (The plus one in the offset is to get past the tag at
  10718. the beginning of the tuple representation.)
  10719. %
  10720. \begin{center}
  10721. \begin{minipage}{\textwidth}
  10722. {\if\edition\racketEd
  10723. \begin{lstlisting}
  10724. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  10725. |$\Longrightarrow$|
  10726. movq |$\itm{tup}'$|, %r11
  10727. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10728. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  10729. |$\Longrightarrow$|
  10730. movq |$\itm{tup}'$|, %r11
  10731. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10732. movq $0, |$\itm{lhs'}$|
  10733. \end{lstlisting}
  10734. \fi}
  10735. {\if\edition\pythonEd
  10736. \begin{lstlisting}
  10737. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  10738. |$\Longrightarrow$|
  10739. movq |$\itm{tup}'$|, %r11
  10740. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  10741. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  10742. |$\Longrightarrow$|
  10743. movq |$\itm{tup}'$|, %r11
  10744. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  10745. movq $0, |$\itm{lhs'}$|
  10746. \end{lstlisting}
  10747. \fi}
  10748. \end{minipage}
  10749. \end{center}
  10750. The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$ are obtained by
  10751. translating $\itm{tup}$ and $\itm{rhs}$ to x86. The move of $\itm{tup}'$ to
  10752. register \code{r11} ensures that offset expression
  10753. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  10754. removing \code{r11} from consideration by the register allocating.
  10755. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  10756. \code{rax}. Then the generated code for \code{vector-set!} would be
  10757. \begin{lstlisting}
  10758. movq |$\itm{tup}'$|, %rax
  10759. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  10760. movq $0, |$\itm{lhs}'$|
  10761. \end{lstlisting}
  10762. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  10763. \code{patch\_instructions} would insert a move through \code{rax}
  10764. as follows.
  10765. \begin{lstlisting}
  10766. movq |$\itm{tup}'$|, %rax
  10767. movq |$\itm{rhs}'$|, %rax
  10768. movq %rax, |$8(n+1)$|(%rax)
  10769. movq $0, |$\itm{lhs}'$|
  10770. \end{lstlisting}
  10771. But the above sequence of instructions does not work because we're
  10772. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  10773. $\itm{rhs}'$) at the same time!
  10774. We compile the \code{allocate} form to operations on the
  10775. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  10776. is the next free address in the FromSpace, so we copy it into
  10777. \code{r11} and then move it forward by enough space for the tuple
  10778. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  10779. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  10780. initialize the \itm{tag} and finally copy the address in \code{r11} to
  10781. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  10782. tag is organized.
  10783. %
  10784. \racket{We recommend using the Racket operations
  10785. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  10786. during compilation.}
  10787. %
  10788. The type annotation in the \code{allocate} form is used to determine
  10789. the pointer mask region of the tag.
  10790. %
  10791. {\if\edition\racketEd
  10792. \begin{lstlisting}
  10793. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  10794. |$\Longrightarrow$|
  10795. movq free_ptr(%rip), %r11
  10796. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  10797. movq $|$\itm{tag}$|, 0(%r11)
  10798. movq %r11, |$\itm{lhs}'$|
  10799. \end{lstlisting}
  10800. \fi}
  10801. {\if\edition\pythonEd
  10802. \begin{lstlisting}
  10803. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  10804. |$\Longrightarrow$|
  10805. movq free_ptr(%rip), %r11
  10806. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  10807. movq $|$\itm{tag}$|, 0(%r11)
  10808. movq %r11, |$\itm{lhs}'$|
  10809. \end{lstlisting}
  10810. \fi}
  10811. The \code{collect} form is compiled to a call to the \code{collect}
  10812. function in the runtime. The arguments to \code{collect} are 1) the
  10813. top of the root stack and 2) the number of bytes that need to be
  10814. allocated. We use another dedicated register, \code{r15}, to
  10815. store the pointer to the top of the root stack. So \code{r15} is not
  10816. available for use by the register allocator.
  10817. {\if\edition\racketEd
  10818. \begin{lstlisting}
  10819. (collect |$\itm{bytes}$|)
  10820. |$\Longrightarrow$|
  10821. movq %r15, %rdi
  10822. movq $|\itm{bytes}|, %rsi
  10823. callq collect
  10824. \end{lstlisting}
  10825. \fi}
  10826. {\if\edition\pythonEd
  10827. \begin{lstlisting}
  10828. collect(|$\itm{bytes}$|)
  10829. |$\Longrightarrow$|
  10830. movq %r15, %rdi
  10831. movq $|\itm{bytes}|, %rsi
  10832. callq collect
  10833. \end{lstlisting}
  10834. \fi}
  10835. \begin{figure}[tp]
  10836. \fbox{
  10837. \begin{minipage}{0.96\textwidth}
  10838. \[
  10839. \begin{array}{lcl}
  10840. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  10841. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  10842. & & \gray{ \key{main:} \; \Instr\ldots }
  10843. \end{array}
  10844. \]
  10845. \end{minipage}
  10846. }
  10847. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  10848. \label{fig:x86-2-concrete}
  10849. \end{figure}
  10850. \begin{figure}[tp]
  10851. \fbox{
  10852. \begin{minipage}{0.96\textwidth}
  10853. \small
  10854. \[
  10855. \begin{array}{lcl}
  10856. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  10857. \MID \BYTEREG{\Reg}} \\
  10858. &\MID& \GLOBAL{\Var} \\
  10859. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  10860. \end{array}
  10861. \]
  10862. \end{minipage}
  10863. }
  10864. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  10865. \label{fig:x86-2}
  10866. \end{figure}
  10867. The concrete and abstract syntax of the \LangXGlobal{} language is
  10868. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  10869. differs from \LangXIf{} just in the addition of the form for global
  10870. variables.
  10871. %
  10872. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  10873. \code{select\_instructions} pass on the running example.
  10874. \begin{figure}[tbp]
  10875. \centering
  10876. % tests/s2_17.rkt
  10877. \begin{minipage}[t]{0.5\textwidth}
  10878. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10879. block35:
  10880. movq free_ptr(%rip), alloc9024
  10881. addq $16, free_ptr(%rip)
  10882. movq alloc9024, %r11
  10883. movq $131, 0(%r11)
  10884. movq alloc9024, %r11
  10885. movq vecinit9025, 8(%r11)
  10886. movq $0, initret9026
  10887. movq alloc9024, %r11
  10888. movq 8(%r11), tmp9034
  10889. movq tmp9034, %r11
  10890. movq 8(%r11), %rax
  10891. jmp conclusion
  10892. block36:
  10893. movq $0, collectret9027
  10894. jmp block35
  10895. block38:
  10896. movq free_ptr(%rip), alloc9020
  10897. addq $16, free_ptr(%rip)
  10898. movq alloc9020, %r11
  10899. movq $3, 0(%r11)
  10900. movq alloc9020, %r11
  10901. movq vecinit9021, 8(%r11)
  10902. movq $0, initret9022
  10903. movq alloc9020, vecinit9025
  10904. movq free_ptr(%rip), tmp9031
  10905. movq tmp9031, tmp9032
  10906. addq $16, tmp9032
  10907. movq fromspace_end(%rip), tmp9033
  10908. cmpq tmp9033, tmp9032
  10909. jl block36
  10910. jmp block37
  10911. block37:
  10912. movq %r15, %rdi
  10913. movq $16, %rsi
  10914. callq 'collect
  10915. jmp block35
  10916. block39:
  10917. movq $0, collectret9023
  10918. jmp block38
  10919. \end{lstlisting}
  10920. \end{minipage}
  10921. \begin{minipage}[t]{0.45\textwidth}
  10922. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10923. start:
  10924. movq $42, vecinit9021
  10925. movq free_ptr(%rip), tmp9028
  10926. movq tmp9028, tmp9029
  10927. addq $16, tmp9029
  10928. movq fromspace_end(%rip), tmp9030
  10929. cmpq tmp9030, tmp9029
  10930. jl block39
  10931. jmp block40
  10932. block40:
  10933. movq %r15, %rdi
  10934. movq $16, %rsi
  10935. callq 'collect
  10936. jmp block38
  10937. \end{lstlisting}
  10938. \end{minipage}
  10939. \caption{Output of the \code{select\_instructions} pass.}
  10940. \label{fig:select-instr-output-gc}
  10941. \end{figure}
  10942. \clearpage
  10943. \section{Register Allocation}
  10944. \label{sec:reg-alloc-gc}
  10945. \index{subject}{register allocation}
  10946. As discussed earlier in this chapter, the garbage collector needs to
  10947. access all the pointers in the root set, that is, all variables that
  10948. are tuple. It will be the responsibility of the register allocator
  10949. to make sure that:
  10950. \begin{enumerate}
  10951. \item the root stack is used for spilling tuple-typed variables, and
  10952. \item if a tuple-typed variable is live during a call to the
  10953. collector, it must be spilled to ensure it is visible to the
  10954. collector.
  10955. \end{enumerate}
  10956. The later responsibility can be handled during construction of the
  10957. interference graph, by adding interference edges between the call-live
  10958. tuple-typed variables and all the callee-saved registers. (They
  10959. already interfere with the caller-saved registers.)
  10960. %
  10961. \racket{The type information for variables is in the \code{Program}
  10962. form, so we recommend adding another parameter to the
  10963. \code{build\_interference} function to communicate this alist.}
  10964. %
  10965. \python{The type information for variables is generated by the type
  10966. checker for \LangCVec{}, stored a field named \code{var\_types} in
  10967. the \code{CProgram} AST mode. You'll need to propagate that
  10968. information so that it is available in this pass.}
  10969. The spilling of tuple-typed variables to the root stack can be
  10970. handled after graph coloring, when choosing how to assign the colors
  10971. (integers) to registers and stack locations. The \code{Program} output
  10972. of this pass changes to also record the number of spills to the root
  10973. stack.
  10974. % build-interference
  10975. %
  10976. % callq
  10977. % extra parameter for var->type assoc. list
  10978. % update 'program' and 'if'
  10979. % allocate-registers
  10980. % allocate spilled vectors to the rootstack
  10981. % don't change color-graph
  10982. \section{Generate Prelude and Conclusion}
  10983. \label{sec:print-x86-gc}
  10984. \label{sec:prelude-conclusion-x86-gc}
  10985. \index{subject}{prelude}\index{subject}{conclusion}
  10986. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  10987. \code{prelude\_and\_conclusion} pass on the running example. In the
  10988. prelude and conclusion of the \code{main} function, we treat the root
  10989. stack very much like the regular stack in that we move the root stack
  10990. pointer (\code{r15}) to make room for the spills to the root stack,
  10991. except that the root stack grows up instead of down. For the running
  10992. example, there was just one spill so we increment \code{r15} by 8
  10993. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  10994. One issue that deserves special care is that there may be a call to
  10995. \code{collect} prior to the initializing assignments for all the
  10996. variables in the root stack. We do not want the garbage collector to
  10997. accidentally think that some uninitialized variable is a pointer that
  10998. needs to be followed. Thus, we zero-out all locations on the root
  10999. stack in the prelude of \code{main}. In
  11000. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11001. %
  11002. \lstinline{movq $0, (%r15)}
  11003. %
  11004. accomplishes this task. The garbage collector tests each root to see
  11005. if it is null prior to dereferencing it.
  11006. \begin{figure}[htbp]
  11007. % TODO: Python Version -Jeremy
  11008. \begin{minipage}[t]{0.5\textwidth}
  11009. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11010. block35:
  11011. movq free_ptr(%rip), %rcx
  11012. addq $16, free_ptr(%rip)
  11013. movq %rcx, %r11
  11014. movq $131, 0(%r11)
  11015. movq %rcx, %r11
  11016. movq -8(%r15), %rax
  11017. movq %rax, 8(%r11)
  11018. movq $0, %rdx
  11019. movq %rcx, %r11
  11020. movq 8(%r11), %rcx
  11021. movq %rcx, %r11
  11022. movq 8(%r11), %rax
  11023. jmp conclusion
  11024. block36:
  11025. movq $0, %rcx
  11026. jmp block35
  11027. block38:
  11028. movq free_ptr(%rip), %rcx
  11029. addq $16, free_ptr(%rip)
  11030. movq %rcx, %r11
  11031. movq $3, 0(%r11)
  11032. movq %rcx, %r11
  11033. movq %rbx, 8(%r11)
  11034. movq $0, %rdx
  11035. movq %rcx, -8(%r15)
  11036. movq free_ptr(%rip), %rcx
  11037. addq $16, %rcx
  11038. movq fromspace_end(%rip), %rdx
  11039. cmpq %rdx, %rcx
  11040. jl block36
  11041. movq %r15, %rdi
  11042. movq $16, %rsi
  11043. callq collect
  11044. jmp block35
  11045. block39:
  11046. movq $0, %rcx
  11047. jmp block38
  11048. \end{lstlisting}
  11049. \end{minipage}
  11050. \begin{minipage}[t]{0.45\textwidth}
  11051. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11052. start:
  11053. movq $42, %rbx
  11054. movq free_ptr(%rip), %rdx
  11055. addq $16, %rdx
  11056. movq fromspace_end(%rip), %rcx
  11057. cmpq %rcx, %rdx
  11058. jl block39
  11059. movq %r15, %rdi
  11060. movq $16, %rsi
  11061. callq collect
  11062. jmp block38
  11063. .globl main
  11064. main:
  11065. pushq %rbp
  11066. movq %rsp, %rbp
  11067. pushq %r13
  11068. pushq %r12
  11069. pushq %rbx
  11070. pushq %r14
  11071. subq $0, %rsp
  11072. movq $16384, %rdi
  11073. movq $16384, %rsi
  11074. callq initialize
  11075. movq rootstack_begin(%rip), %r15
  11076. movq $0, (%r15)
  11077. addq $8, %r15
  11078. jmp start
  11079. conclusion:
  11080. subq $8, %r15
  11081. addq $0, %rsp
  11082. popq %r14
  11083. popq %rbx
  11084. popq %r12
  11085. popq %r13
  11086. popq %rbp
  11087. retq
  11088. \end{lstlisting}
  11089. \end{minipage}
  11090. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11091. \label{fig:print-x86-output-gc}
  11092. \end{figure}
  11093. \begin{figure}[p]
  11094. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11095. \node (Lvec) at (0,2) {\large \LangVec{}};
  11096. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11097. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11098. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11099. \node (Lvec-5) at (12,2) {\large \LangAllocANF{}};
  11100. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11101. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11102. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11103. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11104. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11105. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11106. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11107. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11108. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11109. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11110. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11111. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11112. \path[->,bend left=20] (Lvec-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11113. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11114. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11115. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11116. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11117. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11118. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11119. \end{tikzpicture}
  11120. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11121. \label{fig:Lvec-passes}
  11122. \end{figure}
  11123. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11124. for the compilation of \LangVec{}.
  11125. {\if\edition\racketEd
  11126. \section{Challenge: Simple Structures}
  11127. \label{sec:simple-structures}
  11128. \index{subject}{struct}
  11129. \index{subject}{structure}
  11130. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  11131. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  11132. Recall that a \code{struct} in Typed Racket is a user-defined data
  11133. type that contains named fields and that is heap allocated, similar to
  11134. a vector. The following is an example of a structure definition, in
  11135. this case the definition of a \code{point} type.
  11136. \begin{lstlisting}
  11137. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11138. \end{lstlisting}
  11139. \begin{figure}[tbp]
  11140. \centering
  11141. \fbox{
  11142. \begin{minipage}{0.96\textwidth}
  11143. \[
  11144. \begin{array}{lcl}
  11145. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  11146. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  11147. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  11148. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  11149. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  11150. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  11151. \MID (\key{and}\;\Exp\;\Exp)
  11152. \MID (\key{or}\;\Exp\;\Exp)
  11153. \MID (\key{not}\;\Exp) } \\
  11154. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  11155. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  11156. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  11157. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  11158. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  11159. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  11160. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11161. \LangStruct{} &::=& \Def \ldots \; \Exp
  11162. \end{array}
  11163. \]
  11164. \end{minipage}
  11165. }
  11166. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11167. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11168. \label{fig:r3s-concrete-syntax}
  11169. \end{figure}
  11170. An instance of a structure is created using function call syntax, with
  11171. the name of the structure in the function position:
  11172. \begin{lstlisting}
  11173. (point 7 12)
  11174. \end{lstlisting}
  11175. Function-call syntax is also used to read the value in a field of a
  11176. structure. The function name is formed by the structure name, a dash,
  11177. and the field name. The following example uses \code{point-x} and
  11178. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11179. instances.
  11180. \begin{center}
  11181. \begin{lstlisting}
  11182. (let ([pt1 (point 7 12)])
  11183. (let ([pt2 (point 4 3)])
  11184. (+ (- (point-x pt1) (point-x pt2))
  11185. (- (point-y pt1) (point-y pt2)))))
  11186. \end{lstlisting}
  11187. \end{center}
  11188. Similarly, to write to a field of a structure, use its set function,
  11189. whose name starts with \code{set-}, followed by the structure name,
  11190. then a dash, then the field name, and concluded with an exclamation
  11191. mark. The following example uses \code{set-point-x!} to change the
  11192. \code{x} field from \code{7} to \code{42}.
  11193. \begin{center}
  11194. \begin{lstlisting}
  11195. (let ([pt (point 7 12)])
  11196. (let ([_ (set-point-x! pt 42)])
  11197. (point-x pt)))
  11198. \end{lstlisting}
  11199. \end{center}
  11200. \begin{exercise}\normalfont
  11201. Extend your compiler with support for simple structures, compiling
  11202. \LangStruct{} to x86 assembly code. Create five new test cases that use
  11203. structures and test your compiler.
  11204. \end{exercise}
  11205. \section{Challenge: Arrays}
  11206. \label{sec:arrays}
  11207. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11208. elements whose length is determined at compile-time and where each
  11209. element of a tuple may have a different type (they are
  11210. heterogeous). This challenge is also about sequences, but this time
  11211. the length is determined at run-time and all the elements have the same
  11212. type (they are homogeneous). We use the term ``array'' for this later
  11213. kind of sequence.
  11214. The Racket language does not distinguish between tuples and arrays,
  11215. they are both represented by vectors. However, Typed Racket
  11216. distinguishes between tuples and arrays: the \code{Vector} type is for
  11217. tuples and the \code{Vectorof} type is for arrays.
  11218. %
  11219. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11220. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11221. and the \code{make-vector} primitive operator for creating an array,
  11222. whose arguments are the length of the array and an initial value for
  11223. all the elements in the array. The \code{vector-length},
  11224. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11225. for tuples become overloaded for use with arrays.
  11226. %
  11227. We also include integer multiplication in \LangArray{}, as it is
  11228. useful in many examples involving arrays such as computing the
  11229. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11230. \begin{figure}[tp]
  11231. \centering
  11232. \fbox{
  11233. \begin{minipage}{0.96\textwidth}
  11234. \small
  11235. \[
  11236. \begin{array}{lcl}
  11237. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11238. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11239. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11240. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11241. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11242. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11243. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11244. \MID \LP\key{not}\;\Exp\RP } \\
  11245. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11246. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11247. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11248. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11249. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11250. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11251. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11252. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11253. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11254. \MID \CWHILE{\Exp}{\Exp} } \\
  11255. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11256. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11257. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11258. \end{array}
  11259. \]
  11260. \end{minipage}
  11261. }
  11262. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11263. \label{fig:Lvecof-concrete-syntax}
  11264. \end{figure}
  11265. \begin{figure}[tp]
  11266. \begin{lstlisting}
  11267. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11268. [n : Integer]) : Integer
  11269. (let ([i 0])
  11270. (let ([prod 0])
  11271. (begin
  11272. (while (< i n)
  11273. (begin
  11274. (set! prod (+ prod (* (vector-ref A i)
  11275. (vector-ref B i))))
  11276. (set! i (+ i 1))
  11277. ))
  11278. prod))))
  11279. (let ([A (make-vector 2 2)])
  11280. (let ([B (make-vector 2 3)])
  11281. (+ (inner-product A B 2)
  11282. 30)))
  11283. \end{lstlisting}
  11284. \caption{Example program that computes the inner-product.}
  11285. \label{fig:inner-product}
  11286. \end{figure}
  11287. The type checker for \LangArray{} is define in
  11288. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11289. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11290. of the intializing expression. The length expression is required to
  11291. have type \code{Integer}. The type checking of the operators
  11292. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11293. updated to handle the situation where the vector has type
  11294. \code{Vectorof}. In these cases we translate the operators to their
  11295. \code{vectorof} form so that later passes can easily distinguish
  11296. between operations on tuples versus arrays. We override the
  11297. \code{operator-types} method to provide the type signature for
  11298. multiplication: it takes two integers and returns an integer. To
  11299. support injection and projection of arrays to the \code{Any} type
  11300. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11301. predicate.
  11302. \begin{figure}[tbp]
  11303. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11304. (define type-check-Lvecof_class
  11305. (class type-check-Rwhile_class
  11306. (super-new)
  11307. (inherit check-type-equal?)
  11308. (define/override (flat-ty? ty)
  11309. (match ty
  11310. ['(Vectorof Any) #t]
  11311. [else (super flat-ty? ty)]))
  11312. (define/override (operator-types)
  11313. (append '((* . ((Integer Integer) . Integer)))
  11314. (super operator-types)))
  11315. (define/override (type-check-exp env)
  11316. (lambda (e)
  11317. (define recur (type-check-exp env))
  11318. (match e
  11319. [(Prim 'make-vector (list e1 e2))
  11320. (define-values (e1^ t1) (recur e1))
  11321. (define-values (e2^ elt-type) (recur e2))
  11322. (define vec-type `(Vectorof ,elt-type))
  11323. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11324. vec-type)]
  11325. [(Prim 'vector-ref (list e1 e2))
  11326. (define-values (e1^ t1) (recur e1))
  11327. (define-values (e2^ t2) (recur e2))
  11328. (match* (t1 t2)
  11329. [(`(Vectorof ,elt-type) 'Integer)
  11330. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11331. [(other wise) ((super type-check-exp env) e)])]
  11332. [(Prim 'vector-set! (list e1 e2 e3) )
  11333. (define-values (e-vec t-vec) (recur e1))
  11334. (define-values (e2^ t2) (recur e2))
  11335. (define-values (e-arg^ t-arg) (recur e3))
  11336. (match t-vec
  11337. [`(Vectorof ,elt-type)
  11338. (check-type-equal? elt-type t-arg e)
  11339. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11340. [else ((super type-check-exp env) e)])]
  11341. [(Prim 'vector-length (list e1))
  11342. (define-values (e1^ t1) (recur e1))
  11343. (match t1
  11344. [`(Vectorof ,t)
  11345. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11346. [else ((super type-check-exp env) e)])]
  11347. [else ((super type-check-exp env) e)])))
  11348. ))
  11349. (define (type-check-Lvecof p)
  11350. (send (new type-check-Lvecof_class) type-check-program p))
  11351. \end{lstlisting}
  11352. \caption{Type checker for the \LangArray{} language.}
  11353. \label{fig:type-check-Lvecof}
  11354. \end{figure}
  11355. The interpreter for \LangArray{} is defined in
  11356. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11357. implemented with Racket's \code{make-vector} function and
  11358. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11359. integers.
  11360. \begin{figure}[tbp]
  11361. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11362. (define interp-Lvecof_class
  11363. (class interp-Rwhile_class
  11364. (super-new)
  11365. (define/override (interp-op op)
  11366. (verbose "Lvecof/interp-op" op)
  11367. (match op
  11368. ['make-vector make-vector]
  11369. ['* fx*]
  11370. [else (super interp-op op)]))
  11371. ))
  11372. (define (interp-Lvecof p)
  11373. (send (new interp-Lvecof_class) interp-program p))
  11374. \end{lstlisting}
  11375. \caption{Interpreter for \LangArray{}.}
  11376. \label{fig:interp-Lvecof}
  11377. \end{figure}
  11378. \subsection{Data Representation}
  11379. \label{sec:array-rep}
  11380. Just like tuples, we store arrays on the heap which means that the
  11381. garbage collector will need to inspect arrays. An immediate thought is
  11382. to use the same representation for arrays that we use for tuples.
  11383. However, we limit tuples to a length of $50$ so that their length and
  11384. pointer mask can fit into the 64-bit tag at the beginning of each
  11385. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11386. millions of elements, so we need more bits to store the length.
  11387. However, because arrays are homogeneous, we only need $1$ bit for the
  11388. pointer mask instead of one bit per array elements. Finally, the
  11389. garbage collector will need to be able to distinguish between tuples
  11390. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11391. arrive at the following layout for the 64-bit tag at the beginning of
  11392. an array:
  11393. \begin{itemize}
  11394. \item The right-most bit is the forwarding bit, just like in a tuple.
  11395. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11396. it is not.
  11397. \item The next bit to the left is the pointer mask. A $0$ indicates
  11398. that none of the elements are pointers to the heap and a $1$
  11399. indicates that all of the elements are pointers.
  11400. \item The next $61$ bits store the length of the array.
  11401. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11402. array ($1$).
  11403. \end{itemize}
  11404. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  11405. differentiate the kinds of values that have been injected into the
  11406. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11407. to indicate that the value is an array.
  11408. In the following subsections we provide hints regarding how to update
  11409. the passes to handle arrays.
  11410. \subsection{Reveal Casts}
  11411. The array-access operators \code{vectorof-ref} and
  11412. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11413. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  11414. that the type checker cannot tell whether the index will be in bounds,
  11415. so the bounds check must be performed at run time. Recall that the
  11416. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11417. an \code{If} arround a vector reference for update to check whether
  11418. the index is less than the length. You should do the same for
  11419. \code{vectorof-ref} and \code{vectorof-set!} .
  11420. In addition, the handling of the \code{any-vector} operators in
  11421. \code{reveal-casts} needs to be updated to account for arrays that are
  11422. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11423. generated code should test whether the tag is for tuples (\code{010})
  11424. or arrays (\code{110}) and then dispatch to either
  11425. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11426. we add a case in \code{select\_instructions} to generate the
  11427. appropriate instructions for accessing the array length from the
  11428. header of an array.
  11429. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11430. the generated code needs to check that the index is less than the
  11431. vector length, so like the code for \code{any-vector-length}, check
  11432. the tag to determine whether to use \code{any-vector-length} or
  11433. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11434. is complete, the generated code can use \code{any-vector-ref} and
  11435. \code{any-vector-set!} for both tuples and arrays because the
  11436. instructions used for those operators do not look at the tag at the
  11437. front of the tuple or array.
  11438. \subsection{Expose Allocation}
  11439. This pass should translate the \code{make-vector} operator into
  11440. lower-level operations. In particular, the new AST node
  11441. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11442. length specified by the $\Exp$, but does not initialize the elements
  11443. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11444. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11445. element type for the array. Regarding the initialization of the array,
  11446. we recommend generated a \code{while} loop that uses
  11447. \code{vector-set!} to put the initializing value into every element of
  11448. the array.
  11449. \subsection{Remove Complex Operands}
  11450. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11451. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11452. complex and its subexpression must be atomic.
  11453. \subsection{Explicate Control}
  11454. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11455. \code{explicate\_assign}.
  11456. \subsection{Select Instructions}
  11457. Generate instructions for \code{AllocateArray} similar to those for
  11458. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11459. that the tag at the front of the array should instead use the
  11460. representation discussed in Section~\ref{sec:array-rep}.
  11461. Regarding \code{vectorof-length}, extract the length from the tag
  11462. according to the representation discussed in
  11463. Section~\ref{sec:array-rep}.
  11464. The instructions generated for \code{vectorof-ref} differ from those
  11465. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11466. that the index is not a constant so the offset must be computed at
  11467. runtime, similar to the instructions generated for
  11468. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11469. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11470. appear in an assignment and as a stand-alone statement, so make sure
  11471. to handle both situations in this pass.
  11472. Finally, the instructions for \code{any-vectorof-length} should be
  11473. similar to those for \code{vectorof-length}, except that one must
  11474. first project the array by writing zeroes into the $3$-bit tag
  11475. \begin{exercise}\normalfont
  11476. Implement a compiler for the \LangArray{} language by extending your
  11477. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11478. programs, including the one in Figure~\ref{fig:inner-product} and also
  11479. a program that multiplies two matrices. Note that matrices are
  11480. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11481. arrays by laying out each row in the array, one after the next.
  11482. \end{exercise}
  11483. \section{Challenge: Generational Collection}
  11484. The copying collector described in Section~\ref{sec:GC} can incur
  11485. significant runtime overhead because the call to \code{collect} takes
  11486. time proportional to all of the live data. One way to reduce this
  11487. overhead is to reduce how much data is inspected in each call to
  11488. \code{collect}. In particular, researchers have observed that recently
  11489. allocated data is more likely to become garbage then data that has
  11490. survived one or more previous calls to \code{collect}. This insight
  11491. motivated the creation of \emph{generational garbage collectors}
  11492. \index{subject}{generational garbage collector} that
  11493. 1) segregates data according to its age into two or more generations,
  11494. 2) allocates less space for younger generations, so collecting them is
  11495. faster, and more space for the older generations, and 3) performs
  11496. collection on the younger generations more frequently then for older
  11497. generations~\citep{Wilson:1992fk}.
  11498. For this challenge assignment, the goal is to adapt the copying
  11499. collector implemented in \code{runtime.c} to use two generations, one
  11500. for young data and one for old data. Each generation consists of a
  11501. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11502. \code{collect} function to use the two generations.
  11503. \begin{enumerate}
  11504. \item Copy the young generation's FromSpace to its ToSpace then switch
  11505. the role of the ToSpace and FromSpace
  11506. \item If there is enough space for the requested number of bytes in
  11507. the young FromSpace, then return from \code{collect}.
  11508. \item If there is not enough space in the young FromSpace for the
  11509. requested bytes, then move the data from the young generation to the
  11510. old one with the following steps:
  11511. \begin{enumerate}
  11512. \item If there is enough room in the old FromSpace, copy the young
  11513. FromSpace to the old FromSpace and then return.
  11514. \item If there is not enough room in the old FromSpace, then collect
  11515. the old generation by copying the old FromSpace to the old ToSpace
  11516. and swap the roles of the old FromSpace and ToSpace.
  11517. \item If there is enough room now, copy the young FromSpace to the
  11518. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11519. and ToSpace for the old generation. Copy the young FromSpace and
  11520. the old FromSpace into the larger FromSpace for the old
  11521. generation and then return.
  11522. \end{enumerate}
  11523. \end{enumerate}
  11524. We recommend that you generalize the \code{cheney} function so that it
  11525. can be used for all the copies mentioned above: between the young
  11526. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11527. between the young FromSpace and old FromSpace. This can be
  11528. accomplished by adding parameters to \code{cheney} that replace its
  11529. use of the global variables \code{fromspace\_begin},
  11530. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11531. Note that the collection of the young generation does not traverse the
  11532. old generation. This introduces a potential problem: there may be
  11533. young data that is only reachable through pointers in the old
  11534. generation. If these pointers are not taken into account, the
  11535. collector could throw away young data that is live! One solution,
  11536. called \emph{pointer recording}, is to maintain a set of all the
  11537. pointers from the old generation into the new generation and consider
  11538. this set as part of the root set. To maintain this set, the compiler
  11539. must insert extra instructions around every \code{vector-set!}. If the
  11540. vector being modified is in the old generation, and if the value being
  11541. written is a pointer into the new generation, than that pointer must
  11542. be added to the set. Also, if the value being overwritten was a
  11543. pointer into the new generation, then that pointer should be removed
  11544. from the set.
  11545. \begin{exercise}\normalfont
  11546. Adapt the \code{collect} function in \code{runtime.c} to implement
  11547. generational garbage collection, as outlined in this section.
  11548. Update the code generation for \code{vector-set!} to implement
  11549. pointer recording. Make sure that your new compiler and runtime
  11550. passes your test suite.
  11551. \end{exercise}
  11552. \fi}
  11553. % Further Reading
  11554. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11555. \chapter{Functions}
  11556. \label{ch:Rfun}
  11557. \index{subject}{function}
  11558. \if\edition\racketEd
  11559. This chapter studies the compilation of functions similar to those
  11560. found in the C language. This corresponds to a subset of Typed Racket
  11561. in which only top-level function definitions are allowed. This kind of
  11562. function is an important stepping stone to implementing
  11563. lexically-scoped functions, that is, \key{lambda} abstractions, which
  11564. is the topic of Chapter~\ref{ch:Rlam}.
  11565. \section{The \LangFun{} Language}
  11566. The concrete and abstract syntax for function definitions and function
  11567. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11568. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11569. \LangFun{} begin with zero or more function definitions. The function
  11570. names from these definitions are in-scope for the entire program,
  11571. including all other function definitions (so the ordering of function
  11572. definitions does not matter). The concrete syntax for function
  11573. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  11574. where the first expression must
  11575. evaluate to a function and the rest are the arguments.
  11576. The abstract syntax for function application is
  11577. $\APPLY{\Exp}{\Exp\ldots}$.
  11578. %% The syntax for function application does not include an explicit
  11579. %% keyword, which is error prone when using \code{match}. To alleviate
  11580. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  11581. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  11582. Functions are first-class in the sense that a function pointer
  11583. \index{subject}{function pointer} is data and can be stored in memory or passed
  11584. as a parameter to another function. Thus, we introduce a function
  11585. type, written
  11586. \begin{lstlisting}
  11587. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  11588. \end{lstlisting}
  11589. for a function whose $n$ parameters have the types $\Type_1$ through
  11590. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  11591. these functions (with respect to Racket functions) is that they are
  11592. not lexically scoped. That is, the only external entities that can be
  11593. referenced from inside a function body are other globally-defined
  11594. functions. The syntax of \LangFun{} prevents functions from being nested
  11595. inside each other.
  11596. \begin{figure}[tp]
  11597. \centering
  11598. \fbox{
  11599. \begin{minipage}{0.96\textwidth}
  11600. \small
  11601. \[
  11602. \begin{array}{lcl}
  11603. \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  11604. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  11605. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  11606. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11607. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11608. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  11609. \MID (\key{and}\;\Exp\;\Exp)
  11610. \MID (\key{or}\;\Exp\;\Exp)
  11611. \MID (\key{not}\;\Exp)} \\
  11612. &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11613. &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  11614. (\key{vector-ref}\;\Exp\;\Int)} \\
  11615. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11616. \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  11617. &\MID& \LP\Exp \; \Exp \ldots\RP \\
  11618. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  11619. \LangFunM{} &::=& \Def \ldots \; \Exp
  11620. \end{array}
  11621. \]
  11622. \end{minipage}
  11623. }
  11624. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11625. \label{fig:Rfun-concrete-syntax}
  11626. \end{figure}
  11627. \begin{figure}[tp]
  11628. \centering
  11629. \fbox{
  11630. \begin{minipage}{0.96\textwidth}
  11631. \small
  11632. \[
  11633. \begin{array}{lcl}
  11634. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11635. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11636. &\MID& \gray{ \BOOL{\itm{bool}}
  11637. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11638. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  11639. \MID \APPLY{\Exp}{\Exp\ldots}\\
  11640. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  11641. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11642. \end{array}
  11643. \]
  11644. \end{minipage}
  11645. }
  11646. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  11647. \label{fig:Rfun-syntax}
  11648. \end{figure}
  11649. The program in Figure~\ref{fig:Rfun-function-example} is a
  11650. representative example of defining and using functions in \LangFun{}. We
  11651. define a function \code{map-vec} that applies some other function
  11652. \code{f} to both elements of a vector and returns a new
  11653. vector containing the results. We also define a function \code{add1}.
  11654. The program applies
  11655. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  11656. \code{(vector 1 42)}, from which we return the \code{42}.
  11657. \begin{figure}[tbp]
  11658. \begin{lstlisting}
  11659. (define (map-vec [f : (Integer -> Integer)]
  11660. [v : (Vector Integer Integer)])
  11661. : (Vector Integer Integer)
  11662. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11663. (define (add1 [x : Integer]) : Integer
  11664. (+ x 1))
  11665. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11666. \end{lstlisting}
  11667. \caption{Example of using functions in \LangFun{}.}
  11668. \label{fig:Rfun-function-example}
  11669. \end{figure}
  11670. The definitional interpreter for \LangFun{} is in
  11671. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  11672. responsible for setting up the mutual recursion between the top-level
  11673. function definitions. We use the classic back-patching \index{subject}{back-patching}
  11674. approach that uses mutable variables and makes two passes over the function
  11675. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  11676. top-level environment using a mutable cons cell for each function
  11677. definition. Note that the \code{lambda} value for each function is
  11678. incomplete; it does not yet include the environment. Once the
  11679. top-level environment is constructed, we then iterate over it and
  11680. update the \code{lambda} values to use the top-level environment.
  11681. \begin{figure}[tp]
  11682. \begin{lstlisting}
  11683. (define interp-Rfun_class
  11684. (class interp-Lvec_class
  11685. (super-new)
  11686. (define/override ((interp-exp env) e)
  11687. (define recur (interp-exp env))
  11688. (match e
  11689. [(Var x) (unbox (dict-ref env x))]
  11690. [(Let x e body)
  11691. (define new-env (dict-set env x (box (recur e))))
  11692. ((interp-exp new-env) body)]
  11693. [(Apply fun args)
  11694. (define fun-val (recur fun))
  11695. (define arg-vals (for/list ([e args]) (recur e)))
  11696. (match fun-val
  11697. [`(function (,xs ...) ,body ,fun-env)
  11698. (define params-args (for/list ([x xs] [arg arg-vals])
  11699. (cons x (box arg))))
  11700. (define new-env (append params-args fun-env))
  11701. ((interp-exp new-env) body)]
  11702. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  11703. [else ((super interp-exp env) e)]
  11704. ))
  11705. (define/public (interp-def d)
  11706. (match d
  11707. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  11708. (cons f (box `(function ,xs ,body ())))]))
  11709. (define/override (interp-program p)
  11710. (match p
  11711. [(ProgramDefsExp info ds body)
  11712. (let ([top-level (for/list ([d ds]) (interp-def d))])
  11713. (for/list ([f (in-dict-values top-level)])
  11714. (set-box! f (match (unbox f)
  11715. [`(function ,xs ,body ())
  11716. `(function ,xs ,body ,top-level)])))
  11717. ((interp-exp top-level) body))]))
  11718. ))
  11719. (define (interp-Rfun p)
  11720. (send (new interp-Rfun_class) interp-program p))
  11721. \end{lstlisting}
  11722. \caption{Interpreter for the \LangFun{} language.}
  11723. \label{fig:interp-Rfun}
  11724. \end{figure}
  11725. %\margincomment{TODO: explain type checker}
  11726. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  11727. \begin{figure}[tp]
  11728. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11729. (define type-check-Rfun_class
  11730. (class type-check-Lvec_class
  11731. (super-new)
  11732. (inherit check-type-equal?)
  11733. (define/public (type-check-apply env e es)
  11734. (define-values (e^ ty) ((type-check-exp env) e))
  11735. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  11736. ((type-check-exp env) e)))
  11737. (match ty
  11738. [`(,ty^* ... -> ,rt)
  11739. (for ([arg-ty ty*] [param-ty ty^*])
  11740. (check-type-equal? arg-ty param-ty (Apply e es)))
  11741. (values e^ e* rt)]))
  11742. (define/override (type-check-exp env)
  11743. (lambda (e)
  11744. (match e
  11745. [(FunRef f)
  11746. (values (FunRef f) (dict-ref env f))]
  11747. [(Apply e es)
  11748. (define-values (e^ es^ rt) (type-check-apply env e es))
  11749. (values (Apply e^ es^) rt)]
  11750. [(Call e es)
  11751. (define-values (e^ es^ rt) (type-check-apply env e es))
  11752. (values (Call e^ es^) rt)]
  11753. [else ((super type-check-exp env) e)])))
  11754. (define/public (type-check-def env)
  11755. (lambda (e)
  11756. (match e
  11757. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  11758. (define new-env (append (map cons xs ps) env))
  11759. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11760. (check-type-equal? ty^ rt body)
  11761. (Def f p:t* rt info body^)])))
  11762. (define/public (fun-def-type d)
  11763. (match d
  11764. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  11765. (define/override (type-check-program e)
  11766. (match e
  11767. [(ProgramDefsExp info ds body)
  11768. (define new-env (for/list ([d ds])
  11769. (cons (Def-name d) (fun-def-type d))))
  11770. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  11771. (define-values (body^ ty) ((type-check-exp new-env) body))
  11772. (check-type-equal? ty 'Integer body)
  11773. (ProgramDefsExp info ds^ body^)]))))
  11774. (define (type-check-Rfun p)
  11775. (send (new type-check-Rfun_class) type-check-program p))
  11776. \end{lstlisting}
  11777. \caption{Type checker for the \LangFun{} language.}
  11778. \label{fig:type-check-Rfun}
  11779. \end{figure}
  11780. \section{Functions in x86}
  11781. \label{sec:fun-x86}
  11782. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  11783. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  11784. %% \margincomment{\tiny Talk about the return address on the
  11785. %% stack and what callq and retq does.\\ --Jeremy }
  11786. The x86 architecture provides a few features to support the
  11787. implementation of functions. We have already seen that x86 provides
  11788. labels so that one can refer to the location of an instruction, as is
  11789. needed for jump instructions. Labels can also be used to mark the
  11790. beginning of the instructions for a function. Going further, we can
  11791. obtain the address of a label by using the \key{leaq} instruction and
  11792. PC-relative addressing. For example, the following puts the
  11793. address of the \code{add1} label into the \code{rbx} register.
  11794. \begin{lstlisting}
  11795. leaq add1(%rip), %rbx
  11796. \end{lstlisting}
  11797. The instruction pointer register \key{rip} (aka. the program counter
  11798. \index{subject}{program counter}) always points to the next instruction to be
  11799. executed. When combined with an label, as in \code{add1(\%rip)}, the
  11800. linker computes the distance $d$ between the address of \code{add1}
  11801. and where the \code{rip} would be at that moment and then changes
  11802. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  11803. the address of \code{add1}.
  11804. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  11805. jump to a function whose location is given by a label. To support
  11806. function calls in this chapter we instead will be jumping to a
  11807. function whose location is given by an address in a register, that is,
  11808. we need to make an \emph{indirect function call}. The x86 syntax for
  11809. this is a \code{callq} instruction but with an asterisk before the
  11810. register name.\index{subject}{indirect function call}
  11811. \begin{lstlisting}
  11812. callq *%rbx
  11813. \end{lstlisting}
  11814. \subsection{Calling Conventions}
  11815. \index{subject}{calling conventions}
  11816. The \code{callq} instruction provides partial support for implementing
  11817. functions: it pushes the return address on the stack and it jumps to
  11818. the target. However, \code{callq} does not handle
  11819. \begin{enumerate}
  11820. \item parameter passing,
  11821. \item pushing frames on the procedure call stack and popping them off,
  11822. or
  11823. \item determining how registers are shared by different functions.
  11824. \end{enumerate}
  11825. Regarding (1) parameter passing, recall that the following six
  11826. registers are used to pass arguments to a function, in this order.
  11827. \begin{lstlisting}
  11828. rdi rsi rdx rcx r8 r9
  11829. \end{lstlisting}
  11830. If there are
  11831. more than six arguments, then the convention is to use space on the
  11832. frame of the caller for the rest of the arguments. However, to ease
  11833. the implementation of efficient tail calls
  11834. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  11835. arguments.
  11836. %
  11837. Also recall that the register \code{rax} is for the return value of
  11838. the function.
  11839. \index{subject}{prelude}\index{subject}{conclusion}
  11840. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  11841. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  11842. the stack grows down, with each function call using a chunk of space
  11843. called a frame. The caller sets the stack pointer, register
  11844. \code{rsp}, to the last data item in its frame. The callee must not
  11845. change anything in the caller's frame, that is, anything that is at or
  11846. above the stack pointer. The callee is free to use locations that are
  11847. below the stack pointer.
  11848. Recall that we are storing variables of vector type on the root stack.
  11849. So the prelude needs to move the root stack pointer \code{r15} up and
  11850. the conclusion needs to move the root stack pointer back down. Also,
  11851. the prelude must initialize to \code{0} this frame's slots in the root
  11852. stack to signal to the garbage collector that those slots do not yet
  11853. contain a pointer to a vector. Otherwise the garbage collector will
  11854. interpret the garbage bits in those slots as memory addresses and try
  11855. to traverse them, causing serious mayhem!
  11856. Regarding (3) the sharing of registers between different functions,
  11857. recall from Section~\ref{sec:calling-conventions} that the registers
  11858. are divided into two groups, the caller-saved registers and the
  11859. callee-saved registers. The caller should assume that all the
  11860. caller-saved registers get overwritten with arbitrary values by the
  11861. callee. That is why we recommend in
  11862. Section~\ref{sec:calling-conventions} that variables that are live
  11863. during a function call should not be assigned to caller-saved
  11864. registers.
  11865. On the flip side, if the callee wants to use a callee-saved register,
  11866. the callee must save the contents of those registers on their stack
  11867. frame and then put them back prior to returning to the caller. That
  11868. is why we recommended in Section~\ref{sec:calling-conventions} that if
  11869. the register allocator assigns a variable to a callee-saved register,
  11870. then the prelude of the \code{main} function must save that register
  11871. to the stack and the conclusion of \code{main} must restore it. This
  11872. recommendation now generalizes to all functions.
  11873. Also recall that the base pointer, register \code{rbp}, is used as a
  11874. point-of-reference within a frame, so that each local variable can be
  11875. accessed at a fixed offset from the base pointer
  11876. (Section~\ref{sec:x86}).
  11877. %
  11878. Figure~\ref{fig:call-frames} shows the general layout of the caller
  11879. and callee frames.
  11880. \begin{figure}[tbp]
  11881. \centering
  11882. \begin{tabular}{r|r|l|l} \hline
  11883. Caller View & Callee View & Contents & Frame \\ \hline
  11884. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  11885. 0(\key{\%rbp}) & & old \key{rbp} \\
  11886. -8(\key{\%rbp}) & & callee-saved $1$ \\
  11887. \ldots & & \ldots \\
  11888. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  11889. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  11890. \ldots & & \ldots \\
  11891. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  11892. %% & & \\
  11893. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  11894. %% & \ldots & \ldots \\
  11895. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  11896. \hline
  11897. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  11898. & 0(\key{\%rbp}) & old \key{rbp} \\
  11899. & -8(\key{\%rbp}) & callee-saved $1$ \\
  11900. & \ldots & \ldots \\
  11901. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  11902. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  11903. & \ldots & \ldots \\
  11904. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  11905. \end{tabular}
  11906. \caption{Memory layout of caller and callee frames.}
  11907. \label{fig:call-frames}
  11908. \end{figure}
  11909. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  11910. %% local variables and for storing the values of callee-saved registers
  11911. %% (we shall refer to all of these collectively as ``locals''), and that
  11912. %% at the beginning of a function we move the stack pointer \code{rsp}
  11913. %% down to make room for them.
  11914. %% We recommend storing the local variables
  11915. %% first and then the callee-saved registers, so that the local variables
  11916. %% can be accessed using \code{rbp} the same as before the addition of
  11917. %% functions.
  11918. %% To make additional room for passing arguments, we shall
  11919. %% move the stack pointer even further down. We count how many stack
  11920. %% arguments are needed for each function call that occurs inside the
  11921. %% body of the function and find their maximum. Adding this number to the
  11922. %% number of locals gives us how much the \code{rsp} should be moved at
  11923. %% the beginning of the function. In preparation for a function call, we
  11924. %% offset from \code{rsp} to set up the stack arguments. We put the first
  11925. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  11926. %% so on.
  11927. %% Upon calling the function, the stack arguments are retrieved by the
  11928. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  11929. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  11930. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  11931. %% the layout of the caller and callee frames. Notice how important it is
  11932. %% that we correctly compute the maximum number of arguments needed for
  11933. %% function calls; if that number is too small then the arguments and
  11934. %% local variables will smash into each other!
  11935. \subsection{Efficient Tail Calls}
  11936. \label{sec:tail-call}
  11937. In general, the amount of stack space used by a program is determined
  11938. by the longest chain of nested function calls. That is, if function
  11939. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  11940. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  11941. $n$ can grow quite large in the case of recursive or mutually
  11942. recursive functions. However, in some cases we can arrange to use only
  11943. constant space, i.e. $O(1)$, instead of $O(n)$.
  11944. If a function call is the last action in a function body, then that
  11945. call is said to be a \emph{tail call}\index{subject}{tail call}.
  11946. For example, in the following
  11947. program, the recursive call to \code{tail-sum} is a tail call.
  11948. \begin{center}
  11949. \begin{lstlisting}
  11950. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  11951. (if (eq? n 0)
  11952. r
  11953. (tail-sum (- n 1) (+ n r))))
  11954. (+ (tail-sum 5 0) 27)
  11955. \end{lstlisting}
  11956. \end{center}
  11957. At a tail call, the frame of the caller is no longer needed, so we
  11958. can pop the caller's frame before making the tail call. With this
  11959. approach, a recursive function that only makes tail calls will only
  11960. use $O(1)$ stack space. Functional languages like Racket typically
  11961. rely heavily on recursive functions, so they typically guarantee that
  11962. all tail calls will be optimized in this way.
  11963. \index{subject}{frame}
  11964. However, some care is needed with regards to argument passing in tail
  11965. calls. As mentioned above, for arguments beyond the sixth, the
  11966. convention is to use space in the caller's frame for passing
  11967. arguments. But for a tail call we pop the caller's frame and can no
  11968. longer use it. Another alternative is to use space in the callee's
  11969. frame for passing arguments. However, this option is also problematic
  11970. because the caller and callee's frame overlap in memory. As we begin
  11971. to copy the arguments from their sources in the caller's frame, the
  11972. target locations in the callee's frame might overlap with the sources
  11973. for later arguments! We solve this problem by using the heap instead
  11974. of the stack for passing more than six arguments, as we describe in
  11975. the Section~\ref{sec:limit-functions-r4}.
  11976. As mentioned above, for a tail call we pop the caller's frame prior to
  11977. making the tail call. The instructions for popping a frame are the
  11978. instructions that we usually place in the conclusion of a
  11979. function. Thus, we also need to place such code immediately before
  11980. each tail call. These instructions include restoring the callee-saved
  11981. registers, so it is good that the argument passing registers are all
  11982. caller-saved registers.
  11983. One last note regarding which instruction to use to make the tail
  11984. call. When the callee is finished, it should not return to the current
  11985. function, but it should return to the function that called the current
  11986. one. Thus, the return address that is already on the stack is the
  11987. right one, and we should not use \key{callq} to make the tail call, as
  11988. that would unnecessarily overwrite the return address. Instead we can
  11989. simply use the \key{jmp} instruction. Like the indirect function call,
  11990. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  11991. prefixed with an asterisk. We recommend using \code{rax} to hold the
  11992. jump target because the preceding conclusion overwrites just about
  11993. everything else.
  11994. \begin{lstlisting}
  11995. jmp *%rax
  11996. \end{lstlisting}
  11997. \section{Shrink \LangFun{}}
  11998. \label{sec:shrink-r4}
  11999. The \code{shrink} pass performs a minor modification to ease the
  12000. later passes. This pass introduces an explicit \code{main} function
  12001. and changes the top \code{ProgramDefsExp} form to
  12002. \code{ProgramDefs} as follows.
  12003. \begin{lstlisting}
  12004. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12005. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12006. \end{lstlisting}
  12007. where $\itm{mainDef}$ is
  12008. \begin{lstlisting}
  12009. (Def 'main '() 'Integer '() |$\Exp'$|)
  12010. \end{lstlisting}
  12011. \section{Reveal Functions and the \LangFunRef{} language}
  12012. \label{sec:reveal-functions-r4}
  12013. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  12014. respect: it conflates the use of function names and local
  12015. variables. This is a problem because we need to compile the use of a
  12016. function name differently than the use of a local variable; we need to
  12017. use \code{leaq} to convert the function name (a label in x86) to an
  12018. address in a register. Thus, it is a good idea to create a new pass
  12019. that changes function references from just a symbol $f$ to
  12020. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  12021. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  12022. The concrete syntax for a function reference is $\CFUNREF{f}$.
  12023. \begin{figure}[tp]
  12024. \centering
  12025. \fbox{
  12026. \begin{minipage}{0.96\textwidth}
  12027. \[
  12028. \begin{array}{lcl}
  12029. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  12030. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12031. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12032. \end{array}
  12033. \]
  12034. \end{minipage}
  12035. }
  12036. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12037. (Figure~\ref{fig:Rfun-syntax}).}
  12038. \label{fig:f1-syntax}
  12039. \end{figure}
  12040. %% Distinguishing between calls in tail position and non-tail position
  12041. %% requires the pass to have some notion of context. We recommend using
  12042. %% two mutually recursive functions, one for processing expressions in
  12043. %% tail position and another for the rest.
  12044. Placing this pass after \code{uniquify} will make sure that there are
  12045. no local variables and functions that share the same name. On the
  12046. other hand, \code{reveal-functions} needs to come before the
  12047. \code{explicate\_control} pass because that pass helps us compile
  12048. \code{FunRef} forms into assignment statements.
  12049. \section{Limit Functions}
  12050. \label{sec:limit-functions-r4}
  12051. Recall that we wish to limit the number of function parameters to six
  12052. so that we do not need to use the stack for argument passing, which
  12053. makes it easier to implement efficient tail calls. However, because
  12054. the input language \LangFun{} supports arbitrary numbers of function
  12055. arguments, we have some work to do!
  12056. This pass transforms functions and function calls that involve more
  12057. than six arguments to pass the first five arguments as usual, but it
  12058. packs the rest of the arguments into a vector and passes it as the
  12059. sixth argument.
  12060. Each function definition with too many parameters is transformed as
  12061. follows.
  12062. \begin{lstlisting}
  12063. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12064. |$\Rightarrow$|
  12065. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12066. \end{lstlisting}
  12067. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  12068. the occurrences of the later parameters with vector references.
  12069. \begin{lstlisting}
  12070. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  12071. \end{lstlisting}
  12072. For function calls with too many arguments, the \code{limit-functions}
  12073. pass transforms them in the following way.
  12074. \begin{tabular}{lll}
  12075. \begin{minipage}{0.2\textwidth}
  12076. \begin{lstlisting}
  12077. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12078. \end{lstlisting}
  12079. \end{minipage}
  12080. &
  12081. $\Rightarrow$
  12082. &
  12083. \begin{minipage}{0.4\textwidth}
  12084. \begin{lstlisting}
  12085. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12086. \end{lstlisting}
  12087. \end{minipage}
  12088. \end{tabular}
  12089. \section{Remove Complex Operands}
  12090. \label{sec:rco-r4}
  12091. The primary decisions to make for this pass is whether to classify
  12092. \code{FunRef} and \code{Apply} as either atomic or complex
  12093. expressions. Recall that a simple expression will eventually end up as
  12094. just an immediate argument of an x86 instruction. Function
  12095. application will be translated to a sequence of instructions, so
  12096. \code{Apply} must be classified as complex expression.
  12097. On the other hand, the arguments of \code{Apply} should be
  12098. atomic expressions.
  12099. %
  12100. Regarding \code{FunRef}, as discussed above, the function label needs
  12101. to be converted to an address using the \code{leaq} instruction. Thus,
  12102. even though \code{FunRef} seems rather simple, it needs to be
  12103. classified as a complex expression so that we generate an assignment
  12104. statement with a left-hand side that can serve as the target of the
  12105. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  12106. output language \LangFunANF{} of this pass.
  12107. \begin{figure}[tp]
  12108. \centering
  12109. \fbox{
  12110. \begin{minipage}{0.96\textwidth}
  12111. \small
  12112. \[
  12113. \begin{array}{rcl}
  12114. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12115. \MID \VOID{} } \\
  12116. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12117. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12118. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12119. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12120. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12121. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12122. \MID \LP\key{GlobalValue}~\Var\RP }\\
  12123. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12124. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12125. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12126. \end{array}
  12127. \]
  12128. \end{minipage}
  12129. }
  12130. \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12131. \label{fig:Rfun-anf-syntax}
  12132. \end{figure}
  12133. \section{Explicate Control and the \LangCFun{} language}
  12134. \label{sec:explicate-control-r4}
  12135. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12136. output of \code{explicate\_control}. (The concrete syntax is given in
  12137. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  12138. functions for assignment and tail contexts should be updated with
  12139. cases for \code{Apply} and \code{FunRef} and the function for
  12140. predicate context should be updated for \code{Apply} but not
  12141. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  12142. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  12143. tail position \code{Apply} becomes \code{TailCall}. We recommend
  12144. defining a new auxiliary function for processing function definitions.
  12145. This code is similar to the case for \code{Program} in \LangVec{}. The
  12146. top-level \code{explicate\_control} function that handles the
  12147. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  12148. all the function definitions.
  12149. \begin{figure}[tp]
  12150. \fbox{
  12151. \begin{minipage}{0.96\textwidth}
  12152. \small
  12153. \[
  12154. \begin{array}{lcl}
  12155. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  12156. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  12157. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  12158. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  12159. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  12160. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  12161. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  12162. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  12163. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  12164. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12165. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  12166. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  12167. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  12168. \MID \GOTO{\itm{label}} } \\
  12169. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  12170. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  12171. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  12172. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12173. \end{array}
  12174. \]
  12175. \end{minipage}
  12176. }
  12177. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12178. \label{fig:c3-syntax}
  12179. \end{figure}
  12180. \section{Select Instructions and the \LangXIndCall{} Language}
  12181. \label{sec:select-r4}
  12182. \index{subject}{instruction selection}
  12183. The output of select instructions is a program in the \LangXIndCall{}
  12184. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12185. \index{subject}{x86}
  12186. \begin{figure}[tp]
  12187. \fbox{
  12188. \begin{minipage}{0.96\textwidth}
  12189. \small
  12190. \[
  12191. \begin{array}{lcl}
  12192. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  12193. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  12194. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12195. \Instr &::=& \ldots
  12196. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12197. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12198. \Block &::= & \Instr\ldots \\
  12199. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  12200. \LangXIndCallM{} &::= & \Def\ldots
  12201. \end{array}
  12202. \]
  12203. \end{minipage}
  12204. }
  12205. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12206. \label{fig:x86-3-concrete}
  12207. \end{figure}
  12208. \begin{figure}[tp]
  12209. \fbox{
  12210. \begin{minipage}{0.96\textwidth}
  12211. \small
  12212. \[
  12213. \begin{array}{lcl}
  12214. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12215. \MID \BYTEREG{\Reg} } \\
  12216. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  12217. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12218. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12219. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12220. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12221. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12222. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12223. \end{array}
  12224. \]
  12225. \end{minipage}
  12226. }
  12227. \caption{The abstract syntax of \LangXIndCall{} (extends
  12228. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  12229. \label{fig:x86-3}
  12230. \end{figure}
  12231. An assignment of a function reference to a variable becomes a
  12232. load-effective-address instruction as follows, where $\itm{lhs}'$
  12233. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  12234. to \Arg{} in \LangXIndCallVar{}. \\
  12235. \begin{tabular}{lcl}
  12236. \begin{minipage}{0.35\textwidth}
  12237. \begin{lstlisting}
  12238. |$\itm{lhs}$| = (fun-ref |$f$|);
  12239. \end{lstlisting}
  12240. \end{minipage}
  12241. &
  12242. $\Rightarrow$\qquad\qquad
  12243. &
  12244. \begin{minipage}{0.3\textwidth}
  12245. \begin{lstlisting}
  12246. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  12247. \end{lstlisting}
  12248. \end{minipage}
  12249. \end{tabular} \\
  12250. Regarding function definitions, we need to remove the parameters and
  12251. instead perform parameter passing using the conventions discussed in
  12252. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  12253. registers. We recommend turning the parameters into local variables
  12254. and generating instructions at the beginning of the function to move
  12255. from the argument passing registers to these local variables.
  12256. \begin{lstlisting}
  12257. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  12258. |$\Rightarrow$|
  12259. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  12260. \end{lstlisting}
  12261. The $G'$ control-flow graph is the same as $G$ except that the
  12262. \code{start} block is modified to add the instructions for moving from
  12263. the argument registers to the parameter variables. So the \code{start}
  12264. block of $G$ shown on the left is changed to the code on the right.
  12265. \begin{center}
  12266. \begin{minipage}{0.3\textwidth}
  12267. \begin{lstlisting}
  12268. start:
  12269. |$\itm{instr}_1$|
  12270. |$\vdots$|
  12271. |$\itm{instr}_n$|
  12272. \end{lstlisting}
  12273. \end{minipage}
  12274. $\Rightarrow$
  12275. \begin{minipage}{0.3\textwidth}
  12276. \begin{lstlisting}
  12277. start:
  12278. movq %rdi, |$x_1$|
  12279. movq %rsi, |$x_2$|
  12280. |$\vdots$|
  12281. |$\itm{instr}_1$|
  12282. |$\vdots$|
  12283. |$\itm{instr}_n$|
  12284. \end{lstlisting}
  12285. \end{minipage}
  12286. \end{center}
  12287. By changing the parameters to local variables, we are giving the
  12288. register allocator control over which registers or stack locations to
  12289. use for them. If you implemented the move-biasing challenge
  12290. (Section~\ref{sec:move-biasing}), the register allocator will try to
  12291. assign the parameter variables to the corresponding argument register,
  12292. in which case the \code{patch\_instructions} pass will remove the
  12293. \code{movq} instruction. This happens in the example translation in
  12294. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  12295. the \code{add} function.
  12296. %
  12297. Also, note that the register allocator will perform liveness analysis
  12298. on this sequence of move instructions and build the interference
  12299. graph. So, for example, $x_1$ will be marked as interfering with
  12300. \code{rsi} and that will prevent the assignment of $x_1$ to
  12301. \code{rsi}, which is good, because that would overwrite the argument
  12302. that needs to move into $x_2$.
  12303. Next, consider the compilation of function calls. In the mirror image
  12304. of handling the parameters of function definitions, the arguments need
  12305. to be moved to the argument passing registers. The function call
  12306. itself is performed with an indirect function call. The return value
  12307. from the function is stored in \code{rax}, so it needs to be moved
  12308. into the \itm{lhs}.
  12309. \begin{lstlisting}
  12310. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  12311. |$\Rightarrow$|
  12312. movq |$\itm{arg}_1$|, %rdi
  12313. movq |$\itm{arg}_2$|, %rsi
  12314. |$\vdots$|
  12315. callq *|\itm{fun}|
  12316. movq %rax, |\itm{lhs}|
  12317. \end{lstlisting}
  12318. The \code{IndirectCallq} AST node includes an integer for the arity of
  12319. the function, i.e., the number of parameters. That information is
  12320. useful in the \code{uncover-live} pass for determining which
  12321. argument-passing registers are potentially read during the call.
  12322. For tail calls, the parameter passing is the same as non-tail calls:
  12323. generate instructions to move the arguments into to the argument
  12324. passing registers. After that we need to pop the frame from the
  12325. procedure call stack. However, we do not yet know how big the frame
  12326. is; that gets determined during register allocation. So instead of
  12327. generating those instructions here, we invent a new instruction that
  12328. means ``pop the frame and then do an indirect jump'', which we name
  12329. \code{TailJmp}. The abstract syntax for this instruction includes an
  12330. argument that specifies where to jump and an integer that represents
  12331. the arity of the function being called.
  12332. Recall that in Section~\ref{sec:explicate-control-Lvar} we recommended
  12333. using the label \code{start} for the initial block of a program, and
  12334. in Section~\ref{sec:select-Lvar} we recommended labeling the conclusion
  12335. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  12336. can be compiled to an assignment to \code{rax} followed by a jump to
  12337. \code{conclusion}. With the addition of function definitions, we will
  12338. have a starting block and conclusion for each function, but their
  12339. labels need to be unique. We recommend prepending the function's name
  12340. to \code{start} and \code{conclusion}, respectively, to obtain unique
  12341. labels. (Alternatively, one could \code{gensym} labels for the start
  12342. and conclusion and store them in the $\itm{info}$ field of the
  12343. function definition.)
  12344. \section{Register Allocation}
  12345. \label{sec:register-allocation-r4}
  12346. \subsection{Liveness Analysis}
  12347. \label{sec:liveness-analysis-r4}
  12348. \index{subject}{liveness analysis}
  12349. %% The rest of the passes need only minor modifications to handle the new
  12350. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  12351. %% \code{leaq}.
  12352. The \code{IndirectCallq} instruction should be treated like
  12353. \code{Callq} regarding its written locations $W$, in that they should
  12354. include all the caller-saved registers. Recall that the reason for
  12355. that is to force call-live variables to be assigned to callee-saved
  12356. registers or to be spilled to the stack.
  12357. Regarding the set of read locations $R$ the arity field of
  12358. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  12359. argument-passing registers should be considered as read by those
  12360. instructions.
  12361. \subsection{Build Interference Graph}
  12362. \label{sec:build-interference-r4}
  12363. With the addition of function definitions, we compute an interference
  12364. graph for each function (not just one for the whole program).
  12365. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  12366. spill vector-typed variables that are live during a call to the
  12367. \code{collect}. With the addition of functions to our language, we
  12368. need to revisit this issue. Many functions perform allocation and
  12369. therefore have calls to the collector inside of them. Thus, we should
  12370. not only spill a vector-typed variable when it is live during a call
  12371. to \code{collect}, but we should spill the variable if it is live
  12372. during any function call. Thus, in the \code{build\_interference} pass,
  12373. we recommend adding interference edges between call-live vector-typed
  12374. variables and the callee-saved registers (in addition to the usual
  12375. addition of edges between call-live variables and the caller-saved
  12376. registers).
  12377. \subsection{Allocate Registers}
  12378. The primary change to the \code{allocate\_registers} pass is adding an
  12379. auxiliary function for handling definitions (the \Def{} non-terminal
  12380. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  12381. logic is the same as described in
  12382. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  12383. allocation is performed many times, once for each function definition,
  12384. instead of just once for the whole program.
  12385. \section{Patch Instructions}
  12386. In \code{patch\_instructions}, you should deal with the x86
  12387. idiosyncrasy that the destination argument of \code{leaq} must be a
  12388. register. Additionally, you should ensure that the argument of
  12389. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  12390. code generation more convenient, because we trample many registers
  12391. before the tail call (as explained in the next section).
  12392. \section{Print x86}
  12393. For the \code{print\_x86} pass, the cases for \code{FunRef} and
  12394. \code{IndirectCallq} are straightforward: output their concrete
  12395. syntax.
  12396. \begin{lstlisting}
  12397. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  12398. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  12399. \end{lstlisting}
  12400. The \code{TailJmp} node requires a bit work. A straightforward
  12401. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  12402. before the jump we need to pop the current frame. This sequence of
  12403. instructions is the same as the code for the conclusion of a function,
  12404. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  12405. Regarding function definitions, you will need to generate a prelude
  12406. and conclusion for each one. This code is similar to the prelude and
  12407. conclusion that you generated for the \code{main} function in
  12408. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  12409. should carry out the following steps.
  12410. \begin{enumerate}
  12411. \item Start with \code{.global} and \code{.align} directives followed
  12412. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  12413. example.)
  12414. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  12415. pointer.
  12416. \item Push to the stack all of the callee-saved registers that were
  12417. used for register allocation.
  12418. \item Move the stack pointer \code{rsp} down by the size of the stack
  12419. frame for this function, which depends on the number of regular
  12420. spills. (Aligned to 16 bytes.)
  12421. \item Move the root stack pointer \code{r15} up by the size of the
  12422. root-stack frame for this function, which depends on the number of
  12423. spilled vectors. \label{root-stack-init}
  12424. \item Initialize to zero all of the entries in the root-stack frame.
  12425. \item Jump to the start block.
  12426. \end{enumerate}
  12427. The prelude of the \code{main} function has one additional task: call
  12428. the \code{initialize} function to set up the garbage collector and
  12429. move the value of the global \code{rootstack\_begin} in
  12430. \code{r15}. This should happen before step \ref{root-stack-init}
  12431. above, which depends on \code{r15}.
  12432. The conclusion of every function should do the following.
  12433. \begin{enumerate}
  12434. \item Move the stack pointer back up by the size of the stack frame
  12435. for this function.
  12436. \item Restore the callee-saved registers by popping them from the
  12437. stack.
  12438. \item Move the root stack pointer back down by the size of the
  12439. root-stack frame for this function.
  12440. \item Restore \code{rbp} by popping it from the stack.
  12441. \item Return to the caller with the \code{retq} instruction.
  12442. \end{enumerate}
  12443. \begin{exercise}\normalfont
  12444. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  12445. Create 5 new programs that use functions, including examples that pass
  12446. functions and return functions from other functions, recursive
  12447. functions, functions that create vectors, and functions that make tail
  12448. calls. Test your compiler on these new programs and all of your
  12449. previously created test programs.
  12450. \end{exercise}
  12451. \begin{figure}[tbp]
  12452. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12453. \node (Rfun) at (0,2) {\large \LangFun{}};
  12454. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  12455. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  12456. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  12457. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  12458. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  12459. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  12460. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  12461. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12462. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12463. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12464. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12465. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12466. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12467. \path[->,bend left=15] (Rfun) edge [above] node
  12468. {\ttfamily\footnotesize shrink} (Rfun-1);
  12469. \path[->,bend left=15] (Rfun-1) edge [above] node
  12470. {\ttfamily\footnotesize uniquify} (Rfun-2);
  12471. \path[->,bend left=15] (Rfun-2) edge [right] node
  12472. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  12473. \path[->,bend left=15] (F1-1) edge [below] node
  12474. {\ttfamily\footnotesize limit\_functions} (F1-2);
  12475. \path[->,bend right=15] (F1-2) edge [above] node
  12476. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  12477. \path[->,bend right=15] (F1-3) edge [above] node
  12478. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  12479. \path[->,bend left=15] (F1-4) edge [right] node
  12480. {\ttfamily\footnotesize explicate\_control} (C3-2);
  12481. \path[->,bend right=15] (C3-2) edge [left] node
  12482. {\ttfamily\footnotesize select\_instr.} (x86-2);
  12483. \path[->,bend left=15] (x86-2) edge [left] node
  12484. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12485. \path[->,bend right=15] (x86-2-1) edge [below] node
  12486. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  12487. \path[->,bend right=15] (x86-2-2) edge [left] node
  12488. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  12489. \path[->,bend left=15] (x86-3) edge [above] node
  12490. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  12491. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  12492. \end{tikzpicture}
  12493. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  12494. \label{fig:Rfun-passes}
  12495. \end{figure}
  12496. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  12497. compiling \LangFun{} to x86.
  12498. \section{An Example Translation}
  12499. \label{sec:functions-example}
  12500. Figure~\ref{fig:add-fun} shows an example translation of a simple
  12501. function in \LangFun{} to x86. The figure also includes the results of the
  12502. \code{explicate\_control} and \code{select\_instructions} passes.
  12503. \begin{figure}[htbp]
  12504. \begin{tabular}{ll}
  12505. \begin{minipage}{0.5\textwidth}
  12506. % s3_2.rkt
  12507. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12508. (define (add [x : Integer] [y : Integer])
  12509. : Integer
  12510. (+ x y))
  12511. (add 40 2)
  12512. \end{lstlisting}
  12513. $\Downarrow$
  12514. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12515. (define (add86 [x87 : Integer]
  12516. [y88 : Integer]) : Integer
  12517. add86start:
  12518. return (+ x87 y88);
  12519. )
  12520. (define (main) : Integer ()
  12521. mainstart:
  12522. tmp89 = (fun-ref add86);
  12523. (tail-call tmp89 40 2)
  12524. )
  12525. \end{lstlisting}
  12526. \end{minipage}
  12527. &
  12528. $\Rightarrow$
  12529. \begin{minipage}{0.5\textwidth}
  12530. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12531. (define (add86) : Integer
  12532. add86start:
  12533. movq %rdi, x87
  12534. movq %rsi, y88
  12535. movq x87, %rax
  12536. addq y88, %rax
  12537. jmp add11389conclusion
  12538. )
  12539. (define (main) : Integer
  12540. mainstart:
  12541. leaq (fun-ref add86), tmp89
  12542. movq $40, %rdi
  12543. movq $2, %rsi
  12544. tail-jmp tmp89
  12545. )
  12546. \end{lstlisting}
  12547. $\Downarrow$
  12548. \end{minipage}
  12549. \end{tabular}
  12550. \begin{tabular}{ll}
  12551. \begin{minipage}{0.3\textwidth}
  12552. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12553. .globl add86
  12554. .align 16
  12555. add86:
  12556. pushq %rbp
  12557. movq %rsp, %rbp
  12558. jmp add86start
  12559. add86start:
  12560. movq %rdi, %rax
  12561. addq %rsi, %rax
  12562. jmp add86conclusion
  12563. add86conclusion:
  12564. popq %rbp
  12565. retq
  12566. \end{lstlisting}
  12567. \end{minipage}
  12568. &
  12569. \begin{minipage}{0.5\textwidth}
  12570. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12571. .globl main
  12572. .align 16
  12573. main:
  12574. pushq %rbp
  12575. movq %rsp, %rbp
  12576. movq $16384, %rdi
  12577. movq $16384, %rsi
  12578. callq initialize
  12579. movq rootstack_begin(%rip), %r15
  12580. jmp mainstart
  12581. mainstart:
  12582. leaq add86(%rip), %rcx
  12583. movq $40, %rdi
  12584. movq $2, %rsi
  12585. movq %rcx, %rax
  12586. popq %rbp
  12587. jmp *%rax
  12588. mainconclusion:
  12589. popq %rbp
  12590. retq
  12591. \end{lstlisting}
  12592. \end{minipage}
  12593. \end{tabular}
  12594. \caption{Example compilation of a simple function to x86.}
  12595. \label{fig:add-fun}
  12596. \end{figure}
  12597. % Challenge idea: inlining! (simple version)
  12598. % Further Reading
  12599. \fi % racketEd
  12600. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12601. \chapter{Lexically Scoped Functions}
  12602. \label{ch:Rlam}
  12603. \index{subject}{lambda}
  12604. \index{subject}{lexical scoping}
  12605. \if\edition\racketEd
  12606. This chapter studies lexically scoped functions as they appear in
  12607. functional languages such as Racket. By lexical scoping we mean that a
  12608. function's body may refer to variables whose binding site is outside
  12609. of the function, in an enclosing scope.
  12610. %
  12611. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  12612. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  12613. \key{lambda} form. The body of the \key{lambda}, refers to three
  12614. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  12615. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  12616. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  12617. parameter of function \code{f}. The \key{lambda} is returned from the
  12618. function \code{f}. The main expression of the program includes two
  12619. calls to \code{f} with different arguments for \code{x}, first
  12620. \code{5} then \code{3}. The functions returned from \code{f} are bound
  12621. to variables \code{g} and \code{h}. Even though these two functions
  12622. were created by the same \code{lambda}, they are really different
  12623. functions because they use different values for \code{x}. Applying
  12624. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  12625. \code{15} produces \code{22}. The result of this program is \code{42}.
  12626. \begin{figure}[btp]
  12627. % s4_6.rkt
  12628. \begin{lstlisting}
  12629. (define (f [x : Integer]) : (Integer -> Integer)
  12630. (let ([y 4])
  12631. (lambda: ([z : Integer]) : Integer
  12632. (+ x (+ y z)))))
  12633. (let ([g (f 5)])
  12634. (let ([h (f 3)])
  12635. (+ (g 11) (h 15))))
  12636. \end{lstlisting}
  12637. \caption{Example of a lexically scoped function.}
  12638. \label{fig:lexical-scoping}
  12639. \end{figure}
  12640. The approach that we take for implementing lexically scoped
  12641. functions is to compile them into top-level function definitions,
  12642. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  12643. provide special treatment for variable occurrences such as \code{x}
  12644. and \code{y} in the body of the \code{lambda} of
  12645. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  12646. refer to variables defined outside of it. To identify such variable
  12647. occurrences, we review the standard notion of free variable.
  12648. \begin{definition}
  12649. A variable is \emph{free in expression} $e$ if the variable occurs
  12650. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  12651. variable}
  12652. \end{definition}
  12653. For example, in the expression \code{(+ x (+ y z))} the variables
  12654. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  12655. only \code{x} and \code{y} are free in the following expression
  12656. because \code{z} is bound by the \code{lambda}.
  12657. \begin{lstlisting}
  12658. (lambda: ([z : Integer]) : Integer
  12659. (+ x (+ y z)))
  12660. \end{lstlisting}
  12661. So the free variables of a \code{lambda} are the ones that will need
  12662. special treatment. We need to arrange for some way to transport, at
  12663. runtime, the values of those variables from the point where the
  12664. \code{lambda} was created to the point where the \code{lambda} is
  12665. applied. An efficient solution to the problem, due to
  12666. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  12667. free variables together with the function pointer for the lambda's
  12668. code, an arrangement called a \emph{flat closure} (which we shorten to
  12669. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  12670. we have all the ingredients to make closures, Chapter~\ref{ch:Lvec}
  12671. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  12672. pointers. The function pointer resides at index $0$ and the
  12673. values for the free variables will fill in the rest of the vector.
  12674. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  12675. how closures work. It's a three-step dance. The program first calls
  12676. function \code{f}, which creates a closure for the \code{lambda}. The
  12677. closure is a vector whose first element is a pointer to the top-level
  12678. function that we will generate for the \code{lambda}, the second
  12679. element is the value of \code{x}, which is \code{5}, and the third
  12680. element is \code{4}, the value of \code{y}. The closure does not
  12681. contain an element for \code{z} because \code{z} is not a free
  12682. variable of the \code{lambda}. Creating the closure is step 1 of the
  12683. dance. The closure is returned from \code{f} and bound to \code{g}, as
  12684. shown in Figure~\ref{fig:closures}.
  12685. %
  12686. The second call to \code{f} creates another closure, this time with
  12687. \code{3} in the second slot (for \code{x}). This closure is also
  12688. returned from \code{f} but bound to \code{h}, which is also shown in
  12689. Figure~\ref{fig:closures}.
  12690. \begin{figure}[tbp]
  12691. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  12692. \caption{Example closure representation for the \key{lambda}'s
  12693. in Figure~\ref{fig:lexical-scoping}.}
  12694. \label{fig:closures}
  12695. \end{figure}
  12696. Continuing with the example, consider the application of \code{g} to
  12697. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  12698. obtain the function pointer in the first element of the closure and
  12699. call it, passing in the closure itself and then the regular arguments,
  12700. in this case \code{11}. This technique for applying a closure is step
  12701. 2 of the dance.
  12702. %
  12703. But doesn't this \code{lambda} only take 1 argument, for parameter
  12704. \code{z}? The third and final step of the dance is generating a
  12705. top-level function for a \code{lambda}. We add an additional
  12706. parameter for the closure and we insert a \code{let} at the beginning
  12707. of the function for each free variable, to bind those variables to the
  12708. appropriate elements from the closure parameter.
  12709. %
  12710. This three-step dance is known as \emph{closure conversion}. We
  12711. discuss the details of closure conversion in
  12712. Section~\ref{sec:closure-conversion} and the code generated from the
  12713. example in Section~\ref{sec:example-lambda}. But first we define the
  12714. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  12715. \section{The \LangLam{} Language}
  12716. \label{sec:r5}
  12717. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  12718. functions and lexical scoping, is defined in
  12719. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  12720. the \key{lambda} form to the grammar for \LangFun{}, which already has
  12721. syntax for function application.
  12722. \begin{figure}[tp]
  12723. \centering
  12724. \fbox{
  12725. \begin{minipage}{0.96\textwidth}
  12726. \small
  12727. \[
  12728. \begin{array}{lcl}
  12729. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  12730. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  12731. \MID (\Type\ldots \; \key{->}\; \Type)} \\
  12732. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  12733. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  12734. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  12735. &\MID& \gray{\key{\#t} \MID \key{\#f}
  12736. \MID (\key{and}\;\Exp\;\Exp)
  12737. \MID (\key{or}\;\Exp\;\Exp)
  12738. \MID (\key{not}\;\Exp) } \\
  12739. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  12740. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  12741. (\key{vector-ref}\;\Exp\;\Int)} \\
  12742. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  12743. \MID (\Exp \; \Exp\ldots) } \\
  12744. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  12745. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  12746. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12747. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  12748. \end{array}
  12749. \]
  12750. \end{minipage}
  12751. }
  12752. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  12753. with \key{lambda}.}
  12754. \label{fig:Rlam-concrete-syntax}
  12755. \end{figure}
  12756. \begin{figure}[tp]
  12757. \centering
  12758. \fbox{
  12759. \begin{minipage}{0.96\textwidth}
  12760. \small
  12761. \[
  12762. \begin{array}{lcl}
  12763. \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  12764. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  12765. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  12766. &\MID& \gray{ \BOOL{\itm{bool}}
  12767. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  12768. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  12769. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  12770. &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  12771. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  12772. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12773. \end{array}
  12774. \]
  12775. \end{minipage}
  12776. }
  12777. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  12778. \label{fig:Rlam-syntax}
  12779. \end{figure}
  12780. \index{subject}{interpreter}
  12781. \label{sec:interp-Rlambda}
  12782. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  12783. \LangLam{}. The case for \key{lambda} saves the current environment
  12784. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  12785. the environment from the \key{lambda}, the \code{lam-env}, when
  12786. interpreting the body of the \key{lambda}. The \code{lam-env}
  12787. environment is extended with the mapping of parameters to argument
  12788. values.
  12789. \begin{figure}[tbp]
  12790. \begin{lstlisting}
  12791. (define interp-Rlambda_class
  12792. (class interp-Rfun_class
  12793. (super-new)
  12794. (define/override (interp-op op)
  12795. (match op
  12796. ['procedure-arity
  12797. (lambda (v)
  12798. (match v
  12799. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  12800. [else (error 'interp-op "expected a function, not ~a" v)]))]
  12801. [else (super interp-op op)]))
  12802. (define/override ((interp-exp env) e)
  12803. (define recur (interp-exp env))
  12804. (match e
  12805. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  12806. `(function ,xs ,body ,env)]
  12807. [else ((super interp-exp env) e)]))
  12808. ))
  12809. (define (interp-Rlambda p)
  12810. (send (new interp-Rlambda_class) interp-program p))
  12811. \end{lstlisting}
  12812. \caption{Interpreter for \LangLam{}.}
  12813. \label{fig:interp-Rlambda}
  12814. \end{figure}
  12815. \label{sec:type-check-r5}
  12816. \index{subject}{type checking}
  12817. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  12818. \key{lambda} form. The body of the \key{lambda} is checked in an
  12819. environment that includes the current environment (because it is
  12820. lexically scoped) and also includes the \key{lambda}'s parameters. We
  12821. require the body's type to match the declared return type.
  12822. \begin{figure}[tbp]
  12823. \begin{lstlisting}
  12824. (define (type-check-Rlambda env)
  12825. (lambda (e)
  12826. (match e
  12827. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  12828. (define-values (new-body bodyT)
  12829. ((type-check-exp (append (map cons xs Ts) env)) body))
  12830. (define ty `(,@Ts -> ,rT))
  12831. (cond
  12832. [(equal? rT bodyT)
  12833. (values (HasType (Lambda params rT new-body) ty) ty)]
  12834. [else
  12835. (error "mismatch in return type" bodyT rT)])]
  12836. ...
  12837. )))
  12838. \end{lstlisting}
  12839. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  12840. \label{fig:type-check-Rlambda}
  12841. \end{figure}
  12842. \section{Assignment and Lexically Scoped Functions}
  12843. \label{sec:assignment-scoping}
  12844. [UNDER CONSTRUCTION: This section was just moved into this location
  12845. and may need to be updated. -Jeremy]
  12846. The combination of lexically-scoped functions and assignment
  12847. (i.e. \code{set!}) raises a challenge with our approach to
  12848. implementing lexically-scoped functions. Consider the following
  12849. example in which function \code{f} has a free variable \code{x} that
  12850. is changed after \code{f} is created but before the call to \code{f}.
  12851. % loop_test_11.rkt
  12852. \begin{lstlisting}
  12853. (let ([x 0])
  12854. (let ([y 0])
  12855. (let ([z 20])
  12856. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  12857. (begin
  12858. (set! x 10)
  12859. (set! y 12)
  12860. (f y))))))
  12861. \end{lstlisting}
  12862. The correct output for this example is \code{42} because the call to
  12863. \code{f} is required to use the current value of \code{x} (which is
  12864. \code{10}). Unfortunately, the closure conversion pass
  12865. (Section~\ref{sec:closure-conversion}) generates code for the
  12866. \code{lambda} that copies the old value of \code{x} into a
  12867. closure. Thus, if we naively add support for assignment to our current
  12868. compiler, the output of this program would be \code{32}.
  12869. A first attempt at solving this problem would be to save a pointer to
  12870. \code{x} in the closure and change the occurrences of \code{x} inside
  12871. the lambda to dereference the pointer. Of course, this would require
  12872. assigning \code{x} to the stack and not to a register. However, the
  12873. problem goes a bit deeper. Consider the following example in which we
  12874. create a counter abstraction by creating a pair of functions that
  12875. share the free variable \code{x}.
  12876. % similar to loop_test_10.rkt
  12877. \begin{lstlisting}
  12878. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  12879. (vector
  12880. (lambda: () : Integer x)
  12881. (lambda: () : Void (set! x (+ 1 x)))))
  12882. (let ([counter (f 0)])
  12883. (let ([get (vector-ref counter 0)])
  12884. (let ([inc (vector-ref counter 1)])
  12885. (begin
  12886. (inc)
  12887. (get)))))
  12888. \end{lstlisting}
  12889. In this example, the lifetime of \code{x} extends beyond the lifetime
  12890. of the call to \code{f}. Thus, if we were to store \code{x} on the
  12891. stack frame for the call to \code{f}, it would be gone by the time we
  12892. call \code{inc} and \code{get}, leaving us with dangling pointers for
  12893. \code{x}. This example demonstrates that when a variable occurs free
  12894. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  12895. value of the variable needs to live on the heap. The verb ``box'' is
  12896. often used for allocating a single value on the heap, producing a
  12897. pointer, and ``unbox'' for dereferencing the pointer.
  12898. We recommend solving these problems by ``boxing'' the local variables
  12899. that are in the intersection of 1) variables that appear on the
  12900. left-hand-side of a \code{set!} and 2) variables that occur free
  12901. inside a \code{lambda}. We shall introduce a new pass named
  12902. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  12903. perform this translation. But before diving into the compiler passes,
  12904. we one more problem to discuss.
  12905. \section{Reveal Functions and the $F_2$ language}
  12906. \label{sec:reveal-functions-r5}
  12907. To support the \code{procedure-arity} operator we need to communicate
  12908. the arity of a function to the point of closure creation. We can
  12909. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  12910. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  12911. output of this pass is the language $F_2$, whose syntax is defined in
  12912. Figure~\ref{fig:f2-syntax}.
  12913. \begin{figure}[tp]
  12914. \centering
  12915. \fbox{
  12916. \begin{minipage}{0.96\textwidth}
  12917. \[
  12918. \begin{array}{lcl}
  12919. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  12920. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12921. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  12922. \end{array}
  12923. \]
  12924. \end{minipage}
  12925. }
  12926. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  12927. (Figure~\ref{fig:Rlam-syntax}).}
  12928. \label{fig:f2-syntax}
  12929. \end{figure}
  12930. \section{Convert Assignments}
  12931. \label{sec:convert-assignments}
  12932. [UNDER CONSTRUCTION: This section was just moved into this location
  12933. and may need to be updated. -Jeremy]
  12934. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  12935. the combination of assignments and lexically-scoped functions requires
  12936. that we box those variables that are both assigned-to and that appear
  12937. free inside a \code{lambda}. The purpose of the
  12938. \code{convert-assignments} pass is to carry out that transformation.
  12939. We recommend placing this pass after \code{uniquify} but before
  12940. \code{reveal-functions}.
  12941. Consider again the first example from
  12942. Section~\ref{sec:assignment-scoping}:
  12943. \begin{lstlisting}
  12944. (let ([x 0])
  12945. (let ([y 0])
  12946. (let ([z 20])
  12947. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  12948. (begin
  12949. (set! x 10)
  12950. (set! y 12)
  12951. (f y))))))
  12952. \end{lstlisting}
  12953. The variables \code{x} and \code{y} are assigned-to. The variables
  12954. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  12955. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  12956. The boxing of \code{x} consists of three transformations: initialize
  12957. \code{x} with a vector, replace reads from \code{x} with
  12958. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  12959. \code{vector-set!}. The output of \code{convert-assignments} for this
  12960. example is as follows.
  12961. \begin{lstlisting}
  12962. (define (main) : Integer
  12963. (let ([x0 (vector 0)])
  12964. (let ([y1 0])
  12965. (let ([z2 20])
  12966. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  12967. (+ a3 (+ (vector-ref x0 0) z2)))])
  12968. (begin
  12969. (vector-set! x0 0 10)
  12970. (set! y1 12)
  12971. (f4 y1)))))))
  12972. \end{lstlisting}
  12973. \paragraph{Assigned \& Free}
  12974. We recommend defining an auxiliary function named
  12975. \code{assigned\&free} that takes an expression and simultaneously
  12976. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  12977. that occur free within lambda's, and 3) a new version of the
  12978. expression that records which bound variables occurred in the
  12979. intersection of $A$ and $F$. You can use the struct
  12980. \code{AssignedFree} to do this. Consider the case for
  12981. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  12982. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  12983. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  12984. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  12985. \begin{lstlisting}
  12986. (Let |$x$| |$rhs$| |$body$|)
  12987. |$\Rightarrow$|
  12988. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  12989. \end{lstlisting}
  12990. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  12991. The set of assigned variables for this \code{Let} is
  12992. $A_r \cup (A_b - \{x\})$
  12993. and the set of variables free in lambda's is
  12994. $F_r \cup (F_b - \{x\})$.
  12995. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  12996. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  12997. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  12998. and $F_r$.
  12999. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  13000. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  13001. recursively processing \itm{body}. Wrap each of parameter that occurs
  13002. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  13003. Let $P$ be the set of parameter names in \itm{params}. The result is
  13004. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  13005. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  13006. variables of an expression (see Chapter~\ref{ch:Rlam}).
  13007. \paragraph{Convert Assignments}
  13008. Next we discuss the \code{convert-assignment} pass with its auxiliary
  13009. functions for expressions and definitions. The function for
  13010. expressions, \code{cnvt-assign-exp}, should take an expression and a
  13011. set of assigned-and-free variables (obtained from the result of
  13012. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  13013. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  13014. \code{vector-ref}.
  13015. \begin{lstlisting}
  13016. (Var |$x$|)
  13017. |$\Rightarrow$|
  13018. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  13019. \end{lstlisting}
  13020. %
  13021. In the case for $\LET{\LP\code{AssignedFree}\,
  13022. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  13023. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  13024. \itm{body'} but with $x$ added to the set of assigned-and-free
  13025. variables. Translate the let-expression as follows to bind $x$ to a
  13026. boxed value.
  13027. \begin{lstlisting}
  13028. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  13029. |$\Rightarrow$|
  13030. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  13031. \end{lstlisting}
  13032. %
  13033. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  13034. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  13035. variables, translate the \code{set!} into a \code{vector-set!}
  13036. as follows.
  13037. \begin{lstlisting}
  13038. (SetBang |$x$| |$\itm{rhs}$|)
  13039. |$\Rightarrow$|
  13040. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  13041. \end{lstlisting}
  13042. %
  13043. The case for \code{Lambda} is non-trivial, but it is similar to the
  13044. case for function definitions, which we discuss next.
  13045. The auxiliary function for definitions, \code{cnvt-assign-def},
  13046. applies assignment conversion to function definitions.
  13047. We translate a function definition as follows.
  13048. \begin{lstlisting}
  13049. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  13050. |$\Rightarrow$|
  13051. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  13052. \end{lstlisting}
  13053. So it remains to explain \itm{params'} and $\itm{body}_4$.
  13054. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  13055. \code{assigned\&free} on $\itm{body_1}$.
  13056. Let $P$ be the parameter names in \itm{params}.
  13057. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  13058. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  13059. as the set of assigned-and-free variables.
  13060. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  13061. in a sequence of let-expressions that box the parameters
  13062. that are in $A_b \cap F_b$.
  13063. %
  13064. Regarding \itm{params'}, change the names of the parameters that are
  13065. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  13066. variables can retain the original names). Recall the second example in
  13067. Section~\ref{sec:assignment-scoping} involving a counter
  13068. abstraction. The following is the output of assignment version for
  13069. function \code{f}.
  13070. \begin{lstlisting}
  13071. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  13072. (vector
  13073. (lambda: () : Integer x1)
  13074. (lambda: () : Void (set! x1 (+ 1 x1)))))
  13075. |$\Rightarrow$|
  13076. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  13077. (let ([x1 (vector param_x1)])
  13078. (vector (lambda: () : Integer (vector-ref x1 0))
  13079. (lambda: () : Void
  13080. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  13081. \end{lstlisting}
  13082. \section{Closure Conversion}
  13083. \label{sec:closure-conversion}
  13084. \index{subject}{closure conversion}
  13085. The compiling of lexically-scoped functions into top-level function
  13086. definitions is accomplished in the pass \code{convert-to-closures}
  13087. that comes after \code{reveal-functions} and before
  13088. \code{limit-functions}.
  13089. As usual, we implement the pass as a recursive function over the
  13090. AST. All of the action is in the cases for \key{Lambda} and
  13091. \key{Apply}. We transform a \key{Lambda} expression into an expression
  13092. that creates a closure, that is, a vector whose first element is a
  13093. function pointer and the rest of the elements are the free variables
  13094. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  13095. using \code{vector} so that we can distinguish closures from vectors
  13096. in Section~\ref{sec:optimize-closures} and to record the arity. In
  13097. the generated code below, the \itm{name} is a unique symbol generated
  13098. to identify the function and the \itm{arity} is the number of
  13099. parameters (the length of \itm{ps}).
  13100. \begin{lstlisting}
  13101. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  13102. |$\Rightarrow$|
  13103. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  13104. \end{lstlisting}
  13105. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  13106. create a top-level function definition for each \key{Lambda}, as
  13107. shown below.\\
  13108. \begin{minipage}{0.8\textwidth}
  13109. \begin{lstlisting}
  13110. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  13111. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  13112. ...
  13113. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  13114. |\itm{body'}|)...))
  13115. \end{lstlisting}
  13116. \end{minipage}\\
  13117. The \code{clos} parameter refers to the closure. Translate the type
  13118. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  13119. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  13120. $\itm{fvts}$ are the types of the free variables in the lambda and the
  13121. underscore \code{\_} is a dummy type that we use because it is rather
  13122. difficult to give a type to the function in the closure's
  13123. type.\footnote{To give an accurate type to a closure, we would need to
  13124. add existential types to the type checker~\citep{Minamide:1996ys}.}
  13125. The dummy type is considered to be equal to any other type during type
  13126. checking. The sequence of \key{Let} forms bind the free variables to
  13127. their values obtained from the closure.
  13128. Closure conversion turns functions into vectors, so the type
  13129. annotations in the program must also be translated. We recommend
  13130. defining a auxiliary recursive function for this purpose. Function
  13131. types should be translated as follows.
  13132. \begin{lstlisting}
  13133. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  13134. |$\Rightarrow$|
  13135. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  13136. \end{lstlisting}
  13137. The above type says that the first thing in the vector is a function
  13138. pointer. The first parameter of the function pointer is a vector (a
  13139. closure) and the rest of the parameters are the ones from the original
  13140. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  13141. the closure omits the types of the free variables because 1) those
  13142. types are not available in this context and 2) we do not need them in
  13143. the code that is generated for function application.
  13144. We transform function application into code that retrieves the
  13145. function pointer from the closure and then calls the function, passing
  13146. in the closure as the first argument. We bind $e'$ to a temporary
  13147. variable to avoid code duplication.
  13148. \begin{lstlisting}
  13149. (Apply |$e$| |\itm{es}|)
  13150. |$\Rightarrow$|
  13151. (Let |\itm{tmp}| |$e'$|
  13152. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  13153. \end{lstlisting}
  13154. There is also the question of what to do with references top-level
  13155. function definitions. To maintain a uniform translation of function
  13156. application, we turn function references into closures.
  13157. \begin{tabular}{lll}
  13158. \begin{minipage}{0.3\textwidth}
  13159. \begin{lstlisting}
  13160. (FunRefArity |$f$| |$n$|)
  13161. \end{lstlisting}
  13162. \end{minipage}
  13163. &
  13164. $\Rightarrow$
  13165. &
  13166. \begin{minipage}{0.5\textwidth}
  13167. \begin{lstlisting}
  13168. (Closure |$n$| (FunRef |$f$|) '())
  13169. \end{lstlisting}
  13170. \end{minipage}
  13171. \end{tabular} \\
  13172. %
  13173. The top-level function definitions need to be updated as well to take
  13174. an extra closure parameter.
  13175. \section{An Example Translation}
  13176. \label{sec:example-lambda}
  13177. Figure~\ref{fig:lexical-functions-example} shows the result of
  13178. \code{reveal-functions} and \code{convert-to-closures} for the example
  13179. program demonstrating lexical scoping that we discussed at the
  13180. beginning of this chapter.
  13181. \begin{figure}[tbp]
  13182. \begin{minipage}{0.8\textwidth}
  13183. % tests/lambda_test_6.rkt
  13184. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13185. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  13186. (let ([y8 4])
  13187. (lambda: ([z9 : Integer]) : Integer
  13188. (+ x7 (+ y8 z9)))))
  13189. (define (main) : Integer
  13190. (let ([g0 ((fun-ref-arity f6 1) 5)])
  13191. (let ([h1 ((fun-ref-arity f6 1) 3)])
  13192. (+ (g0 11) (h1 15)))))
  13193. \end{lstlisting}
  13194. $\Rightarrow$
  13195. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13196. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  13197. (let ([y8 4])
  13198. (closure 1 (list (fun-ref lambda2) x7 y8))))
  13199. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  13200. (let ([x7 (vector-ref fvs3 1)])
  13201. (let ([y8 (vector-ref fvs3 2)])
  13202. (+ x7 (+ y8 z9)))))
  13203. (define (main) : Integer
  13204. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  13205. ((vector-ref clos5 0) clos5 5))])
  13206. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  13207. ((vector-ref clos6 0) clos6 3))])
  13208. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  13209. \end{lstlisting}
  13210. \end{minipage}
  13211. \caption{Example of closure conversion.}
  13212. \label{fig:lexical-functions-example}
  13213. \end{figure}
  13214. \begin{exercise}\normalfont
  13215. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  13216. Create 5 new programs that use \key{lambda} functions and make use of
  13217. lexical scoping. Test your compiler on these new programs and all of
  13218. your previously created test programs.
  13219. \end{exercise}
  13220. \section{Expose Allocation}
  13221. \label{sec:expose-allocation-r5}
  13222. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  13223. that allocates and initializes a vector, similar to the translation of
  13224. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  13225. The only difference is replacing the use of
  13226. \ALLOC{\itm{len}}{\itm{type}} with
  13227. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  13228. \section{Explicate Control and \LangCLam{}}
  13229. \label{sec:explicate-r5}
  13230. The output language of \code{explicate\_control} is \LangCLam{} whose
  13231. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  13232. difference with respect to \LangCFun{} is the addition of the
  13233. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  13234. of \code{AllocateClosure} in the \code{explicate\_control} pass is
  13235. similar to the handling of other expressions such as primitive
  13236. operators.
  13237. \begin{figure}[tp]
  13238. \fbox{
  13239. \begin{minipage}{0.96\textwidth}
  13240. \small
  13241. \[
  13242. \begin{array}{lcl}
  13243. \Exp &::= & \ldots
  13244. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  13245. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  13246. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  13247. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  13248. \MID \GOTO{\itm{label}} } \\
  13249. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  13250. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  13251. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  13252. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  13253. \end{array}
  13254. \]
  13255. \end{minipage}
  13256. }
  13257. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  13258. \label{fig:c4-syntax}
  13259. \end{figure}
  13260. \section{Select Instructions}
  13261. \label{sec:select-instructions-Rlambda}
  13262. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  13263. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  13264. (Section~\ref{sec:select-instructions-gc}). The only difference is
  13265. that you should place the \itm{arity} in the tag that is stored at
  13266. position $0$ of the vector. Recall that in
  13267. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  13268. was not used. We store the arity in the $5$ bits starting at position
  13269. $58$.
  13270. Compile the \code{procedure-arity} operator into a sequence of
  13271. instructions that access the tag from position $0$ of the vector and
  13272. extract the $5$-bits starting at position $58$ from the tag.
  13273. \begin{figure}[p]
  13274. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13275. \node (Rfun) at (0,2) {\large \LangLam{}};
  13276. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  13277. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  13278. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  13279. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  13280. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13281. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  13282. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13283. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13284. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13285. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13286. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13287. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13288. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13289. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13290. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13291. \path[->,bend left=15] (Rfun) edge [above] node
  13292. {\ttfamily\footnotesize shrink} (Rfun-2);
  13293. \path[->,bend left=15] (Rfun-2) edge [above] node
  13294. {\ttfamily\footnotesize uniquify} (Rfun-3);
  13295. \path[->,bend left=15] (Rfun-3) edge [above] node
  13296. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  13297. \path[->,bend left=15] (F1-0) edge [right] node
  13298. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  13299. \path[->,bend left=15] (F1-1) edge [below] node
  13300. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  13301. \path[->,bend right=15] (F1-2) edge [above] node
  13302. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  13303. \path[->,bend right=15] (F1-3) edge [above] node
  13304. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13305. \path[->,bend right=15] (F1-4) edge [above] node
  13306. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13307. \path[->,bend right=15] (F1-5) edge [right] node
  13308. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13309. \path[->,bend left=15] (C3-2) edge [left] node
  13310. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13311. \path[->,bend right=15] (x86-2) edge [left] node
  13312. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13313. \path[->,bend right=15] (x86-2-1) edge [below] node
  13314. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13315. \path[->,bend right=15] (x86-2-2) edge [left] node
  13316. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13317. \path[->,bend left=15] (x86-3) edge [above] node
  13318. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13319. \path[->,bend left=15] (x86-4) edge [right] node
  13320. {\ttfamily\footnotesize print\_x86} (x86-5);
  13321. \end{tikzpicture}
  13322. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  13323. functions.}
  13324. \label{fig:Rlambda-passes}
  13325. \end{figure}
  13326. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  13327. for the compilation of \LangLam{}.
  13328. \clearpage
  13329. \section{Challenge: Optimize Closures}
  13330. \label{sec:optimize-closures}
  13331. In this chapter we compiled lexically-scoped functions into a
  13332. relatively efficient representation: flat closures. However, even this
  13333. representation comes with some overhead. For example, consider the
  13334. following program with a function \code{tail-sum} that does not have
  13335. any free variables and where all the uses of \code{tail-sum} are in
  13336. applications where we know that only \code{tail-sum} is being applied
  13337. (and not any other functions).
  13338. \begin{center}
  13339. \begin{minipage}{0.95\textwidth}
  13340. \begin{lstlisting}
  13341. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  13342. (if (eq? n 0)
  13343. r
  13344. (tail-sum (- n 1) (+ n r))))
  13345. (+ (tail-sum 5 0) 27)
  13346. \end{lstlisting}
  13347. \end{minipage}
  13348. \end{center}
  13349. As described in this chapter, we uniformly apply closure conversion to
  13350. all functions, obtaining the following output for this program.
  13351. \begin{center}
  13352. \begin{minipage}{0.95\textwidth}
  13353. \begin{lstlisting}
  13354. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  13355. (if (eq? n2 0)
  13356. r3
  13357. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  13358. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  13359. (define (main) : Integer
  13360. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  13361. ((vector-ref clos6 0) clos6 5 0)) 27))
  13362. \end{lstlisting}
  13363. \end{minipage}
  13364. \end{center}
  13365. In the previous Chapter, there would be no allocation in the program
  13366. and the calls to \code{tail-sum} would be direct calls. In contrast,
  13367. the above program allocates memory for each \code{closure} and the
  13368. calls to \code{tail-sum} are indirect. These two differences incur
  13369. considerable overhead in a program such as this one, where the
  13370. allocations and indirect calls occur inside a tight loop.
  13371. One might think that this problem is trivial to solve: can't we just
  13372. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  13373. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  13374. e'_n$)} instead of treating it like a call to a closure? We would
  13375. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  13376. %
  13377. However, this problem is not so trivial because a global function may
  13378. ``escape'' and become involved in applications that also involve
  13379. closures. Consider the following example in which the application
  13380. \code{(f 41)} needs to be compiled into a closure application, because
  13381. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  13382. function might also get bound to \code{f}.
  13383. \begin{lstlisting}
  13384. (define (add1 [x : Integer]) : Integer
  13385. (+ x 1))
  13386. (let ([y (read)])
  13387. (let ([f (if (eq? (read) 0)
  13388. add1
  13389. (lambda: ([x : Integer]) : Integer (- x y)))])
  13390. (f 41)))
  13391. \end{lstlisting}
  13392. If a global function name is used in any way other than as the
  13393. operator in a direct call, then we say that the function
  13394. \emph{escapes}. If a global function does not escape, then we do not
  13395. need to perform closure conversion on the function.
  13396. \begin{exercise}\normalfont
  13397. Implement an auxiliary function for detecting which global
  13398. functions escape. Using that function, implement an improved version
  13399. of closure conversion that does not apply closure conversion to
  13400. global functions that do not escape but instead compiles them as
  13401. regular functions. Create several new test cases that check whether
  13402. you properly detect whether global functions escape or not.
  13403. \end{exercise}
  13404. So far we have reduced the overhead of calling global functions, but
  13405. it would also be nice to reduce the overhead of calling a
  13406. \code{lambda} when we can determine at compile time which
  13407. \code{lambda} will be called. We refer to such calls as \emph{known
  13408. calls}. Consider the following example in which a \code{lambda} is
  13409. bound to \code{f} and then applied.
  13410. \begin{lstlisting}
  13411. (let ([y (read)])
  13412. (let ([f (lambda: ([x : Integer]) : Integer
  13413. (+ x y))])
  13414. (f 21)))
  13415. \end{lstlisting}
  13416. Closure conversion compiles \code{(f 21)} into an indirect call:
  13417. \begin{lstlisting}
  13418. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  13419. (let ([y2 (vector-ref fvs6 1)])
  13420. (+ x3 y2)))
  13421. (define (main) : Integer
  13422. (let ([y2 (read)])
  13423. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  13424. ((vector-ref f4 0) f4 21))))
  13425. \end{lstlisting}
  13426. but we can instead compile the application \code{(f 21)} into a direct call
  13427. to \code{lambda5}:
  13428. \begin{lstlisting}
  13429. (define (main) : Integer
  13430. (let ([y2 (read)])
  13431. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  13432. ((fun-ref lambda5) f4 21))))
  13433. \end{lstlisting}
  13434. The problem of determining which lambda will be called from a
  13435. particular application is quite challenging in general and the topic
  13436. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  13437. following exercise we recommend that you compile an application to a
  13438. direct call when the operator is a variable and the variable is
  13439. \code{let}-bound to a closure. This can be accomplished by maintaining
  13440. an environment mapping \code{let}-bound variables to function names.
  13441. Extend the environment whenever you encounter a closure on the
  13442. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  13443. to the name of the global function for the closure. This pass should
  13444. come after closure conversion.
  13445. \begin{exercise}\normalfont
  13446. Implement a compiler pass, named \code{optimize-known-calls}, that
  13447. compiles known calls into direct calls. Verify that your compiler is
  13448. successful in this regard on several example programs.
  13449. \end{exercise}
  13450. These exercises only scratches the surface of optimizing of
  13451. closures. A good next step for the interested reader is to look at the
  13452. work of \citet{Keep:2012ab}.
  13453. \section{Further Reading}
  13454. The notion of lexically scoped anonymous functions predates modern
  13455. computers by about a decade. They were invented by
  13456. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  13457. foundation for logic. Anonymous functions were included in the
  13458. LISP~\citep{McCarthy:1960dz} programming language but were initially
  13459. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  13460. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  13461. compile Scheme programs. However, environments were represented as
  13462. linked lists, so variable lookup was linear in the size of the
  13463. environment. In this chapter we represent environments using flat
  13464. closures, which were invented by
  13465. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  13466. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  13467. closures, variable lookup is constant time but the time to create a
  13468. closure is proportional to the number of its free variables. Flat
  13469. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  13470. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  13471. \fi
  13472. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13473. \chapter{Dynamic Typing}
  13474. \label{ch:Rdyn}
  13475. \index{subject}{dynamic typing}
  13476. \if\edition\racketEd
  13477. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  13478. typed language that is a subset of Racket. This is in contrast to the
  13479. previous chapters, which have studied the compilation of Typed
  13480. Racket. In dynamically typed languages such as \LangDyn{}, a given
  13481. expression may produce a value of a different type each time it is
  13482. executed. Consider the following example with a conditional \code{if}
  13483. expression that may return a Boolean or an integer depending on the
  13484. input to the program.
  13485. % part of dynamic_test_25.rkt
  13486. \begin{lstlisting}
  13487. (not (if (eq? (read) 1) #f 0))
  13488. \end{lstlisting}
  13489. Languages that allow expressions to produce different kinds of values
  13490. are called \emph{polymorphic}, a word composed of the Greek roots
  13491. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  13492. are several kinds of polymorphism in programming languages, such as
  13493. subtype polymorphism and parametric
  13494. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  13495. study in this chapter does not have a special name but it is the kind
  13496. that arises in dynamically typed languages.
  13497. Another characteristic of dynamically typed languages is that
  13498. primitive operations, such as \code{not}, are often defined to operate
  13499. on many different types of values. In fact, in Racket, the \code{not}
  13500. operator produces a result for any kind of value: given \code{\#f} it
  13501. returns \code{\#t} and given anything else it returns \code{\#f}.
  13502. Furthermore, even when primitive operations restrict their inputs to
  13503. values of a certain type, this restriction is enforced at runtime
  13504. instead of during compilation. For example, the following vector
  13505. reference results in a run-time contract violation because the index
  13506. must be in integer, not a Boolean such as \code{\#t}.
  13507. \begin{lstlisting}
  13508. (vector-ref (vector 42) #t)
  13509. \end{lstlisting}
  13510. \begin{figure}[tp]
  13511. \centering
  13512. \fbox{
  13513. \begin{minipage}{0.97\textwidth}
  13514. \[
  13515. \begin{array}{rcl}
  13516. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  13517. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  13518. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  13519. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  13520. &\MID& \key{\#t} \MID \key{\#f}
  13521. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  13522. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  13523. \MID \CUNIOP{\key{not}}{\Exp} \\
  13524. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  13525. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  13526. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  13527. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  13528. &\MID& \LP\Exp \; \Exp\ldots\RP
  13529. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  13530. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  13531. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  13532. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  13533. \LangDynM{} &::=& \Def\ldots\; \Exp
  13534. \end{array}
  13535. \]
  13536. \end{minipage}
  13537. }
  13538. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  13539. \label{fig:r7-concrete-syntax}
  13540. \end{figure}
  13541. \begin{figure}[tp]
  13542. \centering
  13543. \fbox{
  13544. \begin{minipage}{0.96\textwidth}
  13545. \small
  13546. \[
  13547. \begin{array}{lcl}
  13548. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  13549. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  13550. &\MID& \BOOL{\itm{bool}}
  13551. \MID \IF{\Exp}{\Exp}{\Exp} \\
  13552. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  13553. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  13554. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  13555. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13556. \end{array}
  13557. \]
  13558. \end{minipage}
  13559. }
  13560. \caption{The abstract syntax of \LangDyn{}.}
  13561. \label{fig:r7-syntax}
  13562. \end{figure}
  13563. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  13564. defined in Figures~\ref{fig:r7-concrete-syntax} and
  13565. \ref{fig:r7-syntax}.
  13566. %
  13567. There is no type checker for \LangDyn{} because it is not a statically
  13568. typed language (it's dynamically typed!).
  13569. The definitional interpreter for \LangDyn{} is presented in
  13570. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  13571. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  13572. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  13573. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  13574. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  13575. value} that combines an underlying value with a tag that identifies
  13576. what kind of value it is. We define the following struct
  13577. to represented tagged values.
  13578. \begin{lstlisting}
  13579. (struct Tagged (value tag) #:transparent)
  13580. \end{lstlisting}
  13581. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  13582. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  13583. but don't always capture all the information that a type does. For
  13584. example, a vector of type \code{(Vector Any Any)} is tagged with
  13585. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  13586. is tagged with \code{Procedure}.
  13587. Next consider the match case for \code{vector-ref}. The
  13588. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  13589. is used to ensure that the first argument is a vector and the second
  13590. is an integer. If they are not, a \code{trapped-error} is raised.
  13591. Recall from Section~\ref{sec:interp_Lint} that when a definition
  13592. interpreter raises a \code{trapped-error} error, the compiled code
  13593. must also signal an error by exiting with return code \code{255}. A
  13594. \code{trapped-error} is also raised if the index is not less than
  13595. length of the vector.
  13596. \begin{figure}[tbp]
  13597. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13598. (define ((interp-Rdyn-exp env) ast)
  13599. (define recur (interp-Rdyn-exp env))
  13600. (match ast
  13601. [(Var x) (lookup x env)]
  13602. [(Int n) (Tagged n 'Integer)]
  13603. [(Bool b) (Tagged b 'Boolean)]
  13604. [(Lambda xs rt body)
  13605. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  13606. [(Prim 'vector es)
  13607. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  13608. [(Prim 'vector-ref (list e1 e2))
  13609. (define vec (recur e1)) (define i (recur e2))
  13610. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  13611. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  13612. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  13613. (vector-ref (Tagged-value vec) (Tagged-value i))]
  13614. [(Prim 'vector-set! (list e1 e2 e3))
  13615. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  13616. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  13617. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  13618. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  13619. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  13620. (Tagged (void) 'Void)]
  13621. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  13622. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  13623. [(Prim 'or (list e1 e2))
  13624. (define v1 (recur e1))
  13625. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  13626. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  13627. [(Prim op (list e1))
  13628. #:when (set-member? type-predicates op)
  13629. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  13630. [(Prim op es)
  13631. (define args (map recur es))
  13632. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  13633. (unless (for/or ([expected-tags (op-tags op)])
  13634. (equal? expected-tags tags))
  13635. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  13636. (tag-value
  13637. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  13638. [(If q t f)
  13639. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  13640. [(Apply f es)
  13641. (define new-f (recur f)) (define args (map recur es))
  13642. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  13643. (match f-val
  13644. [`(function ,xs ,body ,lam-env)
  13645. (unless (eq? (length xs) (length args))
  13646. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  13647. (define new-env (append (map cons xs args) lam-env))
  13648. ((interp-Rdyn-exp new-env) body)]
  13649. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  13650. \end{lstlisting}
  13651. \caption{Interpreter for the \LangDyn{} language.}
  13652. \label{fig:interp-Rdyn}
  13653. \end{figure}
  13654. \begin{figure}[tbp]
  13655. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13656. (define (interp-op op)
  13657. (match op
  13658. ['+ fx+]
  13659. ['- fx-]
  13660. ['read read-fixnum]
  13661. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  13662. ['< (lambda (v1 v2)
  13663. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  13664. ['<= (lambda (v1 v2)
  13665. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  13666. ['> (lambda (v1 v2)
  13667. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  13668. ['>= (lambda (v1 v2)
  13669. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  13670. ['boolean? boolean?]
  13671. ['integer? fixnum?]
  13672. ['void? void?]
  13673. ['vector? vector?]
  13674. ['vector-length vector-length]
  13675. ['procedure? (match-lambda
  13676. [`(functions ,xs ,body ,env) #t] [else #f])]
  13677. [else (error 'interp-op "unknown operator" op)]))
  13678. (define (op-tags op)
  13679. (match op
  13680. ['+ '((Integer Integer))]
  13681. ['- '((Integer Integer) (Integer))]
  13682. ['read '(())]
  13683. ['not '((Boolean))]
  13684. ['< '((Integer Integer))]
  13685. ['<= '((Integer Integer))]
  13686. ['> '((Integer Integer))]
  13687. ['>= '((Integer Integer))]
  13688. ['vector-length '((Vector))]))
  13689. (define type-predicates
  13690. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  13691. (define (tag-value v)
  13692. (cond [(boolean? v) (Tagged v 'Boolean)]
  13693. [(fixnum? v) (Tagged v 'Integer)]
  13694. [(procedure? v) (Tagged v 'Procedure)]
  13695. [(vector? v) (Tagged v 'Vector)]
  13696. [(void? v) (Tagged v 'Void)]
  13697. [else (error 'tag-value "unidentified value ~a" v)]))
  13698. (define (check-tag val expected ast)
  13699. (define tag (Tagged-tag val))
  13700. (unless (eq? tag expected)
  13701. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  13702. \end{lstlisting}
  13703. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  13704. \label{fig:interp-Rdyn-aux}
  13705. \end{figure}
  13706. \clearpage
  13707. \section{Representation of Tagged Values}
  13708. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  13709. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  13710. values at the bit level. Because almost every operation in \LangDyn{}
  13711. involves manipulating tagged values, the representation must be
  13712. efficient. Recall that all of our values are 64 bits. We shall steal
  13713. the 3 right-most bits to encode the tag. We use $001$ to identify
  13714. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  13715. and $101$ for the void value. We define the following auxiliary
  13716. function for mapping types to tag codes.
  13717. \begin{align*}
  13718. \itm{tagof}(\key{Integer}) &= 001 \\
  13719. \itm{tagof}(\key{Boolean}) &= 100 \\
  13720. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  13721. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  13722. \itm{tagof}(\key{Void}) &= 101
  13723. \end{align*}
  13724. This stealing of 3 bits comes at some price: our integers are reduced
  13725. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  13726. affect vectors and procedures because those values are addresses, and
  13727. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  13728. they are always $000$. Thus, we do not lose information by overwriting
  13729. the rightmost 3 bits with the tag and we can simply zero-out the tag
  13730. to recover the original address.
  13731. To make tagged values into first-class entities, we can give them a
  13732. type, called \code{Any}, and define operations such as \code{Inject}
  13733. and \code{Project} for creating and using them, yielding the \LangAny{}
  13734. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  13735. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  13736. in greater detail.
  13737. \section{The \LangAny{} Language}
  13738. \label{sec:Rany-lang}
  13739. \begin{figure}[tp]
  13740. \centering
  13741. \fbox{
  13742. \begin{minipage}{0.96\textwidth}
  13743. \small
  13744. \[
  13745. \begin{array}{lcl}
  13746. \Type &::= & \ldots \MID \key{Any} \\
  13747. \itm{op} &::= & \ldots \MID \code{any-vector-length}
  13748. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  13749. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  13750. \MID \code{procedure?} \MID \code{void?} \\
  13751. \Exp &::=& \ldots
  13752. \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  13753. &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  13754. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  13755. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  13756. \end{array}
  13757. \]
  13758. \end{minipage}
  13759. }
  13760. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  13761. \label{fig:Rany-syntax}
  13762. \end{figure}
  13763. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  13764. (The concrete syntax of \LangAny{} is in the Appendix,
  13765. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  13766. converts the value produced by expression $e$ of type $T$ into a
  13767. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  13768. produced by expression $e$ into a value of type $T$ or else halts the
  13769. program if the type tag is not equivalent to $T$.
  13770. %
  13771. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  13772. restricted to a flat type $\FType$, which simplifies the
  13773. implementation and corresponds with what is needed for compiling \LangDyn{}.
  13774. The \code{any-vector} operators adapt the vector operations so that
  13775. they can be applied to a value of type \code{Any}. They also
  13776. generalize the vector operations in that the index is not restricted
  13777. to be a literal integer in the grammar but is allowed to be any
  13778. expression.
  13779. The type predicates such as \key{boolean?} expect their argument to
  13780. produce a tagged value; they return \key{\#t} if the tag corresponds
  13781. to the predicate and they return \key{\#f} otherwise.
  13782. The type checker for \LangAny{} is shown in
  13783. Figures~\ref{fig:type-check-Rany-part-1} and
  13784. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  13785. Figure~\ref{fig:type-check-Rany-aux}.
  13786. %
  13787. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  13788. auxiliary functions \code{apply-inject} and \code{apply-project} are
  13789. in Figure~\ref{fig:apply-project}.
  13790. \begin{figure}[btp]
  13791. \begin{lstlisting}[basicstyle=\ttfamily\small]
  13792. (define type-check-Rany_class
  13793. (class type-check-Rlambda_class
  13794. (super-new)
  13795. (inherit check-type-equal?)
  13796. (define/override (type-check-exp env)
  13797. (lambda (e)
  13798. (define recur (type-check-exp env))
  13799. (match e
  13800. [(Inject e1 ty)
  13801. (unless (flat-ty? ty)
  13802. (error 'type-check "may only inject from flat type, not ~a" ty))
  13803. (define-values (new-e1 e-ty) (recur e1))
  13804. (check-type-equal? e-ty ty e)
  13805. (values (Inject new-e1 ty) 'Any)]
  13806. [(Project e1 ty)
  13807. (unless (flat-ty? ty)
  13808. (error 'type-check "may only project to flat type, not ~a" ty))
  13809. (define-values (new-e1 e-ty) (recur e1))
  13810. (check-type-equal? e-ty 'Any e)
  13811. (values (Project new-e1 ty) ty)]
  13812. [(Prim 'any-vector-length (list e1))
  13813. (define-values (e1^ t1) (recur e1))
  13814. (check-type-equal? t1 'Any e)
  13815. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  13816. [(Prim 'any-vector-ref (list e1 e2))
  13817. (define-values (e1^ t1) (recur e1))
  13818. (define-values (e2^ t2) (recur e2))
  13819. (check-type-equal? t1 'Any e)
  13820. (check-type-equal? t2 'Integer e)
  13821. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  13822. [(Prim 'any-vector-set! (list e1 e2 e3))
  13823. (define-values (e1^ t1) (recur e1))
  13824. (define-values (e2^ t2) (recur e2))
  13825. (define-values (e3^ t3) (recur e3))
  13826. (check-type-equal? t1 'Any e)
  13827. (check-type-equal? t2 'Integer e)
  13828. (check-type-equal? t3 'Any e)
  13829. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  13830. \end{lstlisting}
  13831. \caption{Type checker for the \LangAny{} language, part 1.}
  13832. \label{fig:type-check-Rany-part-1}
  13833. \end{figure}
  13834. \begin{figure}[btp]
  13835. \begin{lstlisting}[basicstyle=\ttfamily\small]
  13836. [(ValueOf e ty)
  13837. (define-values (new-e e-ty) (recur e))
  13838. (values (ValueOf new-e ty) ty)]
  13839. [(Prim pred (list e1))
  13840. #:when (set-member? (type-predicates) pred)
  13841. (define-values (new-e1 e-ty) (recur e1))
  13842. (check-type-equal? e-ty 'Any e)
  13843. (values (Prim pred (list new-e1)) 'Boolean)]
  13844. [(If cnd thn els)
  13845. (define-values (cnd^ Tc) (recur cnd))
  13846. (define-values (thn^ Tt) (recur thn))
  13847. (define-values (els^ Te) (recur els))
  13848. (check-type-equal? Tc 'Boolean cnd)
  13849. (check-type-equal? Tt Te e)
  13850. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  13851. [(Exit) (values (Exit) '_)]
  13852. [(Prim 'eq? (list arg1 arg2))
  13853. (define-values (e1 t1) (recur arg1))
  13854. (define-values (e2 t2) (recur arg2))
  13855. (match* (t1 t2)
  13856. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  13857. [(other wise) (check-type-equal? t1 t2 e)])
  13858. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  13859. [else ((super type-check-exp env) e)])))
  13860. ))
  13861. \end{lstlisting}
  13862. \caption{Type checker for the \LangAny{} language, part 2.}
  13863. \label{fig:type-check-Rany-part-2}
  13864. \end{figure}
  13865. \begin{figure}[tbp]
  13866. \begin{lstlisting}
  13867. (define/override (operator-types)
  13868. (append
  13869. '((integer? . ((Any) . Boolean))
  13870. (vector? . ((Any) . Boolean))
  13871. (procedure? . ((Any) . Boolean))
  13872. (void? . ((Any) . Boolean))
  13873. (tag-of-any . ((Any) . Integer))
  13874. (make-any . ((_ Integer) . Any))
  13875. )
  13876. (super operator-types)))
  13877. (define/public (type-predicates)
  13878. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  13879. (define/public (combine-types t1 t2)
  13880. (match (list t1 t2)
  13881. [(list '_ t2) t2]
  13882. [(list t1 '_) t1]
  13883. [(list `(Vector ,ts1 ...)
  13884. `(Vector ,ts2 ...))
  13885. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  13886. (combine-types t1 t2)))]
  13887. [(list `(,ts1 ... -> ,rt1)
  13888. `(,ts2 ... -> ,rt2))
  13889. `(,@(for/list ([t1 ts1] [t2 ts2])
  13890. (combine-types t1 t2))
  13891. -> ,(combine-types rt1 rt2))]
  13892. [else t1]))
  13893. (define/public (flat-ty? ty)
  13894. (match ty
  13895. [(or `Integer `Boolean '_ `Void) #t]
  13896. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  13897. [`(,ts ... -> ,rt)
  13898. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  13899. [else #f]))
  13900. \end{lstlisting}
  13901. \caption{Auxiliary methods for type checking \LangAny{}.}
  13902. \label{fig:type-check-Rany-aux}
  13903. \end{figure}
  13904. \begin{figure}[btp]
  13905. \begin{lstlisting}
  13906. (define interp-Rany_class
  13907. (class interp-Rlambda_class
  13908. (super-new)
  13909. (define/override (interp-op op)
  13910. (match op
  13911. ['boolean? (match-lambda
  13912. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  13913. [else #f])]
  13914. ['integer? (match-lambda
  13915. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  13916. [else #f])]
  13917. ['vector? (match-lambda
  13918. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  13919. [else #f])]
  13920. ['procedure? (match-lambda
  13921. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  13922. [else #f])]
  13923. ['eq? (match-lambda*
  13924. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  13925. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  13926. [ls (apply (super interp-op op) ls)])]
  13927. ['any-vector-ref (lambda (v i)
  13928. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  13929. ['any-vector-set! (lambda (v i a)
  13930. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  13931. ['any-vector-length (lambda (v)
  13932. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  13933. [else (super interp-op op)]))
  13934. (define/override ((interp-exp env) e)
  13935. (define recur (interp-exp env))
  13936. (match e
  13937. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  13938. [(Project e ty2) (apply-project (recur e) ty2)]
  13939. [else ((super interp-exp env) e)]))
  13940. ))
  13941. (define (interp-Rany p)
  13942. (send (new interp-Rany_class) interp-program p))
  13943. \end{lstlisting}
  13944. \caption{Interpreter for \LangAny{}.}
  13945. \label{fig:interp-Rany}
  13946. \end{figure}
  13947. \begin{figure}[tbp]
  13948. \begin{lstlisting}
  13949. (define/public (apply-inject v tg) (Tagged v tg))
  13950. (define/public (apply-project v ty2)
  13951. (define tag2 (any-tag ty2))
  13952. (match v
  13953. [(Tagged v1 tag1)
  13954. (cond
  13955. [(eq? tag1 tag2)
  13956. (match ty2
  13957. [`(Vector ,ts ...)
  13958. (define l1 ((interp-op 'vector-length) v1))
  13959. (cond
  13960. [(eq? l1 (length ts)) v1]
  13961. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  13962. l1 (length ts))])]
  13963. [`(,ts ... -> ,rt)
  13964. (match v1
  13965. [`(function ,xs ,body ,env)
  13966. (cond [(eq? (length xs) (length ts)) v1]
  13967. [else
  13968. (error 'apply-project "arity mismatch ~a != ~a"
  13969. (length xs) (length ts))])]
  13970. [else (error 'apply-project "expected function not ~a" v1)])]
  13971. [else v1])]
  13972. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  13973. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  13974. \end{lstlisting}
  13975. \caption{Auxiliary functions for injection and projection.}
  13976. \label{fig:apply-project}
  13977. \end{figure}
  13978. \clearpage
  13979. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  13980. \label{sec:compile-r7}
  13981. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  13982. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  13983. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  13984. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  13985. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  13986. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  13987. the Boolean \code{\#t}, which must be injected to produce an
  13988. expression of type \key{Any}.
  13989. %
  13990. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  13991. addition, is representative of compilation for many primitive
  13992. operations: the arguments have type \key{Any} and must be projected to
  13993. \key{Integer} before the addition can be performed.
  13994. The compilation of \key{lambda} (third row of
  13995. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  13996. produce type annotations: we simply use \key{Any}.
  13997. %
  13998. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  13999. has to account for some differences in behavior between \LangDyn{} and
  14000. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  14001. kind of values can be used in various places. For example, the
  14002. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  14003. the arguments need not be of the same type (in that case the
  14004. result is \code{\#f}).
  14005. \begin{figure}[btp]
  14006. \centering
  14007. \begin{tabular}{|lll|} \hline
  14008. \begin{minipage}{0.27\textwidth}
  14009. \begin{lstlisting}
  14010. #t
  14011. \end{lstlisting}
  14012. \end{minipage}
  14013. &
  14014. $\Rightarrow$
  14015. &
  14016. \begin{minipage}{0.65\textwidth}
  14017. \begin{lstlisting}
  14018. (inject #t Boolean)
  14019. \end{lstlisting}
  14020. \end{minipage}
  14021. \\[2ex]\hline
  14022. \begin{minipage}{0.27\textwidth}
  14023. \begin{lstlisting}
  14024. (+ |$e_1$| |$e_2$|)
  14025. \end{lstlisting}
  14026. \end{minipage}
  14027. &
  14028. $\Rightarrow$
  14029. &
  14030. \begin{minipage}{0.65\textwidth}
  14031. \begin{lstlisting}
  14032. (inject
  14033. (+ (project |$e'_1$| Integer)
  14034. (project |$e'_2$| Integer))
  14035. Integer)
  14036. \end{lstlisting}
  14037. \end{minipage}
  14038. \\[2ex]\hline
  14039. \begin{minipage}{0.27\textwidth}
  14040. \begin{lstlisting}
  14041. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  14042. \end{lstlisting}
  14043. \end{minipage}
  14044. &
  14045. $\Rightarrow$
  14046. &
  14047. \begin{minipage}{0.65\textwidth}
  14048. \begin{lstlisting}
  14049. (inject
  14050. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  14051. (Any|$\ldots$|Any -> Any))
  14052. \end{lstlisting}
  14053. \end{minipage}
  14054. \\[2ex]\hline
  14055. \begin{minipage}{0.27\textwidth}
  14056. \begin{lstlisting}
  14057. (|$e_0$| |$e_1 \ldots e_n$|)
  14058. \end{lstlisting}
  14059. \end{minipage}
  14060. &
  14061. $\Rightarrow$
  14062. &
  14063. \begin{minipage}{0.65\textwidth}
  14064. \begin{lstlisting}
  14065. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  14066. \end{lstlisting}
  14067. \end{minipage}
  14068. \\[2ex]\hline
  14069. \begin{minipage}{0.27\textwidth}
  14070. \begin{lstlisting}
  14071. (vector-ref |$e_1$| |$e_2$|)
  14072. \end{lstlisting}
  14073. \end{minipage}
  14074. &
  14075. $\Rightarrow$
  14076. &
  14077. \begin{minipage}{0.65\textwidth}
  14078. \begin{lstlisting}
  14079. (any-vector-ref |$e_1'$| |$e_2'$|)
  14080. \end{lstlisting}
  14081. \end{minipage}
  14082. \\[2ex]\hline
  14083. \begin{minipage}{0.27\textwidth}
  14084. \begin{lstlisting}
  14085. (if |$e_1$| |$e_2$| |$e_3$|)
  14086. \end{lstlisting}
  14087. \end{minipage}
  14088. &
  14089. $\Rightarrow$
  14090. &
  14091. \begin{minipage}{0.65\textwidth}
  14092. \begin{lstlisting}
  14093. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  14094. \end{lstlisting}
  14095. \end{minipage}
  14096. \\[2ex]\hline
  14097. \begin{minipage}{0.27\textwidth}
  14098. \begin{lstlisting}
  14099. (eq? |$e_1$| |$e_2$|)
  14100. \end{lstlisting}
  14101. \end{minipage}
  14102. &
  14103. $\Rightarrow$
  14104. &
  14105. \begin{minipage}{0.65\textwidth}
  14106. \begin{lstlisting}
  14107. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  14108. \end{lstlisting}
  14109. \end{minipage}
  14110. \\[2ex]\hline
  14111. \begin{minipage}{0.27\textwidth}
  14112. \begin{lstlisting}
  14113. (not |$e_1$|)
  14114. \end{lstlisting}
  14115. \end{minipage}
  14116. &
  14117. $\Rightarrow$
  14118. &
  14119. \begin{minipage}{0.65\textwidth}
  14120. \begin{lstlisting}
  14121. (if (eq? |$e'_1$| (inject #f Boolean))
  14122. (inject #t Boolean) (inject #f Boolean))
  14123. \end{lstlisting}
  14124. \end{minipage}
  14125. \\[2ex]\hline
  14126. \end{tabular}
  14127. \caption{Cast Insertion}
  14128. \label{fig:compile-r7-Rany}
  14129. \end{figure}
  14130. \section{Reveal Casts}
  14131. \label{sec:reveal-casts-Rany}
  14132. % TODO: define R'_6
  14133. In the \code{reveal-casts} pass we recommend compiling \code{project}
  14134. into an \code{if} expression that checks whether the value's tag
  14135. matches the target type; if it does, the value is converted to a value
  14136. of the target type by removing the tag; if it does not, the program
  14137. exits. To perform these actions we need a new primitive operation,
  14138. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  14139. The \code{tag-of-any} operation retrieves the type tag from a tagged
  14140. value of type \code{Any}. The \code{ValueOf} form retrieves the
  14141. underlying value from a tagged value. The \code{ValueOf} form
  14142. includes the type for the underlying value which is used by the type
  14143. checker. Finally, the \code{Exit} form ends the execution of the
  14144. program.
  14145. If the target type of the projection is \code{Boolean} or
  14146. \code{Integer}, then \code{Project} can be translated as follows.
  14147. \begin{center}
  14148. \begin{minipage}{1.0\textwidth}
  14149. \begin{lstlisting}
  14150. (Project |$e$| |$\FType$|)
  14151. |$\Rightarrow$|
  14152. (Let |$\itm{tmp}$| |$e'$|
  14153. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  14154. (Int |$\itm{tagof}(\FType)$|)))
  14155. (ValueOf |$\itm{tmp}$| |$\FType$|)
  14156. (Exit)))
  14157. \end{lstlisting}
  14158. \end{minipage}
  14159. \end{center}
  14160. If the target type of the projection is a vector or function type,
  14161. then there is a bit more work to do. For vectors, check that the
  14162. length of the vector type matches the length of the vector (using the
  14163. \code{vector-length} primitive). For functions, check that the number
  14164. of parameters in the function type matches the function's arity (using
  14165. \code{procedure-arity}).
  14166. Regarding \code{inject}, we recommend compiling it to a slightly
  14167. lower-level primitive operation named \code{make-any}. This operation
  14168. takes a tag instead of a type.
  14169. \begin{center}
  14170. \begin{minipage}{1.0\textwidth}
  14171. \begin{lstlisting}
  14172. (Inject |$e$| |$\FType$|)
  14173. |$\Rightarrow$|
  14174. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  14175. \end{lstlisting}
  14176. \end{minipage}
  14177. \end{center}
  14178. The type predicates (\code{boolean?}, etc.) can be translated into
  14179. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  14180. translation of \code{Project}.
  14181. The \code{any-vector-ref} and \code{any-vector-set!} operations
  14182. combine the projection action with the vector operation. Also, the
  14183. read and write operations allow arbitrary expressions for the index so
  14184. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  14185. cannot guarantee that the index is within bounds. Thus, we insert code
  14186. to perform bounds checking at runtime. The translation for
  14187. \code{any-vector-ref} is as follows and the other two operations are
  14188. translated in a similar way.
  14189. \begin{lstlisting}
  14190. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  14191. |$\Rightarrow$|
  14192. (Let |$v$| |$e'_1$|
  14193. (Let |$i$| |$e'_2$|
  14194. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  14195. (If (Prim '< (list (Var |$i$|)
  14196. (Prim 'any-vector-length (list (Var |$v$|)))))
  14197. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  14198. (Exit))))
  14199. \end{lstlisting}
  14200. \section{Remove Complex Operands}
  14201. \label{sec:rco-Rany}
  14202. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  14203. The subexpression of \code{ValueOf} must be atomic.
  14204. \section{Explicate Control and \LangCAny{}}
  14205. \label{sec:explicate-Rany}
  14206. The output of \code{explicate\_control} is the \LangCAny{} language whose
  14207. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  14208. form that we added to \LangAny{} remains an expression and the \code{Exit}
  14209. expression becomes a $\Tail$. Also, note that the index argument of
  14210. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  14211. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  14212. \begin{figure}[tp]
  14213. \fbox{
  14214. \begin{minipage}{0.96\textwidth}
  14215. \small
  14216. \[
  14217. \begin{array}{lcl}
  14218. \Exp &::= & \ldots
  14219. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  14220. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  14221. &\MID& \VALUEOF{\Exp}{\FType} \\
  14222. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14223. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  14224. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14225. \MID \GOTO{\itm{label}} } \\
  14226. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14227. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  14228. \MID \LP\key{Exit}\RP \\
  14229. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14230. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14231. \end{array}
  14232. \]
  14233. \end{minipage}
  14234. }
  14235. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  14236. \label{fig:c5-syntax}
  14237. \end{figure}
  14238. \section{Select Instructions}
  14239. \label{sec:select-Rany}
  14240. In the \code{select\_instructions} pass we translate the primitive
  14241. operations on the \code{Any} type to x86 instructions that involve
  14242. manipulating the 3 tag bits of the tagged value.
  14243. \paragraph{Make-any}
  14244. We recommend compiling the \key{make-any} primitive as follows if the
  14245. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  14246. shifts the destination to the left by the number of bits specified its
  14247. source argument (in this case $3$, the length of the tag) and it
  14248. preserves the sign of the integer. We use the \key{orq} instruction to
  14249. combine the tag and the value to form the tagged value. \\
  14250. \begin{lstlisting}
  14251. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  14252. |$\Rightarrow$|
  14253. movq |$e'$|, |\itm{lhs'}|
  14254. salq $3, |\itm{lhs'}|
  14255. orq $|$\itm{tag}$|, |\itm{lhs'}|
  14256. \end{lstlisting}
  14257. The instruction selection for vectors and procedures is different
  14258. because their is no need to shift them to the left. The rightmost 3
  14259. bits are already zeros as described at the beginning of this
  14260. chapter. So we just combine the value and the tag using \key{orq}. \\
  14261. \begin{lstlisting}
  14262. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  14263. |$\Rightarrow$|
  14264. movq |$e'$|, |\itm{lhs'}|
  14265. orq $|$\itm{tag}$|, |\itm{lhs'}|
  14266. \end{lstlisting}
  14267. \paragraph{Tag-of-any}
  14268. Recall that the \code{tag-of-any} operation extracts the type tag from
  14269. a value of type \code{Any}. The type tag is the bottom three bits, so
  14270. we obtain the tag by taking the bitwise-and of the value with $111$
  14271. ($7$ in decimal).
  14272. \begin{lstlisting}
  14273. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  14274. |$\Rightarrow$|
  14275. movq |$e'$|, |\itm{lhs'}|
  14276. andq $7, |\itm{lhs'}|
  14277. \end{lstlisting}
  14278. \paragraph{ValueOf}
  14279. Like \key{make-any}, the instructions for \key{ValueOf} are different
  14280. depending on whether the type $T$ is a pointer (vector or procedure)
  14281. or not (Integer or Boolean). The following shows the instruction
  14282. selection for Integer and Boolean. We produce an untagged value by
  14283. shifting it to the right by 3 bits.
  14284. \begin{lstlisting}
  14285. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  14286. |$\Rightarrow$|
  14287. movq |$e'$|, |\itm{lhs'}|
  14288. sarq $3, |\itm{lhs'}|
  14289. \end{lstlisting}
  14290. %
  14291. In the case for vectors and procedures, there is no need to
  14292. shift. Instead we just need to zero-out the rightmost 3 bits. We
  14293. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  14294. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  14295. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  14296. then apply \code{andq} with the tagged value to get the desired
  14297. result. \\
  14298. \begin{lstlisting}
  14299. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  14300. |$\Rightarrow$|
  14301. movq $|$-8$|, |\itm{lhs'}|
  14302. andq |$e'$|, |\itm{lhs'}|
  14303. \end{lstlisting}
  14304. %% \paragraph{Type Predicates} We leave it to the reader to
  14305. %% devise a sequence of instructions to implement the type predicates
  14306. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  14307. \paragraph{Any-vector-length}
  14308. \begin{lstlisting}
  14309. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  14310. |$\Longrightarrow$|
  14311. movq |$\neg 111$|, %r11
  14312. andq |$a_1'$|, %r11
  14313. movq 0(%r11), %r11
  14314. andq $126, %r11
  14315. sarq $1, %r11
  14316. movq %r11, |$\itm{lhs'}$|
  14317. \end{lstlisting}
  14318. \paragraph{Any-vector-ref}
  14319. The index may be an arbitrary atom so instead of computing the offset
  14320. at compile time, instructions need to be generated to compute the
  14321. offset at runtime as follows. Note the use of the new instruction
  14322. \code{imulq}.
  14323. \begin{center}
  14324. \begin{minipage}{0.96\textwidth}
  14325. \begin{lstlisting}
  14326. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  14327. |$\Longrightarrow$|
  14328. movq |$\neg 111$|, %r11
  14329. andq |$a_1'$|, %r11
  14330. movq |$a_2'$|, %rax
  14331. addq $1, %rax
  14332. imulq $8, %rax
  14333. addq %rax, %r11
  14334. movq 0(%r11) |$\itm{lhs'}$|
  14335. \end{lstlisting}
  14336. \end{minipage}
  14337. \end{center}
  14338. \paragraph{Any-vector-set!}
  14339. The code generation for \code{any-vector-set!} is similar to the other
  14340. \code{any-vector} operations.
  14341. \section{Register Allocation for \LangAny{}}
  14342. \label{sec:register-allocation-Rany}
  14343. \index{subject}{register allocation}
  14344. There is an interesting interaction between tagged values and garbage
  14345. collection that has an impact on register allocation. A variable of
  14346. type \code{Any} might refer to a vector and therefore it might be a
  14347. root that needs to be inspected and copied during garbage
  14348. collection. Thus, we need to treat variables of type \code{Any} in a
  14349. similar way to variables of type \code{Vector} for purposes of
  14350. register allocation. In particular,
  14351. \begin{itemize}
  14352. \item If a variable of type \code{Any} is live during a function call,
  14353. then it must be spilled. This can be accomplished by changing
  14354. \code{build\_interference} to mark all variables of type \code{Any}
  14355. that are live after a \code{callq} as interfering with all the
  14356. registers.
  14357. \item If a variable of type \code{Any} is spilled, it must be spilled
  14358. to the root stack instead of the normal procedure call stack.
  14359. \end{itemize}
  14360. Another concern regarding the root stack is that the garbage collector
  14361. needs to differentiate between (1) plain old pointers to tuples, (2) a
  14362. tagged value that points to a tuple, and (3) a tagged value that is
  14363. not a tuple. We enable this differentiation by choosing not to use the
  14364. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  14365. reserved for identifying plain old pointers to tuples. That way, if
  14366. one of the first three bits is set, then we have a tagged value and
  14367. inspecting the tag can differentiation between vectors ($010$) and the
  14368. other kinds of values.
  14369. \begin{exercise}\normalfont
  14370. Expand your compiler to handle \LangAny{} as discussed in the last few
  14371. sections. Create 5 new programs that use the \code{Any} type and the
  14372. new operations (\code{inject}, \code{project}, \code{boolean?},
  14373. etc.). Test your compiler on these new programs and all of your
  14374. previously created test programs.
  14375. \end{exercise}
  14376. \begin{exercise}\normalfont
  14377. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  14378. Create tests for \LangDyn{} by adapting ten of your previous test programs
  14379. by removing type annotations. Add 5 more tests programs that
  14380. specifically rely on the language being dynamically typed. That is,
  14381. they should not be legal programs in a statically typed language, but
  14382. nevertheless, they should be valid \LangDyn{} programs that run to
  14383. completion without error.
  14384. \end{exercise}
  14385. \begin{figure}[p]
  14386. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14387. \node (Rfun) at (0,4) {\large \LangDyn{}};
  14388. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  14389. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  14390. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  14391. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  14392. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  14393. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  14394. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  14395. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  14396. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  14397. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  14398. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  14399. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14400. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14401. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14402. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14403. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14404. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14405. \path[->,bend left=15] (Rfun) edge [above] node
  14406. {\ttfamily\footnotesize shrink} (Rfun-2);
  14407. \path[->,bend left=15] (Rfun-2) edge [above] node
  14408. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14409. \path[->,bend left=15] (Rfun-3) edge [above] node
  14410. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  14411. \path[->,bend right=15] (Rfun-4) edge [left] node
  14412. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  14413. \path[->,bend left=15] (Rfun-5) edge [above] node
  14414. {\ttfamily\footnotesize check\_bounds} (Rfun-6);
  14415. \path[->,bend left=15] (Rfun-6) edge [left] node
  14416. {\ttfamily\footnotesize reveal\_casts} (Rfun-7);
  14417. \path[->,bend left=15] (Rfun-7) edge [below] node
  14418. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14419. \path[->,bend right=15] (F1-2) edge [above] node
  14420. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14421. \path[->,bend right=15] (F1-3) edge [above] node
  14422. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14423. \path[->,bend right=15] (F1-4) edge [above] node
  14424. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14425. \path[->,bend right=15] (F1-5) edge [right] node
  14426. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14427. \path[->,bend left=15] (C3-2) edge [left] node
  14428. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14429. \path[->,bend right=15] (x86-2) edge [left] node
  14430. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14431. \path[->,bend right=15] (x86-2-1) edge [below] node
  14432. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14433. \path[->,bend right=15] (x86-2-2) edge [left] node
  14434. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14435. \path[->,bend left=15] (x86-3) edge [above] node
  14436. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14437. \path[->,bend left=15] (x86-4) edge [right] node
  14438. {\ttfamily\footnotesize print\_x86} (x86-5);
  14439. \end{tikzpicture}
  14440. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  14441. \label{fig:Rdyn-passes}
  14442. \end{figure}
  14443. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  14444. for the compilation of \LangDyn{}.
  14445. % Further Reading
  14446. \fi % racketEd
  14447. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14448. {\if\edition\pythonEd
  14449. \chapter{Objects}
  14450. \label{ch:Robject}
  14451. \index{subject}{objects}
  14452. \index{subject}{classes}
  14453. \fi}
  14454. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14455. \chapter{Gradual Typing}
  14456. \label{ch:Rgrad}
  14457. \index{subject}{gradual typing}
  14458. \if\edition\racketEd
  14459. This chapter studies a language, \LangGrad{}, in which the programmer
  14460. can choose between static and dynamic type checking in different parts
  14461. of a program, thereby mixing the statically typed \LangLoop{} language
  14462. with the dynamically typed \LangDyn{}. There are several approaches to
  14463. mixing static and dynamic typing, including multi-language
  14464. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  14465. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  14466. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  14467. programmer controls the amount of static versus dynamic checking by
  14468. adding or removing type annotations on parameters and
  14469. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  14470. %
  14471. The concrete syntax of \LangGrad{} is defined in
  14472. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  14473. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  14474. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  14475. non-terminals that make type annotations optional. The return types
  14476. are not optional in the abstract syntax; the parser fills in
  14477. \code{Any} when the return type is not specified in the concrete
  14478. syntax.
  14479. \begin{figure}[tp]
  14480. \centering
  14481. \fbox{
  14482. \begin{minipage}{0.96\textwidth}
  14483. \small
  14484. \[
  14485. \begin{array}{lcl}
  14486. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  14487. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  14488. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  14489. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  14490. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  14491. &\MID& \gray{\key{\#t} \MID \key{\#f}
  14492. \MID (\key{and}\;\Exp\;\Exp)
  14493. \MID (\key{or}\;\Exp\;\Exp)
  14494. \MID (\key{not}\;\Exp) } \\
  14495. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  14496. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  14497. (\key{vector-ref}\;\Exp\;\Int)} \\
  14498. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  14499. \MID (\Exp \; \Exp\ldots) } \\
  14500. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  14501. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  14502. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  14503. \MID \CBEGIN{\Exp\ldots}{\Exp}
  14504. \MID \CWHILE{\Exp}{\Exp} } \\
  14505. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  14506. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  14507. \end{array}
  14508. \]
  14509. \end{minipage}
  14510. }
  14511. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  14512. \label{fig:Rgrad-concrete-syntax}
  14513. \end{figure}
  14514. \begin{figure}[tp]
  14515. \centering
  14516. \fbox{
  14517. \begin{minipage}{0.96\textwidth}
  14518. \small
  14519. \[
  14520. \begin{array}{lcl}
  14521. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  14522. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  14523. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  14524. &\MID& \gray{ \BOOL{\itm{bool}}
  14525. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  14526. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  14527. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  14528. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  14529. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  14530. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  14531. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  14532. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14533. \end{array}
  14534. \]
  14535. \end{minipage}
  14536. }
  14537. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  14538. \label{fig:Rgrad-syntax}
  14539. \end{figure}
  14540. Both the type checker and the interpreter for \LangGrad{} require some
  14541. interesting changes to enable gradual typing, which we discuss in the
  14542. next two sections in the context of the \code{map-vec} example from
  14543. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  14544. revised the \code{map-vec} example, omitting the type annotations from
  14545. the \code{add1} function.
  14546. \begin{figure}[btp]
  14547. % gradual_test_9.rkt
  14548. \begin{lstlisting}
  14549. (define (map-vec [f : (Integer -> Integer)]
  14550. [v : (Vector Integer Integer)])
  14551. : (Vector Integer Integer)
  14552. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14553. (define (add1 x) (+ x 1))
  14554. (vector-ref (map-vec add1 (vector 0 41)) 1)
  14555. \end{lstlisting}
  14556. \caption{A partially-typed version of the \code{map-vec} example.}
  14557. \label{fig:gradual-map-vec}
  14558. \end{figure}
  14559. \section{Type Checking \LangGrad{} and \LangCast{}}
  14560. \label{sec:gradual-type-check}
  14561. The type checker for \LangGrad{} uses the \code{Any} type for missing
  14562. parameter and return types. For example, the \code{x} parameter of
  14563. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  14564. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  14565. consider the \code{+} operator inside \code{add1}. It expects both
  14566. arguments to have type \code{Integer}, but its first argument \code{x}
  14567. has type \code{Any}. In a gradually typed language, such differences
  14568. are allowed so long as the types are \emph{consistent}, that is, they
  14569. are equal except in places where there is an \code{Any} type. The type
  14570. \code{Any} is consistent with every other type.
  14571. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  14572. \begin{figure}[tbp]
  14573. \begin{lstlisting}
  14574. (define/public (consistent? t1 t2)
  14575. (match* (t1 t2)
  14576. [('Integer 'Integer) #t]
  14577. [('Boolean 'Boolean) #t]
  14578. [('Void 'Void) #t]
  14579. [('Any t2) #t]
  14580. [(t1 'Any) #t]
  14581. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14582. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  14583. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14584. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  14585. (consistent? rt1 rt2))]
  14586. [(other wise) #f]))
  14587. \end{lstlisting}
  14588. \caption{The consistency predicate on types.}
  14589. \label{fig:consistent}
  14590. \end{figure}
  14591. Returning to the \code{map-vec} example of
  14592. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  14593. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  14594. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  14595. because the two types are consistent. In particular, \code{->} is
  14596. equal to \code{->} and because \code{Any} is consistent with
  14597. \code{Integer}.
  14598. Next consider a program with an error, such as applying the
  14599. \code{map-vec} to a function that sometimes returns a Boolean, as
  14600. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  14601. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  14602. consistent with the type of parameter \code{f} of \code{map-vec}, that
  14603. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  14604. Integer)}. One might say that a gradual type checker is optimistic
  14605. in that it accepts programs that might execute without a runtime type
  14606. error.
  14607. %
  14608. Unfortunately, running this program with input \code{1} triggers an
  14609. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  14610. performs checking at runtime to ensure the integrity of the static
  14611. types, such as the \code{(Integer -> Integer)} annotation on parameter
  14612. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  14613. new \code{Cast} form that is inserted by the type checker. Thus, the
  14614. output of the type checker is a program in the \LangCast{} language, which
  14615. adds \code{Cast} to \LangLoop{}, as shown in
  14616. Figure~\ref{fig:Rgrad-prime-syntax}.
  14617. \begin{figure}[tp]
  14618. \centering
  14619. \fbox{
  14620. \begin{minipage}{0.96\textwidth}
  14621. \small
  14622. \[
  14623. \begin{array}{lcl}
  14624. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  14625. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  14626. \end{array}
  14627. \]
  14628. \end{minipage}
  14629. }
  14630. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  14631. \label{fig:Rgrad-prime-syntax}
  14632. \end{figure}
  14633. \begin{figure}[tbp]
  14634. \begin{lstlisting}
  14635. (define (map-vec [f : (Integer -> Integer)]
  14636. [v : (Vector Integer Integer)])
  14637. : (Vector Integer Integer)
  14638. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14639. (define (add1 x) (+ x 1))
  14640. (define (true) #t)
  14641. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  14642. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  14643. \end{lstlisting}
  14644. \caption{A variant of the \code{map-vec} example with an error.}
  14645. \label{fig:map-vec-maybe-add1}
  14646. \end{figure}
  14647. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  14648. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  14649. inserted every time the type checker sees two types that are
  14650. consistent but not equal. In the \code{add1} function, \code{x} is
  14651. cast to \code{Integer} and the result of the \code{+} is cast to
  14652. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  14653. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  14654. \begin{figure}[btp]
  14655. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14656. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  14657. : (Vector Integer Integer)
  14658. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  14659. (define (add1 [x : Any]) : Any
  14660. (cast (+ (cast x Any Integer) 1) Integer Any))
  14661. (define (true) : Any (cast #t Boolean Any))
  14662. (define (maybe-add1 [x : Any]) : Any
  14663. (if (eq? 0 (read)) (add1 x) (true)))
  14664. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  14665. (vector 0 41)) 0)
  14666. \end{lstlisting}
  14667. \caption{Output of type checking \code{map-vec}
  14668. and \code{maybe-add1}.}
  14669. \label{fig:map-vec-cast}
  14670. \end{figure}
  14671. The type checker for \LangGrad{} is defined in
  14672. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  14673. and \ref{fig:type-check-Rgradual-3}.
  14674. \begin{figure}[tbp]
  14675. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14676. (define type-check-gradual_class
  14677. (class type-check-Rwhile_class
  14678. (super-new)
  14679. (inherit operator-types type-predicates)
  14680. (define/override (type-check-exp env)
  14681. (lambda (e)
  14682. (define recur (type-check-exp env))
  14683. (match e
  14684. [(Prim 'vector-length (list e1))
  14685. (define-values (e1^ t) (recur e1))
  14686. (match t
  14687. [`(Vector ,ts ...)
  14688. (values (Prim 'vector-length (list e1^)) 'Integer)]
  14689. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  14690. [(Prim 'vector-ref (list e1 e2))
  14691. (define-values (e1^ t1) (recur e1))
  14692. (define-values (e2^ t2) (recur e2))
  14693. (check-consistent? t2 'Integer e)
  14694. (match t1
  14695. [`(Vector ,ts ...)
  14696. (match e2^
  14697. [(Int i)
  14698. (unless (and (0 . <= . i) (i . < . (length ts)))
  14699. (error 'type-check "invalid index ~a in ~a" i e))
  14700. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  14701. [else (define e1^^ (make-cast e1^ t1 'Any))
  14702. (define e2^^ (make-cast e2^ t2 'Integer))
  14703. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  14704. ['Any
  14705. (define e2^^ (make-cast e2^ t2 'Integer))
  14706. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  14707. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  14708. [(Prim 'vector-set! (list e1 e2 e3) )
  14709. (define-values (e1^ t1) (recur e1))
  14710. (define-values (e2^ t2) (recur e2))
  14711. (define-values (e3^ t3) (recur e3))
  14712. (check-consistent? t2 'Integer e)
  14713. (match t1
  14714. [`(Vector ,ts ...)
  14715. (match e2^
  14716. [(Int i)
  14717. (unless (and (0 . <= . i) (i . < . (length ts)))
  14718. (error 'type-check "invalid index ~a in ~a" i e))
  14719. (check-consistent? (list-ref ts i) t3 e)
  14720. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  14721. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  14722. [else
  14723. (define e1^^ (make-cast e1^ t1 'Any))
  14724. (define e2^^ (make-cast e2^ t2 'Integer))
  14725. (define e3^^ (make-cast e3^ t3 'Any))
  14726. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  14727. ['Any
  14728. (define e2^^ (make-cast e2^ t2 'Integer))
  14729. (define e3^^ (make-cast e3^ t3 'Any))
  14730. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  14731. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  14732. \end{lstlisting}
  14733. \caption{Type checker for the \LangGrad{} language, part 1.}
  14734. \label{fig:type-check-Rgradual-1}
  14735. \end{figure}
  14736. \begin{figure}[tbp]
  14737. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14738. [(Prim 'eq? (list e1 e2))
  14739. (define-values (e1^ t1) (recur e1))
  14740. (define-values (e2^ t2) (recur e2))
  14741. (check-consistent? t1 t2 e)
  14742. (define T (meet t1 t2))
  14743. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  14744. 'Boolean)]
  14745. [(Prim 'not (list e1))
  14746. (define-values (e1^ t1) (recur e1))
  14747. (match t1
  14748. ['Any
  14749. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  14750. (Bool #t) (Bool #f)))]
  14751. [else
  14752. (define-values (t-ret new-es^)
  14753. (type-check-op 'not (list t1) (list e1^) e))
  14754. (values (Prim 'not new-es^) t-ret)])]
  14755. [(Prim 'and (list e1 e2))
  14756. (recur (If e1 e2 (Bool #f)))]
  14757. [(Prim 'or (list e1 e2))
  14758. (define tmp (gensym 'tmp))
  14759. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  14760. [(Prim op es)
  14761. #:when (not (set-member? explicit-prim-ops op))
  14762. (define-values (new-es ts)
  14763. (for/lists (exprs types) ([e es])
  14764. (recur e)))
  14765. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  14766. (values (Prim op new-es^) t-ret)]
  14767. [(If e1 e2 e3)
  14768. (define-values (e1^ T1) (recur e1))
  14769. (define-values (e2^ T2) (recur e2))
  14770. (define-values (e3^ T3) (recur e3))
  14771. (check-consistent? T2 T3 e)
  14772. (match T1
  14773. ['Boolean
  14774. (define Tif (join T2 T3))
  14775. (values (If e1^ (make-cast e2^ T2 Tif)
  14776. (make-cast e3^ T3 Tif)) Tif)]
  14777. ['Any
  14778. (define Tif (meet T2 T3))
  14779. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  14780. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  14781. Tif)]
  14782. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  14783. [(HasType e1 T)
  14784. (define-values (e1^ T1) (recur e1))
  14785. (check-consistent? T1 T)
  14786. (values (make-cast e1^ T1 T) T)]
  14787. [(SetBang x e1)
  14788. (define-values (e1^ T1) (recur e1))
  14789. (define varT (dict-ref env x))
  14790. (check-consistent? T1 varT e)
  14791. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  14792. [(WhileLoop e1 e2)
  14793. (define-values (e1^ T1) (recur e1))
  14794. (check-consistent? T1 'Boolean e)
  14795. (define-values (e2^ T2) ((type-check-exp env) e2))
  14796. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  14797. \end{lstlisting}
  14798. \caption{Type checker for the \LangGrad{} language, part 2.}
  14799. \label{fig:type-check-Rgradual-2}
  14800. \end{figure}
  14801. \begin{figure}[tbp]
  14802. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14803. [(Apply e1 e2s)
  14804. (define-values (e1^ T1) (recur e1))
  14805. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  14806. (match T1
  14807. [`(,T1ps ... -> ,T1rt)
  14808. (for ([T2 T2s] [Tp T1ps])
  14809. (check-consistent? T2 Tp e))
  14810. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  14811. (make-cast e2 src tgt)))
  14812. (values (Apply e1^ e2s^^) T1rt)]
  14813. [`Any
  14814. (define e1^^ (make-cast e1^ 'Any
  14815. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  14816. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  14817. (make-cast e2 src 'Any)))
  14818. (values (Apply e1^^ e2s^^) 'Any)]
  14819. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  14820. [(Lambda params Tr e1)
  14821. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  14822. (match p
  14823. [`[,x : ,T] (values x T)]
  14824. [(? symbol? x) (values x 'Any)])))
  14825. (define-values (e1^ T1)
  14826. ((type-check-exp (append (map cons xs Ts) env)) e1))
  14827. (check-consistent? Tr T1 e)
  14828. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  14829. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  14830. [else ((super type-check-exp env) e)]
  14831. )))
  14832. \end{lstlisting}
  14833. \caption{Type checker for the \LangGrad{} language, part 3.}
  14834. \label{fig:type-check-Rgradual-3}
  14835. \end{figure}
  14836. \begin{figure}[tbp]
  14837. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  14838. (define/public (join t1 t2)
  14839. (match* (t1 t2)
  14840. [('Integer 'Integer) 'Integer]
  14841. [('Boolean 'Boolean) 'Boolean]
  14842. [('Void 'Void) 'Void]
  14843. [('Any t2) t2]
  14844. [(t1 'Any) t1]
  14845. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14846. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  14847. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14848. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  14849. -> ,(join rt1 rt2))]))
  14850. (define/public (meet t1 t2)
  14851. (match* (t1 t2)
  14852. [('Integer 'Integer) 'Integer]
  14853. [('Boolean 'Boolean) 'Boolean]
  14854. [('Void 'Void) 'Void]
  14855. [('Any t2) 'Any]
  14856. [(t1 'Any) 'Any]
  14857. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  14858. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  14859. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  14860. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  14861. -> ,(meet rt1 rt2))]))
  14862. (define/public (make-cast e src tgt)
  14863. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  14864. (define/public (check-consistent? t1 t2 e)
  14865. (unless (consistent? t1 t2)
  14866. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  14867. (define/override (type-check-op op arg-types args e)
  14868. (match (dict-ref (operator-types) op)
  14869. [`(,param-types . ,return-type)
  14870. (for ([at arg-types] [pt param-types])
  14871. (check-consistent? at pt e))
  14872. (values return-type
  14873. (for/list ([e args] [s arg-types] [t param-types])
  14874. (make-cast e s t)))]
  14875. [else (error 'type-check-op "unrecognized ~a" op)]))
  14876. (define explicit-prim-ops
  14877. (set-union
  14878. (type-predicates)
  14879. (set 'procedure-arity 'eq?
  14880. 'vector 'vector-length 'vector-ref 'vector-set!
  14881. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  14882. (define/override (fun-def-type d)
  14883. (match d
  14884. [(Def f params rt info body)
  14885. (define ps
  14886. (for/list ([p params])
  14887. (match p
  14888. [`[,x : ,T] T]
  14889. [(? symbol?) 'Any]
  14890. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  14891. `(,@ps -> ,rt)]
  14892. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  14893. \end{lstlisting}
  14894. \caption{Auxiliary functions for type checking \LangGrad{}.}
  14895. \label{fig:type-check-Rgradual-aux}
  14896. \end{figure}
  14897. \clearpage
  14898. \section{Interpreting \LangCast{}}
  14899. \label{sec:interp-casts}
  14900. The runtime behavior of first-order casts is straightforward, that is,
  14901. casts involving simple types such as \code{Integer} and
  14902. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  14903. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  14904. puts the integer into a tagged value
  14905. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  14906. \code{Integer} is accomplished with the \code{Project} operator, that
  14907. is, by checking the value's tag and either retrieving the underlying
  14908. integer or signaling an error if it the tag is not the one for
  14909. integers (Figure~\ref{fig:apply-project}).
  14910. %
  14911. Things get more interesting for higher-order casts, that is, casts
  14912. involving function or vector types.
  14913. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  14914. Any)} to \code{(Integer -> Integer)}. When a function flows through
  14915. this cast at runtime, we can't know in general whether the function
  14916. will always return an integer.\footnote{Predicting the return value of
  14917. a function is equivalent to the halting problem, which is
  14918. undecidable.} The \LangCast{} interpreter therefore delays the checking
  14919. of the cast until the function is applied. This is accomplished by
  14920. wrapping \code{maybe-add1} in a new function that casts its parameter
  14921. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  14922. casts the return value from \code{Any} to \code{Integer}.
  14923. Turning our attention to casts involving vector types, we consider the
  14924. example in Figure~\ref{fig:map-vec-bang} that defines a
  14925. partially-typed version of \code{map-vec} whose parameter \code{v} has
  14926. type \code{(Vector Any Any)} and that updates \code{v} in place
  14927. instead of returning a new vector. So we name this function
  14928. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  14929. the type checker inserts a cast from \code{(Vector Integer Integer)}
  14930. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  14931. cast between vector types would be a build a new vector whose elements
  14932. are the result of casting each of the original elements to the
  14933. appropriate target type. However, this approach is only valid for
  14934. immutable vectors; and our vectors are mutable. In the example of
  14935. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  14936. the updates inside of \code{map-vec!} would happen to the new vector
  14937. and not the original one.
  14938. \begin{figure}[tbp]
  14939. % gradual_test_11.rkt
  14940. \begin{lstlisting}
  14941. (define (map-vec! [f : (Any -> Any)]
  14942. [v : (Vector Any Any)]) : Void
  14943. (begin
  14944. (vector-set! v 0 (f (vector-ref v 0)))
  14945. (vector-set! v 1 (f (vector-ref v 1)))))
  14946. (define (add1 x) (+ x 1))
  14947. (let ([v (vector 0 41)])
  14948. (begin (map-vec! add1 v) (vector-ref v 1)))
  14949. \end{lstlisting}
  14950. \caption{An example involving casts on vectors.}
  14951. \label{fig:map-vec-bang}
  14952. \end{figure}
  14953. Instead the interpreter needs to create a new kind of value, a
  14954. \emph{vector proxy}, that intercepts every vector operation. On a
  14955. read, the proxy reads from the underlying vector and then applies a
  14956. cast to the resulting value. On a write, the proxy casts the argument
  14957. value and then performs the write to the underlying vector. For the
  14958. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  14959. \code{0} from \code{Integer} to \code{Any}. For the first
  14960. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  14961. to \code{Integer}.
  14962. The final category of cast that we need to consider are casts between
  14963. the \code{Any} type and either a function or a vector
  14964. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  14965. in which parameter \code{v} does not have a type annotation, so it is
  14966. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  14967. type \code{(Vector Integer Integer)} so the type checker inserts a
  14968. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  14969. thought is to use \code{Inject}, but that doesn't work because
  14970. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  14971. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  14972. to \code{Any}.
  14973. \begin{figure}[tbp]
  14974. \begin{lstlisting}
  14975. (define (map-vec! [f : (Any -> Any)] v) : Void
  14976. (begin
  14977. (vector-set! v 0 (f (vector-ref v 0)))
  14978. (vector-set! v 1 (f (vector-ref v 1)))))
  14979. (define (add1 x) (+ x 1))
  14980. (let ([v (vector 0 41)])
  14981. (begin (map-vec! add1 v) (vector-ref v 1)))
  14982. \end{lstlisting}
  14983. \caption{Casting a vector to \code{Any}.}
  14984. \label{fig:map-vec-any}
  14985. \end{figure}
  14986. The \LangCast{} interpreter uses an auxiliary function named
  14987. \code{apply-cast} to cast a value from a source type to a target type,
  14988. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  14989. of the kinds of casts that we've discussed in this section.
  14990. \begin{figure}[tbp]
  14991. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14992. (define/public (apply-cast v s t)
  14993. (match* (s t)
  14994. [(t1 t2) #:when (equal? t1 t2) v]
  14995. [('Any t2)
  14996. (match t2
  14997. [`(,ts ... -> ,rt)
  14998. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  14999. (define v^ (apply-project v any->any))
  15000. (apply-cast v^ any->any `(,@ts -> ,rt))]
  15001. [`(Vector ,ts ...)
  15002. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  15003. (define v^ (apply-project v vec-any))
  15004. (apply-cast v^ vec-any `(Vector ,@ts))]
  15005. [else (apply-project v t2)])]
  15006. [(t1 'Any)
  15007. (match t1
  15008. [`(,ts ... -> ,rt)
  15009. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  15010. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  15011. (apply-inject v^ (any-tag any->any))]
  15012. [`(Vector ,ts ...)
  15013. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  15014. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  15015. (apply-inject v^ (any-tag vec-any))]
  15016. [else (apply-inject v (any-tag t1))])]
  15017. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  15018. (define x (gensym 'x))
  15019. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  15020. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  15021. (define cast-writes
  15022. (for/list ([t1 ts1] [t2 ts2])
  15023. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  15024. `(vector-proxy ,(vector v (apply vector cast-reads)
  15025. (apply vector cast-writes)))]
  15026. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  15027. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  15028. `(function ,xs ,(Cast
  15029. (Apply (Value v)
  15030. (for/list ([x xs][t1 ts1][t2 ts2])
  15031. (Cast (Var x) t2 t1)))
  15032. rt1 rt2) ())]
  15033. ))
  15034. \end{lstlisting}
  15035. \caption{The \code{apply-cast} auxiliary method.}
  15036. \label{fig:apply-cast}
  15037. \end{figure}
  15038. The interpreter for \LangCast{} is defined in
  15039. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  15040. dispatching to \code{apply-cast}. To handle the addition of vector
  15041. proxies, we update the vector primitives in \code{interp-op} using the
  15042. functions in Figure~\ref{fig:guarded-vector}.
  15043. \begin{figure}[tbp]
  15044. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15045. (define interp-Rcast_class
  15046. (class interp-Rwhile_class
  15047. (super-new)
  15048. (inherit apply-fun apply-inject apply-project)
  15049. (define/override (interp-op op)
  15050. (match op
  15051. ['vector-length guarded-vector-length]
  15052. ['vector-ref guarded-vector-ref]
  15053. ['vector-set! guarded-vector-set!]
  15054. ['any-vector-ref (lambda (v i)
  15055. (match v [`(tagged ,v^ ,tg)
  15056. (guarded-vector-ref v^ i)]))]
  15057. ['any-vector-set! (lambda (v i a)
  15058. (match v [`(tagged ,v^ ,tg)
  15059. (guarded-vector-set! v^ i a)]))]
  15060. ['any-vector-length (lambda (v)
  15061. (match v [`(tagged ,v^ ,tg)
  15062. (guarded-vector-length v^)]))]
  15063. [else (super interp-op op)]
  15064. ))
  15065. (define/override ((interp-exp env) e)
  15066. (define (recur e) ((interp-exp env) e))
  15067. (match e
  15068. [(Value v) v]
  15069. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  15070. [else ((super interp-exp env) e)]))
  15071. ))
  15072. (define (interp-Rcast p)
  15073. (send (new interp-Rcast_class) interp-program p))
  15074. \end{lstlisting}
  15075. \caption{The interpreter for \LangCast{}.}
  15076. \label{fig:interp-Rcast}
  15077. \end{figure}
  15078. \begin{figure}[tbp]
  15079. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15080. (define (guarded-vector-ref vec i)
  15081. (match vec
  15082. [`(vector-proxy ,proxy)
  15083. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  15084. (define rd (vector-ref (vector-ref proxy 1) i))
  15085. (apply-fun rd (list val) 'guarded-vector-ref)]
  15086. [else (vector-ref vec i)]))
  15087. (define (guarded-vector-set! vec i arg)
  15088. (match vec
  15089. [`(vector-proxy ,proxy)
  15090. (define wr (vector-ref (vector-ref proxy 2) i))
  15091. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  15092. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  15093. [else (vector-set! vec i arg)]))
  15094. (define (guarded-vector-length vec)
  15095. (match vec
  15096. [`(vector-proxy ,proxy)
  15097. (guarded-vector-length (vector-ref proxy 0))]
  15098. [else (vector-length vec)]))
  15099. \end{lstlisting}
  15100. \caption{The guarded-vector auxiliary functions.}
  15101. \label{fig:guarded-vector}
  15102. \end{figure}
  15103. \section{Lower Casts}
  15104. \label{sec:lower-casts}
  15105. The next step in the journey towards x86 is the \code{lower-casts}
  15106. pass that translates the casts in \LangCast{} to the lower-level
  15107. \code{Inject} and \code{Project} operators and a new operator for
  15108. creating vector proxies, extending the \LangLoop{} language to create
  15109. \LangProxy{}. We recommend creating an auxiliary function named
  15110. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  15111. and a target type, and translates it to expression in \LangProxy{} that has
  15112. the same behavior as casting the expression from the source to the
  15113. target type in the interpreter.
  15114. The \code{lower-cast} function can follow a code structure similar to
  15115. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  15116. the interpreter for \LangCast{} because it must handle the same cases as
  15117. \code{apply-cast} and it needs to mimic the behavior of
  15118. \code{apply-cast}. The most interesting cases are those concerning the
  15119. casts between two vector types and between two function types.
  15120. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  15121. type to another vector type is accomplished by creating a proxy that
  15122. intercepts the operations on the underlying vector. Here we make the
  15123. creation of the proxy explicit with the \code{vector-proxy} primitive
  15124. operation. It takes three arguments, the first is an expression for
  15125. the vector, the second is a vector of functions for casting an element
  15126. that is being read from the vector, and the third is a vector of
  15127. functions for casting an element that is being written to the vector.
  15128. You can create the functions using \code{Lambda}. Also, as we shall
  15129. see in the next section, we need to differentiate these vectors from
  15130. the user-created ones, so we recommend using a new primitive operator
  15131. named \code{raw-vector} instead of \code{vector} to create these
  15132. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  15133. the output of \code{lower-casts} on the example in
  15134. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  15135. integers to a vector of \code{Any}.
  15136. \begin{figure}[tbp]
  15137. \begin{lstlisting}
  15138. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  15139. (begin
  15140. (vector-set! v 0 (f (vector-ref v 0)))
  15141. (vector-set! v 1 (f (vector-ref v 1)))))
  15142. (define (add1 [x : Any]) : Any
  15143. (inject (+ (project x Integer) 1) Integer))
  15144. (let ([v (vector 0 41)])
  15145. (begin
  15146. (map-vec! add1 (vector-proxy v
  15147. (raw-vector (lambda: ([x9 : Integer]) : Any
  15148. (inject x9 Integer))
  15149. (lambda: ([x9 : Integer]) : Any
  15150. (inject x9 Integer)))
  15151. (raw-vector (lambda: ([x9 : Any]) : Integer
  15152. (project x9 Integer))
  15153. (lambda: ([x9 : Any]) : Integer
  15154. (project x9 Integer)))))
  15155. (vector-ref v 1)))
  15156. \end{lstlisting}
  15157. \caption{Output of \code{lower-casts} on the example in
  15158. Figure~\ref{fig:map-vec-bang}.}
  15159. \label{fig:map-vec-bang-lower-cast}
  15160. \end{figure}
  15161. A cast from one function type to another function type is accomplished
  15162. by generating a \code{Lambda} whose parameter and return types match
  15163. the target function type. The body of the \code{Lambda} should cast
  15164. the parameters from the target type to the source type (yes,
  15165. backwards! functions are contravariant\index{subject}{contravariant} in the
  15166. parameters), then call the underlying function, and finally cast the
  15167. result from the source return type to the target return type.
  15168. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  15169. \code{lower-casts} pass on the \code{map-vec} example in
  15170. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  15171. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  15172. \begin{figure}[tbp]
  15173. \begin{lstlisting}
  15174. (define (map-vec [f : (Integer -> Integer)]
  15175. [v : (Vector Integer Integer)])
  15176. : (Vector Integer Integer)
  15177. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15178. (define (add1 [x : Any]) : Any
  15179. (inject (+ (project x Integer) 1) Integer))
  15180. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  15181. (project (add1 (inject x9 Integer)) Integer))
  15182. (vector 0 41)) 1)
  15183. \end{lstlisting}
  15184. \caption{Output of \code{lower-casts} on the example in
  15185. Figure~\ref{fig:gradual-map-vec}.}
  15186. \label{fig:map-vec-lower-cast}
  15187. \end{figure}
  15188. \section{Differentiate Proxies}
  15189. \label{sec:differentiate-proxies}
  15190. So far the job of differentiating vectors and vector proxies has been
  15191. the job of the interpreter. For example, the interpreter for \LangCast{}
  15192. implements \code{vector-ref} using the \code{guarded-vector-ref}
  15193. function in Figure~\ref{fig:guarded-vector}. In the
  15194. \code{differentiate-proxies} pass we shift this responsibility to the
  15195. generated code.
  15196. We begin by designing the output language $R^p_8$. In
  15197. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  15198. proxies. In $R^p_8$ we return the \code{Vector} type to
  15199. its original meaning, as the type of real vectors, and we introduce a
  15200. new type, \code{PVector}, whose values can be either real vectors or
  15201. vector proxies. This new type comes with a suite of new primitive
  15202. operations for creating and using values of type \code{PVector}. We
  15203. don't need to introduce a new type to represent vector proxies. A
  15204. proxy is represented by a vector containing three things: 1) the
  15205. underlying vector, 2) a vector of functions for casting elements that
  15206. are read from the vector, and 3) a vector of functions for casting
  15207. values to be written to the vector. So we define the following
  15208. abbreviation for the type of a vector proxy:
  15209. \[
  15210. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  15211. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  15212. \to (\key{PVector}~ T' \ldots)
  15213. \]
  15214. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  15215. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  15216. %
  15217. Next we describe each of the new primitive operations.
  15218. \begin{description}
  15219. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  15220. (\key{PVector} $T \ldots$)]\ \\
  15221. %
  15222. This operation brands a vector as a value of the \code{PVector} type.
  15223. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  15224. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  15225. %
  15226. This operation brands a vector proxy as value of the \code{PVector} type.
  15227. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  15228. \code{Boolean}] \ \\
  15229. %
  15230. returns true if the value is a vector proxy and false if it is a
  15231. real vector.
  15232. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  15233. (\key{Vector} $T \ldots$)]\ \\
  15234. %
  15235. Assuming that the input is a vector (and not a proxy), this
  15236. operation returns the vector.
  15237. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  15238. $\to$ \code{Boolean}]\ \\
  15239. %
  15240. Given a vector proxy, this operation returns the length of the
  15241. underlying vector.
  15242. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  15243. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  15244. %
  15245. Given a vector proxy, this operation returns the $i$th element of
  15246. the underlying vector.
  15247. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  15248. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  15249. proxy, this operation writes a value to the $i$th element of the
  15250. underlying vector.
  15251. \end{description}
  15252. Now to discuss the translation that differentiates vectors from
  15253. proxies. First, every type annotation in the program must be
  15254. translated (recursively) to replace \code{Vector} with \code{PVector}.
  15255. Next, we must insert uses of \code{PVector} operations in the
  15256. appropriate places. For example, we wrap every vector creation with an
  15257. \code{inject-vector}.
  15258. \begin{lstlisting}
  15259. (vector |$e_1 \ldots e_n$|)
  15260. |$\Rightarrow$|
  15261. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  15262. \end{lstlisting}
  15263. The \code{raw-vector} operator that we introduced in the previous
  15264. section does not get injected.
  15265. \begin{lstlisting}
  15266. (raw-vector |$e_1 \ldots e_n$|)
  15267. |$\Rightarrow$|
  15268. (vector |$e'_1 \ldots e'_n$|)
  15269. \end{lstlisting}
  15270. The \code{vector-proxy} primitive translates as follows.
  15271. \begin{lstlisting}
  15272. (vector-proxy |$e_1~e_2~e_3$|)
  15273. |$\Rightarrow$|
  15274. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  15275. \end{lstlisting}
  15276. We translate the vector operations into conditional expressions that
  15277. check whether the value is a proxy and then dispatch to either the
  15278. appropriate proxy vector operation or the regular vector operation.
  15279. For example, the following is the translation for \code{vector-ref}.
  15280. \begin{lstlisting}
  15281. (vector-ref |$e_1$| |$i$|)
  15282. |$\Rightarrow$|
  15283. (let ([|$v~e_1$|])
  15284. (if (proxy? |$v$|)
  15285. (proxy-vector-ref |$v$| |$i$|)
  15286. (vector-ref (project-vector |$v$|) |$i$|)
  15287. \end{lstlisting}
  15288. Note in the case of a real vector, we must apply \code{project-vector}
  15289. before the \code{vector-ref}.
  15290. \section{Reveal Casts}
  15291. \label{sec:reveal-casts-gradual}
  15292. Recall that the \code{reveal-casts} pass
  15293. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  15294. \code{Inject} and \code{Project} into lower-level operations. In
  15295. particular, \code{Project} turns into a conditional expression that
  15296. inspects the tag and retrieves the underlying value. Here we need to
  15297. augment the translation of \code{Project} to handle the situation when
  15298. the target type is \code{PVector}. Instead of using
  15299. \code{vector-length} we need to use \code{proxy-vector-length}.
  15300. \begin{lstlisting}
  15301. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  15302. |$\Rightarrow$|
  15303. (let |$\itm{tmp}$| |$e'$|
  15304. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  15305. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  15306. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  15307. (exit)))
  15308. \end{lstlisting}
  15309. \section{Closure Conversion}
  15310. \label{sec:closure-conversion-gradual}
  15311. The closure conversion pass only requires one minor adjustment. The
  15312. auxiliary function that translates type annotations needs to be
  15313. updated to handle the \code{PVector} type.
  15314. \section{Explicate Control}
  15315. \label{sec:explicate-control-gradual}
  15316. Update the \code{explicate\_control} pass to handle the new primitive
  15317. operations on the \code{PVector} type.
  15318. \section{Select Instructions}
  15319. \label{sec:select-instructions-gradual}
  15320. Recall that the \code{select\_instructions} pass is responsible for
  15321. lowering the primitive operations into x86 instructions. So we need
  15322. to translate the new \code{PVector} operations to x86. To do so, the
  15323. first question we need to answer is how will we differentiate the two
  15324. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  15325. We need just one bit to accomplish this, and use the bit in position
  15326. $57$ of the 64-bit tag at the front of every vector (see
  15327. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  15328. for \code{inject-vector} we leave it that way.
  15329. \begin{lstlisting}
  15330. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  15331. |$\Rightarrow$|
  15332. movq |$e'_1$|, |$\itm{lhs'}$|
  15333. \end{lstlisting}
  15334. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  15335. \begin{lstlisting}
  15336. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  15337. |$\Rightarrow$|
  15338. movq |$e'_1$|, %r11
  15339. movq |$(1 << 57)$|, %rax
  15340. orq 0(%r11), %rax
  15341. movq %rax, 0(%r11)
  15342. movq %r11, |$\itm{lhs'}$|
  15343. \end{lstlisting}
  15344. The \code{proxy?} operation consumes the information so carefully
  15345. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  15346. isolates the $57$th bit to tell whether the value is a real vector or
  15347. a proxy.
  15348. \begin{lstlisting}
  15349. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  15350. |$\Rightarrow$|
  15351. movq |$e_1'$|, %r11
  15352. movq 0(%r11), %rax
  15353. sarq $57, %rax
  15354. andq $1, %rax
  15355. movq %rax, |$\itm{lhs'}$|
  15356. \end{lstlisting}
  15357. The \code{project-vector} operation is straightforward to translate,
  15358. so we leave it up to the reader.
  15359. Regarding the \code{proxy-vector} operations, the runtime provides
  15360. procedures that implement them (they are recursive functions!) so
  15361. here we simply need to translate these vector operations into the
  15362. appropriate function call. For example, here is the translation for
  15363. \code{proxy-vector-ref}.
  15364. \begin{lstlisting}
  15365. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  15366. |$\Rightarrow$|
  15367. movq |$e_1'$|, %rdi
  15368. movq |$e_2'$|, %rsi
  15369. callq proxy_vector_ref
  15370. movq %rax, |$\itm{lhs'}$|
  15371. \end{lstlisting}
  15372. We have another batch of vector operations to deal with, those for the
  15373. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  15374. \code{any-vector-ref} when there is a \code{vector-ref} on something
  15375. of type \code{Any}, and similarly for \code{any-vector-set!} and
  15376. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  15377. Section~\ref{sec:select-Rany} we selected instructions for these
  15378. operations based on the idea that the underlying value was a real
  15379. vector. But in the current setting, the underlying value is of type
  15380. \code{PVector}. So \code{any-vector-ref} can be translates to
  15381. pseudo-x86 as follows. We begin by projecting the underlying value out
  15382. of the tagged value and then call the \code{proxy\_vector\_ref}
  15383. procedure in the runtime.
  15384. \begin{lstlisting}
  15385. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  15386. movq |$\neg 111$|, %rdi
  15387. andq |$e_1'$|, %rdi
  15388. movq |$e_2'$|, %rsi
  15389. callq proxy_vector_ref
  15390. movq %rax, |$\itm{lhs'}$|
  15391. \end{lstlisting}
  15392. The \code{any-vector-set!} and \code{any-vector-length} operators can
  15393. be translated in a similar way.
  15394. \begin{exercise}\normalfont
  15395. Implement a compiler for the gradually-typed \LangGrad{} language by
  15396. extending and adapting your compiler for \LangLoop{}. Create 10 new
  15397. partially-typed test programs. In addition to testing with these
  15398. new programs, also test your compiler on all the tests for \LangLoop{}
  15399. and tests for \LangDyn{}. Sometimes you may get a type checking error
  15400. on the \LangDyn{} programs but you can adapt them by inserting
  15401. a cast to the \code{Any} type around each subexpression
  15402. causing a type error. While \LangDyn{} doesn't have explicit casts,
  15403. you can induce one by wrapping the subexpression \code{e}
  15404. with a call to an un-annotated identity function, like this:
  15405. \code{((lambda (x) x) e)}.
  15406. \end{exercise}
  15407. \begin{figure}[p]
  15408. \begin{tikzpicture}[baseline=(current bounding box.center)]
  15409. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  15410. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  15411. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  15412. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  15413. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  15414. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  15415. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  15416. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  15417. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  15418. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  15419. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  15420. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  15421. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  15422. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  15423. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15424. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15425. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15426. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15427. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15428. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15429. \path[->,bend right=15] (Rgradual) edge [above] node
  15430. {\ttfamily\footnotesize type\_check} (Rgradualp);
  15431. \path[->,bend right=15] (Rgradualp) edge [above] node
  15432. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  15433. \path[->,bend right=15] (Rwhilepp) edge [right] node
  15434. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  15435. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  15436. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  15437. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  15438. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  15439. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  15440. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  15441. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  15442. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  15443. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  15444. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15445. \path[->,bend left=15] (F1-1) edge [below] node
  15446. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15447. \path[->,bend right=15] (F1-2) edge [above] node
  15448. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15449. \path[->,bend right=15] (F1-3) edge [above] node
  15450. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15451. \path[->,bend right=15] (F1-4) edge [above] node
  15452. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  15453. \path[->,bend right=15] (F1-5) edge [right] node
  15454. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15455. \path[->,bend left=15] (C3-2) edge [left] node
  15456. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15457. \path[->,bend right=15] (x86-2) edge [left] node
  15458. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15459. \path[->,bend right=15] (x86-2-1) edge [below] node
  15460. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15461. \path[->,bend right=15] (x86-2-2) edge [left] node
  15462. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15463. \path[->,bend left=15] (x86-3) edge [above] node
  15464. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15465. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  15466. \end{tikzpicture}
  15467. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  15468. \label{fig:Rgradual-passes}
  15469. \end{figure}
  15470. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  15471. for the compilation of \LangGrad{}.
  15472. \section{Further Reading}
  15473. This chapter just scratches the surface of gradual typing. The basic
  15474. approach described here is missing two key ingredients that one would
  15475. want in a implementation of gradual typing: blame
  15476. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  15477. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  15478. problem addressed by blame tracking is that when a cast on a
  15479. higher-order value fails, it often does so at a point in the program
  15480. that is far removed from the original cast. Blame tracking is a
  15481. technique for propagating extra information through casts and proxies
  15482. so that when a cast fails, the error message can point back to the
  15483. original location of the cast in the source program.
  15484. The problem addressed by space-efficient casts also relates to
  15485. higher-order casts. It turns out that in partially typed programs, a
  15486. function or vector can flow through very-many casts at runtime. With
  15487. the approach described in this chapter, each cast adds another
  15488. \code{lambda} wrapper or a vector proxy. Not only does this take up
  15489. considerable space, but it also makes the function calls and vector
  15490. operations slow. For example, a partially-typed version of quicksort
  15491. could, in the worst case, build a chain of proxies of length $O(n)$
  15492. around the vector, changing the overall time complexity of the
  15493. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  15494. solution to this problem by representing casts using the coercion
  15495. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  15496. long chains of proxies by compressing them into a concise normal
  15497. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  15498. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  15499. the Grift compiler.
  15500. \begin{center}
  15501. \url{https://github.com/Gradual-Typing/Grift}
  15502. \end{center}
  15503. There are also interesting interactions between gradual typing and
  15504. other language features, such as parametetric polymorphism,
  15505. information-flow types, and type inference, to name a few. We
  15506. recommend the reader to the online gradual typing bibliography:
  15507. \begin{center}
  15508. \url{http://samth.github.io/gradual-typing-bib/}
  15509. \end{center}
  15510. % TODO: challenge problem:
  15511. % type analysis and type specialization?
  15512. % coercions?
  15513. \fi
  15514. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15515. \chapter{Parametric Polymorphism}
  15516. \label{ch:Rpoly}
  15517. \index{subject}{parametric polymorphism}
  15518. \index{subject}{generics}
  15519. \if\edition\racketEd
  15520. This chapter studies the compilation of parametric
  15521. polymorphism\index{subject}{parametric polymorphism}
  15522. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  15523. Racket. Parametric polymorphism enables improved code reuse by
  15524. parameterizing functions and data structures with respect to the types
  15525. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  15526. revisits the \code{map-vec} example but this time gives it a more
  15527. fitting type. This \code{map-vec} function is parameterized with
  15528. respect to the element type of the vector. The type of \code{map-vec}
  15529. is the following polymorphic type as specified by the \code{All} and
  15530. the type parameter \code{a}.
  15531. \begin{lstlisting}
  15532. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15533. \end{lstlisting}
  15534. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  15535. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  15536. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  15537. \code{a}, but we could have just as well applied \code{map-vec} to a
  15538. vector of Booleans (and a function on Booleans).
  15539. \begin{figure}[tbp]
  15540. % poly_test_2.rkt
  15541. \begin{lstlisting}
  15542. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  15543. (define (map-vec f v)
  15544. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15545. (define (add1 [x : Integer]) : Integer (+ x 1))
  15546. (vector-ref (map-vec add1 (vector 0 41)) 1)
  15547. \end{lstlisting}
  15548. \caption{The \code{map-vec} example using parametric polymorphism.}
  15549. \label{fig:map-vec-poly}
  15550. \end{figure}
  15551. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  15552. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  15553. syntax. We add a second form for function definitions in which a type
  15554. declaration comes before the \code{define}. In the abstract syntax,
  15555. the return type in the \code{Def} is \code{Any}, but that should be
  15556. ignored in favor of the return type in the type declaration. (The
  15557. \code{Any} comes from using the same parser as in
  15558. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  15559. enables the use of an \code{All} type for a function, thereby making
  15560. it polymorphic. The grammar for types is extended to include
  15561. polymorphic types and type variables.
  15562. \begin{figure}[tp]
  15563. \centering
  15564. \fbox{
  15565. \begin{minipage}{0.96\textwidth}
  15566. \small
  15567. \[
  15568. \begin{array}{lcl}
  15569. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15570. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  15571. &\MID& \LP\key{:}~\Var~\Type\RP \\
  15572. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  15573. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  15574. \end{array}
  15575. \]
  15576. \end{minipage}
  15577. }
  15578. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  15579. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  15580. \label{fig:Rpoly-concrete-syntax}
  15581. \end{figure}
  15582. \begin{figure}[tp]
  15583. \centering
  15584. \fbox{
  15585. \begin{minipage}{0.96\textwidth}
  15586. \small
  15587. \[
  15588. \begin{array}{lcl}
  15589. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15590. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  15591. &\MID& \DECL{\Var}{\Type} \\
  15592. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  15593. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15594. \end{array}
  15595. \]
  15596. \end{minipage}
  15597. }
  15598. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  15599. (Figure~\ref{fig:Lwhile-syntax}).}
  15600. \label{fig:Rpoly-syntax}
  15601. \end{figure}
  15602. By including polymorphic types in the $\Type$ non-terminal we choose
  15603. to make them first-class which has interesting repercussions on the
  15604. compiler. Many languages with polymorphism, such as
  15605. C++~\citep{stroustrup88:_param_types} and Standard
  15606. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  15607. it is useful to see an example of first-class polymorphism. In
  15608. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  15609. whose parameter is a polymorphic function. The occurrence of a
  15610. polymorphic type underneath a function type is enabled by the normal
  15611. recursive structure of the grammar for $\Type$ and the categorization
  15612. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  15613. applies the polymorphic function to a Boolean and to an integer.
  15614. \begin{figure}[tbp]
  15615. \begin{lstlisting}
  15616. (: apply-twice ((All (b) (b -> b)) -> Integer))
  15617. (define (apply-twice f)
  15618. (if (f #t) (f 42) (f 777)))
  15619. (: id (All (a) (a -> a)))
  15620. (define (id x) x)
  15621. (apply-twice id)
  15622. \end{lstlisting}
  15623. \caption{An example illustrating first-class polymorphism.}
  15624. \label{fig:apply-twice}
  15625. \end{figure}
  15626. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  15627. three new responsibilities (compared to \LangLoop{}). The type checking of
  15628. function application is extended to handle the case where the operator
  15629. expression is a polymorphic function. In that case the type arguments
  15630. are deduced by matching the type of the parameters with the types of
  15631. the arguments.
  15632. %
  15633. The \code{match-types} auxiliary function carries out this deduction
  15634. by recursively descending through a parameter type \code{pt} and the
  15635. corresponding argument type \code{at}, making sure that they are equal
  15636. except when there is a type parameter on the left (in the parameter
  15637. type). If it's the first time that the type parameter has been
  15638. encountered, then the algorithm deduces an association of the type
  15639. parameter to the corresponding type on the right (in the argument
  15640. type). If it's not the first time that the type parameter has been
  15641. encountered, the algorithm looks up its deduced type and makes sure
  15642. that it is equal to the type on the right.
  15643. %
  15644. Once the type arguments are deduced, the operator expression is
  15645. wrapped in an \code{Inst} AST node (for instantiate) that records the
  15646. type of the operator, but more importantly, records the deduced type
  15647. arguments. The return type of the application is the return type of
  15648. the polymorphic function, but with the type parameters replaced by the
  15649. deduced type arguments, using the \code{subst-type} function.
  15650. The second responsibility of the type checker is extending the
  15651. function \code{type-equal?} to handle the \code{All} type. This is
  15652. not quite a simple as equal on other types, such as function and
  15653. vector types, because two polymorphic types can be syntactically
  15654. different even though they are equivalent types. For example,
  15655. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  15656. Two polymorphic types should be considered equal if they differ only
  15657. in the choice of the names of the type parameters. The
  15658. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  15659. renames the type parameters of the first type to match the type
  15660. parameters of the second type.
  15661. The third responsibility of the type checker is making sure that only
  15662. defined type variables appear in type annotations. The
  15663. \code{check-well-formed} function defined in
  15664. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  15665. sure that each type variable has been defined.
  15666. The output language of the type checker is \LangInst{}, defined in
  15667. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  15668. declaration and polymorphic function into a single definition, using
  15669. the \code{Poly} form, to make polymorphic functions more convenient to
  15670. process in next pass of the compiler.
  15671. \begin{figure}[tp]
  15672. \centering
  15673. \fbox{
  15674. \begin{minipage}{0.96\textwidth}
  15675. \small
  15676. \[
  15677. \begin{array}{lcl}
  15678. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  15679. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  15680. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  15681. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  15682. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  15683. \end{array}
  15684. \]
  15685. \end{minipage}
  15686. }
  15687. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  15688. (Figure~\ref{fig:Lwhile-syntax}).}
  15689. \label{fig:Rpoly-prime-syntax}
  15690. \end{figure}
  15691. The output of the type checker on the polymorphic \code{map-vec}
  15692. example is listed in Figure~\ref{fig:map-vec-type-check}.
  15693. \begin{figure}[tbp]
  15694. % poly_test_2.rkt
  15695. \begin{lstlisting}
  15696. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  15697. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  15698. (define (add1 [x : Integer]) : Integer (+ x 1))
  15699. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15700. (Integer))
  15701. add1 (vector 0 41)) 1)
  15702. \end{lstlisting}
  15703. \caption{Output of the type checker on the \code{map-vec} example.}
  15704. \label{fig:map-vec-type-check}
  15705. \end{figure}
  15706. \begin{figure}[tbp]
  15707. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15708. (define type-check-poly-class
  15709. (class type-check-Rwhile-class
  15710. (super-new)
  15711. (inherit check-type-equal?)
  15712. (define/override (type-check-apply env e1 es)
  15713. (define-values (e^ ty) ((type-check-exp env) e1))
  15714. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  15715. ((type-check-exp env) e)))
  15716. (match ty
  15717. [`(,ty^* ... -> ,rt)
  15718. (for ([arg-ty ty*] [param-ty ty^*])
  15719. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  15720. (values e^ es^ rt)]
  15721. [`(All ,xs (,tys ... -> ,rt))
  15722. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  15723. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  15724. (match-types env^^ param-ty arg-ty)))
  15725. (define targs
  15726. (for/list ([x xs])
  15727. (match (dict-ref env^^ x (lambda () #f))
  15728. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  15729. x (Apply e1 es))]
  15730. [ty ty])))
  15731. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  15732. [else (error 'type-check "expected a function, not ~a" ty)]))
  15733. (define/override ((type-check-exp env) e)
  15734. (match e
  15735. [(Lambda `([,xs : ,Ts] ...) rT body)
  15736. (for ([T Ts]) ((check-well-formed env) T))
  15737. ((check-well-formed env) rT)
  15738. ((super type-check-exp env) e)]
  15739. [(HasType e1 ty)
  15740. ((check-well-formed env) ty)
  15741. ((super type-check-exp env) e)]
  15742. [else ((super type-check-exp env) e)]))
  15743. (define/override ((type-check-def env) d)
  15744. (verbose 'type-check "poly/def" d)
  15745. (match d
  15746. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  15747. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  15748. (for ([p ps]) ((check-well-formed ts-env) p))
  15749. ((check-well-formed ts-env) rt)
  15750. (define new-env (append ts-env (map cons xs ps) env))
  15751. (define-values (body^ ty^) ((type-check-exp new-env) body))
  15752. (check-type-equal? ty^ rt body)
  15753. (Generic ts (Def f p:t* rt info body^))]
  15754. [else ((super type-check-def env) d)]))
  15755. (define/override (type-check-program p)
  15756. (match p
  15757. [(Program info body)
  15758. (type-check-program (ProgramDefsExp info '() body))]
  15759. [(ProgramDefsExp info ds body)
  15760. (define ds^ (combine-decls-defs ds))
  15761. (define new-env (for/list ([d ds^])
  15762. (cons (def-name d) (fun-def-type d))))
  15763. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  15764. (define-values (body^ ty) ((type-check-exp new-env) body))
  15765. (check-type-equal? ty 'Integer body)
  15766. (ProgramDefsExp info ds^^ body^)]))
  15767. ))
  15768. \end{lstlisting}
  15769. \caption{Type checker for the \LangPoly{} language.}
  15770. \label{fig:type-check-Lvar0}
  15771. \end{figure}
  15772. \begin{figure}[tbp]
  15773. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  15774. (define/override (type-equal? t1 t2)
  15775. (match* (t1 t2)
  15776. [(`(All ,xs ,T1) `(All ,ys ,T2))
  15777. (define env (map cons xs ys))
  15778. (type-equal? (subst-type env T1) T2)]
  15779. [(other wise)
  15780. (super type-equal? t1 t2)]))
  15781. (define/public (match-types env pt at)
  15782. (match* (pt at)
  15783. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  15784. [('Void 'Void) env] [('Any 'Any) env]
  15785. [(`(Vector ,pts ...) `(Vector ,ats ...))
  15786. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  15787. (match-types env^ pt1 at1))]
  15788. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  15789. (define env^ (match-types env prt art))
  15790. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  15791. (match-types env^^ pt1 at1))]
  15792. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  15793. (define env^ (append (map cons pxs axs) env))
  15794. (match-types env^ pt1 at1)]
  15795. [((? symbol? x) at)
  15796. (match (dict-ref env x (lambda () #f))
  15797. [#f (error 'type-check "undefined type variable ~a" x)]
  15798. ['Type (cons (cons x at) env)]
  15799. [t^ (check-type-equal? at t^ 'matching) env])]
  15800. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  15801. (define/public (subst-type env pt)
  15802. (match pt
  15803. ['Integer 'Integer] ['Boolean 'Boolean]
  15804. ['Void 'Void] ['Any 'Any]
  15805. [`(Vector ,ts ...)
  15806. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  15807. [`(,ts ... -> ,rt)
  15808. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  15809. [`(All ,xs ,t)
  15810. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  15811. [(? symbol? x) (dict-ref env x)]
  15812. [else (error 'type-check "expected a type not ~a" pt)]))
  15813. (define/public (combine-decls-defs ds)
  15814. (match ds
  15815. ['() '()]
  15816. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  15817. (unless (equal? name f)
  15818. (error 'type-check "name mismatch, ~a != ~a" name f))
  15819. (match type
  15820. [`(All ,xs (,ps ... -> ,rt))
  15821. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  15822. (cons (Generic xs (Def name params^ rt info body))
  15823. (combine-decls-defs ds^))]
  15824. [`(,ps ... -> ,rt)
  15825. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  15826. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  15827. [else (error 'type-check "expected a function type, not ~a" type) ])]
  15828. [`(,(Def f params rt info body) . ,ds^)
  15829. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  15830. \end{lstlisting}
  15831. \caption{Auxiliary functions for type checking \LangPoly{}.}
  15832. \label{fig:type-check-Lvar0-aux}
  15833. \end{figure}
  15834. \begin{figure}[tbp]
  15835. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  15836. (define/public ((check-well-formed env) ty)
  15837. (match ty
  15838. ['Integer (void)]
  15839. ['Boolean (void)]
  15840. ['Void (void)]
  15841. [(? symbol? a)
  15842. (match (dict-ref env a (lambda () #f))
  15843. ['Type (void)]
  15844. [else (error 'type-check "undefined type variable ~a" a)])]
  15845. [`(Vector ,ts ...)
  15846. (for ([t ts]) ((check-well-formed env) t))]
  15847. [`(,ts ... -> ,t)
  15848. (for ([t ts]) ((check-well-formed env) t))
  15849. ((check-well-formed env) t)]
  15850. [`(All ,xs ,t)
  15851. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  15852. ((check-well-formed env^) t)]
  15853. [else (error 'type-check "unrecognized type ~a" ty)]))
  15854. \end{lstlisting}
  15855. \caption{Well-formed types.}
  15856. \label{fig:well-formed-types}
  15857. \end{figure}
  15858. % TODO: interpreter for R'_10
  15859. \section{Compiling Polymorphism}
  15860. \label{sec:compiling-poly}
  15861. Broadly speaking, there are four approaches to compiling parametric
  15862. polymorphism, which we describe below.
  15863. \begin{description}
  15864. \item[Monomorphization] generates a different version of a polymorphic
  15865. function for each set of type arguments that it is used with,
  15866. producing type-specialized code. This approach results in the most
  15867. efficient code but requires whole-program compilation (no separate
  15868. compilation) and increases code size. For our current purposes
  15869. monomorphization is a non-starter because, with first-class
  15870. polymorphism, it is sometimes not possible to determine which
  15871. generic functions are used with which type arguments during
  15872. compilation. (It can be done at runtime, with just-in-time
  15873. compilation.) This approach is used to compile C++
  15874. templates~\citep{stroustrup88:_param_types} and polymorphic
  15875. functions in NESL~\citep{Blelloch:1993aa} and
  15876. ML~\citep{Weeks:2006aa}.
  15877. \item[Uniform representation] generates one version of each
  15878. polymorphic function but requires all values have a common ``boxed''
  15879. format, such as the tagged values of type \code{Any} in
  15880. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  15881. similarly to code in a dynamically typed language (like \LangDyn{}),
  15882. in which primitive operators require their arguments to be projected
  15883. from \code{Any} and their results are injected into \code{Any}. (In
  15884. object-oriented languages, the projection is accomplished via
  15885. virtual method dispatch.) The uniform representation approach is
  15886. compatible with separate compilation and with first-class
  15887. polymorphism. However, it produces the least-efficient code because
  15888. it introduces overhead in the entire program, including
  15889. non-polymorphic code. This approach is used in implementations of
  15890. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  15891. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  15892. Java~\citep{Bracha:1998fk}.
  15893. \item[Mixed representation] generates one version of each polymorphic
  15894. function, using a boxed representation for type
  15895. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  15896. and conversions are performed at the boundaries between monomorphic
  15897. and polymorphic (e.g. when a polymorphic function is instantiated
  15898. and called). This approach is compatible with separate compilation
  15899. and first-class polymorphism and maintains the efficiency of
  15900. monomorphic code. The tradeoff is increased overhead at the boundary
  15901. between monomorphic and polymorphic code. This approach is used in
  15902. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  15903. Java 5 with the addition of autoboxing.
  15904. \item[Type passing] uses the unboxed representation in both
  15905. monomorphic and polymorphic code. Each polymorphic function is
  15906. compiled to a single function with extra parameters that describe
  15907. the type arguments. The type information is used by the generated
  15908. code to know how to access the unboxed values at runtime. This
  15909. approach is used in implementation of the Napier88
  15910. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  15911. passing is compatible with separate compilation and first-class
  15912. polymorphism and maintains the efficiency for monomorphic
  15913. code. There is runtime overhead in polymorphic code from dispatching
  15914. on type information.
  15915. \end{description}
  15916. In this chapter we use the mixed representation approach, partly
  15917. because of its favorable attributes, and partly because it is
  15918. straightforward to implement using the tools that we have already
  15919. built to support gradual typing. To compile polymorphic functions, we
  15920. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  15921. \LangCast{}.
  15922. \section{Erase Types}
  15923. \label{sec:erase-types}
  15924. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  15925. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  15926. shows the output of the \code{erase-types} pass on the polymorphic
  15927. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  15928. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  15929. \code{All} types are removed from the type of \code{map-vec}.
  15930. \begin{figure}[tbp]
  15931. \begin{lstlisting}
  15932. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  15933. : (Vector Any Any)
  15934. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  15935. (define (add1 [x : Integer]) : Integer (+ x 1))
  15936. (vector-ref ((cast map-vec
  15937. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  15938. ((Integer -> Integer) (Vector Integer Integer)
  15939. -> (Vector Integer Integer)))
  15940. add1 (vector 0 41)) 1)
  15941. \end{lstlisting}
  15942. \caption{The polymorphic \code{map-vec} example after type erasure.}
  15943. \label{fig:map-vec-erase}
  15944. \end{figure}
  15945. This process of type erasure creates a challenge at points of
  15946. instantiation. For example, consider the instantiation of
  15947. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  15948. The type of \code{map-vec} is
  15949. \begin{lstlisting}
  15950. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  15951. \end{lstlisting}
  15952. and it is instantiated to
  15953. \begin{lstlisting}
  15954. ((Integer -> Integer) (Vector Integer Integer)
  15955. -> (Vector Integer Integer))
  15956. \end{lstlisting}
  15957. After erasure, the type of \code{map-vec} is
  15958. \begin{lstlisting}
  15959. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  15960. \end{lstlisting}
  15961. but we need to convert it to the instantiated type. This is easy to
  15962. do in the target language \LangCast{} with a single \code{cast}. In
  15963. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  15964. has been compiled to a \code{cast} from the type of \code{map-vec} to
  15965. the instantiated type. The source and target type of a cast must be
  15966. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  15967. because both the source and target are obtained from the same
  15968. polymorphic type of \code{map-vec}, replacing the type parameters with
  15969. \code{Any} in the former and with the deduced type arguments in the
  15970. later. (Recall that the \code{Any} type is consistent with any type.)
  15971. To implement the \code{erase-types} pass, we recommend defining a
  15972. recursive auxiliary function named \code{erase-type} that applies the
  15973. following two transformations. It replaces type variables with
  15974. \code{Any}
  15975. \begin{lstlisting}
  15976. |$x$|
  15977. |$\Rightarrow$|
  15978. Any
  15979. \end{lstlisting}
  15980. and it removes the polymorphic \code{All} types.
  15981. \begin{lstlisting}
  15982. (All |$xs$| |$T_1$|)
  15983. |$\Rightarrow$|
  15984. |$T'_1$|
  15985. \end{lstlisting}
  15986. Apply the \code{erase-type} function to all of the type annotations in
  15987. the program.
  15988. Regarding the translation of expressions, the case for \code{Inst} is
  15989. the interesting one. We translate it into a \code{Cast}, as shown
  15990. below. The type of the subexpression $e$ is the polymorphic type
  15991. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  15992. $T$, the type $T'$. The target type $T''$ is the result of
  15993. substituting the arguments types $ts$ for the type parameters $xs$ in
  15994. $T$ followed by doing type erasure.
  15995. \begin{lstlisting}
  15996. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  15997. |$\Rightarrow$|
  15998. (Cast |$e'$| |$T'$| |$T''$|)
  15999. \end{lstlisting}
  16000. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  16001. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  16002. Finally, each polymorphic function is translated to a regular
  16003. functions in which type erasure has been applied to all the type
  16004. annotations and the body.
  16005. \begin{lstlisting}
  16006. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  16007. |$\Rightarrow$|
  16008. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  16009. \end{lstlisting}
  16010. \begin{exercise}\normalfont
  16011. Implement a compiler for the polymorphic language \LangPoly{} by
  16012. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  16013. programs that use polymorphic functions. Some of them should make
  16014. use of first-class polymorphism.
  16015. \end{exercise}
  16016. \begin{figure}[p]
  16017. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16018. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  16019. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  16020. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  16021. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  16022. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  16023. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  16024. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  16025. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  16026. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  16027. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  16028. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  16029. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  16030. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  16031. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  16032. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  16033. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16034. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16035. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16036. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16037. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16038. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16039. \path[->,bend right=15] (Rpoly) edge [above] node
  16040. {\ttfamily\footnotesize type\_check} (Rpolyp);
  16041. \path[->,bend right=15] (Rpolyp) edge [above] node
  16042. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  16043. \path[->,bend right=15] (Rgradualp) edge [above] node
  16044. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  16045. \path[->,bend right=15] (Rwhilepp) edge [right] node
  16046. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  16047. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  16048. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  16049. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  16050. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  16051. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  16052. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  16053. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  16054. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  16055. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  16056. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16057. \path[->,bend left=15] (F1-1) edge [below] node
  16058. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16059. \path[->,bend right=15] (F1-2) edge [above] node
  16060. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16061. \path[->,bend right=15] (F1-3) edge [above] node
  16062. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16063. \path[->,bend right=15] (F1-4) edge [above] node
  16064. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16065. \path[->,bend right=15] (F1-5) edge [right] node
  16066. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16067. \path[->,bend left=15] (C3-2) edge [left] node
  16068. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16069. \path[->,bend right=15] (x86-2) edge [left] node
  16070. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16071. \path[->,bend right=15] (x86-2-1) edge [below] node
  16072. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16073. \path[->,bend right=15] (x86-2-2) edge [left] node
  16074. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16075. \path[->,bend left=15] (x86-3) edge [above] node
  16076. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16077. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  16078. \end{tikzpicture}
  16079. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  16080. \label{fig:Rpoly-passes}
  16081. \end{figure}
  16082. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  16083. for the compilation of \LangPoly{}.
  16084. % TODO: challenge problem: specialization of instantiations
  16085. % Further Reading
  16086. \fi
  16087. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16088. \clearpage
  16089. \appendix
  16090. \chapter{Appendix}
  16091. \if\edition\racketEd
  16092. \section{Interpreters}
  16093. \label{appendix:interp}
  16094. \index{subject}{interpreter}
  16095. We provide interpreters for each of the source languages \LangInt{},
  16096. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  16097. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  16098. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  16099. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  16100. and x86 are in the \key{interp.rkt} file.
  16101. \section{Utility Functions}
  16102. \label{appendix:utilities}
  16103. The utility functions described in this section are in the
  16104. \key{utilities.rkt} file of the support code.
  16105. \paragraph{\code{interp-tests}}
  16106. The \key{interp-tests} function runs the compiler passes and the
  16107. interpreters on each of the specified tests to check whether each pass
  16108. is correct. The \key{interp-tests} function has the following
  16109. parameters:
  16110. \begin{description}
  16111. \item[name (a string)] a name to identify the compiler,
  16112. \item[typechecker] a function of exactly one argument that either
  16113. raises an error using the \code{error} function when it encounters a
  16114. type error, or returns \code{\#f} when it encounters a type
  16115. error. If there is no type error, the type checker returns the
  16116. program.
  16117. \item[passes] a list with one entry per pass. An entry is a list with
  16118. four things:
  16119. \begin{enumerate}
  16120. \item a string giving the name of the pass,
  16121. \item the function that implements the pass (a translator from AST
  16122. to AST),
  16123. \item a function that implements the interpreter (a function from
  16124. AST to result value) for the output language,
  16125. \item and a type checker for the output language. Type checkers for
  16126. the $R$ and $C$ languages are provided in the support code. For
  16127. example, the type checkers for \LangVar{} and \LangCVar{} are in
  16128. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  16129. type checker entry is optional. The support code does not provide
  16130. type checkers for the x86 languages.
  16131. \end{enumerate}
  16132. \item[source-interp] an interpreter for the source language. The
  16133. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  16134. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  16135. \item[tests] a list of test numbers that specifies which tests to
  16136. run. (see below)
  16137. \end{description}
  16138. %
  16139. The \key{interp-tests} function assumes that the subdirectory
  16140. \key{tests} has a collection of Racket programs whose names all start
  16141. with the family name, followed by an underscore and then the test
  16142. number, ending with the file extension \key{.rkt}. Also, for each test
  16143. program that calls \code{read} one or more times, there is a file with
  16144. the same name except that the file extension is \key{.in} that
  16145. provides the input for the Racket program. If the test program is
  16146. expected to fail type checking, then there should be an empty file of
  16147. the same name but with extension \key{.tyerr}.
  16148. \paragraph{\code{compiler-tests}}
  16149. runs the compiler passes to generate x86 (a \key{.s} file) and then
  16150. runs the GNU C compiler (gcc) to generate machine code. It runs the
  16151. machine code and checks that the output is $42$. The parameters to the
  16152. \code{compiler-tests} function are similar to those of the
  16153. \code{interp-tests} function, and consist of
  16154. \begin{itemize}
  16155. \item a compiler name (a string),
  16156. \item a type checker,
  16157. \item description of the passes,
  16158. \item name of a test-family, and
  16159. \item a list of test numbers.
  16160. \end{itemize}
  16161. \paragraph{\code{compile-file}}
  16162. takes a description of the compiler passes (see the comment for
  16163. \key{interp-tests}) and returns a function that, given a program file
  16164. name (a string ending in \key{.rkt}), applies all of the passes and
  16165. writes the output to a file whose name is the same as the program file
  16166. name but with \key{.rkt} replaced with \key{.s}.
  16167. \paragraph{\code{read-program}}
  16168. takes a file path and parses that file (it must be a Racket program)
  16169. into an abstract syntax tree.
  16170. \paragraph{\code{parse-program}}
  16171. takes an S-expression representation of an abstract syntax tree and converts it into
  16172. the struct-based representation.
  16173. \paragraph{\code{assert}}
  16174. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  16175. and displays the message \key{msg} if the Boolean \key{bool} is false.
  16176. \paragraph{\code{lookup}}
  16177. % remove discussion of lookup? -Jeremy
  16178. takes a key and an alist, and returns the first value that is
  16179. associated with the given key, if there is one. If not, an error is
  16180. triggered. The alist may contain both immutable pairs (built with
  16181. \key{cons}) and mutable pairs (built with \key{mcons}).
  16182. %The \key{map2} function ...
  16183. \fi %\racketEd
  16184. \section{x86 Instruction Set Quick-Reference}
  16185. \label{sec:x86-quick-reference}
  16186. \index{subject}{x86}
  16187. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  16188. do. We write $A \to B$ to mean that the value of $A$ is written into
  16189. location $B$. Address offsets are given in bytes. The instruction
  16190. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  16191. registers (such as \code{\%rax}), or memory references (such as
  16192. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  16193. reference per instruction. Other operands must be immediates or
  16194. registers.
  16195. \begin{table}[tbp]
  16196. \centering
  16197. \begin{tabular}{l|l}
  16198. \textbf{Instruction} & \textbf{Operation} \\ \hline
  16199. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  16200. \texttt{negq} $A$ & $- A \to A$ \\
  16201. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  16202. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  16203. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  16204. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  16205. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  16206. \texttt{retq} & Pops the return address and jumps to it \\
  16207. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  16208. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  16209. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  16210. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  16211. be an immediate) \\
  16212. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  16213. matches the condition code of the instruction, otherwise go to the
  16214. next instructions. The condition codes are \key{e} for ``equal'',
  16215. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  16216. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  16217. \texttt{jl} $L$ & \\
  16218. \texttt{jle} $L$ & \\
  16219. \texttt{jg} $L$ & \\
  16220. \texttt{jge} $L$ & \\
  16221. \texttt{jmp} $L$ & Jump to label $L$ \\
  16222. \texttt{movq} $A$, $B$ & $A \to B$ \\
  16223. \texttt{movzbq} $A$, $B$ &
  16224. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  16225. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  16226. and the extra bytes of $B$ are set to zero.} \\
  16227. & \\
  16228. & \\
  16229. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  16230. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  16231. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  16232. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  16233. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  16234. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  16235. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  16236. description of the condition codes. $A$ must be a single byte register
  16237. (e.g., \texttt{al} or \texttt{cl}).} \\
  16238. \texttt{setl} $A$ & \\
  16239. \texttt{setle} $A$ & \\
  16240. \texttt{setg} $A$ & \\
  16241. \texttt{setge} $A$ &
  16242. \end{tabular}
  16243. \vspace{5pt}
  16244. \caption{Quick-reference for the x86 instructions used in this book.}
  16245. \label{tab:x86-instr}
  16246. \end{table}
  16247. \if\edition\racketEd
  16248. \cleardoublepage
  16249. \section{Concrete Syntax for Intermediate Languages}
  16250. The concrete syntax of \LangAny{} is defined in
  16251. Figure~\ref{fig:Rany-concrete-syntax}.
  16252. \begin{figure}[tp]
  16253. \centering
  16254. \fbox{
  16255. \begin{minipage}{0.97\textwidth}\small
  16256. \[
  16257. \begin{array}{lcl}
  16258. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  16259. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  16260. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  16261. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16262. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  16263. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  16264. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  16265. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  16266. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  16267. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  16268. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  16269. \MID \LP\key{void?}\;\Exp\RP \\
  16270. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  16271. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  16272. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  16273. \end{array}
  16274. \]
  16275. \end{minipage}
  16276. }
  16277. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  16278. (Figure~\ref{fig:Rlam-syntax}).}
  16279. \label{fig:Rany-concrete-syntax}
  16280. \end{figure}
  16281. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  16282. defined in Figures~\ref{fig:c0-concrete-syntax},
  16283. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  16284. and \ref{fig:c3-concrete-syntax}, respectively.
  16285. \begin{figure}[tbp]
  16286. \fbox{
  16287. \begin{minipage}{0.96\textwidth}
  16288. \small
  16289. \[
  16290. \begin{array}{lcl}
  16291. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  16292. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  16293. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  16294. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  16295. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  16296. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  16297. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  16298. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  16299. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  16300. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  16301. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  16302. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  16303. \end{array}
  16304. \]
  16305. \end{minipage}
  16306. }
  16307. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  16308. \label{fig:c2-concrete-syntax}
  16309. \end{figure}
  16310. \begin{figure}[tp]
  16311. \fbox{
  16312. \begin{minipage}{0.96\textwidth}
  16313. \small
  16314. \[
  16315. \begin{array}{lcl}
  16316. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  16317. \\
  16318. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  16319. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  16320. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  16321. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  16322. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  16323. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  16324. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  16325. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  16326. \MID \LP\key{collect} \,\itm{int}\RP }\\
  16327. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  16328. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  16329. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  16330. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  16331. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  16332. \LangCFunM{} & ::= & \Def\ldots
  16333. \end{array}
  16334. \]
  16335. \end{minipage}
  16336. }
  16337. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  16338. \label{fig:c3-concrete-syntax}
  16339. \end{figure}
  16340. \fi % racketEd
  16341. \backmatter
  16342. \addtocontents{toc}{\vspace{11pt}}
  16343. %% \addtocontents{toc}{\vspace{11pt}}
  16344. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  16345. \nocite{*}\let\bibname\refname
  16346. \addcontentsline{toc}{fmbm}{\refname}
  16347. \printbibliography
  16348. \printindex{authors}{Author Index}
  16349. \printindex{subject}{Subject Index}
  16350. \end{document}
  16351. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  16352. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  16353. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  16354. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  16355. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  16356. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  16357. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  16358. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  16359. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  16360. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  16361. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  16362. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  16363. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  16364. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  16365. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  16366. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  16367. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  16368. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  16369. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  16370. % LocalWords: morekeywords fullflexible