book.bak 809 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. % material that is specific to the Python edition of the book
  31. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  32. %% For multiple indices:
  33. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  34. \makeindex{subject}
  35. %\makeindex{authors}
  36. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  37. \if\edition\racketEd
  38. \lstset{%
  39. language=Lisp,
  40. basicstyle=\ttfamily\small,
  41. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  42. deletekeywords={read,mapping,vector},
  43. escapechar=|,
  44. columns=flexible,
  45. %moredelim=[is][\color{red}]{~}{~},
  46. showstringspaces=false
  47. }
  48. \fi
  49. \if\edition\pythonEd
  50. \lstset{%
  51. language=Python,
  52. basicstyle=\ttfamily\small,
  53. morekeywords={match,case,bool,int,let},
  54. deletekeywords={},
  55. escapechar=|,
  56. columns=flexible,
  57. %moredelim=[is][\color{red}]{~}{~},
  58. showstringspaces=false
  59. }
  60. \fi
  61. %%% Any shortcut own defined macros place here
  62. %% sample of author macro:
  63. \input{defs}
  64. \newtheorem{exercise}[theorem]{Exercise}
  65. \numberwithin{theorem}{chapter}
  66. \numberwithin{definition}{chapter}
  67. \numberwithin{equation}{chapter}
  68. % Adjusted settings
  69. \setlength{\columnsep}{4pt}
  70. %% \begingroup
  71. %% \setlength{\intextsep}{0pt}%
  72. %% \setlength{\columnsep}{0pt}%
  73. %% \begin{wrapfigure}{r}{0.5\textwidth}
  74. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  75. %% \caption{Basic layout}
  76. %% \end{wrapfigure}
  77. %% \lipsum[1]
  78. %% \endgroup
  79. \newbox\oiintbox
  80. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  81. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  82. \def\oiint{\copy\oiintbox}
  83. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  84. %\usepackage{showframe}
  85. \def\ShowFrameLinethickness{0.125pt}
  86. \addbibresource{book.bib}
  87. \if\edition\pythonEd
  88. \addbibresource{python.bib}
  89. \fi
  90. \begin{document}
  91. \frontmatter
  92. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  93. \HalfTitle{Essentials of Compilation}
  94. \halftitlepage
  95. \clearemptydoublepage
  96. \Title{Essentials of Compilation}
  97. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  98. %\edition{First Edition}
  99. \BookAuthor{Jeremy G. Siek}
  100. \imprint{The MIT Press\\
  101. Cambridge, Massachusetts\\
  102. London, England}
  103. \begin{copyrightpage}
  104. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  105. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  106. Subject to such license, all rights are reserved. \\[2ex]
  107. \includegraphics{CCBY-logo}
  108. The MIT Press would like to thank the anonymous peer reviewers who
  109. provided comments on drafts of this book. The generous work of
  110. academic experts is essential for establishing the authority and
  111. quality of our publications. We acknowledge with gratitude the
  112. contributions of these otherwise uncredited readers.
  113. This book was set in Times LT Std Roman by the author. Printed and
  114. bound in the United States of America.
  115. Library of Congress Cataloging-in-Publication Data is available.
  116. ISBN:
  117. 10 9 8 7 6 5 4 3 2 1
  118. %% Jeremy G. Siek. Available for free viewing
  119. %% or personal downloading under the
  120. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  121. %% license.
  122. %% Copyright in this monograph has been licensed exclusively to The MIT
  123. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  124. %% version to the public in 2022. All inquiries regarding rights should
  125. %% be addressed to The MIT Press, Rights and Permissions Department.
  126. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  127. %% All rights reserved. No part of this book may be reproduced in any
  128. %% form by any electronic or mechanical means (including photocopying,
  129. %% recording, or information storage and retrieval) without permission in
  130. %% writing from the publisher.
  131. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  132. %% United States of America.
  133. %% Library of Congress Cataloging-in-Publication Data is available.
  134. %% ISBN:
  135. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  136. \end{copyrightpage}
  137. \dedication{This book is dedicated to Katie, my partner in everything,
  138. my children, who grew up during the writing of this book, and the
  139. programming language students at Indiana University, whose
  140. thoughtful questions made this a better book.}
  141. %% \begin{epigraphpage}
  142. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  143. %% \textit{Book Name if any}}
  144. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  145. %% \end{epigraphpage}
  146. \tableofcontents
  147. %\listoffigures
  148. %\listoftables
  149. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  150. \chapter*{Preface}
  151. \addcontentsline{toc}{fmbm}{Preface}
  152. There is a magical moment when a programmer presses the run button
  153. and the software begins to execute. Somehow a program written in a
  154. high-level language is running on a computer that is capable only of
  155. shuffling bits. Here we reveal the wizardry that makes that moment
  156. possible. Beginning with the groundbreaking work of Backus and
  157. colleagues in the 1950s, computer scientists developed techniques for
  158. constructing programs called \emph{compilers} that automatically
  159. translate high-level programs into machine code.
  160. We take you on a journey through constructing your own compiler for a
  161. small but powerful language. Along the way we explain the essential
  162. concepts, algorithms, and data structures that underlie compilers. We
  163. develop your understanding of how programs are mapped onto computer
  164. hardware, which is helpful in reasoning about properties at the
  165. junction of hardware and software, such as execution time, software
  166. errors, and security vulnerabilities. For those interested in
  167. pursuing compiler construction as a career, our goal is to provide a
  168. stepping-stone to advanced topics such as just-in-time compilation,
  169. program analysis, and program optimization. For those interested in
  170. designing and implementing programming languages, we connect language
  171. design choices to their impact on the compiler and the generated code.
  172. A compiler is typically organized as a sequence of stages that
  173. progressively translate a program to the code that runs on
  174. hardware. We take this approach to the extreme by partitioning our
  175. compiler into a large number of \emph{nanopasses}, each of which
  176. performs a single task. This enables the testing of each pass in
  177. isolation and focuses our attention, making the compiler far easier to
  178. understand.
  179. The most familiar approach to describing compilers is to dedicate each
  180. chapter to one pass. The problem with that approach is that it
  181. obfuscates how language features motivate design choices in a
  182. compiler. We instead take an \emph{incremental} approach in which we
  183. build a complete compiler in each chapter, starting with a small input
  184. language that includes only arithmetic and variables. We add new
  185. language features in subsequent chapters, extending the compiler as
  186. necessary.
  187. Our choice of language features is designed to elicit fundamental
  188. concepts and algorithms used in compilers.
  189. \begin{itemize}
  190. \item We begin with integer arithmetic and local variables in
  191. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  192. the fundamental tools of compiler construction: \emph{abstract
  193. syntax trees} and \emph{recursive functions}.
  194. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  195. \emph{graph coloring} to assign variables to machine registers.
  196. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  197. motivates an elegant recursive algorithm for translating them into
  198. conditional \code{goto} statements.
  199. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  200. variables}. This elicits the need for \emph{dataflow
  201. analysis} in the register allocator.
  202. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  203. \emph{garbage collection}.
  204. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  205. without lexical scoping, similar to functions in the C programming
  206. language~\citep{Kernighan:1988nx}. The reader learns about the
  207. procedure call stack and \emph{calling conventions} and how they interact
  208. with register allocation and garbage collection. The chapter also
  209. describes how to generate efficient tail calls.
  210. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  211. scoping, that is, \emph{lambda} expressions. The reader learns about
  212. \emph{closure conversion}, in which lambdas are translated into a
  213. combination of functions and tuples.
  214. % Chapter about classes and objects?
  215. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  216. point the input languages are statically typed. The reader extends
  217. the statically typed language with an \code{Any} type that serves
  218. as a target for compiling the dynamically typed language.
  219. %% {\if\edition\pythonEd
  220. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  221. %% \emph{classes}.
  222. %% \fi}
  223. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  224. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  225. in which different regions of a program may be static or dynamically
  226. typed. The reader implements runtime support for \emph{proxies} that
  227. allow values to safely move between regions.
  228. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  229. leveraging the \code{Any} type and type casts developed in chapters
  230. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  231. \end{itemize}
  232. There are many language features that we do not include. Our choices
  233. balance the incidental complexity of a feature versus the fundamental
  234. concepts that it exposes. For example, we include tuples and not
  235. records because although they both elicit the study of heap allocation and
  236. garbage collection, records come with more incidental complexity.
  237. Since 2009, drafts of this book have served as the textbook for
  238. sixteen week compiler courses for upper-level undergraduates and
  239. first-year graduate students at the University of Colorado and Indiana
  240. University.
  241. %
  242. Students come into the course having learned the basics of
  243. programming, data structures and algorithms, and discrete
  244. mathematics.
  245. %
  246. At the beginning of the course, students form groups of two to four
  247. people. The groups complete one chapter every two weeks, starting
  248. with chapter~\ref{ch:Lvar} and finishing with
  249. chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  250. that we assign to the graduate students. The last two weeks of the
  251. course involve a final project in which students design and implement
  252. a compiler extension of their choosing. The last few chapters can be
  253. used in support of these projects. For compiler courses at
  254. universities on the quarter system (about ten weeks in length), we
  255. recommend completing the course through chapter~\ref{ch:Lvec} or
  256. chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  257. students for each compiler pass.
  258. %
  259. The course can be adapted to emphasize functional languages by
  260. skipping chapter~\ref{ch:Lwhile} (loops) and including
  261. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  262. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  263. %
  264. %% \python{A course that emphasizes object-oriented languages would
  265. %% include Chapter~\ref{ch:Lobject}.}
  266. %
  267. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  268. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  269. chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  270. tail calls.
  271. This book has been used in compiler courses at California Polytechnic
  272. State University, Portland State University, Rose–Hulman Institute of
  273. Technology, University of Freiburg, University of Massachusetts
  274. Lowell, and the University of Vermont.
  275. \begin{figure}[tp]
  276. \begin{tcolorbox}[colback=white]
  277. {\if\edition\racketEd
  278. \begin{tikzpicture}[baseline=(current bounding box.center)]
  279. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  280. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  281. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  282. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  283. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  284. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  285. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  286. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  287. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  288. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  289. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  290. \path[->] (C1) edge [above] node {} (C2);
  291. \path[->] (C2) edge [above] node {} (C3);
  292. \path[->] (C3) edge [above] node {} (C4);
  293. \path[->] (C4) edge [above] node {} (C5);
  294. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  295. \path[->] (C5) edge [above] node {} (C7);
  296. \path[->] (C6) edge [above] node {} (C7);
  297. \path[->] (C4) edge [above] node {} (C8);
  298. \path[->] (C4) edge [above] node {} (C9);
  299. \path[->] (C7) edge [above] node {} (C10);
  300. \path[->] (C8) edge [above] node {} (C10);
  301. \path[->] (C10) edge [above] node {} (C11);
  302. \end{tikzpicture}
  303. \fi}
  304. {\if\edition\pythonEd
  305. \begin{tikzpicture}[baseline=(current bounding box.center)]
  306. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  307. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  308. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  309. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  310. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  311. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  312. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  313. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  314. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  315. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  316. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  317. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  318. \path[->] (C1) edge [above] node {} (C2);
  319. \path[->] (C2) edge [above] node {} (C3);
  320. \path[->] (C3) edge [above] node {} (C4);
  321. \path[->] (C4) edge [above] node {} (C5);
  322. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  323. \path[->] (C5) edge [above] node {} (C7);
  324. \path[->] (C6) edge [above] node {} (C7);
  325. \path[->] (C4) edge [above] node {} (C8);
  326. \path[->] (C4) edge [above] node {} (C9);
  327. \path[->] (C7) edge [above] node {} (C10);
  328. \path[->] (C8) edge [above] node {} (C10);
  329. % \path[->] (C8) edge [above] node {} (CO);
  330. \path[->] (C10) edge [above] node {} (C11);
  331. \end{tikzpicture}
  332. \fi}
  333. \end{tcolorbox}
  334. \caption{Diagram of chapter dependencies.}
  335. \label{fig:chapter-dependences}
  336. \end{figure}
  337. \racket{
  338. We use the \href{https://racket-lang.org/}{Racket} language both for
  339. the implementation of the compiler and for the input language, so the
  340. reader should be proficient with Racket or Scheme. There are many
  341. excellent resources for learning Scheme and
  342. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  343. }
  344. \python{
  345. This edition of the book uses \href{https://www.python.org/}{Python}
  346. both for the implementation of the compiler and for the input language, so the
  347. reader should be proficient with Python. There are many
  348. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  349. }
  350. The support code for this book is in the GitHub repository at
  351. the following location:
  352. \begin{center}\small\texttt
  353. https://github.com/IUCompilerCourse/
  354. \end{center}
  355. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  356. is helpful but not necessary for the reader to have taken a computer
  357. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  358. assembly language that are needed in the compiler.
  359. %
  360. We follow the System V calling
  361. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  362. that we generate works with the runtime system (written in C) when it
  363. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  364. operating systems on Intel hardware.
  365. %
  366. On the Windows operating system, \code{gcc} uses the Microsoft x64
  367. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  368. assembly code that we generate does \emph{not} work with the runtime
  369. system on Windows. One workaround is to use a virtual machine with
  370. Linux as the guest operating system.
  371. \section*{Acknowledgments}
  372. The tradition of compiler construction at Indiana University goes back
  373. to research and courses on programming languages by Daniel Friedman in
  374. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  375. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  376. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  377. the compiler course and continued the development of Chez Scheme.
  378. %
  379. The compiler course evolved to incorporate novel pedagogical ideas
  380. while also including elements of real-world compilers. One of
  381. Friedman's ideas was to split the compiler into many small
  382. passes. Another idea, called ``the game,'' was to test the code
  383. generated by each pass using interpreters.
  384. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  385. developed infrastructure to support this approach and evolved the
  386. course to use even smaller
  387. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  388. design decisions in this book are inspired by the assignment
  389. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  390. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  391. organization of the course made it difficult for students to
  392. understand the rationale for the compiler design. Ghuloum proposed the
  393. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  394. based.
  395. We thank the many students who served as teaching assistants for the
  396. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  397. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  398. garbage collector and x86 interpreter, Michael Vollmer for work on
  399. efficient tail calls, and Michael Vitousek for help with the first
  400. offering of the incremental compiler course at IU.
  401. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  402. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  403. Michael Wollowski for teaching courses based on drafts of this book
  404. and for their feedback. We thank the National Science Foundation for
  405. the grants that helped to support this work: Grant Numbers 1518844,
  406. 1763922, and 1814460.
  407. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  408. course in the early 2000s and especially for finding the bug that
  409. sent our garbage collector on a wild goose chase!
  410. \mbox{}\\
  411. \noindent Jeremy G. Siek \\
  412. Bloomington, Indiana
  413. \mainmatter
  414. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  415. \chapter{Preliminaries}
  416. \label{ch:trees-recur}
  417. \setcounter{footnote}{0}
  418. In this chapter we review the basic tools needed to implement a
  419. compiler. Programs are typically input by a programmer as text, that
  420. is, a sequence of characters. The program-as-text representation is
  421. called \emph{concrete syntax}. We use concrete syntax to concisely
  422. write down and talk about programs. Inside the compiler, we use
  423. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  424. that efficiently supports the operations that the compiler needs to
  425. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  426. syntax}\index{subject}{abstract syntax
  427. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  428. The process of translating from concrete syntax to abstract syntax is
  429. called \emph{parsing}~\citep{Aho:2006wb}. This book does not cover the
  430. theory and implementation of parsing.
  431. %
  432. \racket{A parser is provided in the support code for translating from
  433. concrete to abstract syntax.}
  434. %
  435. \python{We use Python's \code{ast} module to translate from concrete
  436. to abstract syntax.}
  437. ASTs can be represented inside the compiler in many different ways,
  438. depending on the programming language used to write the compiler.
  439. %
  440. \racket{We use Racket's
  441. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  442. feature to represent ASTs (section~\ref{sec:ast}).}
  443. %
  444. \python{We use Python classes and objects to represent ASTs, especially the
  445. classes defined in the standard \code{ast} module for the Python
  446. source language.}
  447. %
  448. We use grammars to define the abstract syntax of programming languages
  449. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  450. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  451. recursive functions to construct and deconstruct ASTs
  452. (section~\ref{sec:recursion}). This chapter provides a brief
  453. introduction to these components.
  454. \racket{\index{subject}{struct}}
  455. \python{\index{subject}{class}\index{subject}{object}}
  456. \section{Abstract Syntax Trees}
  457. \label{sec:ast}
  458. Compilers use abstract syntax trees to represent programs because they
  459. often need to ask questions such as, for a given part of a program,
  460. what kind of language feature is it? What are its subparts? Consider
  461. the program on the left and the diagram of its AST on the
  462. right~\eqref{eq:arith-prog}. This program is an addition operation
  463. that has two subparts, a \racket{read}\python{input} operation and a
  464. negation. The negation has another subpart, the integer constant
  465. \code{8}. By using a tree to represent the program, we can easily
  466. follow the links to go from one part of a program to its subparts.
  467. \begin{center}
  468. \begin{minipage}{0.4\textwidth}
  469. \if\edition\racketEd
  470. \begin{lstlisting}
  471. (+ (read) (- 8))
  472. \end{lstlisting}
  473. \fi
  474. \if\edition\pythonEd
  475. \begin{lstlisting}
  476. input_int() + -8
  477. \end{lstlisting}
  478. \fi
  479. \end{minipage}
  480. \begin{minipage}{0.4\textwidth}
  481. \begin{equation}
  482. \begin{tikzpicture}
  483. \node[draw] (plus) at (0 , 0) {\key{+}};
  484. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  485. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  486. \node[draw] (8) at (1 , -3) {\key{8}};
  487. \draw[->] (plus) to (read);
  488. \draw[->] (plus) to (minus);
  489. \draw[->] (minus) to (8);
  490. \end{tikzpicture}
  491. \label{eq:arith-prog}
  492. \end{equation}
  493. \end{minipage}
  494. \end{center}
  495. We use the standard terminology for trees to describe ASTs: each
  496. rectangle above is called a \emph{node}. The arrows connect a node to its
  497. \emph{children}, which are also nodes. The top-most node is the
  498. \emph{root}. Every node except for the root has a \emph{parent} (the
  499. node of which it is the child). If a node has no children, it is a
  500. \emph{leaf} node; otherwise it is an \emph{internal} node.
  501. \index{subject}{node}
  502. \index{subject}{children}
  503. \index{subject}{root}
  504. \index{subject}{parent}
  505. \index{subject}{leaf}
  506. \index{subject}{internal node}
  507. %% Recall that an \emph{symbolic expression} (S-expression) is either
  508. %% \begin{enumerate}
  509. %% \item an atom, or
  510. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  511. %% where $e_1$ and $e_2$ are each an S-expression.
  512. %% \end{enumerate}
  513. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  514. %% null value \code{'()}, etc. We can create an S-expression in Racket
  515. %% simply by writing a backquote (called a quasi-quote in Racket)
  516. %% followed by the textual representation of the S-expression. It is
  517. %% quite common to use S-expressions to represent a list, such as $a, b
  518. %% ,c$ in the following way:
  519. %% \begin{lstlisting}
  520. %% `(a . (b . (c . ())))
  521. %% \end{lstlisting}
  522. %% Each element of the list is in the first slot of a pair, and the
  523. %% second slot is either the rest of the list or the null value, to mark
  524. %% the end of the list. Such lists are so common that Racket provides
  525. %% special notation for them that removes the need for the periods
  526. %% and so many parenthesis:
  527. %% \begin{lstlisting}
  528. %% `(a b c)
  529. %% \end{lstlisting}
  530. %% The following expression creates an S-expression that represents AST
  531. %% \eqref{eq:arith-prog}.
  532. %% \begin{lstlisting}
  533. %% `(+ (read) (- 8))
  534. %% \end{lstlisting}
  535. %% When using S-expressions to represent ASTs, the convention is to
  536. %% represent each AST node as a list and to put the operation symbol at
  537. %% the front of the list. The rest of the list contains the children. So
  538. %% in the above case, the root AST node has operation \code{`+} and its
  539. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  540. %% diagram \eqref{eq:arith-prog}.
  541. %% To build larger S-expressions one often needs to splice together
  542. %% several smaller S-expressions. Racket provides the comma operator to
  543. %% splice an S-expression into a larger one. For example, instead of
  544. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  545. %% we could have first created an S-expression for AST
  546. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  547. %% S-expression.
  548. %% \begin{lstlisting}
  549. %% (define ast1.4 `(- 8))
  550. %% (define ast1_1 `(+ (read) ,ast1.4))
  551. %% \end{lstlisting}
  552. %% In general, the Racket expression that follows the comma (splice)
  553. %% can be any expression that produces an S-expression.
  554. {\if\edition\racketEd
  555. We define a Racket \code{struct} for each kind of node. For this
  556. chapter we require just two kinds of nodes: one for integer constants
  557. and one for primitive operations. The following is the \code{struct}
  558. definition for integer constants.\footnote{All the AST structures are
  559. defined in the file \code{utilities.rkt} in the support code.}
  560. \begin{lstlisting}
  561. (struct Int (value))
  562. \end{lstlisting}
  563. An integer node contains just one thing: the integer value.
  564. We establish the convention that \code{struct} names, such
  565. as \code{Int}, are capitalized.
  566. To create an AST node for the integer $8$, we write \INT{8}.
  567. \begin{lstlisting}
  568. (define eight (Int 8))
  569. \end{lstlisting}
  570. We say that the value created by \INT{8} is an
  571. \emph{instance} of the
  572. \code{Int} structure.
  573. The following is the \code{struct} definition for primitive operations.
  574. \begin{lstlisting}
  575. (struct Prim (op args))
  576. \end{lstlisting}
  577. A primitive operation node includes an operator symbol \code{op} and a
  578. list of child arguments called \code{args}. For example, to create an
  579. AST that negates the number $8$, we write the following.
  580. \begin{lstlisting}
  581. (define neg-eight (Prim '- (list eight)))
  582. \end{lstlisting}
  583. Primitive operations may have zero or more children. The \code{read}
  584. operator has zero:
  585. \begin{lstlisting}
  586. (define rd (Prim 'read '()))
  587. \end{lstlisting}
  588. The addition operator has two children:
  589. \begin{lstlisting}
  590. (define ast1_1 (Prim '+ (list rd neg-eight)))
  591. \end{lstlisting}
  592. We have made a design choice regarding the \code{Prim} structure.
  593. Instead of using one structure for many different operations
  594. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  595. structure for each operation, as follows:
  596. \begin{lstlisting}
  597. (struct Read ())
  598. (struct Add (left right))
  599. (struct Neg (value))
  600. \end{lstlisting}
  601. The reason that we choose to use just one structure is that many parts
  602. of the compiler can use the same code for the different primitive
  603. operators, so we might as well just write that code once by using a
  604. single structure.
  605. %
  606. \fi}
  607. {\if\edition\pythonEd
  608. We use a Python \code{class} for each kind of node.
  609. The following is the class definition for
  610. constants from the Python \code{ast} module.
  611. \begin{lstlisting}
  612. class Constant:
  613. def __init__(self, value):
  614. self.value = value
  615. \end{lstlisting}
  616. An integer constant node includes just one thing: the integer value.
  617. To create an AST node for the integer $8$, we write \INT{8}.
  618. \begin{lstlisting}
  619. eight = Constant(8)
  620. \end{lstlisting}
  621. We say that the value created by \INT{8} is an
  622. \emph{instance} of the \code{Constant} class.
  623. The following is the class definition for unary operators.
  624. \begin{lstlisting}
  625. class UnaryOp:
  626. def __init__(self, op, operand):
  627. self.op = op
  628. self.operand = operand
  629. \end{lstlisting}
  630. The specific operation is specified by the \code{op} parameter. For
  631. example, the class \code{USub} is for unary subtraction.
  632. (More unary operators are introduced in later chapters.) To create an AST that
  633. negates the number $8$, we write the following.
  634. \begin{lstlisting}
  635. neg_eight = UnaryOp(USub(), eight)
  636. \end{lstlisting}
  637. The call to the \code{input\_int} function is represented by the
  638. \code{Call} and \code{Name} classes.
  639. \begin{lstlisting}
  640. class Call:
  641. def __init__(self, func, args):
  642. self.func = func
  643. self.args = args
  644. class Name:
  645. def __init__(self, id):
  646. self.id = id
  647. \end{lstlisting}
  648. To create an AST node that calls \code{input\_int}, we write
  649. \begin{lstlisting}
  650. read = Call(Name('input_int'), [])
  651. \end{lstlisting}
  652. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  653. the \code{BinOp} class for binary operators.
  654. \begin{lstlisting}
  655. class BinOp:
  656. def __init__(self, left, op, right):
  657. self.op = op
  658. self.left = left
  659. self.right = right
  660. \end{lstlisting}
  661. Similar to \code{UnaryOp}, the specific operation is specified by the
  662. \code{op} parameter, which for now is just an instance of the
  663. \code{Add} class. So to create the AST
  664. node that adds negative eight to some user input, we write the following.
  665. \begin{lstlisting}
  666. ast1_1 = BinOp(read, Add(), neg_eight)
  667. \end{lstlisting}
  668. \fi}
  669. To compile a program such as \eqref{eq:arith-prog}, we need to know
  670. that the operation associated with the root node is addition and we
  671. need to be able to access its two
  672. children. \racket{Racket}\python{Python} provides pattern matching to
  673. support these kinds of queries, as we see in
  674. section~\ref{sec:pattern-matching}.
  675. We often write down the concrete syntax of a program even when we
  676. actually have in mind the AST, because the concrete syntax is more
  677. concise. We recommend that you always think of programs as abstract
  678. syntax trees.
  679. \section{Grammars}
  680. \label{sec:grammar}
  681. \index{subject}{integer}
  682. \index{subject}{literal}
  683. %\index{subject}{constant}
  684. A programming language can be thought of as a \emph{set} of programs.
  685. The set is infinite (that is, one can always create larger programs),
  686. so one cannot simply describe a language by listing all the
  687. programs in the language. Instead we write down a set of rules, a
  688. \emph{grammar}, for building programs. Grammars are often used to
  689. define the concrete syntax of a language, but they can also be used to
  690. describe the abstract syntax. We write our rules in a variant of
  691. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  692. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  693. we describe a small language, named \LangInt{}, that consists of
  694. integers and arithmetic operations. \index{subject}{grammar}
  695. The first grammar rule for the abstract syntax of \LangInt{} says that an
  696. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  697. \begin{equation}
  698. \Exp ::= \INT{\Int} \label{eq:arith-int}
  699. \end{equation}
  700. %
  701. Each rule has a left-hand side and a right-hand side.
  702. If you have an AST node that matches the
  703. right-hand side, then you can categorize it according to the
  704. left-hand side.
  705. %
  706. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  707. are \emph{terminal} symbols and must literally appear in the program for the
  708. rule to be applicable.\index{subject}{terminal}
  709. %
  710. Our grammars do not mention \emph{white space}, that is, delimiter
  711. characters like spaces, tabs, and new lines. White space may be
  712. inserted between symbols for disambiguation and to improve
  713. readability. \index{subject}{white space}
  714. %
  715. A name such as $\Exp$ that is defined by the grammar rules is a
  716. \emph{nonterminal}. \index{subject}{nonterminal}
  717. %
  718. The name $\Int$ is also a nonterminal, but instead of defining it with
  719. a grammar rule, we define it with the following explanation. An
  720. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  721. $-$ (for negative integers), such that the sequence of decimals
  722. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  723. enables the representation of integers using 63 bits, which simplifies
  724. several aspects of compilation.
  725. %
  726. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  727. datatype on a 64-bit machine.}
  728. %
  729. \python{In contrast, integers in Python have unlimited precision, but
  730. the techniques needed to handle unlimited precision fall outside the
  731. scope of this book.}
  732. The second grammar rule is the \READOP{} operation, which receives an
  733. input integer from the user of the program.
  734. \begin{equation}
  735. \Exp ::= \READ{} \label{eq:arith-read}
  736. \end{equation}
  737. The third rule categorizes the negation of an $\Exp$ node as an
  738. $\Exp$.
  739. \begin{equation}
  740. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  741. \end{equation}
  742. We can apply these rules to categorize the ASTs that are in the
  743. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  744. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  745. following AST is an $\Exp$.
  746. \begin{center}
  747. \begin{minipage}{0.5\textwidth}
  748. \NEG{\INT{\code{8}}}
  749. \end{minipage}
  750. \begin{minipage}{0.25\textwidth}
  751. \begin{equation}
  752. \begin{tikzpicture}
  753. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  754. \node[draw, circle] (8) at (0, -1.2) {$8$};
  755. \draw[->] (minus) to (8);
  756. \end{tikzpicture}
  757. \label{eq:arith-neg8}
  758. \end{equation}
  759. \end{minipage}
  760. \end{center}
  761. The next two grammar rules are for addition and subtraction expressions:
  762. \begin{align}
  763. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  764. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  765. \end{align}
  766. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  767. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  768. \eqref{eq:arith-read}, and we have already categorized
  769. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  770. to show that
  771. \[
  772. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  773. \]
  774. is an $\Exp$ in the \LangInt{} language.
  775. If you have an AST for which these rules do not apply, then the
  776. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  777. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  778. because there is no rule for the \key{*} operator. Whenever we
  779. define a language with a grammar, the language includes only those
  780. programs that are justified by the grammar rules.
  781. {\if\edition\pythonEd
  782. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  783. There is a statement for printing the value of an expression
  784. \[
  785. \Stmt{} ::= \PRINT{\Exp}
  786. \]
  787. and a statement that evaluates an expression but ignores the result.
  788. \[
  789. \Stmt{} ::= \EXPR{\Exp}
  790. \]
  791. \fi}
  792. {\if\edition\racketEd
  793. The last grammar rule for \LangInt{} states that there is a
  794. \code{Program} node to mark the top of the whole program:
  795. \[
  796. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  797. \]
  798. The \code{Program} structure is defined as follows:
  799. \begin{lstlisting}
  800. (struct Program (info body))
  801. \end{lstlisting}
  802. where \code{body} is an expression. In further chapters, the \code{info}
  803. part is used to store auxiliary information, but for now it is
  804. just the empty list.
  805. \fi}
  806. {\if\edition\pythonEd
  807. The last grammar rule for \LangInt{} states that there is a
  808. \code{Module} node to mark the top of the whole program:
  809. \[
  810. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  811. \]
  812. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  813. this case, a list of statements.
  814. %
  815. The \code{Module} class is defined as follows
  816. \begin{lstlisting}
  817. class Module:
  818. def __init__(self, body):
  819. self.body = body
  820. \end{lstlisting}
  821. where \code{body} is a list of statements.
  822. \fi}
  823. It is common to have many grammar rules with the same left-hand side
  824. but different right-hand sides, such as the rules for $\Exp$ in the
  825. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  826. combine several right-hand sides into a single rule.
  827. The concrete syntax for \LangInt{} is shown in
  828. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  829. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.
  830. \racket{The \code{read-program} function provided in
  831. \code{utilities.rkt} of the support code reads a program from a file
  832. (the sequence of characters in the concrete syntax of Racket) and
  833. parses it into an abstract syntax tree. Refer to the description of
  834. \code{read-program} in appendix~\ref{appendix:utilities} for more
  835. details.}
  836. \python{The \code{parse} function in Python's \code{ast} module
  837. converts the concrete syntax (represented as a string) into an
  838. abstract syntax tree.}
  839. \newcommand{\LintGrammarRacket}{
  840. \begin{array}{rcl}
  841. \Type &::=& \key{Integer} \\
  842. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  843. \MID \CSUB{\Exp}{\Exp}
  844. \end{array}
  845. }
  846. \newcommand{\LintASTRacket}{
  847. \begin{array}{rcl}
  848. \Type &::=& \key{Integer} \\
  849. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  850. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  851. \end{array}
  852. }
  853. \newcommand{\LintGrammarPython}{
  854. \begin{array}{rcl}
  855. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  856. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  857. \end{array}
  858. }
  859. \newcommand{\LintASTPython}{
  860. \begin{array}{rcl}
  861. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  862. \itm{unaryop} &::= & \code{USub()} \\
  863. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  864. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  865. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  866. \end{array}
  867. }
  868. \begin{figure}[tp]
  869. \begin{tcolorbox}[colback=white]
  870. {\if\edition\racketEd
  871. \[
  872. \begin{array}{l}
  873. \LintGrammarRacket \\
  874. \begin{array}{rcl}
  875. \LangInt{} &::=& \Exp
  876. \end{array}
  877. \end{array}
  878. \]
  879. \fi}
  880. {\if\edition\pythonEd
  881. \[
  882. \begin{array}{l}
  883. \LintGrammarPython \\
  884. \begin{array}{rcl}
  885. \LangInt{} &::=& \Stmt^{*}
  886. \end{array}
  887. \end{array}
  888. \]
  889. \fi}
  890. \end{tcolorbox}
  891. \caption{The concrete syntax of \LangInt{}.}
  892. \label{fig:r0-concrete-syntax}
  893. \end{figure}
  894. \begin{figure}[tp]
  895. \begin{tcolorbox}[colback=white]
  896. {\if\edition\racketEd
  897. \[
  898. \begin{array}{l}
  899. \LintASTRacket{} \\
  900. \begin{array}{rcl}
  901. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  902. \end{array}
  903. \end{array}
  904. \]
  905. \fi}
  906. {\if\edition\pythonEd
  907. \[
  908. \begin{array}{l}
  909. \LintASTPython\\
  910. \begin{array}{rcl}
  911. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  912. \end{array}
  913. \end{array}
  914. \]
  915. \fi}
  916. \end{tcolorbox}
  917. \python{
  918. \index{subject}{Constant@\texttt{Constant}}
  919. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  920. \index{subject}{USub@\texttt{USub}}
  921. \index{subject}{inputint@\texttt{input\_int}}
  922. \index{subject}{Call@\texttt{Call}}
  923. \index{subject}{Name@\texttt{Name}}
  924. \index{subject}{BinOp@\texttt{BinOp}}
  925. \index{subject}{Add@\texttt{Add}}
  926. \index{subject}{Sub@\texttt{Sub}}
  927. \index{subject}{print@\texttt{print}}
  928. \index{subject}{Expr@\texttt{Expr}}
  929. \index{subject}{Module@\texttt{Module}}
  930. }
  931. \caption{The abstract syntax of \LangInt{}.}
  932. \label{fig:r0-syntax}
  933. \end{figure}
  934. \section{Pattern Matching}
  935. \label{sec:pattern-matching}
  936. As mentioned in section~\ref{sec:ast}, compilers often need to access
  937. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  938. provides the \texttt{match} feature to access the parts of a value.
  939. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  940. \begin{center}
  941. \begin{minipage}{0.5\textwidth}
  942. {\if\edition\racketEd
  943. \begin{lstlisting}
  944. (match ast1_1
  945. [(Prim op (list child1 child2))
  946. (print op)])
  947. \end{lstlisting}
  948. \fi}
  949. {\if\edition\pythonEd
  950. \begin{lstlisting}
  951. match ast1_1:
  952. case BinOp(child1, op, child2):
  953. print(op)
  954. \end{lstlisting}
  955. \fi}
  956. \end{minipage}
  957. \end{center}
  958. {\if\edition\racketEd
  959. %
  960. In this example, the \texttt{match} form checks whether the AST
  961. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  962. three pattern variables \texttt{op}, \texttt{child1}, and
  963. \texttt{child2}. In general, a match clause consists of a
  964. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  965. recursively defined to be a pattern variable, a structure name
  966. followed by a pattern for each of the structure's arguments, or an
  967. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  968. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  969. and chapter 9 of The Racket
  970. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  971. for complete descriptions of \code{match}.)
  972. %
  973. The body of a match clause may contain arbitrary Racket code. The
  974. pattern variables can be used in the scope of the body, such as
  975. \code{op} in \code{(print op)}.
  976. %
  977. \fi}
  978. %
  979. %
  980. {\if\edition\pythonEd
  981. %
  982. In the above example, the \texttt{match} form checks whether the AST
  983. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  984. three pattern variables \texttt{child1}, \texttt{op}, and
  985. \texttt{child2}, and then prints out the operator. In general, each
  986. \code{case} consists of a \emph{pattern} and a
  987. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  988. to be either a pattern variable, a class name followed by a pattern
  989. for each of its constructor's arguments, or other literals such as
  990. strings, lists, etc.
  991. %
  992. The body of each \code{case} may contain arbitrary Python code. The
  993. pattern variables can be used in the body, such as \code{op} in
  994. \code{print(op)}.
  995. %
  996. \fi}
  997. A \code{match} form may contain several clauses, as in the following
  998. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  999. the AST. The \code{match} proceeds through the clauses in order,
  1000. checking whether the pattern can match the input AST. The body of the
  1001. first clause that matches is executed. The output of \code{leaf} for
  1002. several ASTs is shown on the right side of the following:
  1003. \begin{center}
  1004. \begin{minipage}{0.6\textwidth}
  1005. {\if\edition\racketEd
  1006. \begin{lstlisting}
  1007. (define (leaf arith)
  1008. (match arith
  1009. [(Int n) #t]
  1010. [(Prim 'read '()) #t]
  1011. [(Prim '- (list e1)) #f]
  1012. [(Prim '+ (list e1 e2)) #f]
  1013. [(Prim '- (list e1 e2)) #f]))
  1014. (leaf (Prim 'read '()))
  1015. (leaf (Prim '- (list (Int 8))))
  1016. (leaf (Int 8))
  1017. \end{lstlisting}
  1018. \fi}
  1019. {\if\edition\pythonEd
  1020. \begin{lstlisting}
  1021. def leaf(arith):
  1022. match arith:
  1023. case Constant(n):
  1024. return True
  1025. case Call(Name('input_int'), []):
  1026. return True
  1027. case UnaryOp(USub(), e1):
  1028. return False
  1029. case BinOp(e1, Add(), e2):
  1030. return False
  1031. case BinOp(e1, Sub(), e2):
  1032. return False
  1033. print(leaf(Call(Name('input_int'), [])))
  1034. print(leaf(UnaryOp(USub(), eight)))
  1035. print(leaf(Constant(8)))
  1036. \end{lstlisting}
  1037. \fi}
  1038. \end{minipage}
  1039. \vrule
  1040. \begin{minipage}{0.25\textwidth}
  1041. {\if\edition\racketEd
  1042. \begin{lstlisting}
  1043. #t
  1044. #f
  1045. #t
  1046. \end{lstlisting}
  1047. \fi}
  1048. {\if\edition\pythonEd
  1049. \begin{lstlisting}
  1050. True
  1051. False
  1052. True
  1053. \end{lstlisting}
  1054. \fi}
  1055. \end{minipage}
  1056. \end{center}
  1057. When constructing a \code{match} expression, we refer to the grammar
  1058. definition to identify which nonterminal we are expecting to match
  1059. against, and then we make sure that (1) we have one
  1060. \racket{clause}\python{case} for each alternative of that nonterminal
  1061. and (2) the pattern in each \racket{clause}\python{case}
  1062. corresponds to the corresponding right-hand side of a grammar
  1063. rule. For the \code{match} in the \code{leaf} function, we refer to
  1064. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1065. nonterminal has four alternatives, so the \code{match} has four
  1066. \racket{clauses}\python{cases}. The pattern in each
  1067. \racket{clause}\python{case} corresponds to the right-hand side of a
  1068. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1069. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1070. translating from grammars to patterns, replace nonterminals such as
  1071. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1072. \code{e2}).
  1073. \section{Recursive Functions}
  1074. \label{sec:recursion}
  1075. \index{subject}{recursive function}
  1076. Programs are inherently recursive. For example, an expression is often
  1077. made of smaller expressions. Thus, the natural way to process an
  1078. entire program is to use a recursive function. As a first example of
  1079. such a recursive function, we define the function \code{is\_exp} as
  1080. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1081. value and determine whether or not it is an expression in \LangInt{}.
  1082. %
  1083. We say that a function is defined by \emph{structural recursion} if
  1084. it is defined using a sequence of match \racket{clauses}\python{cases}
  1085. that correspond to a grammar and the body of each
  1086. \racket{clause}\python{case} makes a recursive call on each child
  1087. node.\footnote{This principle of structuring code according to the
  1088. data definition is advocated in the book \emph{How to Design
  1089. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1090. second function, named \code{stmt}, that recognizes whether a value
  1091. is a \LangInt{} statement.} \python{Finally, }
  1092. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1093. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1094. In general, we can write one recursive function to handle each
  1095. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1096. two examples at the bottom of the figure, the first is in
  1097. \LangInt{} and the second is not.
  1098. \begin{figure}[tp]
  1099. \begin{tcolorbox}[colback=white]
  1100. {\if\edition\racketEd
  1101. \begin{lstlisting}
  1102. (define (is_exp ast)
  1103. (match ast
  1104. [(Int n) #t]
  1105. [(Prim 'read '()) #t]
  1106. [(Prim '- (list e)) (is_exp e)]
  1107. [(Prim '+ (list e1 e2))
  1108. (and (is_exp e1) (is_exp e2))]
  1109. [(Prim '- (list e1 e2))
  1110. (and (is_exp e1) (is_exp e2))]
  1111. [else #f]))
  1112. (define (is_Lint ast)
  1113. (match ast
  1114. [(Program '() e) (is_exp e)]
  1115. [else #f]))
  1116. (is_Lint (Program '() ast1_1)
  1117. (is_Lint (Program '()
  1118. (Prim '* (list (Prim 'read '())
  1119. (Prim '+ (list (Int 8)))))))
  1120. \end{lstlisting}
  1121. \fi}
  1122. {\if\edition\pythonEd
  1123. \begin{lstlisting}
  1124. def is_exp(e):
  1125. match e:
  1126. case Constant(n):
  1127. return True
  1128. case Call(Name('input_int'), []):
  1129. return True
  1130. case UnaryOp(USub(), e1):
  1131. return is_exp(e1)
  1132. case BinOp(e1, Add(), e2):
  1133. return is_exp(e1) and is_exp(e2)
  1134. case BinOp(e1, Sub(), e2):
  1135. return is_exp(e1) and is_exp(e2)
  1136. case _:
  1137. return False
  1138. def stmt(s):
  1139. match s:
  1140. case Expr(Call(Name('print'), [e])):
  1141. return is_exp(e)
  1142. case Expr(e):
  1143. return is_exp(e)
  1144. case _:
  1145. return False
  1146. def is_Lint(p):
  1147. match p:
  1148. case Module(body):
  1149. return all([stmt(s) for s in body])
  1150. case _:
  1151. return False
  1152. print(is_Lint(Module([Expr(ast1_1)])))
  1153. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1154. UnaryOp(Add(), Constant(8))))])))
  1155. \end{lstlisting}
  1156. \fi}
  1157. \end{tcolorbox}
  1158. \caption{Example of recursive functions for \LangInt{}. These functions
  1159. recognize whether an AST is in \LangInt{}.}
  1160. \label{fig:exp-predicate}
  1161. \end{figure}
  1162. %% You may be tempted to merge the two functions into one, like this:
  1163. %% \begin{center}
  1164. %% \begin{minipage}{0.5\textwidth}
  1165. %% \begin{lstlisting}
  1166. %% (define (Lint ast)
  1167. %% (match ast
  1168. %% [(Int n) #t]
  1169. %% [(Prim 'read '()) #t]
  1170. %% [(Prim '- (list e)) (Lint e)]
  1171. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1172. %% [(Program '() e) (Lint e)]
  1173. %% [else #f]))
  1174. %% \end{lstlisting}
  1175. %% \end{minipage}
  1176. %% \end{center}
  1177. %% %
  1178. %% Sometimes such a trick will save a few lines of code, especially when
  1179. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1180. %% \emph{not} recommended because it can get you into trouble.
  1181. %% %
  1182. %% For example, the above function is subtly wrong:
  1183. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1184. %% returns true when it should return false.
  1185. \section{Interpreters}
  1186. \label{sec:interp_Lint}
  1187. \index{subject}{interpreter}
  1188. The behavior of a program is defined by the specification of the
  1189. programming language.
  1190. %
  1191. \racket{For example, the Scheme language is defined in the report by
  1192. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1193. reference manual~\citep{plt-tr}.}
  1194. %
  1195. \python{For example, the Python language is defined in the Python
  1196. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1197. %
  1198. In this book we use interpreters to specify each language that we
  1199. consider. An interpreter that is designated as the definition of a
  1200. language is called a \emph{definitional
  1201. interpreter}~\citep{reynolds72:_def_interp}.
  1202. \index{subject}{definitional interpreter} We warm up by creating a
  1203. definitional interpreter for the \LangInt{} language. This interpreter
  1204. serves as a second example of structural recursion. The definition of the
  1205. \code{interp\_Lint} function is shown in
  1206. figure~\ref{fig:interp_Lint}.
  1207. %
  1208. \racket{The body of the function is a match on the input program
  1209. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1210. which in turn has one match clause per grammar rule for \LangInt{}
  1211. expressions.}
  1212. %
  1213. \python{The body of the function matches on the \code{Module} AST node
  1214. and then invokes \code{interp\_stmt} on each statement in the
  1215. module. The \code{interp\_stmt} function includes a case for each
  1216. grammar rule of the \Stmt{} nonterminal and it calls
  1217. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1218. function includes a case for each grammar rule of the \Exp{}
  1219. nonterminal.}
  1220. \begin{figure}[tp]
  1221. \begin{tcolorbox}[colback=white]
  1222. {\if\edition\racketEd
  1223. \begin{lstlisting}
  1224. (define (interp_exp e)
  1225. (match e
  1226. [(Int n) n]
  1227. [(Prim 'read '())
  1228. (define r (read))
  1229. (cond [(fixnum? r) r]
  1230. [else (error 'interp_exp "read expected an integer" r)])]
  1231. [(Prim '- (list e))
  1232. (define v (interp_exp e))
  1233. (fx- 0 v)]
  1234. [(Prim '+ (list e1 e2))
  1235. (define v1 (interp_exp e1))
  1236. (define v2 (interp_exp e2))
  1237. (fx+ v1 v2)]
  1238. [(Prim '- (list e1 e2))
  1239. (define v1 ((interp-exp env) e1))
  1240. (define v2 ((interp-exp env) e2))
  1241. (fx- v1 v2)]))
  1242. (define (interp_Lint p)
  1243. (match p
  1244. [(Program '() e) (interp_exp e)]))
  1245. \end{lstlisting}
  1246. \fi}
  1247. {\if\edition\pythonEd
  1248. \begin{lstlisting}
  1249. def interp_exp(e):
  1250. match e:
  1251. case BinOp(left, Add(), right):
  1252. l = interp_exp(left); r = interp_exp(right)
  1253. return l + r
  1254. case BinOp(left, Sub(), right):
  1255. l = interp_exp(left); r = interp_exp(right)
  1256. return l - r
  1257. case UnaryOp(USub(), v):
  1258. return - interp_exp(v)
  1259. case Constant(value):
  1260. return value
  1261. case Call(Name('input_int'), []):
  1262. return int(input())
  1263. def interp_stmt(s):
  1264. match s:
  1265. case Expr(Call(Name('print'), [arg])):
  1266. print(interp_exp(arg))
  1267. case Expr(value):
  1268. interp_exp(value)
  1269. def interp_Lint(p):
  1270. match p:
  1271. case Module(body):
  1272. for s in body:
  1273. interp_stmt(s)
  1274. \end{lstlisting}
  1275. \fi}
  1276. \end{tcolorbox}
  1277. \caption{Interpreter for the \LangInt{} language.}
  1278. \label{fig:interp_Lint}
  1279. \end{figure}
  1280. Let us consider the result of interpreting a few \LangInt{} programs. The
  1281. following program adds two integers:
  1282. {\if\edition\racketEd
  1283. \begin{lstlisting}
  1284. (+ 10 32)
  1285. \end{lstlisting}
  1286. \fi}
  1287. {\if\edition\pythonEd
  1288. \begin{lstlisting}
  1289. print(10 + 32)
  1290. \end{lstlisting}
  1291. \fi}
  1292. %
  1293. \noindent The result is \key{42}, the answer to life, the universe,
  1294. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1295. the Galaxy} by Douglas Adams.}
  1296. %
  1297. We wrote this program in concrete syntax, whereas the parsed
  1298. abstract syntax is
  1299. {\if\edition\racketEd
  1300. \begin{lstlisting}
  1301. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1302. \end{lstlisting}
  1303. \fi}
  1304. {\if\edition\pythonEd
  1305. \begin{lstlisting}
  1306. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1307. \end{lstlisting}
  1308. \fi}
  1309. The following program demonstrates that expressions may be nested within
  1310. each other, in this case nesting several additions and negations.
  1311. {\if\edition\racketEd
  1312. \begin{lstlisting}
  1313. (+ 10 (- (+ 12 20)))
  1314. \end{lstlisting}
  1315. \fi}
  1316. {\if\edition\pythonEd
  1317. \begin{lstlisting}
  1318. print(10 + -(12 + 20))
  1319. \end{lstlisting}
  1320. \fi}
  1321. %
  1322. \noindent What is the result of this program?
  1323. {\if\edition\racketEd
  1324. As mentioned previously, the \LangInt{} language does not support
  1325. arbitrarily large integers but only $63$-bit integers, so we
  1326. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1327. in Racket.
  1328. Suppose that
  1329. \[
  1330. n = 999999999999999999
  1331. \]
  1332. which indeed fits in $63$ bits. What happens when we run the
  1333. following program in our interpreter?
  1334. \begin{lstlisting}
  1335. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1336. \end{lstlisting}
  1337. It produces the following error:
  1338. \begin{lstlisting}
  1339. fx+: result is not a fixnum
  1340. \end{lstlisting}
  1341. We establish the convention that if running the definitional
  1342. interpreter on a program produces an error, then the meaning of that
  1343. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1344. error is a \code{trapped-error}. A compiler for the language is under
  1345. no obligation regarding programs with unspecified behavior; it does
  1346. not have to produce an executable, and if it does, that executable can
  1347. do anything. On the other hand, if the error is a
  1348. \code{trapped-error}, then the compiler must produce an executable and
  1349. it is required to report that an error occurred. To signal an error,
  1350. exit with a return code of \code{255}. The interpreters in chapters
  1351. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1352. \code{trapped-error}.
  1353. \fi}
  1354. % TODO: how to deal with too-large integers in the Python interpreter?
  1355. %% This convention applies to the languages defined in this
  1356. %% book, as a way to simplify the student's task of implementing them,
  1357. %% but this convention is not applicable to all programming languages.
  1358. %%
  1359. The last feature of the \LangInt{} language, the \READOP{} operation,
  1360. prompts the user of the program for an integer. Recall that program
  1361. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1362. \code{8}. So, if we run {\if\edition\racketEd
  1363. \begin{lstlisting}
  1364. (interp_Lint (Program '() ast1_1))
  1365. \end{lstlisting}
  1366. \fi}
  1367. {\if\edition\pythonEd
  1368. \begin{lstlisting}
  1369. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1370. \end{lstlisting}
  1371. \fi}
  1372. \noindent and if the input is \code{50}, the result is \code{42}.
  1373. We include the \READOP{} operation in \LangInt{} so that a clever
  1374. student cannot implement a compiler for \LangInt{} that simply runs
  1375. the interpreter during compilation to obtain the output and then
  1376. generates the trivial code to produce the output.\footnote{Yes, a
  1377. clever student did this in the first instance of this course!}
  1378. The job of a compiler is to translate a program in one language into a
  1379. program in another language so that the output program behaves the
  1380. same way as the input program. This idea is depicted in the
  1381. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1382. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1383. Given a compiler that translates from language $\mathcal{L}_1$ to
  1384. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1385. compiler must translate it into some program $P_2$ such that
  1386. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1387. same input $i$ yields the same output $o$.
  1388. \begin{equation} \label{eq:compile-correct}
  1389. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1390. \node (p1) at (0, 0) {$P_1$};
  1391. \node (p2) at (3, 0) {$P_2$};
  1392. \node (o) at (3, -2.5) {$o$};
  1393. \path[->] (p1) edge [above] node {compile} (p2);
  1394. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1395. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1396. \end{tikzpicture}
  1397. \end{equation}
  1398. In the next section we see our first example of a compiler.
  1399. \section{Example Compiler: A Partial Evaluator}
  1400. \label{sec:partial-evaluation}
  1401. In this section we consider a compiler that translates \LangInt{}
  1402. programs into \LangInt{} programs that may be more efficient. The
  1403. compiler eagerly computes the parts of the program that do not depend
  1404. on any inputs, a process known as \emph{partial
  1405. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1406. For example, given the following program
  1407. {\if\edition\racketEd
  1408. \begin{lstlisting}
  1409. (+ (read) (- (+ 5 3)))
  1410. \end{lstlisting}
  1411. \fi}
  1412. {\if\edition\pythonEd
  1413. \begin{lstlisting}
  1414. print(input_int() + -(5 + 3) )
  1415. \end{lstlisting}
  1416. \fi}
  1417. \noindent our compiler translates it into the program
  1418. {\if\edition\racketEd
  1419. \begin{lstlisting}
  1420. (+ (read) -8)
  1421. \end{lstlisting}
  1422. \fi}
  1423. {\if\edition\pythonEd
  1424. \begin{lstlisting}
  1425. print(input_int() + -8)
  1426. \end{lstlisting}
  1427. \fi}
  1428. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1429. evaluator for the \LangInt{} language. The output of the partial evaluator
  1430. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1431. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1432. whereas the code for partially evaluating the negation and addition
  1433. operations is factored into three auxiliary functions:
  1434. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1435. functions is the output of partially evaluating the children.
  1436. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1437. arguments are integers and if they are, perform the appropriate
  1438. arithmetic. Otherwise, they create an AST node for the arithmetic
  1439. operation.
  1440. \begin{figure}[tp]
  1441. \begin{tcolorbox}[colback=white]
  1442. {\if\edition\racketEd
  1443. \begin{lstlisting}
  1444. (define (pe_neg r)
  1445. (match r
  1446. [(Int n) (Int (fx- 0 n))]
  1447. [else (Prim '- (list r))]))
  1448. (define (pe_add r1 r2)
  1449. (match* (r1 r2)
  1450. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1451. [(_ _) (Prim '+ (list r1 r2))]))
  1452. (define (pe_sub r1 r2)
  1453. (match* (r1 r2)
  1454. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1455. [(_ _) (Prim '- (list r1 r2))]))
  1456. (define (pe_exp e)
  1457. (match e
  1458. [(Int n) (Int n)]
  1459. [(Prim 'read '()) (Prim 'read '())]
  1460. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1461. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1462. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1463. (define (pe_Lint p)
  1464. (match p
  1465. [(Program '() e) (Program '() (pe_exp e))]))
  1466. \end{lstlisting}
  1467. \fi}
  1468. {\if\edition\pythonEd
  1469. \begin{lstlisting}
  1470. def pe_neg(r):
  1471. match r:
  1472. case Constant(n):
  1473. return Constant(-n)
  1474. case _:
  1475. return UnaryOp(USub(), r)
  1476. def pe_add(r1, r2):
  1477. match (r1, r2):
  1478. case (Constant(n1), Constant(n2)):
  1479. return Constant(n1 + n2)
  1480. case _:
  1481. return BinOp(r1, Add(), r2)
  1482. def pe_sub(r1, r2):
  1483. match (r1, r2):
  1484. case (Constant(n1), Constant(n2)):
  1485. return Constant(n1 - n2)
  1486. case _:
  1487. return BinOp(r1, Sub(), r2)
  1488. def pe_exp(e):
  1489. match e:
  1490. case BinOp(left, Add(), right):
  1491. return pe_add(pe_exp(left), pe_exp(right))
  1492. case BinOp(left, Sub(), right):
  1493. return pe_sub(pe_exp(left), pe_exp(right))
  1494. case UnaryOp(USub(), v):
  1495. return pe_neg(pe_exp(v))
  1496. case Constant(value):
  1497. return e
  1498. case Call(Name('input_int'), []):
  1499. return e
  1500. def pe_stmt(s):
  1501. match s:
  1502. case Expr(Call(Name('print'), [arg])):
  1503. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1504. case Expr(value):
  1505. return Expr(pe_exp(value))
  1506. def pe_P_int(p):
  1507. match p:
  1508. case Module(body):
  1509. new_body = [pe_stmt(s) for s in body]
  1510. return Module(new_body)
  1511. \end{lstlisting}
  1512. \fi}
  1513. \end{tcolorbox}
  1514. \caption{A partial evaluator for \LangInt{}.}
  1515. \label{fig:pe-arith}
  1516. \end{figure}
  1517. To gain some confidence that the partial evaluator is correct, we can
  1518. test whether it produces programs that produce the same result as the
  1519. input programs. That is, we can test whether it satisfies the diagram
  1520. of \eqref{eq:compile-correct}.
  1521. %
  1522. {\if\edition\racketEd
  1523. The following code runs the partial evaluator on several examples and
  1524. tests the output program. The \texttt{parse-program} and
  1525. \texttt{assert} functions are defined in
  1526. appendix~\ref{appendix:utilities}.\\
  1527. \begin{minipage}{1.0\textwidth}
  1528. \begin{lstlisting}
  1529. (define (test_pe p)
  1530. (assert "testing pe_Lint"
  1531. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1532. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1533. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1534. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1535. \end{lstlisting}
  1536. \end{minipage}
  1537. \fi}
  1538. % TODO: python version of testing the PE
  1539. \begin{exercise}\normalfont\normalsize
  1540. Create three programs in the \LangInt{} language and test whether
  1541. partially evaluating them with \code{pe\_Lint} and then
  1542. interpreting them with \code{interp\_Lint} gives the same result
  1543. as directly interpreting them with \code{interp\_Lint}.
  1544. \end{exercise}
  1545. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1546. \chapter{Integers and Variables}
  1547. \label{ch:Lvar}
  1548. \setcounter{footnote}{0}
  1549. This chapter covers compiling a subset of
  1550. \racket{Racket}\python{Python} to x86-64 assembly
  1551. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1552. integer arithmetic and local variables. We often refer to x86-64
  1553. simply as x86. The chapter first describes the \LangVar{} language
  1554. (section~\ref{sec:s0}) and then introduces x86 assembly
  1555. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1556. discuss only the instructions needed for compiling \LangVar{}. We
  1557. introduce more x86 instructions in subsequent chapters. After
  1558. introducing \LangVar{} and x86, we reflect on their differences and
  1559. create a plan to break down the translation from \LangVar{} to x86
  1560. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1561. the chapter gives detailed hints regarding each step. We aim to give
  1562. enough hints that the well-prepared reader, together with a few
  1563. friends, can implement a compiler from \LangVar{} to x86 in a short
  1564. time. To suggest the scale of this first compiler, we note that the
  1565. instructor solution for the \LangVar{} compiler is approximately
  1566. \racket{500}\python{300} lines of code.
  1567. \section{The \LangVar{} Language}
  1568. \label{sec:s0}
  1569. \index{subject}{variable}
  1570. The \LangVar{} language extends the \LangInt{} language with
  1571. variables. The concrete syntax of the \LangVar{} language is defined
  1572. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1573. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1574. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1575. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1576. \key{-} is a unary operator, and \key{+} is a binary operator.
  1577. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1578. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1579. the top of the program.
  1580. %% The $\itm{info}$
  1581. %% field of the \key{Program} structure contains an \emph{association
  1582. %% list} (a list of key-value pairs) that is used to communicate
  1583. %% auxiliary data from one compiler pass the next.
  1584. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1585. exhibit several compilation techniques.
  1586. \newcommand{\LvarGrammarRacket}{
  1587. \begin{array}{rcl}
  1588. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1589. \end{array}
  1590. }
  1591. \newcommand{\LvarASTRacket}{
  1592. \begin{array}{rcl}
  1593. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1594. \end{array}
  1595. }
  1596. \newcommand{\LvarGrammarPython}{
  1597. \begin{array}{rcl}
  1598. \Exp &::=& \Var{} \\
  1599. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1600. \end{array}
  1601. }
  1602. \newcommand{\LvarASTPython}{
  1603. \begin{array}{rcl}
  1604. \Exp{} &::=& \VAR{\Var{}} \\
  1605. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1606. \end{array}
  1607. }
  1608. \begin{figure}[tp]
  1609. \centering
  1610. \begin{tcolorbox}[colback=white]
  1611. {\if\edition\racketEd
  1612. \[
  1613. \begin{array}{l}
  1614. \gray{\LintGrammarRacket{}} \\ \hline
  1615. \LvarGrammarRacket{} \\
  1616. \begin{array}{rcl}
  1617. \LangVarM{} &::=& \Exp
  1618. \end{array}
  1619. \end{array}
  1620. \]
  1621. \fi}
  1622. {\if\edition\pythonEd
  1623. \[
  1624. \begin{array}{l}
  1625. \gray{\LintGrammarPython} \\ \hline
  1626. \LvarGrammarPython \\
  1627. \begin{array}{rcl}
  1628. \LangVarM{} &::=& \Stmt^{*}
  1629. \end{array}
  1630. \end{array}
  1631. \]
  1632. \fi}
  1633. \end{tcolorbox}
  1634. \caption{The concrete syntax of \LangVar{}.}
  1635. \label{fig:Lvar-concrete-syntax}
  1636. \end{figure}
  1637. \begin{figure}[tp]
  1638. \centering
  1639. \begin{tcolorbox}[colback=white]
  1640. {\if\edition\racketEd
  1641. \[
  1642. \begin{array}{l}
  1643. \gray{\LintASTRacket{}} \\ \hline
  1644. \LvarASTRacket \\
  1645. \begin{array}{rcl}
  1646. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1647. \end{array}
  1648. \end{array}
  1649. \]
  1650. \fi}
  1651. {\if\edition\pythonEd
  1652. \[
  1653. \begin{array}{l}
  1654. \gray{\LintASTPython}\\ \hline
  1655. \LvarASTPython \\
  1656. \begin{array}{rcl}
  1657. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1658. \end{array}
  1659. \end{array}
  1660. \]
  1661. \fi}
  1662. \end{tcolorbox}
  1663. \caption{The abstract syntax of \LangVar{}.}
  1664. \label{fig:Lvar-syntax}
  1665. \end{figure}
  1666. {\if\edition\racketEd
  1667. Let us dive further into the syntax and semantics of the \LangVar{}
  1668. language. The \key{let} feature defines a variable for use within its
  1669. body and initializes the variable with the value of an expression.
  1670. The abstract syntax for \key{let} is shown in
  1671. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1672. \begin{lstlisting}
  1673. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1674. \end{lstlisting}
  1675. For example, the following program initializes \code{x} to $32$ and then
  1676. evaluates the body \code{(+ 10 x)}, producing $42$.
  1677. \begin{lstlisting}
  1678. (let ([x (+ 12 20)]) (+ 10 x))
  1679. \end{lstlisting}
  1680. \fi}
  1681. %
  1682. {\if\edition\pythonEd
  1683. %
  1684. The \LangVar{} language includes assignment statements, which define a
  1685. variable for use in later statements and initializes the variable with
  1686. the value of an expression. The abstract syntax for assignment is
  1687. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1688. assignment is \index{subject}{Assign@\texttt{Assign}}
  1689. \begin{lstlisting}
  1690. |$\itm{var}$| = |$\itm{exp}$|
  1691. \end{lstlisting}
  1692. For example, the following program initializes the variable \code{x}
  1693. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1694. \begin{lstlisting}
  1695. x = 12 + 20
  1696. print(10 + x)
  1697. \end{lstlisting}
  1698. \fi}
  1699. {\if\edition\racketEd
  1700. %
  1701. When there are multiple \key{let}s for the same variable, the closest
  1702. enclosing \key{let} is used. That is, variable definitions overshadow
  1703. prior definitions. Consider the following program with two \key{let}s
  1704. that define two variables named \code{x}. Can you figure out the
  1705. result?
  1706. \begin{lstlisting}
  1707. (let ([x 32]) (+ (let ([x 10]) x) x))
  1708. \end{lstlisting}
  1709. For the purposes of depicting which variable occurrences correspond to
  1710. which definitions, the following shows the \code{x}'s annotated with
  1711. subscripts to distinguish them. Double check that your answer for the
  1712. previous program is the same as your answer for this annotated version
  1713. of the program.
  1714. \begin{lstlisting}
  1715. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1716. \end{lstlisting}
  1717. The initializing expression is always evaluated before the body of the
  1718. \key{let}, so in the following, the \key{read} for \code{x} is
  1719. performed before the \key{read} for \code{y}. Given the input
  1720. $52$ then $10$, the following produces $42$ (not $-42$).
  1721. \begin{lstlisting}
  1722. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1723. \end{lstlisting}
  1724. \fi}
  1725. \subsection{Extensible Interpreters via Method Overriding}
  1726. \label{sec:extensible-interp}
  1727. To prepare for discussing the interpreter of \LangVar{}, we explain
  1728. why we implement it in an object-oriented style. Throughout this book
  1729. we define many interpreters, one for each language that we
  1730. study. Because each language builds on the prior one, there is a lot
  1731. of commonality between these interpreters. We want to write down the
  1732. common parts just once instead of many times. A naive interpreter for
  1733. \LangVar{} would handle the \racket{cases for variables and
  1734. \code{let}} \python{case for variables} but dispatch to an
  1735. interpreter for \LangInt{} in the rest of the cases. The following
  1736. code sketches this idea. (We explain the \code{env} parameter in
  1737. section~\ref{sec:interp-Lvar}.)
  1738. \begin{center}
  1739. {\if\edition\racketEd
  1740. \begin{minipage}{0.45\textwidth}
  1741. \begin{lstlisting}
  1742. (define ((interp_Lint env) e)
  1743. (match e
  1744. [(Prim '- (list e1))
  1745. (fx- 0 ((interp_Lint env) e1))]
  1746. ...))
  1747. \end{lstlisting}
  1748. \end{minipage}
  1749. \begin{minipage}{0.45\textwidth}
  1750. \begin{lstlisting}
  1751. (define ((interp_Lvar env) e)
  1752. (match e
  1753. [(Var x)
  1754. (dict-ref env x)]
  1755. [(Let x e body)
  1756. (define v ((interp_exp env) e))
  1757. (define env^ (dict-set env x v))
  1758. ((interp_exp env^) body)]
  1759. [else ((interp_Lint env) e)]))
  1760. \end{lstlisting}
  1761. \end{minipage}
  1762. \fi}
  1763. {\if\edition\pythonEd
  1764. \begin{minipage}{0.45\textwidth}
  1765. \begin{lstlisting}
  1766. def interp_Lint(e, env):
  1767. match e:
  1768. case UnaryOp(USub(), e1):
  1769. return - interp_Lint(e1, env)
  1770. ...
  1771. \end{lstlisting}
  1772. \end{minipage}
  1773. \begin{minipage}{0.45\textwidth}
  1774. \begin{lstlisting}
  1775. def interp_Lvar(e, env):
  1776. match e:
  1777. case Name(id):
  1778. return env[id]
  1779. case _:
  1780. return interp_Lint(e, env)
  1781. \end{lstlisting}
  1782. \end{minipage}
  1783. \fi}
  1784. \end{center}
  1785. The problem with this naive approach is that it does not handle
  1786. situations in which an \LangVar{} feature, such as a variable, is
  1787. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1788. in the following program.
  1789. {\if\edition\racketEd
  1790. \begin{lstlisting}
  1791. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1792. \end{lstlisting}
  1793. \fi}
  1794. {\if\edition\pythonEd
  1795. \begin{minipage}{0.96\textwidth}
  1796. \begin{lstlisting}
  1797. y = 10
  1798. print(-y)
  1799. \end{lstlisting}
  1800. \end{minipage}
  1801. \fi}
  1802. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1803. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1804. then it recursively calls \code{interp\_Lint} again on its argument.
  1805. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1806. an error!
  1807. To make our interpreters extensible we need something called
  1808. \emph{open recursion}\index{subject}{open recursion}, in which the
  1809. tying of the recursive knot is delayed until the functions are
  1810. composed. Object-oriented languages provide open recursion via method
  1811. overriding\index{subject}{method overriding}. The following code uses
  1812. method overriding to interpret \LangInt{} and \LangVar{} using
  1813. %
  1814. \racket{the
  1815. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1816. \index{subject}{class} feature of Racket.}
  1817. %
  1818. \python{a Python \code{class} definition.}
  1819. %
  1820. We define one class for each language and define a method for
  1821. interpreting expressions inside each class. The class for \LangVar{}
  1822. inherits from the class for \LangInt{}, and the method
  1823. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1824. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1825. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1826. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1827. \code{interp\_exp} in \LangInt{}.
  1828. \begin{center}
  1829. \hspace{-20pt}
  1830. {\if\edition\racketEd
  1831. \begin{minipage}{0.45\textwidth}
  1832. \begin{lstlisting}
  1833. (define interp-Lint-class
  1834. (class object%
  1835. (define/public ((interp_exp env) e)
  1836. (match e
  1837. [(Prim '- (list e))
  1838. (fx- 0 ((interp_exp env) e))]
  1839. ...))
  1840. ...))
  1841. \end{lstlisting}
  1842. \end{minipage}
  1843. \begin{minipage}{0.45\textwidth}
  1844. \begin{lstlisting}
  1845. (define interp-Lvar-class
  1846. (class interp-Lint-class
  1847. (define/override ((interp_exp env) e)
  1848. (match e
  1849. [(Var x)
  1850. (dict-ref env x)]
  1851. [(Let x e body)
  1852. (define v ((interp_exp env) e))
  1853. (define env^ (dict-set env x v))
  1854. ((interp_exp env^) body)]
  1855. [else
  1856. (super (interp_exp env) e)]))
  1857. ...
  1858. ))
  1859. \end{lstlisting}
  1860. \end{minipage}
  1861. \fi}
  1862. {\if\edition\pythonEd
  1863. \begin{minipage}{0.45\textwidth}
  1864. \begin{lstlisting}
  1865. class InterpLint:
  1866. def interp_exp(e):
  1867. match e:
  1868. case UnaryOp(USub(), e1):
  1869. return -self.interp_exp(e1)
  1870. ...
  1871. ...
  1872. \end{lstlisting}
  1873. \end{minipage}
  1874. \begin{minipage}{0.45\textwidth}
  1875. \begin{lstlisting}
  1876. def InterpLvar(InterpLint):
  1877. def interp_exp(e):
  1878. match e:
  1879. case Name(id):
  1880. return env[id]
  1881. case _:
  1882. return super().interp_exp(e)
  1883. ...
  1884. \end{lstlisting}
  1885. \end{minipage}
  1886. \fi}
  1887. \end{center}
  1888. Getting back to the troublesome example, repeated here
  1889. {\if\edition\racketEd
  1890. \begin{lstlisting}
  1891. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1892. \end{lstlisting}
  1893. \fi}
  1894. {\if\edition\pythonEd
  1895. \begin{lstlisting}
  1896. y = 10
  1897. print(-y)
  1898. \end{lstlisting}
  1899. \fi}
  1900. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1901. \racket{on this expression,}
  1902. \python{on the \code{-y} expression,}
  1903. %
  1904. which we call \code{e0}, by creating an object of the \LangVar{} class
  1905. and calling the \code{interp\_exp} method
  1906. {\if\edition\racketEd
  1907. \begin{lstlisting}
  1908. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1909. \end{lstlisting}
  1910. \fi}
  1911. {\if\edition\pythonEd
  1912. \begin{lstlisting}
  1913. InterpLvar().interp_exp(e0)
  1914. \end{lstlisting}
  1915. \fi}
  1916. \noindent To process the \code{-} operator, the default case of
  1917. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1918. method in \LangInt{}. But then for the recursive method call, it
  1919. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1920. \code{Var} node is handled correctly. Thus, method overriding gives us
  1921. the open recursion that we need to implement our interpreters in an
  1922. extensible way.
  1923. \subsection{Definitional Interpreter for \LangVar{}}
  1924. \label{sec:interp-Lvar}
  1925. Having justified the use of classes and methods to implement
  1926. interpreters, we revisit the definitional interpreter for \LangInt{}
  1927. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1928. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1929. The interpreter for \LangVar{} adds two new \key{match} cases for
  1930. variables and \racket{\key{let}}\python{assignment}. For
  1931. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1932. value bound to a variable to all the uses of the variable. To
  1933. accomplish this, we maintain a mapping from variables to values called
  1934. an \emph{environment}\index{subject}{environment}.
  1935. %
  1936. We use
  1937. %
  1938. \racket{an association list (alist) }%
  1939. %
  1940. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1941. %
  1942. to represent the environment.
  1943. %
  1944. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1945. and the \code{racket/dict} package.}
  1946. %
  1947. The \code{interp\_exp} function takes the current environment,
  1948. \code{env}, as an extra parameter. When the interpreter encounters a
  1949. variable, it looks up the corresponding value in the dictionary.
  1950. %
  1951. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1952. initializing expression, extends the environment with the result
  1953. value bound to the variable, using \code{dict-set}, then evaluates
  1954. the body of the \key{Let}.}
  1955. %
  1956. \python{When the interpreter encounters an assignment, it evaluates
  1957. the initializing expression and then associates the resulting value
  1958. with the variable in the environment.}
  1959. \begin{figure}[tp]
  1960. \begin{tcolorbox}[colback=white]
  1961. {\if\edition\racketEd
  1962. \begin{lstlisting}
  1963. (define interp-Lint-class
  1964. (class object%
  1965. (super-new)
  1966. (define/public ((interp_exp env) e)
  1967. (match e
  1968. [(Int n) n]
  1969. [(Prim 'read '())
  1970. (define r (read))
  1971. (cond [(fixnum? r) r]
  1972. [else (error 'interp_exp "expected an integer" r)])]
  1973. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1974. [(Prim '+ (list e1 e2))
  1975. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1976. [(Prim '- (list e1 e2))
  1977. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1978. (define/public (interp_program p)
  1979. (match p
  1980. [(Program '() e) ((interp_exp '()) e)]))
  1981. ))
  1982. \end{lstlisting}
  1983. \fi}
  1984. {\if\edition\pythonEd
  1985. \begin{lstlisting}
  1986. class InterpLint:
  1987. def interp_exp(self, e, env):
  1988. match e:
  1989. case BinOp(left, Add(), right):
  1990. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1991. case BinOp(left, Sub(), right):
  1992. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1993. case UnaryOp(USub(), v):
  1994. return - self.interp_exp(v, env)
  1995. case Constant(value):
  1996. return value
  1997. case Call(Name('input_int'), []):
  1998. return int(input())
  1999. def interp_stmts(self, ss, env):
  2000. if len(ss) == 0:
  2001. return
  2002. match ss[0]:
  2003. case Expr(Call(Name('print'), [arg])):
  2004. print(self.interp_exp(arg, env), end='')
  2005. return self.interp_stmts(ss[1:], env)
  2006. case Expr(value):
  2007. self.interp_exp(value, env)
  2008. return self.interp_stmts(ss[1:], env)
  2009. def interp(self, p):
  2010. match p:
  2011. case Module(body):
  2012. self.interp_stmts(body, {})
  2013. def interp_Lint(p):
  2014. return InterpLint().interp(p)
  2015. \end{lstlisting}
  2016. \fi}
  2017. \end{tcolorbox}
  2018. \caption{Interpreter for \LangInt{} as a class.}
  2019. \label{fig:interp-Lint-class}
  2020. \end{figure}
  2021. \begin{figure}[tp]
  2022. \begin{tcolorbox}[colback=white]
  2023. {\if\edition\racketEd
  2024. \begin{lstlisting}
  2025. (define interp-Lvar-class
  2026. (class interp-Lint-class
  2027. (super-new)
  2028. (define/override ((interp_exp env) e)
  2029. (match e
  2030. [(Var x) (dict-ref env x)]
  2031. [(Let x e body)
  2032. (define new-env (dict-set env x ((interp_exp env) e)))
  2033. ((interp_exp new-env) body)]
  2034. [else ((super interp-exp env) e)]))
  2035. ))
  2036. (define (interp_Lvar p)
  2037. (send (new interp-Lvar-class) interp_program p))
  2038. \end{lstlisting}
  2039. \fi}
  2040. {\if\edition\pythonEd
  2041. \begin{lstlisting}
  2042. class InterpLvar(InterpLint):
  2043. def interp_exp(self, e, env):
  2044. match e:
  2045. case Name(id):
  2046. return env[id]
  2047. case _:
  2048. return super().interp_exp(e, env)
  2049. def interp_stmts(self, ss, env):
  2050. if len(ss) == 0:
  2051. return
  2052. match ss[0]:
  2053. case Assign([lhs], value):
  2054. env[lhs.id] = self.interp_exp(value, env)
  2055. return self.interp_stmts(ss[1:], env)
  2056. case _:
  2057. return super().interp_stmts(ss, env)
  2058. def interp_Lvar(p):
  2059. return InterpLvar().interp(p)
  2060. \end{lstlisting}
  2061. \fi}
  2062. \end{tcolorbox}
  2063. \caption{Interpreter for the \LangVar{} language.}
  2064. \label{fig:interp-Lvar}
  2065. \end{figure}
  2066. {\if\edition\racketEd
  2067. \begin{figure}[tp]
  2068. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2069. \small
  2070. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2071. An \emph{association list} (called an alist) is a list of key-value pairs.
  2072. For example, we can map people to their ages with an alist
  2073. \index{subject}{alist}\index{subject}{association list}
  2074. \begin{lstlisting}[basicstyle=\ttfamily]
  2075. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2076. \end{lstlisting}
  2077. The \emph{dictionary} interface is for mapping keys to values.
  2078. Every alist implements this interface. \index{subject}{dictionary}
  2079. The package
  2080. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2081. provides many functions for working with dictionaries, such as
  2082. \begin{description}
  2083. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2084. returns the value associated with the given $\itm{key}$.
  2085. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2086. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2087. and otherwise is the same as $\itm{dict}$.
  2088. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2089. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2090. of keys and values in $\itm{dict}$. For example, the following
  2091. creates a new alist in which the ages are incremented:
  2092. \end{description}
  2093. \vspace{-10pt}
  2094. \begin{lstlisting}[basicstyle=\ttfamily]
  2095. (for/list ([(k v) (in-dict ages)])
  2096. (cons k (add1 v)))
  2097. \end{lstlisting}
  2098. \end{tcolorbox}
  2099. %\end{wrapfigure}
  2100. \caption{Association lists implement the dictionary interface.}
  2101. \label{fig:alist}
  2102. \end{figure}
  2103. \fi}
  2104. The goal for this chapter is to implement a compiler that translates
  2105. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2106. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2107. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2108. That is, they output the same integer $n$. We depict this correctness
  2109. criteria in the following diagram:
  2110. \[
  2111. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2112. \node (p1) at (0, 0) {$P_1$};
  2113. \node (p2) at (4, 0) {$P_2$};
  2114. \node (o) at (4, -2) {$n$};
  2115. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2116. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2117. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2118. \end{tikzpicture}
  2119. \]
  2120. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2121. compiling \LangVar{}.
  2122. \section{The \LangXInt{} Assembly Language}
  2123. \label{sec:x86}
  2124. \index{subject}{x86}
  2125. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2126. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2127. assembler.
  2128. %
  2129. A program begins with a \code{main} label followed by a sequence of
  2130. instructions. The \key{globl} directive makes the \key{main} procedure
  2131. externally visible so that the operating system can call it.
  2132. %
  2133. An x86 program is stored in the computer's memory. For our purposes,
  2134. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2135. values. The computer has a \emph{program counter}
  2136. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2137. \code{rip} register that points to the address of the next instruction
  2138. to be executed. For most instructions, the program counter is
  2139. incremented after the instruction is executed so that it points to the
  2140. next instruction in memory. Most x86 instructions take two operands,
  2141. each of which is an integer constant (called an \emph{immediate
  2142. value}\index{subject}{immediate value}), a
  2143. \emph{register}\index{subject}{register}, or a memory location.
  2144. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2145. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2146. && \key{r8} \MID \key{r9} \MID \key{r10}
  2147. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2148. \MID \key{r14} \MID \key{r15}}
  2149. \newcommand{\GrammarXInt}{
  2150. \begin{array}{rcl}
  2151. \Reg &::=& \allregisters{} \\
  2152. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2153. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2154. \key{subq} \; \Arg\key{,} \Arg \MID
  2155. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2156. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2157. \key{callq} \; \mathit{label} \MID
  2158. \key{retq} \MID
  2159. \key{jmp}\,\itm{label} \MID \\
  2160. && \itm{label}\key{:}\; \Instr
  2161. \end{array}
  2162. }
  2163. \begin{figure}[tp]
  2164. \begin{tcolorbox}[colback=white]
  2165. {\if\edition\racketEd
  2166. \[
  2167. \begin{array}{l}
  2168. \GrammarXInt \\
  2169. \begin{array}{lcl}
  2170. \LangXIntM{} &::= & \key{.globl main}\\
  2171. & & \key{main:} \; \Instr\ldots
  2172. \end{array}
  2173. \end{array}
  2174. \]
  2175. \fi}
  2176. {\if\edition\pythonEd
  2177. \[
  2178. \begin{array}{lcl}
  2179. \Reg &::=& \allregisters{} \\
  2180. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2181. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2182. \key{subq} \; \Arg\key{,} \Arg \MID
  2183. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2184. && \key{callq} \; \mathit{label} \MID
  2185. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2186. \LangXIntM{} &::= & \key{.globl main}\\
  2187. & & \key{main:} \; \Instr^{*}
  2188. \end{array}
  2189. \]
  2190. \fi}
  2191. \end{tcolorbox}
  2192. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2193. \label{fig:x86-int-concrete}
  2194. \end{figure}
  2195. A register is a special kind of variable that holds a 64-bit
  2196. value. There are 16 general-purpose registers in the computer; their
  2197. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2198. written with a percent sign, \key{\%}, followed by the register name,
  2199. for example \key{\%rax}.
  2200. An immediate value is written using the notation \key{\$}$n$ where $n$
  2201. is an integer.
  2202. %
  2203. %
  2204. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2205. which obtains the address stored in register $r$ and then adds $n$
  2206. bytes to the address. The resulting address is used to load or to store
  2207. to memory depending on whether it occurs as a source or destination
  2208. argument of an instruction.
  2209. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2210. the source $s$ and destination $d$, applies the arithmetic operation,
  2211. and then writes the result to the destination $d$. \index{subject}{instruction}
  2212. %
  2213. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2214. stores the result in $d$.
  2215. %
  2216. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2217. specified by the label, and $\key{retq}$ returns from a procedure to
  2218. its caller.
  2219. %
  2220. We discuss procedure calls in more detail further in this chapter and
  2221. in chapter~\ref{ch:Lfun}.
  2222. %
  2223. The last letter \key{q} indicates that these instructions operate on
  2224. quadwords which are 64-bit values.
  2225. %
  2226. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2227. counter to the address of the instruction immediately after the
  2228. specified label.}
  2229. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2230. all the x86 instructions used in this book.
  2231. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2232. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2233. \lstinline{movq $10, %rax}
  2234. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2235. adds $32$ to the $10$ in \key{rax} and
  2236. puts the result, $42$, into \key{rax}.
  2237. %
  2238. The last instruction \key{retq} finishes the \key{main} function by
  2239. returning the integer in \key{rax} to the operating system. The
  2240. operating system interprets this integer as the program's exit
  2241. code. By convention, an exit code of 0 indicates that a program has
  2242. completed successfully, and all other exit codes indicate various
  2243. errors.
  2244. %
  2245. \racket{However, in this book we return the result of the program
  2246. as the exit code.}
  2247. \begin{figure}[tbp]
  2248. \begin{minipage}{0.45\textwidth}
  2249. \begin{tcolorbox}[colback=white]
  2250. \begin{lstlisting}
  2251. .globl main
  2252. main:
  2253. movq $10, %rax
  2254. addq $32, %rax
  2255. retq
  2256. \end{lstlisting}
  2257. \end{tcolorbox}
  2258. \end{minipage}
  2259. \caption{An x86 program that computes
  2260. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2261. \label{fig:p0-x86}
  2262. \end{figure}
  2263. We exhibit the use of memory for storing intermediate results in the
  2264. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2265. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2266. uses a region of memory called the \emph{procedure call stack}
  2267. (\emph{stack} for
  2268. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2269. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2270. for each procedure call. The memory layout for an individual frame is
  2271. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2272. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2273. address of the item at the top of the stack. In general, we use the
  2274. term \emph{pointer}\index{subject}{pointer} for something that
  2275. contains an address. The stack grows downward in memory, so we
  2276. increase the size of the stack by subtracting from the stack pointer.
  2277. In the context of a procedure call, the \emph{return
  2278. address}\index{subject}{return address} is the location of the
  2279. instruction that immediately follows the call instruction on the
  2280. caller side. The function call instruction, \code{callq}, pushes the
  2281. return address onto the stack prior to jumping to the procedure. The
  2282. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2283. pointer} and is used to access variables that are stored in the
  2284. frame of the current procedure call. The base pointer of the caller
  2285. is stored immediately after the return address.
  2286. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2287. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2288. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2289. $-16\key{(\%rbp)}$, and so on.
  2290. \begin{figure}[tbp]
  2291. \begin{minipage}{0.66\textwidth}
  2292. \begin{tcolorbox}[colback=white]
  2293. {\if\edition\racketEd
  2294. \begin{lstlisting}
  2295. start:
  2296. movq $10, -8(%rbp)
  2297. negq -8(%rbp)
  2298. movq -8(%rbp), %rax
  2299. addq $52, %rax
  2300. jmp conclusion
  2301. .globl main
  2302. main:
  2303. pushq %rbp
  2304. movq %rsp, %rbp
  2305. subq $16, %rsp
  2306. jmp start
  2307. conclusion:
  2308. addq $16, %rsp
  2309. popq %rbp
  2310. retq
  2311. \end{lstlisting}
  2312. \fi}
  2313. {\if\edition\pythonEd
  2314. \begin{lstlisting}
  2315. .globl main
  2316. main:
  2317. pushq %rbp
  2318. movq %rsp, %rbp
  2319. subq $16, %rsp
  2320. movq $10, -8(%rbp)
  2321. negq -8(%rbp)
  2322. movq -8(%rbp), %rax
  2323. addq $52, %rax
  2324. addq $16, %rsp
  2325. popq %rbp
  2326. retq
  2327. \end{lstlisting}
  2328. \fi}
  2329. \end{tcolorbox}
  2330. \end{minipage}
  2331. \caption{An x86 program that computes
  2332. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2333. \label{fig:p1-x86}
  2334. \end{figure}
  2335. \begin{figure}[tbp]
  2336. \begin{minipage}{0.66\textwidth}
  2337. \begin{tcolorbox}[colback=white]
  2338. \centering
  2339. \begin{tabular}{|r|l|} \hline
  2340. Position & Contents \\ \hline
  2341. $8$(\key{\%rbp}) & return address \\
  2342. $0$(\key{\%rbp}) & old \key{rbp} \\
  2343. $-8$(\key{\%rbp}) & variable $1$ \\
  2344. $-16$(\key{\%rbp}) & variable $2$ \\
  2345. \ldots & \ldots \\
  2346. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2347. \end{tabular}
  2348. \end{tcolorbox}
  2349. \end{minipage}
  2350. \caption{Memory layout of a frame.}
  2351. \label{fig:frame}
  2352. \end{figure}
  2353. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2354. is transferred from the operating system to the \code{main} function.
  2355. The operating system issues a \code{callq main} instruction that
  2356. pushes its return address on the stack and then jumps to
  2357. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2358. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2359. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2360. out of alignment (because the \code{callq} pushed the return address).
  2361. The first three instructions are the typical
  2362. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2363. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2364. pointer \code{rsp} and then saves the base pointer of the caller at
  2365. address \code{rsp} on the stack. The next instruction \code{movq
  2366. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2367. which is pointing to the location of the old base pointer. The
  2368. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2369. make enough room for storing variables. This program needs one
  2370. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2371. 16-byte-aligned, and then we are ready to make calls to other functions.
  2372. \racket{The last instruction of the prelude is \code{jmp start}, which
  2373. transfers control to the instructions that were generated from the
  2374. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2375. \racket{The first instruction under the \code{start} label is}
  2376. %
  2377. \python{The first instruction after the prelude is}
  2378. %
  2379. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2380. %
  2381. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2382. $1$ to $-10$.
  2383. %
  2384. The next instruction moves the $-10$ from variable $1$ into the
  2385. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2386. the value in \code{rax}, updating its contents to $42$.
  2387. \racket{The three instructions under the label \code{conclusion} are the
  2388. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2389. %
  2390. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2391. \code{main} function consists of the last three instructions.}
  2392. %
  2393. The first two restore the \code{rsp} and \code{rbp} registers to their
  2394. states at the beginning of the procedure. In particular,
  2395. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2396. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2397. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2398. \key{retq}, jumps back to the procedure that called this one and adds
  2399. $8$ to the stack pointer.
  2400. Our compiler needs a convenient representation for manipulating x86
  2401. programs, so we define an abstract syntax for x86, shown in
  2402. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2403. \LangXInt{}.
  2404. %
  2405. {\if\edition\pythonEd%
  2406. The main difference between this and the concrete syntax of \LangXInt{}
  2407. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2408. names, and register names are explicitly represented by strings.
  2409. \fi} %
  2410. {\if\edition\racketEd
  2411. The main difference between this and the concrete syntax of \LangXInt{}
  2412. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2413. front of every instruction. Instead instructions are grouped into
  2414. \emph{basic blocks}\index{subject}{basic block} with a
  2415. label associated with every basic block; this is why the \key{X86Program}
  2416. struct includes an alist mapping labels to basic blocks. The reason for this
  2417. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2418. introduce conditional branching. The \code{Block} structure includes
  2419. an $\itm{info}$ field that is not needed in this chapter but becomes
  2420. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2421. $\itm{info}$ field should contain an empty list.
  2422. \fi}
  2423. %
  2424. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2425. node includes an integer for representing the arity of the function,
  2426. that is, the number of arguments, which is helpful to know during
  2427. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2428. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2429. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2430. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2431. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2432. \MID \skey{r14} \MID \skey{r15}}
  2433. \newcommand{\ASTXIntRacket}{
  2434. \begin{array}{lcl}
  2435. \Reg &::=& \allregisters{} \\
  2436. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2437. \MID \DEREF{\Reg}{\Int} \\
  2438. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2439. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2440. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2441. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2442. &\MID& \PUSHQ{\Arg}
  2443. \MID \POPQ{\Arg} \\
  2444. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2445. \MID \RETQ{}
  2446. \MID \JMP{\itm{label}} \\
  2447. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2448. \end{array}
  2449. }
  2450. \begin{figure}[tp]
  2451. \begin{tcolorbox}[colback=white]
  2452. \small
  2453. {\if\edition\racketEd
  2454. \[\arraycolsep=3pt
  2455. \begin{array}{l}
  2456. \ASTXIntRacket \\
  2457. \begin{array}{lcl}
  2458. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2459. \end{array}
  2460. \end{array}
  2461. \]
  2462. \fi}
  2463. {\if\edition\pythonEd
  2464. \[
  2465. \begin{array}{lcl}
  2466. \Reg &::=& \allastregisters{} \\
  2467. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2468. \MID \DEREF{\Reg}{\Int} \\
  2469. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2470. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2471. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2472. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2473. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2474. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2475. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2476. \end{array}
  2477. \]
  2478. \fi}
  2479. \end{tcolorbox}
  2480. \caption{The abstract syntax of \LangXInt{} assembly.}
  2481. \label{fig:x86-int-ast}
  2482. \end{figure}
  2483. \section{Planning the Trip to x86}
  2484. \label{sec:plan-s0-x86}
  2485. To compile one language to another, it helps to focus on the
  2486. differences between the two languages because the compiler will need
  2487. to bridge those differences. What are the differences between \LangVar{}
  2488. and x86 assembly? Here are some of the most important ones:
  2489. \begin{enumerate}
  2490. \item x86 arithmetic instructions typically have two arguments and
  2491. update the second argument in place. In contrast, \LangVar{}
  2492. arithmetic operations take two arguments and produce a new value.
  2493. An x86 instruction may have at most one memory-accessing argument.
  2494. Furthermore, some x86 instructions place special restrictions on
  2495. their arguments.
  2496. \item An argument of an \LangVar{} operator can be a deeply nested
  2497. expression, whereas x86 instructions restrict their arguments to be
  2498. integer constants, registers, and memory locations.
  2499. {\if\edition\racketEd
  2500. \item The order of execution in x86 is explicit in the syntax, which
  2501. is a sequence of instructions and jumps to labeled positions,
  2502. whereas in \LangVar{} the order of evaluation is a left-to-right
  2503. depth-first traversal of the abstract syntax tree. \fi}
  2504. \item A program in \LangVar{} can have any number of variables,
  2505. whereas x86 has 16 registers and the procedure call stack.
  2506. {\if\edition\racketEd
  2507. \item Variables in \LangVar{} can shadow other variables with the
  2508. same name. In x86, registers have unique names, and memory locations
  2509. have unique addresses.
  2510. \fi}
  2511. \end{enumerate}
  2512. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2513. down the problem into several steps, which deal with these differences
  2514. one at a time. Each of these steps is called a \emph{pass} of the
  2515. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2516. %
  2517. This term indicates that each step passes over, or traverses, the AST
  2518. of the program.
  2519. %
  2520. Furthermore, we follow the nanopass approach, which means that we
  2521. strive for each pass to accomplish one clear objective rather than two
  2522. or three at the same time.
  2523. %
  2524. We begin by sketching how we might implement each pass and give each
  2525. pass a name. We then figure out an ordering of the passes and the
  2526. input/output language for each pass. The very first pass has
  2527. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2528. its output language. In between these two passes, we can choose
  2529. whichever language is most convenient for expressing the output of
  2530. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2531. \emph{intermediate languages} of our own design. Finally, to
  2532. implement each pass we write one recursive function per nonterminal in
  2533. the grammar of the input language of the pass.
  2534. \index{subject}{intermediate language}
  2535. Our compiler for \LangVar{} consists of the following passes:
  2536. %
  2537. \begin{description}
  2538. {\if\edition\racketEd
  2539. \item[\key{uniquify}] deals with the shadowing of variables by
  2540. renaming every variable to a unique name.
  2541. \fi}
  2542. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2543. of a primitive operation or function call is a variable or integer,
  2544. that is, an \emph{atomic} expression. We refer to nonatomic
  2545. expressions as \emph{complex}. This pass introduces temporary
  2546. variables to hold the results of complex
  2547. subexpressions.\index{subject}{atomic
  2548. expression}\index{subject}{complex expression}%
  2549. {\if\edition\racketEd
  2550. \item[\key{explicate\_control}] makes the execution order of the
  2551. program explicit. It converts the abstract syntax tree
  2552. representation into a graph in which each node is a labeled sequence
  2553. of statements and the edges are \code{goto} statements.
  2554. \fi}
  2555. \item[\key{select\_instructions}] handles the difference between
  2556. \LangVar{} operations and x86 instructions. This pass converts each
  2557. \LangVar{} operation to a short sequence of instructions that
  2558. accomplishes the same task.
  2559. \item[\key{assign\_homes}] replaces variables with registers or stack
  2560. locations.
  2561. \end{description}
  2562. %
  2563. {\if\edition\racketEd
  2564. %
  2565. Our treatment of \code{remove\_complex\_operands} and
  2566. \code{explicate\_control} as separate passes is an example of the
  2567. nanopass approach\footnote{For analogous decompositions of the
  2568. translation into continuation passing style, see the work of
  2569. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2570. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2571. %
  2572. \fi}
  2573. The next question is, in what order should we apply these passes? This
  2574. question can be challenging because it is difficult to know ahead of
  2575. time which orderings will be better (that is, will be easier to
  2576. implement, produce more efficient code, and so on), and therefore
  2577. ordering often involves trial and error. Nevertheless, we can plan
  2578. ahead and make educated choices regarding the ordering.
  2579. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2580. \key{uniquify}? The \key{uniquify} pass should come first because
  2581. \key{explicate\_control} changes all the \key{let}-bound variables to
  2582. become local variables whose scope is the entire program, which would
  2583. confuse variables with the same name.}
  2584. %
  2585. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2586. because the later removes the \key{let} form, but it is convenient to
  2587. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2588. %
  2589. \racket{The ordering of \key{uniquify} with respect to
  2590. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2591. \key{uniquify} to come first.}
  2592. The \key{select\_instructions} and \key{assign\_homes} passes are
  2593. intertwined.
  2594. %
  2595. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2596. passing arguments to functions and that it is preferable to assign
  2597. parameters to their corresponding registers. This suggests that it
  2598. would be better to start with the \key{select\_instructions} pass,
  2599. which generates the instructions for argument passing, before
  2600. performing register allocation.
  2601. %
  2602. On the other hand, by selecting instructions first we may run into a
  2603. dead end in \key{assign\_homes}. Recall that only one argument of an
  2604. x86 instruction may be a memory access, but \key{assign\_homes} might
  2605. be forced to assign both arguments to memory locations.
  2606. %
  2607. A sophisticated approach is to repeat the two passes until a solution
  2608. is found. However, to reduce implementation complexity we recommend
  2609. placing \key{select\_instructions} first, followed by the
  2610. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2611. that uses a reserved register to fix outstanding problems.
  2612. \begin{figure}[tbp]
  2613. \begin{tcolorbox}[colback=white]
  2614. {\if\edition\racketEd
  2615. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2616. \node (Lvar) at (0,2) {\large \LangVar{}};
  2617. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2618. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2619. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2620. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2621. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2622. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2623. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2624. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2625. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2626. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2627. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2628. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2629. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2630. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2631. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2632. \end{tikzpicture}
  2633. \fi}
  2634. {\if\edition\pythonEd
  2635. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2636. \node (Lvar) at (0,2) {\large \LangVar{}};
  2637. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2638. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2639. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2640. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2641. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2642. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2643. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  2644. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2645. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2646. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2647. \end{tikzpicture}
  2648. \fi}
  2649. \end{tcolorbox}
  2650. \caption{Diagram of the passes for compiling \LangVar{}. }
  2651. \label{fig:Lvar-passes}
  2652. \end{figure}
  2653. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2654. passes and identifies the input and output language of each pass.
  2655. %
  2656. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2657. language, which extends \LangXInt{} with an unbounded number of
  2658. program-scope variables and removes the restrictions regarding
  2659. instruction arguments.
  2660. %
  2661. The last pass, \key{prelude\_and\_conclusion}, places the program
  2662. instructions inside a \code{main} function with instructions for the
  2663. prelude and conclusion.
  2664. %
  2665. \racket{In the next section we discuss the \LangCVar{} intermediate
  2666. language that serves as the output of \code{explicate\_control}.}
  2667. %
  2668. The remainder of this chapter provides guidance on the implementation
  2669. of each of the compiler passes represented in
  2670. figure~\ref{fig:Lvar-passes}.
  2671. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2672. %% are programs that are still in the \LangVar{} language, though the
  2673. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2674. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2675. %% %
  2676. %% The output of \code{explicate\_control} is in an intermediate language
  2677. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2678. %% syntax, which we introduce in the next section. The
  2679. %% \key{select-instruction} pass translates from \LangCVar{} to
  2680. %% \LangXVar{}. The \key{assign-homes} and
  2681. %% \key{patch-instructions}
  2682. %% passes input and output variants of x86 assembly.
  2683. \newcommand{\CvarGrammarRacket}{
  2684. \begin{array}{lcl}
  2685. \Atm &::=& \Int \MID \Var \\
  2686. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2687. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2688. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2689. \end{array}
  2690. }
  2691. \newcommand{\CvarASTRacket}{
  2692. \begin{array}{lcl}
  2693. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2694. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2695. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2696. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2697. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2698. \end{array}
  2699. }
  2700. {\if\edition\racketEd
  2701. \subsection{The \LangCVar{} Intermediate Language}
  2702. The output of \code{explicate\_control} is similar to the C
  2703. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2704. categories for expressions and statements, so we name it \LangCVar{}.
  2705. This style of intermediate language is also known as
  2706. \emph{three-address code}, to emphasize that the typical form of a
  2707. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2708. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2709. The concrete syntax for \LangCVar{} is shown in
  2710. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2711. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2712. %
  2713. The \LangCVar{} language supports the same operators as \LangVar{} but
  2714. the arguments of operators are restricted to atomic
  2715. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2716. assignment statements that can be executed in sequence using the
  2717. \key{Seq} form. A sequence of statements always ends with
  2718. \key{Return}, a guarantee that is baked into the grammar rules for
  2719. \itm{tail}. The naming of this nonterminal comes from the term
  2720. \emph{tail position}\index{subject}{tail position}, which refers to an
  2721. expression that is the last one to execute within a function or
  2722. program.
  2723. A \LangCVar{} program consists of an alist mapping labels to
  2724. tails. This is more general than necessary for the present chapter, as
  2725. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2726. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2727. there is just one label, \key{start}, and the whole program is
  2728. its tail.
  2729. %
  2730. The $\itm{info}$ field of the \key{CProgram} form, after the
  2731. \code{explicate\_control} pass, contains an alist that associates the
  2732. symbol \key{locals} with a list of all the variables used in the
  2733. program. At the start of the program, these variables are
  2734. uninitialized; they become initialized on their first assignment.
  2735. \begin{figure}[tbp]
  2736. \begin{tcolorbox}[colback=white]
  2737. \[
  2738. \begin{array}{l}
  2739. \CvarGrammarRacket \\
  2740. \begin{array}{lcl}
  2741. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2742. \end{array}
  2743. \end{array}
  2744. \]
  2745. \end{tcolorbox}
  2746. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2747. \label{fig:c0-concrete-syntax}
  2748. \end{figure}
  2749. \begin{figure}[tbp]
  2750. \begin{tcolorbox}[colback=white]
  2751. \[
  2752. \begin{array}{l}
  2753. \CvarASTRacket \\
  2754. \begin{array}{lcl}
  2755. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2756. \end{array}
  2757. \end{array}
  2758. \]
  2759. \end{tcolorbox}
  2760. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2761. \label{fig:c0-syntax}
  2762. \end{figure}
  2763. The definitional interpreter for \LangCVar{} is in the support code,
  2764. in the file \code{interp-Cvar.rkt}.
  2765. \fi}
  2766. {\if\edition\racketEd
  2767. \section{Uniquify Variables}
  2768. \label{sec:uniquify-Lvar}
  2769. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2770. programs in which every \key{let} binds a unique variable name. For
  2771. example, the \code{uniquify} pass should translate the program on the
  2772. left into the program on the right.
  2773. \begin{transformation}
  2774. \begin{lstlisting}
  2775. (let ([x 32])
  2776. (+ (let ([x 10]) x) x))
  2777. \end{lstlisting}
  2778. \compilesto
  2779. \begin{lstlisting}
  2780. (let ([x.1 32])
  2781. (+ (let ([x.2 10]) x.2) x.1))
  2782. \end{lstlisting}
  2783. \end{transformation}
  2784. The following is another example translation, this time of a program
  2785. with a \key{let} nested inside the initializing expression of another
  2786. \key{let}.
  2787. \begin{transformation}
  2788. \begin{lstlisting}
  2789. (let ([x (let ([x 4])
  2790. (+ x 1))])
  2791. (+ x 2))
  2792. \end{lstlisting}
  2793. \compilesto
  2794. \begin{lstlisting}
  2795. (let ([x.2 (let ([x.1 4])
  2796. (+ x.1 1))])
  2797. (+ x.2 2))
  2798. \end{lstlisting}
  2799. \end{transformation}
  2800. We recommend implementing \code{uniquify} by creating a structurally
  2801. recursive function named \code{uniquify\_exp} that does little other
  2802. than copy an expression. However, when encountering a \key{let}, it
  2803. should generate a unique name for the variable and associate the old
  2804. name with the new name in an alist.\footnote{The Racket function
  2805. \code{gensym} is handy for generating unique variable names.} The
  2806. \code{uniquify\_exp} function needs to access this alist when it gets
  2807. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2808. for the alist.
  2809. The skeleton of the \code{uniquify\_exp} function is shown in
  2810. figure~\ref{fig:uniquify-Lvar}.
  2811. %% The function is curried so that it is
  2812. %% convenient to partially apply it to an alist and then apply it to
  2813. %% different expressions, as in the last case for primitive operations in
  2814. %% figure~\ref{fig:uniquify-Lvar}.
  2815. The
  2816. %
  2817. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2818. %
  2819. form of Racket is useful for transforming the element of a list to
  2820. produce a new list.\index{subject}{for/list}
  2821. \begin{figure}[tbp]
  2822. \begin{tcolorbox}[colback=white]
  2823. \begin{lstlisting}
  2824. (define (uniquify_exp env)
  2825. (lambda (e)
  2826. (match e
  2827. [(Var x) ___]
  2828. [(Int n) (Int n)]
  2829. [(Let x e body) ___]
  2830. [(Prim op es)
  2831. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2832. (define (uniquify p)
  2833. (match p
  2834. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2835. \end{lstlisting}
  2836. \end{tcolorbox}
  2837. \caption{Skeleton for the \key{uniquify} pass.}
  2838. \label{fig:uniquify-Lvar}
  2839. \end{figure}
  2840. \begin{exercise}
  2841. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2842. Complete the \code{uniquify} pass by filling in the blanks in
  2843. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2844. variables and for the \key{let} form in the file \code{compiler.rkt}
  2845. in the support code.
  2846. \end{exercise}
  2847. \begin{exercise}
  2848. \normalfont\normalsize
  2849. \label{ex:Lvar}
  2850. Create five \LangVar{} programs that exercise the most interesting
  2851. parts of the \key{uniquify} pass; that is, the programs should include
  2852. \key{let} forms, variables, and variables that shadow each other.
  2853. The five programs should be placed in the subdirectory named
  2854. \key{tests}, and the file names should start with \code{var\_test\_}
  2855. followed by a unique integer and end with the file extension
  2856. \key{.rkt}.
  2857. %
  2858. The \key{run-tests.rkt} script in the support code checks whether the
  2859. output programs produce the same result as the input programs. The
  2860. script uses the \key{interp-tests} function
  2861. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2862. your \key{uniquify} pass on the example programs. The \code{passes}
  2863. parameter of \key{interp-tests} is a list that should have one entry
  2864. for each pass in your compiler. For now, define \code{passes} to
  2865. contain just one entry for \code{uniquify} as follows:
  2866. \begin{lstlisting}
  2867. (define passes
  2868. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2869. \end{lstlisting}
  2870. Run the \key{run-tests.rkt} script in the support code to check
  2871. whether the output programs produce the same result as the input
  2872. programs.
  2873. \end{exercise}
  2874. \fi}
  2875. \section{Remove Complex Operands}
  2876. \label{sec:remove-complex-opera-Lvar}
  2877. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2878. into a restricted form in which the arguments of operations are atomic
  2879. expressions. Put another way, this pass removes complex
  2880. operands\index{subject}{complex operand}, such as the expression
  2881. \racket{\code{(- 10)}}\python{\code{-10}}
  2882. in the following program. This is accomplished by introducing a new
  2883. temporary variable, assigning the complex operand to the new
  2884. variable, and then using the new variable in place of the complex
  2885. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2886. right.
  2887. {\if\edition\racketEd
  2888. \begin{transformation}
  2889. % var_test_19.rkt
  2890. \begin{lstlisting}
  2891. (let ([x (+ 42 (- 10))])
  2892. (+ x 10))
  2893. \end{lstlisting}
  2894. \compilesto
  2895. \begin{lstlisting}
  2896. (let ([x (let ([tmp.1 (- 10)])
  2897. (+ 42 tmp.1))])
  2898. (+ x 10))
  2899. \end{lstlisting}
  2900. \end{transformation}
  2901. \fi}
  2902. {\if\edition\pythonEd
  2903. \begin{transformation}
  2904. \begin{lstlisting}
  2905. x = 42 + -10
  2906. print(x + 10)
  2907. \end{lstlisting}
  2908. \compilesto
  2909. \begin{lstlisting}
  2910. tmp_0 = -10
  2911. x = 42 + tmp_0
  2912. tmp_1 = x + 10
  2913. print(tmp_1)
  2914. \end{lstlisting}
  2915. \end{transformation}
  2916. \fi}
  2917. \newcommand{\LvarMonadASTRacket}{
  2918. \begin{array}{rcl}
  2919. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2920. \Exp &::=& \Atm \MID \READ{} \\
  2921. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2922. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2923. \end{array}
  2924. }
  2925. \newcommand{\LvarMonadASTPython}{
  2926. \begin{array}{rcl}
  2927. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2928. \Exp{} &::=& \Atm \MID \READ{} \\
  2929. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2930. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2931. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2932. \end{array}
  2933. }
  2934. \begin{figure}[tp]
  2935. \centering
  2936. \begin{tcolorbox}[colback=white]
  2937. {\if\edition\racketEd
  2938. \[
  2939. \begin{array}{l}
  2940. \LvarMonadASTRacket \\
  2941. \begin{array}{rcl}
  2942. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2943. \end{array}
  2944. \end{array}
  2945. \]
  2946. \fi}
  2947. {\if\edition\pythonEd
  2948. \[
  2949. \begin{array}{l}
  2950. \LvarMonadASTPython \\
  2951. \begin{array}{rcl}
  2952. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2953. \end{array}
  2954. \end{array}
  2955. \]
  2956. \fi}
  2957. \end{tcolorbox}
  2958. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2959. atomic expressions.}
  2960. \label{fig:Lvar-anf-syntax}
  2961. \end{figure}
  2962. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2963. of this pass, the language \LangVarANF{}. The only difference is that
  2964. operator arguments are restricted to be atomic expressions that are
  2965. defined by the \Atm{} nonterminal. In particular, integer constants
  2966. and variables are atomic.
  2967. The atomic expressions are pure (they do not cause or depend on side
  2968. effects) whereas complex expressions may have side effects, such as
  2969. \READ{}. A language with this separation between pure expression
  2970. versus expressions with side effects is said to be in monadic normal
  2971. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2972. in the name \LangVarANF{}. An important invariant of the
  2973. \code{remove\_complex\_operands} pass is that the relative ordering
  2974. among complex expressions is not changed, but the relative ordering
  2975. between atomic expressions and complex expressions can change and
  2976. often does. The reason that these changes are behavior preserving is
  2977. that the atomic expressions are pure.
  2978. Another well-known form for intermediate languages is the
  2979. \emph{administrative normal form}
  2980. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2981. \index{subject}{administrative normal form} \index{subject}{ANF}
  2982. %
  2983. The \LangVarANF{} language is not quite in ANF because we allow the
  2984. right-hand side of a \code{let} to be a complex expression.
  2985. {\if\edition\racketEd
  2986. We recommend implementing this pass with two mutually recursive
  2987. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2988. \code{rco\_atom} to subexpressions that need to become atomic and to
  2989. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2990. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2991. returns an expression. The \code{rco\_atom} function returns two
  2992. things: an atomic expression and an alist mapping temporary variables to
  2993. complex subexpressions. You can return multiple things from a function
  2994. using Racket's \key{values} form, and you can receive multiple things
  2995. from a function call using the \key{define-values} form.
  2996. \fi}
  2997. %
  2998. {\if\edition\pythonEd
  2999. %
  3000. We recommend implementing this pass with an auxiliary method named
  3001. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3002. Boolean that specifies whether the expression needs to become atomic
  3003. or not. The \code{rco\_exp} method should return a pair consisting of
  3004. the new expression and a list of pairs, associating new temporary
  3005. variables with their initializing expressions.
  3006. %
  3007. \fi}
  3008. {\if\edition\racketEd
  3009. %
  3010. Returning to the example program with the expression \code{(+ 42 (-
  3011. 10))}, the subexpression \code{(- 10)} should be processed using the
  3012. \code{rco\_atom} function because it is an argument of the \code{+}
  3013. operator and therefore needs to become atomic. The output of
  3014. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3015. \begin{transformation}
  3016. \begin{lstlisting}
  3017. (- 10)
  3018. \end{lstlisting}
  3019. \compilesto
  3020. \begin{lstlisting}
  3021. tmp.1
  3022. ((tmp.1 . (- 10)))
  3023. \end{lstlisting}
  3024. \end{transformation}
  3025. \fi}
  3026. %
  3027. {\if\edition\pythonEd
  3028. %
  3029. Returning to the example program with the expression \code{42 + -10},
  3030. the subexpression \code{-10} should be processed using the
  3031. \code{rco\_exp} function with \code{True} as the second argument
  3032. because \code{-10} is an argument of the \code{+} operator and
  3033. therefore needs to become atomic. The output of \code{rco\_exp}
  3034. applied to \code{-10} is as follows.
  3035. \begin{transformation}
  3036. \begin{lstlisting}
  3037. -10
  3038. \end{lstlisting}
  3039. \compilesto
  3040. \begin{lstlisting}
  3041. tmp_1
  3042. [(tmp_1, -10)]
  3043. \end{lstlisting}
  3044. \end{transformation}
  3045. %
  3046. \fi}
  3047. Take special care of programs, such as the following, that
  3048. %
  3049. \racket{bind a variable to an atomic expression.}
  3050. %
  3051. \python{assign an atomic expression to a variable.}
  3052. %
  3053. You should leave such \racket{variable bindings}\python{assignments}
  3054. unchanged, as shown in the program on the right\\
  3055. %
  3056. {\if\edition\racketEd
  3057. \begin{transformation}
  3058. % var_test_20.rkt
  3059. \begin{lstlisting}
  3060. (let ([a 42])
  3061. (let ([b a])
  3062. b))
  3063. \end{lstlisting}
  3064. \compilesto
  3065. \begin{lstlisting}
  3066. (let ([a 42])
  3067. (let ([b a])
  3068. b))
  3069. \end{lstlisting}
  3070. \end{transformation}
  3071. \fi}
  3072. {\if\edition\pythonEd
  3073. \begin{transformation}
  3074. \begin{lstlisting}
  3075. a = 42
  3076. b = a
  3077. print(b)
  3078. \end{lstlisting}
  3079. \compilesto
  3080. \begin{lstlisting}
  3081. a = 42
  3082. b = a
  3083. print(b)
  3084. \end{lstlisting}
  3085. \end{transformation}
  3086. \fi}
  3087. %
  3088. \noindent A careless implementation might produce the following output with
  3089. unnecessary temporary variables.
  3090. \begin{center}
  3091. \begin{minipage}{0.4\textwidth}
  3092. {\if\edition\racketEd
  3093. \begin{lstlisting}
  3094. (let ([tmp.1 42])
  3095. (let ([a tmp.1])
  3096. (let ([tmp.2 a])
  3097. (let ([b tmp.2])
  3098. b))))
  3099. \end{lstlisting}
  3100. \fi}
  3101. {\if\edition\pythonEd
  3102. \begin{lstlisting}
  3103. tmp_1 = 42
  3104. a = tmp_1
  3105. tmp_2 = a
  3106. b = tmp_2
  3107. print(b)
  3108. \end{lstlisting}
  3109. \fi}
  3110. \end{minipage}
  3111. \end{center}
  3112. \begin{exercise}
  3113. \normalfont\normalsize
  3114. {\if\edition\racketEd
  3115. Implement the \code{remove\_complex\_operands} function in
  3116. \code{compiler.rkt}.
  3117. %
  3118. Create three new \LangVar{} programs that exercise the interesting
  3119. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3120. regarding file names described in exercise~\ref{ex:Lvar}.
  3121. %
  3122. In the \code{run-tests.rkt} script, add the following entry to the
  3123. list of \code{passes}, and then run the script to test your compiler.
  3124. \begin{lstlisting}
  3125. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3126. \end{lstlisting}
  3127. In debugging your compiler, it is often useful to see the intermediate
  3128. programs that are output from each pass. To print the intermediate
  3129. programs, place \lstinline{(debug-level 1)} before the call to
  3130. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3131. %
  3132. {\if\edition\pythonEd
  3133. Implement the \code{remove\_complex\_operands} pass in
  3134. \code{compiler.py}, creating auxiliary functions for each
  3135. nonterminal in the grammar, i.e., \code{rco\_exp}
  3136. and \code{rco\_stmt}. We recommend you use the function
  3137. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3138. \fi}
  3139. \end{exercise}
  3140. {\if\edition\pythonEd
  3141. \begin{exercise}
  3142. \normalfont\normalsize
  3143. \label{ex:Lvar}
  3144. Create five \LangVar{} programs that exercise the most interesting
  3145. parts of the \code{remove\_complex\_operands} pass. The five programs
  3146. should be placed in the subdirectory named \key{tests}, and the file
  3147. names should start with \code{var\_test\_} followed by a unique
  3148. integer and end with the file extension \key{.py}.
  3149. %% The \key{run-tests.rkt} script in the support code checks whether the
  3150. %% output programs produce the same result as the input programs. The
  3151. %% script uses the \key{interp-tests} function
  3152. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3153. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3154. %% parameter of \key{interp-tests} is a list that should have one entry
  3155. %% for each pass in your compiler. For now, define \code{passes} to
  3156. %% contain just one entry for \code{uniquify} as shown below.
  3157. %% \begin{lstlisting}
  3158. %% (define passes
  3159. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3160. %% \end{lstlisting}
  3161. Run the \key{run-tests.py} script in the support code to check
  3162. whether the output programs produce the same result as the input
  3163. programs.
  3164. \end{exercise}
  3165. \fi}
  3166. {\if\edition\racketEd
  3167. \section{Explicate Control}
  3168. \label{sec:explicate-control-Lvar}
  3169. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3170. programs that make the order of execution explicit in their
  3171. syntax. For now this amounts to flattening \key{let} constructs into a
  3172. sequence of assignment statements. For example, consider the following
  3173. \LangVar{} program:\\
  3174. % var_test_11.rkt
  3175. \begin{minipage}{0.96\textwidth}
  3176. \begin{lstlisting}
  3177. (let ([y (let ([x 20])
  3178. (+ x (let ([x 22]) x)))])
  3179. y)
  3180. \end{lstlisting}
  3181. \end{minipage}\\
  3182. %
  3183. The output of the previous pass is shown next, on the left, and the
  3184. output of \code{explicate\_control} is on the right. Recall that the
  3185. right-hand side of a \key{let} executes before its body, so that the order
  3186. of evaluation for this program is to assign \code{20} to \code{x.1},
  3187. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3188. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3189. this ordering explicit.
  3190. \begin{transformation}
  3191. \begin{lstlisting}
  3192. (let ([y (let ([x.1 20])
  3193. (let ([x.2 22])
  3194. (+ x.1 x.2)))])
  3195. y)
  3196. \end{lstlisting}
  3197. \compilesto
  3198. \begin{lstlisting}[language=C]
  3199. start:
  3200. x.1 = 20;
  3201. x.2 = 22;
  3202. y = (+ x.1 x.2);
  3203. return y;
  3204. \end{lstlisting}
  3205. \end{transformation}
  3206. \begin{figure}[tbp]
  3207. \begin{tcolorbox}[colback=white]
  3208. \begin{lstlisting}
  3209. (define (explicate_tail e)
  3210. (match e
  3211. [(Var x) ___]
  3212. [(Int n) (Return (Int n))]
  3213. [(Let x rhs body) ___]
  3214. [(Prim op es) ___]
  3215. [else (error "explicate_tail unhandled case" e)]))
  3216. (define (explicate_assign e x cont)
  3217. (match e
  3218. [(Var x) ___]
  3219. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3220. [(Let y rhs body) ___]
  3221. [(Prim op es) ___]
  3222. [else (error "explicate_assign unhandled case" e)]))
  3223. (define (explicate_control p)
  3224. (match p
  3225. [(Program info body) ___]))
  3226. \end{lstlisting}
  3227. \end{tcolorbox}
  3228. \caption{Skeleton for the \code{explicate\_control} pass.}
  3229. \label{fig:explicate-control-Lvar}
  3230. \end{figure}
  3231. The organization of this pass depends on the notion of tail position
  3232. to which we have alluded. Here is the definition.
  3233. \begin{definition}\normalfont
  3234. The following rules define when an expression is in \emph{tail
  3235. position}\index{subject}{tail position} for the language \LangVar{}.
  3236. \begin{enumerate}
  3237. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3238. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3239. \end{enumerate}
  3240. \end{definition}
  3241. We recommend implementing \code{explicate\_control} using two
  3242. recursive functions, \code{explicate\_tail} and
  3243. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3244. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3245. function should be applied to expressions in tail position, whereas the
  3246. \code{explicate\_assign} should be applied to expressions that occur on
  3247. the right-hand side of a \key{let}.
  3248. %
  3249. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3250. input and produces a \Tail{} in \LangCVar{} (see
  3251. figure~\ref{fig:c0-syntax}).
  3252. %
  3253. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3254. the variable to which it is to be assigned to, and a \Tail{} in
  3255. \LangCVar{} for the code that comes after the assignment. The
  3256. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3257. The \code{explicate\_assign} function is in accumulator-passing style:
  3258. the \code{cont} parameter is used for accumulating the output. This
  3259. accumulator-passing style plays an important role in the way that we
  3260. generate high-quality code for conditional expressions in
  3261. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3262. continuation because it contains the generated code that should come
  3263. after the current assignment. This code organization is also related
  3264. to continuation-passing style, except that \code{cont} is not what
  3265. happens next during compilation but is what happens next in the
  3266. generated code.
  3267. \begin{exercise}\normalfont\normalsize
  3268. %
  3269. Implement the \code{explicate\_control} function in
  3270. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3271. exercise the code in \code{explicate\_control}.
  3272. %
  3273. In the \code{run-tests.rkt} script, add the following entry to the
  3274. list of \code{passes} and then run the script to test your compiler.
  3275. \begin{lstlisting}
  3276. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3277. \end{lstlisting}
  3278. \end{exercise}
  3279. \fi}
  3280. \section{Select Instructions}
  3281. \label{sec:select-Lvar}
  3282. \index{subject}{instruction selection}
  3283. In the \code{select\_instructions} pass we begin the work of
  3284. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3285. language of this pass is a variant of x86 that still uses variables,
  3286. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3287. nonterminal of the \LangXInt{} abstract syntax
  3288. (figure~\ref{fig:x86-int-ast}).
  3289. \racket{We recommend implementing the
  3290. \code{select\_instructions} with three auxiliary functions, one for
  3291. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3292. $\Tail$.}
  3293. \python{We recommend implementing an auxiliary function
  3294. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3295. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3296. same and integer constants change to immediates; that is, $\INT{n}$
  3297. changes to $\IMM{n}$.}
  3298. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3299. arithmetic operations. For example, consider the following addition
  3300. operation, on the left side. There is an \key{addq} instruction in
  3301. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3302. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3303. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3304. $\Atm_2$, respectively.
  3305. \begin{transformation}
  3306. {\if\edition\racketEd
  3307. \begin{lstlisting}
  3308. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3309. \end{lstlisting}
  3310. \fi}
  3311. {\if\edition\pythonEd
  3312. \begin{lstlisting}
  3313. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3314. \end{lstlisting}
  3315. \fi}
  3316. \compilesto
  3317. \begin{lstlisting}
  3318. movq |$\Arg_1$|, |$\itm{var}$|
  3319. addq |$\Arg_2$|, |$\itm{var}$|
  3320. \end{lstlisting}
  3321. \end{transformation}
  3322. There are also cases that require special care to avoid generating
  3323. needlessly complicated code. For example, if one of the arguments of
  3324. the addition is the same variable as the left-hand side of the
  3325. assignment, as shown next, then there is no need for the extra move
  3326. instruction. The assignment statement can be translated into a single
  3327. \key{addq} instruction, as follows.
  3328. \begin{transformation}
  3329. {\if\edition\racketEd
  3330. \begin{lstlisting}
  3331. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3332. \end{lstlisting}
  3333. \fi}
  3334. {\if\edition\pythonEd
  3335. \begin{lstlisting}
  3336. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3337. \end{lstlisting}
  3338. \fi}
  3339. \compilesto
  3340. \begin{lstlisting}
  3341. addq |$\Arg_1$|, |$\itm{var}$|
  3342. \end{lstlisting}
  3343. \end{transformation}
  3344. The \READOP{} operation does not have a direct counterpart in x86
  3345. assembly, so we provide this functionality with the function
  3346. \code{read\_int} in the file \code{runtime.c}, written in
  3347. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3348. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3349. system}, or simply the \emph{runtime} for short. When compiling your
  3350. generated x86 assembly code, you need to compile \code{runtime.c} to
  3351. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3352. \code{-c}) and link it into the executable. For our purposes of code
  3353. generation, all you need to do is translate an assignment of
  3354. \READOP{} into a call to the \code{read\_int} function followed by a
  3355. move from \code{rax} to the left-hand side variable. (Recall that the
  3356. return value of a function goes into \code{rax}.)
  3357. \begin{transformation}
  3358. {\if\edition\racketEd
  3359. \begin{lstlisting}
  3360. |$\itm{var}$| = (read);
  3361. \end{lstlisting}
  3362. \fi}
  3363. {\if\edition\pythonEd
  3364. \begin{lstlisting}
  3365. |$\itm{var}$| = input_int();
  3366. \end{lstlisting}
  3367. \fi}
  3368. \compilesto
  3369. \begin{lstlisting}
  3370. callq read_int
  3371. movq %rax, |$\itm{var}$|
  3372. \end{lstlisting}
  3373. \end{transformation}
  3374. {\if\edition\pythonEd
  3375. %
  3376. Similarly, we translate the \code{print} operation, shown below, into
  3377. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3378. In x86, the first six arguments to functions are passed in registers,
  3379. with the first argument passed in register \code{rdi}. So we move the
  3380. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3381. \code{callq} instruction.
  3382. \begin{transformation}
  3383. \begin{lstlisting}
  3384. print(|$\Atm$|)
  3385. \end{lstlisting}
  3386. \compilesto
  3387. \begin{lstlisting}
  3388. movq |$\Arg$|, %rdi
  3389. callq print_int
  3390. \end{lstlisting}
  3391. \end{transformation}
  3392. %
  3393. \fi}
  3394. {\if\edition\racketEd
  3395. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3396. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3397. assignment to the \key{rax} register followed by a jump to the
  3398. conclusion of the program (so the conclusion needs to be labeled).
  3399. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3400. recursively and then append the resulting instructions.
  3401. \fi}
  3402. {\if\edition\pythonEd
  3403. We recommend that you use the function \code{utils.label\_name()} to
  3404. transform a string into an label argument suitably suitable for, e.g.,
  3405. the target of the \code{callq} instruction. This practice makes your
  3406. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3407. all labels.
  3408. \fi}
  3409. \begin{exercise}
  3410. \normalfont\normalsize
  3411. {\if\edition\racketEd
  3412. Implement the \code{select\_instructions} pass in
  3413. \code{compiler.rkt}. Create three new example programs that are
  3414. designed to exercise all the interesting cases in this pass.
  3415. %
  3416. In the \code{run-tests.rkt} script, add the following entry to the
  3417. list of \code{passes} and then run the script to test your compiler.
  3418. \begin{lstlisting}
  3419. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3420. \end{lstlisting}
  3421. \fi}
  3422. {\if\edition\pythonEd
  3423. Implement the \key{select\_instructions} pass in
  3424. \code{compiler.py}. Create three new example programs that are
  3425. designed to exercise all the interesting cases in this pass.
  3426. Run the \code{run-tests.py} script to to check
  3427. whether the output programs produce the same result as the input
  3428. programs.
  3429. \fi}
  3430. \end{exercise}
  3431. \section{Assign Homes}
  3432. \label{sec:assign-Lvar}
  3433. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3434. \LangXVar{} programs that no longer use program variables. Thus, the
  3435. \code{assign\_homes} pass is responsible for placing all the program
  3436. variables in registers or on the stack. For runtime efficiency, it is
  3437. better to place variables in registers, but because there are only
  3438. sixteen registers, some programs must necessarily resort to placing
  3439. some variables on the stack. In this chapter we focus on the mechanics
  3440. of placing variables on the stack. We study an algorithm for placing
  3441. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3442. Consider again the following \LangVar{} program from
  3443. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3444. % var_test_20.rkt
  3445. \begin{minipage}{0.96\textwidth}
  3446. {\if\edition\racketEd
  3447. \begin{lstlisting}
  3448. (let ([a 42])
  3449. (let ([b a])
  3450. b))
  3451. \end{lstlisting}
  3452. \fi}
  3453. {\if\edition\pythonEd
  3454. \begin{lstlisting}
  3455. a = 42
  3456. b = a
  3457. print(b)
  3458. \end{lstlisting}
  3459. \fi}
  3460. \end{minipage}\\
  3461. %
  3462. The output of \code{select\_instructions} is shown next, on the left,
  3463. and the output of \code{assign\_homes} is on the right. In this
  3464. example, we assign variable \code{a} to stack location
  3465. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3466. \begin{transformation}
  3467. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3468. movq $42, a
  3469. movq a, b
  3470. movq b, %rax
  3471. \end{lstlisting}
  3472. \compilesto
  3473. %stack-space: 16
  3474. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3475. movq $42, -8(%rbp)
  3476. movq -8(%rbp), -16(%rbp)
  3477. movq -16(%rbp), %rax
  3478. \end{lstlisting}
  3479. \end{transformation}
  3480. \racket{
  3481. The \code{assign\_homes} pass should replace all variables
  3482. with stack locations.
  3483. The list of variables can be obtained from
  3484. the \code{locals-types} entry in the $\itm{info}$ of the
  3485. \code{X86Program} node. The \code{locals-types} entry is an alist
  3486. mapping all the variables in the program to their types
  3487. (for now, just \code{Integer}).
  3488. As an aside, the \code{locals-types} entry is
  3489. computed by \code{type-check-Cvar} in the support code, which
  3490. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3491. which you should propagate to the \code{X86Program} node.}
  3492. %
  3493. \python{The \code{assign\_homes} pass should replace all uses of
  3494. variables with stack locations.}
  3495. %
  3496. In the process of assigning variables to stack locations, it is
  3497. convenient for you to compute and store the size of the frame (in
  3498. bytes) in
  3499. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3500. %
  3501. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3502. %
  3503. which is needed later to generate the conclusion of the \code{main}
  3504. procedure. The x86-64 standard requires the frame size to be a
  3505. multiple of 16 bytes.\index{subject}{frame}
  3506. % TODO: store the number of variables instead? -Jeremy
  3507. \begin{exercise}\normalfont\normalsize
  3508. Implement the \code{assign\_homes} pass in
  3509. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3510. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3511. grammar. We recommend that the auxiliary functions take an extra
  3512. parameter that maps variable names to homes (stack locations for now).
  3513. %
  3514. {\if\edition\racketEd
  3515. In the \code{run-tests.rkt} script, add the following entry to the
  3516. list of \code{passes} and then run the script to test your compiler.
  3517. \begin{lstlisting}
  3518. (list "assign homes" assign-homes interp_x86-0)
  3519. \end{lstlisting}
  3520. \fi}
  3521. {\if\edition\pythonEd
  3522. Run the \code{run-tests.py} script to to check
  3523. whether the output programs produce the same result as the input
  3524. programs.
  3525. \fi}
  3526. \end{exercise}
  3527. \section{Patch Instructions}
  3528. \label{sec:patch-s0}
  3529. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3530. \LangXInt{} by making sure that each instruction adheres to the
  3531. restriction that at most one argument of an instruction may be a
  3532. memory reference.
  3533. We return to the following example.\\
  3534. \begin{minipage}{0.5\textwidth}
  3535. % var_test_20.rkt
  3536. {\if\edition\racketEd
  3537. \begin{lstlisting}
  3538. (let ([a 42])
  3539. (let ([b a])
  3540. b))
  3541. \end{lstlisting}
  3542. \fi}
  3543. {\if\edition\pythonEd
  3544. \begin{lstlisting}
  3545. a = 42
  3546. b = a
  3547. print(b)
  3548. \end{lstlisting}
  3549. \fi}
  3550. \end{minipage}\\
  3551. The \code{assign\_homes} pass produces the following translation. \\
  3552. \begin{minipage}{0.5\textwidth}
  3553. {\if\edition\racketEd
  3554. \begin{lstlisting}
  3555. movq $42, -8(%rbp)
  3556. movq -8(%rbp), -16(%rbp)
  3557. movq -16(%rbp), %rax
  3558. \end{lstlisting}
  3559. \fi}
  3560. {\if\edition\pythonEd
  3561. \begin{lstlisting}
  3562. movq 42, -8(%rbp)
  3563. movq -8(%rbp), -16(%rbp)
  3564. movq -16(%rbp), %rdi
  3565. callq print_int
  3566. \end{lstlisting}
  3567. \fi}
  3568. \end{minipage}\\
  3569. The second \key{movq} instruction is problematic because both
  3570. arguments are stack locations. We suggest fixing this problem by
  3571. moving from the source location to the register \key{rax} and then
  3572. from \key{rax} to the destination location, as follows.
  3573. \begin{lstlisting}
  3574. movq -8(%rbp), %rax
  3575. movq %rax, -16(%rbp)
  3576. \end{lstlisting}
  3577. \begin{exercise}
  3578. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3579. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3580. Create three new example programs that are
  3581. designed to exercise all the interesting cases in this pass.
  3582. %
  3583. {\if\edition\racketEd
  3584. In the \code{run-tests.rkt} script, add the following entry to the
  3585. list of \code{passes} and then run the script to test your compiler.
  3586. \begin{lstlisting}
  3587. (list "patch instructions" patch_instructions interp_x86-0)
  3588. \end{lstlisting}
  3589. \fi}
  3590. {\if\edition\pythonEd
  3591. Run the \code{run-tests.py} script to to check
  3592. whether the output programs produce the same result as the input
  3593. programs.
  3594. \fi}
  3595. \end{exercise}
  3596. \section{Generate Prelude and Conclusion}
  3597. \label{sec:print-x86}
  3598. \index{subject}{prelude}\index{subject}{conclusion}
  3599. The last step of the compiler from \LangVar{} to x86 is to generate
  3600. the \code{main} function with a prelude and conclusion wrapped around
  3601. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3602. discussed in section~\ref{sec:x86}.
  3603. When running on Mac OS X, your compiler should prefix an underscore to
  3604. all labels, e.g., changing \key{main} to \key{\_main}.
  3605. %
  3606. \racket{The Racket call \code{(system-type 'os)} is useful for
  3607. determining which operating system the compiler is running on. It
  3608. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3609. %
  3610. \python{The Python \code{platform} library includes a \code{system()}
  3611. function that returns \code{'Linux'}, \code{'Windows'}, or
  3612. \code{'Darwin'} (for Mac).}
  3613. \begin{exercise}\normalfont\normalsize
  3614. %
  3615. Implement the \key{prelude\_and\_conclusion} pass in
  3616. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3617. %
  3618. {\if\edition\racketEd
  3619. In the \code{run-tests.rkt} script, add the following entry to the
  3620. list of \code{passes} and then run the script to test your compiler.
  3621. \begin{lstlisting}
  3622. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3623. \end{lstlisting}
  3624. %
  3625. Uncomment the call to the \key{compiler-tests} function
  3626. (appendix~\ref{appendix:utilities}), which tests your complete
  3627. compiler by executing the generated x86 code. It translates the x86
  3628. AST that you produce into a string by invoking the \code{print-x86}
  3629. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3630. the provided \key{runtime.c} file to \key{runtime.o} using
  3631. \key{gcc}. Run the script to test your compiler.
  3632. %
  3633. \fi}
  3634. {\if\edition\pythonEd
  3635. %
  3636. Run the \code{run-tests.py} script to to check whether the output
  3637. programs produce the same result as the input programs. That script
  3638. translates the x86 AST that you produce into a string by invoking the
  3639. \code{repr} method that is implemented by the x86 AST classes in
  3640. \code{x86\_ast.py}.
  3641. %
  3642. \fi}
  3643. \end{exercise}
  3644. \section{Challenge: Partial Evaluator for \LangVar{}}
  3645. \label{sec:pe-Lvar}
  3646. \index{subject}{partial evaluation}
  3647. This section describes two optional challenge exercises that involve
  3648. adapting and improving the partial evaluator for \LangInt{} that was
  3649. introduced in section~\ref{sec:partial-evaluation}.
  3650. \begin{exercise}\label{ex:pe-Lvar}
  3651. \normalfont\normalsize
  3652. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3653. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3654. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3655. %
  3656. \racket{\key{let} binding}\python{assignment}
  3657. %
  3658. to the \LangInt{} language, so you will need to add cases for them in
  3659. the \code{pe\_exp}
  3660. %
  3661. \racket{function.}
  3662. %
  3663. \python{and \code{pe\_stmt} functions.}
  3664. %
  3665. Once complete, add the partial evaluation pass to the front of your
  3666. compiler, and make sure that your compiler still passes all the
  3667. tests.
  3668. \end{exercise}
  3669. \begin{exercise}
  3670. \normalfont\normalsize
  3671. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3672. \code{pe\_add} auxiliary functions with functions that know more about
  3673. arithmetic. For example, your partial evaluator should translate
  3674. {\if\edition\racketEd
  3675. \[
  3676. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3677. \code{(+ 2 (read))}
  3678. \]
  3679. \fi}
  3680. {\if\edition\pythonEd
  3681. \[
  3682. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3683. \code{2 + input\_int()}
  3684. \]
  3685. \fi}
  3686. %
  3687. To accomplish this, the \code{pe\_exp} function should produce output
  3688. in the form of the $\itm{residual}$ nonterminal of the following
  3689. grammar. The idea is that when processing an addition expression, we
  3690. can always produce one of the following: (1) an integer constant, (2)
  3691. an addition expression with an integer constant on the left-hand side
  3692. but not the right-hand side, or (3) an addition expression in which
  3693. neither subexpression is a constant.
  3694. %
  3695. {\if\edition\racketEd
  3696. \[
  3697. \begin{array}{lcl}
  3698. \itm{inert} &::=& \Var
  3699. \MID \LP\key{read}\RP
  3700. \MID \LP\key{-} ~\Var\RP
  3701. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3702. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3703. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3704. \itm{residual} &::=& \Int
  3705. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3706. \MID \itm{inert}
  3707. \end{array}
  3708. \]
  3709. \fi}
  3710. {\if\edition\pythonEd
  3711. \[
  3712. \begin{array}{lcl}
  3713. \itm{inert} &::=& \Var
  3714. \MID \key{input\_int}\LP\RP
  3715. \MID \key{-} \Var
  3716. \MID \key{-} \key{input\_int}\LP\RP
  3717. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3718. \itm{residual} &::=& \Int
  3719. \MID \Int ~ \key{+} ~ \itm{inert}
  3720. \MID \itm{inert}
  3721. \end{array}
  3722. \]
  3723. \fi}
  3724. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3725. inputs are $\itm{residual}$ expressions and they should return
  3726. $\itm{residual}$ expressions. Once the improvements are complete,
  3727. make sure that your compiler still passes all the tests. After
  3728. all, fast code is useless if it produces incorrect results!
  3729. \end{exercise}
  3730. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3731. \if\edition\pythonEd
  3732. \chapter{Parsing}
  3733. \label{ch:parsing}
  3734. \setcounter{footnote}{0}
  3735. The main ideas covered in this chapter are
  3736. \begin{description}
  3737. \item[lexical analysis] the identification of tokens (i.e., words)
  3738. within sequences of characters.
  3739. \item[parsing] the identification of sentence structure within
  3740. sequences of tokens.
  3741. \end{description}
  3742. In general, the syntax of the source code for a language is called its
  3743. \emph{concrete syntax}. The concrete syntax of $P_0$ specifies which
  3744. programs, expressed as sequences of characters, are $P_0$ programs.
  3745. The process of transforming a program written in the concrete syntax
  3746. (a sequence of characters) into an abstract syntax tree is
  3747. traditionally subdivided into two parts: \emph{lexical analysis}
  3748. (often called scanning) and \emph{parsing}. The lexical analysis phase
  3749. translates the sequence of characters into a sequence of
  3750. \emph{tokens}, where each token consists of several characters. The
  3751. parsing phase organizes the tokens into a \emph{parse tree} as
  3752. directed by the grammar of the language and then translates the parse
  3753. tree into an abstract syntax tree.
  3754. It is feasible to implement a compiler without doing lexical analysis,
  3755. instead just parsing. However, scannerless parsers tend to be slower,
  3756. which mattered back when computers were slow, and sometimes still
  3757. matters for very large files.
  3758. %(If you need a refresher on how a context-free grammar specifies a
  3759. %language, read Section 3.1 of~\cite{Appel:2003fk}.)
  3760. The Python Lex-Yacc tool, abbreviated PLY~\cite{Beazley:fk}, is an
  3761. easy-to-use Python imitation of the original \texttt{lex} and
  3762. \texttt{yacc} C programs. Lex was written by Eric Schmidt and Mike
  3763. Lesk~\cite{Lesk:1975uq} at Bell Labs, and is the standard lexical
  3764. analyzer generator on many Unix systems.
  3765. %
  3766. %The input to \texttt{lex} is
  3767. %a specification consisting of a list of the kinds of tokens and a
  3768. %regular expression for each. The output of \texttt{lex} is a program
  3769. %that analyzes a text file, turning it into a sequence of tokens.
  3770. %
  3771. YACC stands from Yet Another Compiler Compiler and was originally
  3772. written by Stephen C. Johnson at AT\&T~\cite{Johnson:1979qy}.
  3773. %
  3774. %The input to
  3775. %\texttt{yacc} is a context-free grammar together with an action (a
  3776. %chunk of code) for each production. The output of \texttt{yacc} is a
  3777. %program that parses a text file and fires the appropriate actions when
  3778. %a production is applied.
  3779. %
  3780. The PLY tool combines the functionality of both \texttt{lex} and
  3781. \texttt{yacc}. In this chapter we will use the PLY tool to generate
  3782. a lexer and parser for the $P_0$ subset of Python.
  3783. \section{Lexical analysis}
  3784. \label{sec:lex}
  3785. The lexical analyzer turns a sequence of characters (a string) into a
  3786. sequence of tokens. For example, the string
  3787. \begin{lstlisting}
  3788. 'print 1 + 3'
  3789. \end{lstlisting}
  3790. \noindent will be converted into the list of tokens
  3791. \begin{lstlisting}
  3792. ['print','1','+','3']
  3793. \end{lstlisting}
  3794. Actually, to be more accurate, each token will contain the token
  3795. \texttt{type} and the token's \texttt{value}, which is the string from
  3796. the input that matched the token.
  3797. With the PLY tool, the types of the tokens must be specified by
  3798. initializing the \texttt{tokens} variable. For example,
  3799. \begin{lstlisting}
  3800. tokens = ('PRINT','INT','PLUS')
  3801. \end{lstlisting}
  3802. Next we must specify which sequences of characters will map to each
  3803. type of token. We do this using regular expression. The term
  3804. ``regular'' comes from ``regular languages'', which are the
  3805. (particularly simple) set of languages that can be recognized by a
  3806. finite automata. A \emph{regular expression} is a pattern formed of
  3807. the following core elements:
  3808. \begin{enumerate}
  3809. \item a character, e.g. \texttt{a}. The only string that matches this
  3810. regular expression is \texttt{a}.
  3811. \item two regular expressions, one followed by the other
  3812. (concatenation), e.g. \texttt{bc}. The only string that matches
  3813. this regular expression is \texttt{bc}.
  3814. \item one regular expression or another (alternation), e.g.
  3815. \texttt{a|bc}. Both the string \texttt{'a'} and \texttt{'bc'} would
  3816. be matched by this pattern.
  3817. \item a regular expression repeated zero or more times (Kleene
  3818. closure), e.g. \texttt{(a|bc)*}. The string \texttt{'bcabcbc'}
  3819. would match this pattern, but not \texttt{'bccba'}.
  3820. \item the empty sequence (epsilon)
  3821. \end{enumerate}
  3822. The Python support for regular expressions goes beyond the core
  3823. elements and include many other convenient short-hands, for example
  3824. \texttt{+} is for repetition one or more times. If you want to refer
  3825. to the actual character \texttt{+}, use a backslash to escape it.
  3826. Section \href{http://docs.python.org/lib/re-syntax.html}{4.2.1 Regular
  3827. Expression Syntax} of the Python Library Reference gives an in-depth
  3828. description of the extended regular expressions supported by Python.
  3829. Normal Python strings give a special interpretation to backslashes,
  3830. which can interfere with their interpretation as regular expressions.
  3831. To avoid this problem, use Python's raw strings instead of normal
  3832. strings by prefixing the string with an \texttt{r}. For example, the
  3833. following specifies the regular expression for the \texttt{'PLUS'}
  3834. token.
  3835. \begin{lstlisting}
  3836. t_PLUS = r'\+'
  3837. \end{lstlisting}
  3838. \noindent The \lstinline{t_} is a naming convention that PLY uses to know when
  3839. you are defining the regular expression for a token.
  3840. Sometimes you need to do some extra processing for certain kinds of
  3841. tokens. For example, for the \texttt{INT} token it is nice to convert
  3842. the matched input string into a Python integer. With PLY you can do
  3843. this by defining a function for the token. The function must have the
  3844. regular expression as its documentation string and the body of the
  3845. function should overwrite in the \texttt{value} field of the token. Here's
  3846. how it would look for the \texttt{INT} token. The \lstinline{\d} regular
  3847. expression stands for any decimal numeral (0-9).
  3848. \begin{lstlisting}
  3849. def t_INT(t):
  3850. r'\d+'
  3851. try:
  3852. t.value = int(t.value)
  3853. except ValueError:
  3854. print "integer value too large", t.value
  3855. t.value = 0
  3856. return t
  3857. \end{lstlisting}
  3858. In addition to defining regular expressions for each of the tokens,
  3859. you'll often want to perform special handling of newlines and
  3860. whitespace. The following is the code for counting newlines and for
  3861. telling the lexer to ignore whitespace. (Python has complex rules
  3862. for dealing with whitespace that we'll ignore for now.)
  3863. % (We'll need to reconsider this later to handle Python indentation rules.)
  3864. \begin{lstlisting}
  3865. def t_newline(t):
  3866. r'\n+'
  3867. t.lexer.lineno += len(t.value)
  3868. t_ignore = ' \t'
  3869. \end{lstlisting}
  3870. If a portion of the input string is not matched by any of the tokens,
  3871. then the lexer calls the error function that you provide. The following
  3872. is an example error function.
  3873. \begin{lstlisting}
  3874. def t_error(t):
  3875. print "Illegal character '%s'" % t.value[0]
  3876. t.lexer.skip(1)
  3877. \end{lstlisting}
  3878. \noindent Last but not least, you'll need to instruct PLY to generate
  3879. the lexer from your specification with the following code.
  3880. \begin{lstlisting}
  3881. import ply.lex as lex
  3882. lex.lex()
  3883. \end{lstlisting}
  3884. \noindent Figure~\ref{fig:lex} shows the complete code for an example
  3885. lexer.
  3886. \begin{figure}[htbp]
  3887. \centering
  3888. \begin{tabular}{|cl}
  3889. &
  3890. \begin{lstlisting}
  3891. tokens = ('PRINT','INT','PLUS')
  3892. t_PRINT = r'print'
  3893. t_PLUS = r'\+'
  3894. def t_INT(t):
  3895. r'\d+'
  3896. try:
  3897. t.value = int(t.value)
  3898. except ValueError:
  3899. print "integer value too large", t.value
  3900. t.value = 0
  3901. return t
  3902. t_ignore = ' \t'
  3903. def t_newline(t):
  3904. r'\n+'
  3905. t.lexer.lineno += t.value.count("\n")
  3906. def t_error(t):
  3907. print "Illegal character '%s'" % t.value[0]
  3908. t.lexer.skip(1)
  3909. import ply.lex as lex
  3910. lex.lex()
  3911. \end{lstlisting}
  3912. \end{tabular}
  3913. \caption{Example lexer implemented using the PLY lexer generator.}
  3914. \label{fig:lex}
  3915. \end{figure}
  3916. \begin{exercise}
  3917. Write a PLY lexer specification for $P_0$ and test it on a few input
  3918. programs, looking at the output list of tokens to see if they make
  3919. sense.
  3920. \end{exercise}
  3921. %\section{Parsing}
  3922. %\label{sec:parsing}
  3923. %Explain LR (shift-reduce parsing).
  3924. %Show an example PLY parser.
  3925. %Explain actions and AST construction.
  3926. %Start symbols.
  3927. %Specifying precedence.
  3928. %Looking at the parser.out file.
  3929. %Debugging shift/reduce and reduce/reduce errors.
  3930. %We start with some background on context-free grammars
  3931. %(Section~\ref{sec:cfg}), then discuss how to use PLY to do parsing
  3932. %(Section~\ref{sec:ply-parsing}).
  3933. %, so we
  3934. %discuss the algorithm it uses in Sections \ref{sec:lalr} and
  3935. %\ref{sec:table}. This section concludes with a discussion of using
  3936. %precedence levels to resolve parsing conflicts.
  3937. \section{Background on CFGs and the $P_0$ grammar. }
  3938. \label{sec:cfg}
  3939. A \emph{context-free grammar} (CFG) consists of a set of \emph{rules} (also
  3940. called productions) that describes how to categorize strings of
  3941. various forms. There are two kinds of categories, \emph{terminals} and
  3942. \emph{non-terminals}. The terminals correspond to the tokens from the
  3943. lexical analysis. Non-terminals are used to categorize different parts
  3944. of a language, such as the distinction between statements and
  3945. expressions in Python and C. The term \emph{symbol} refers to both
  3946. terminals and non-terminals. A grammar rule has two parts, the
  3947. left-hand side is a non-terminal and the right-hand side is a sequence
  3948. of zero or more symbols. The notation \lstinline{::=} is used to
  3949. separate the left-hand side from the right-hand side. The following is
  3950. a rule that could be used to specify the syntax for an addition
  3951. operator.
  3952. %
  3953. \begin{lstlisting}
  3954. $(1)$ expression ::= expression PLUS expression
  3955. \end{lstlisting}
  3956. %
  3957. This rule says that if a string can be divided into three parts, where
  3958. the first part can be categorized as an expression, the second part is
  3959. the \texttt{PLUS} non-terminal (token), and the third part can be
  3960. categorized as an expression, then the entire string can be
  3961. categorized as an expression. The next example rule has the
  3962. non-terminal \texttt{INT} on the right-hand side and says that a
  3963. string that is categorized as an integer (by the lexer) can also be
  3964. categorized as an expression. As is apparent here, a string can be
  3965. categorized by more than one non-terminal.
  3966. \begin{lstlisting}
  3967. $(2)$ expression ::= INT
  3968. \end{lstlisting}
  3969. To \emph{parse} a string is to determine how the string can be
  3970. categorized according to a given grammar. Suppose we have the string
  3971. ``\lstinline{1 + 3}''. Both the \texttt{1} and the \texttt{3} can be
  3972. categorized as expressions using rule $2$. We can then use rule 1 to
  3973. categorize the entire string as an expression. A \emph{parse tree} is
  3974. a good way to visualize the parsing process. (You will be tempted to
  3975. confuse parse trees and abstract syntax tress, but the excellent
  3976. students will carefully study the difference to avoid this confusion.)
  3977. A parse tree for ``\lstinline{1 + 3}'' is shown in
  3978. Figure~\ref{fig:parse-tree}. The best way to start drawing a parse
  3979. tree is to first list the tokenized string at the bottom of the page.
  3980. These tokens correspond to terminals and will form the leaves of the
  3981. parse tree. You can then start to categorize non-terminals, or
  3982. sequences of non-terminals, using the parsing rules. For example, we
  3983. can categorize the integer ``\texttt{1}'' as an expression using rule
  3984. $(2)$, so we create a new node above ``\texttt{1}'', label the node
  3985. with the left-hand side terminal, in this case \texttt{expression},
  3986. and draw a line down from the new node down to ``\texttt{1}''. As an
  3987. optional step, we can record which rule we used in parenthesis after
  3988. the name of the terminal. We then repeat this process until all of
  3989. the leaves have been connected into a single tree, or until no more
  3990. rules apply.
  3991. \begin{figure}[htbp]
  3992. \centering
  3993. \includegraphics[width=2.5in]{figs/simple-parse-tree}
  3994. \caption{The parse tree for ``\texttt{1 + 3}''.}
  3995. \label{fig:parse-tree}
  3996. \end{figure}
  3997. There can be more than one parse tree for the same string if the
  3998. grammar is ambiguous. For example, the string ``\texttt{1 + 2 + 3}''
  3999. can be parsed two different ways using rules 1 and 2, as shown in
  4000. Figure~\ref{fig:ambig}. In Section~\ref{sec:precedence} we'll discuss
  4001. ways to avoid ambiguity through the use of precedence levels and
  4002. associativity.
  4003. \begin{figure}[htbp]
  4004. \centering
  4005. \includegraphics[width=5in]{figs/ambig-parse-tree}
  4006. \caption{Two parse trees for ``\texttt{1 + 2 + 3}''.}
  4007. \label{fig:ambig}
  4008. \end{figure}
  4009. The process describe above for creating a parse-tree was
  4010. ``bottom-up''. We started at the leaves of the tree and then worked
  4011. back up to the root. An alternative way to build parse-trees is the
  4012. ``top-down'' \emph{derivation} approach. This approach is not a
  4013. practical way to parse a particular string but it is helpful for
  4014. thinking about all possible strings that are in the language described
  4015. by the grammar. To perform a derivation, start by drawing a single
  4016. node labeled with the starting non-terminal for the grammar. This is
  4017. often the \texttt{program} non-terminal, but in our case we simply
  4018. have \texttt{expression}. We then select at random any grammar rule
  4019. that has \texttt{expression} on the left-hand side and add new edges
  4020. and nodes to the tree according to the right-hand side of the rule.
  4021. The derivation process then repeats by selecting another non-terminal
  4022. that does not yet have children. Figure~\ref{fig:derivation} shows the
  4023. process of building a parse tree by derivation. A \emph{left-most
  4024. derivation} is one in which the left-most non-terminal is always
  4025. chosen as the next non-terminal to expand. A \texttt{right-most
  4026. derivation} is one in which the right-most non-terminal is always
  4027. chosen as the next non-terminal to expand. The derivation in
  4028. Figure~\ref{fig:derivation} is a right-most derivation.
  4029. \begin{figure}[htbp]
  4030. \centering
  4031. \includegraphics[width=5in]{figs/derivation}
  4032. \caption{Building a parse-tree by derivation.}
  4033. \label{fig:derivation}
  4034. \end{figure}
  4035. For each subset of Python in this course, we will specify which
  4036. language features are in a given subset of Python using context-free
  4037. grammars. The notation we'll use for grammars is
  4038. \href{http://en.wikipedia.org/wiki/Extended_Backus\%E2\%80\%93Naur_form}{Extended
  4039. Backus-Naur Form (EBNF)}. The grammar for $P_0$ is shown in
  4040. Figure~\ref{fig:concrete-P0}. This notation does not correspond
  4041. exactly to the notation for grammars used by PLY, but it should not be
  4042. too difficult for the reader to figure out the PLY grammar given the
  4043. EBNF grammar.
  4044. \begin{figure}[htbp]
  4045. \centering
  4046. \begin{tabular}{|cl}
  4047. &
  4048. \begin{lstlisting}
  4049. program ::= module
  4050. module ::= simple_statement+
  4051. simple_statement ::= "print" expression
  4052. | name "=" expression
  4053. | expression
  4054. expression ::= name
  4055. | decimalinteger
  4056. | "-" expression
  4057. | expression "+" expression
  4058. | "(" expression ")"
  4059. | "input" "(" ")"
  4060. \end{lstlisting}
  4061. \end{tabular}
  4062. \caption{Context-free grammar for the $P_0$ subset of Python.}
  4063. \label{fig:concrete-P0}
  4064. \end{figure}
  4065. \section{Generating parser with PLY}
  4066. \label{sec:ply-parsing}
  4067. Figure~\ref{fig:parser1} shows an example use of PLY to generate a
  4068. parser. The code specifies a grammar and it specifies actions for each
  4069. rule. For each grammar rule there is a function whose name must begin
  4070. with \lstinline{p_}. The document string of the function contains the
  4071. specification of the grammar rule. PLY uses just a colon
  4072. \lstinline{:} instead of the usual \lstinline{::=} to separate the
  4073. left and right-hand sides of a grammar production. The left-hand side
  4074. symbol for the first function (as it appears in the Python file) is
  4075. considered the start symbol. The body of these functions contains
  4076. code that carries out the action for the production.
  4077. Typically, what you want to do in the actions is build an abstract
  4078. syntax tree, as we do here. The parameter \lstinline{t} of the
  4079. function contains the results from the actions that were carried out
  4080. to parse the right-hand side of the production. You can index into
  4081. \lstinline{t} to access these results, starting with \lstinline{t[1]}
  4082. for the first symbol of the right-hand side. To specify the result of
  4083. the current action, assign the result into \lstinline{t[0]}. So, for
  4084. example, in the production \lstinline{expression : INT}, we build a
  4085. \lstinline{Const} node containing an integer that we obtain from
  4086. \lstinline{t[1]}, and we assign the \lstinline{Const} node to
  4087. \lstinline{t[0]}.
  4088. \begin{figure}[htbp]
  4089. \centering
  4090. \centering
  4091. \begin{tabular}{|cl}
  4092. &
  4093. \begin{lstlisting}
  4094. from compiler.ast import Printnl, Add, Const
  4095. def p_print_statement(t):
  4096. 'statement : PRINT expression'
  4097. t[0] = Printnl([t[2]], None)
  4098. def p_plus_expression(t):
  4099. 'expression : expression PLUS expression'
  4100. t[0] = Add((t[1], t[3]))
  4101. def p_int_expression(t):
  4102. 'expression : INT'
  4103. t[0] = Const(t[1])
  4104. def p_error(t):
  4105. print "Syntax error at '%s'" % t.value
  4106. import ply.yacc as yacc
  4107. yacc.yacc()
  4108. \end{lstlisting}
  4109. \end{tabular}
  4110. \caption{First attempt at writing a parser using PLY.}
  4111. \label{fig:parser1}
  4112. \end{figure}
  4113. The PLY parser generator takes your grammar and generates a parser
  4114. that uses the LALR(1) shift-reduce algorithm, which is the most common
  4115. parsing algorithm in use today. LALR(1) stands for Look Ahead
  4116. Left-to-right with Rightmost-derivation and 1 token of lookahead.
  4117. Unfortunately, the LALR(1) algorithm cannot handle all context-free
  4118. grammars, so sometimes you will get error messages from PLY. To understand
  4119. these errors and know how to avoid them, you have to know a little bit
  4120. about the parsing algorithm.
  4121. \section{The LALR(1) algorithm}
  4122. \label{sec:lalr}
  4123. To understand the error messages of PLY, one needs to understand the
  4124. underlying parsing algorithm.
  4125. %
  4126. The LALR(1) algorithm uses a stack and a finite automata. Each
  4127. element of the stack is a pair: a state number and a symbol. The
  4128. symbol characterizes the input that has been parsed so-far and the
  4129. state number is used to remember how to proceed once the next
  4130. symbol-worth of input has been parsed. Each state in the finite
  4131. automata represents where the parser stands in the parsing process
  4132. with respect to certain grammar rules. Figure~\ref{fig:shift-reduce}
  4133. shows an example LALR(1) parse table generated by PLY for the grammar
  4134. specified in Figure~\ref{fig:parser1}. When PLY generates a parse
  4135. table, it also outputs a textual representation of the parse table to
  4136. the file \texttt{parser.out} which is useful for debugging purposes.
  4137. Consider state 1 in Figure~\ref{fig:shift-reduce}. The parser has just
  4138. read in a \lstinline{PRINT} token, so the top of the stack is
  4139. \lstinline{(1,PRINT)}. The parser is part of the way through parsing
  4140. the input according to grammar rule 1, which is signified by showing
  4141. rule 1 with a dot after the PRINT token and before the expression
  4142. non-terminal. A rule with a dot in it is called an \emph{item}. There
  4143. are several rules that could apply next, both rule 2 and 3, so state 1
  4144. also shows those rules with a dot at the beginning of their right-hand
  4145. sides. The edges between states indicate which transitions the
  4146. automata should make depending on the next input token. So, for
  4147. example, if the next input token is INT then the parser will push INT
  4148. and the target state 4 on the stack and transition to state 4.
  4149. Suppose we are now at the end of the input. In state 4 it says we
  4150. should reduce by rule 3, so we pop from the stack the same number of
  4151. items as the number of symbols in the right-hand side of the rule, in
  4152. this case just one. We then momentarily jump to the state at the top
  4153. of the stack (state 1) and then follow the goto edge that corresponds
  4154. to the left-hand side of the rule we just reduced by, in this case
  4155. \lstinline{expression}, so we arrive at state 3. (A slightly longer
  4156. example parse is shown in Figure~\ref{fig:shift-reduce}.)
  4157. \begin{figure}[htbp]
  4158. \centering
  4159. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4160. \caption{An LALR(1) parse table and a trace of an example run.}
  4161. \label{fig:shift-reduce}
  4162. \end{figure}
  4163. In general, the shift-reduce algorithm works as follows. Look at the
  4164. next input token.
  4165. \begin{itemize}
  4166. \item If there there is a shift edge for the input token, push the
  4167. edge's target state and the input token on the stack and proceed to
  4168. the edge's target state.
  4169. \item If there is a reduce action for the input token, pop $k$
  4170. elements from the stack, where $k$ is the number of symbols in the
  4171. right-hand side of the rule being reduced. Jump to the state at the
  4172. top of the stack and then follow the goto edge for the non-terminal
  4173. that matches the left-hand side of the rule we're reducing by. Push
  4174. the edge's target state and the non-terminal on the stack.
  4175. \end{itemize}
  4176. Notice that in state 6 of Figure~\ref{fig:shift-reduce} there is both
  4177. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4178. algorithm does not know which action to take in this case. When a
  4179. state has both a shift and a reduce action for the same token, we say
  4180. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4181. will arise, for example, when trying to parse the input
  4182. \lstinline{print 1 + 2 + 3}. After having consumed
  4183. \lstinline{print 1 + 2} the parser will be in state 6, and it will not
  4184. know whether to reduce to form an expression of \lstinline{1 + 2},
  4185. or whether it should proceed by shifting the next \lstinline{+} from
  4186. the input.
  4187. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4188. arises when there are two reduce actions in a state for the same
  4189. token. To understand which grammars gives rise to shift/reduce and
  4190. reduce/reduce conflicts, it helps to know how the parse table is
  4191. generated from the grammar, which we discuss next.
  4192. \subsection{Parse table generation}
  4193. \label{sec:table}
  4194. The parse table is generated one state at a time. State 0 represents
  4195. the start of the parser. We add the production for the start symbol to
  4196. this state with a dot at the beginning of the right-hand side. If the
  4197. dot appears immediately before another non-terminal, we add all the
  4198. productions with that non-terminal on the left-hand side. Again, we
  4199. place a dot at the beginning of the right-hand side of each the new
  4200. productions. This process called \emph{state closure} is continued
  4201. until there are no more productions to add. We then examine each item
  4202. in the current state $I$. Suppose an item has the form $A ::=
  4203. \alpha.X\beta$, where $A$ and $X$ are symbols and $\alpha$ and $\beta$
  4204. are sequences of symbols. We create a new state, call it $J$. If $X$
  4205. is a terminal, we create a shift edge from $I$ to $J$, whereas if $X$
  4206. is a non-terminal, we create a goto edge from $I$ to $J$. We then
  4207. need to add some items to state $J$. We start by adding all items from
  4208. state $I$ that have the form $B ::= \gamma.X\kappa$ (where $B$ is any
  4209. symbol and $\gamma$ and $\kappa$ are arbitrary sequences of symbols),
  4210. but with the dot moved past the $X$. We then perform state closure on
  4211. $J$. This process repeats until there are no more states or edges to
  4212. add.
  4213. We then mark states as accepting states if they have an item that is
  4214. the start production with a dot at the end. Also, to add in the
  4215. reduce actions, we look for any state containing an item with a dot at
  4216. the end. Let $n$ be the rule number for this item. We then put a
  4217. reduce $n$ action into that state for every token $Y$. For example, in
  4218. Figure~\ref{fig:shift-reduce} state 4 has an item with a dot at the
  4219. end. We therefore put a reduce by rule 3 action into state 4 for every
  4220. token. (Figure~\ref{fig:shift-reduce} does not show a reduce rule for
  4221. INT in state 4 because this grammar does not allow
  4222. two consecutive INT tokens in the input. We will not go into how this
  4223. can be figured out, but in any event it does no harm to have a reduce
  4224. rule for INT in state 4; it just means the input will be rejected at a
  4225. later point in the parsing process.)
  4226. \begin{exercise}
  4227. On a piece of paper, walk through the parse table generation
  4228. process for the grammar in Figure~\ref{fig:parser1} and check
  4229. your results against Figure~\ref{fig:shift-reduce}.
  4230. \end{exercise}
  4231. \subsection{Resolving conflicts with precedence declarations}
  4232. \label{sec:precedence}
  4233. To solve the shift/reduce conflict in state 6, we can add the
  4234. following precedence rules, which says addition associates to the left
  4235. and takes precedence over printing. This will cause state 6 to choose
  4236. reduce over shift.
  4237. \begin{lstlisting}
  4238. precedence = (
  4239. ('nonassoc','PRINT'),
  4240. ('left','PLUS')
  4241. )
  4242. \end{lstlisting}
  4243. In general, the precedence variable should be assigned a tuple of
  4244. tuples. The first element of each inner tuple should be an
  4245. associativity (nonassoc, left, or right) and the rest of the elements
  4246. should be tokens. The tokens that appear in the same inner tuple have
  4247. the same precedence, whereas tokens that appear in later tuples have a
  4248. higher precedence. Thus, for the typical precedence for arithmetic
  4249. operations, we would specify the following:
  4250. \begin{lstlisting}
  4251. precedence = (
  4252. ('left','PLUS','MINUS'),
  4253. ('left','TIMES','DIVIDE')
  4254. )
  4255. \end{lstlisting}
  4256. Figure~\ref{fig:parser-resolved} shows the Python code for generating
  4257. a lexer and parser using PLY.
  4258. \begin{figure}[htbp]
  4259. \centering
  4260. \begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
  4261. # Lexer
  4262. tokens = ('PRINT','INT','PLUS')
  4263. t_PRINT = r'print'
  4264. t_PLUS = r'\+'
  4265. def t_INT(t):
  4266. r'\d+'
  4267. try:
  4268. t.value = int(t.value)
  4269. except ValueError:
  4270. print "integer value too large", t.value
  4271. t.value = 0
  4272. return t
  4273. t_ignore = ' \t'
  4274. def t_newline(t):
  4275. r'\n+'
  4276. t.lexer.lineno += t.value.count("\n")
  4277. def t_error(t):
  4278. print "Illegal character '%s'" % t.value[0]
  4279. t.lexer.skip(1)
  4280. import ply.lex as lex
  4281. lex.lex()
  4282. # Parser
  4283. from compiler.ast import Printnl, Add, Const
  4284. precedence = (
  4285. ('nonassoc','PRINT'),
  4286. ('left','PLUS')
  4287. )
  4288. def p_print_statement(t):
  4289. 'statement : PRINT expression'
  4290. t[0] = Printnl([t[2]], None)
  4291. def p_plus_expression(t):
  4292. 'expression : expression PLUS expression'
  4293. t[0] = Add((t[1], t[3]))
  4294. def p_int_expression(t):
  4295. 'expression : INT'
  4296. t[0] = Const(t[1])
  4297. def p_error(t):
  4298. print "Syntax error at '%s'" % t.value
  4299. import ply.yacc as yacc
  4300. yacc.yacc()
  4301. \end{lstlisting}
  4302. \caption{Example parser with precedence declarations to resolve conflicts.}
  4303. \label{fig:parser-resolved}
  4304. \end{figure}
  4305. \begin{exercise}
  4306. Write a PLY grammar specification for $P_0$ and update your compiler
  4307. so that it uses the generated lexer and parser instead of using the
  4308. parser in the \lstinline{compiler} module. In addition to handling
  4309. the grammar in Figure~\ref{fig:concrete-P0}, you also need to handle
  4310. Python-style comments, everything following a \texttt{\#} symbol up
  4311. to the newline should be ignored. Perform regression testing on
  4312. your compiler to make sure that it still passes all of the tests
  4313. that you created for $P_0$.
  4314. \end{exercise}
  4315. \fi
  4316. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4317. \chapter{Register Allocation}
  4318. \label{ch:register-allocation-Lvar}
  4319. \setcounter{footnote}{0}
  4320. \index{subject}{register allocation}
  4321. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4322. storing variables on the procedure call stack. The CPU may require tens
  4323. to hundreds of cycles to access a location on the stack, whereas
  4324. accessing a register takes only a single cycle. In this chapter we
  4325. improve the efficiency of our generated code by storing some variables
  4326. in registers. The goal of register allocation is to fit as many
  4327. variables into registers as possible. Some programs have more
  4328. variables than registers, so we cannot always map each variable to a
  4329. different register. Fortunately, it is common for different variables
  4330. to be in use during different periods of time during program
  4331. execution, and in those cases we can map multiple variables to the
  4332. same register.
  4333. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4334. example. The source program is on the left and the output of
  4335. instruction selection is on the right. The program is almost
  4336. completely in the x86 assembly language, but it still uses variables.
  4337. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4338. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4339. the other hand, is used only after this point, so \code{x} and
  4340. \code{z} could share the same register.
  4341. \begin{figure}
  4342. \begin{tcolorbox}[colback=white]
  4343. \begin{minipage}{0.45\textwidth}
  4344. Example \LangVar{} program:
  4345. % var_test_28.rkt
  4346. {\if\edition\racketEd
  4347. \begin{lstlisting}
  4348. (let ([v 1])
  4349. (let ([w 42])
  4350. (let ([x (+ v 7)])
  4351. (let ([y x])
  4352. (let ([z (+ x w)])
  4353. (+ z (- y)))))))
  4354. \end{lstlisting}
  4355. \fi}
  4356. {\if\edition\pythonEd
  4357. \begin{lstlisting}
  4358. v = 1
  4359. w = 42
  4360. x = v + 7
  4361. y = x
  4362. z = x + w
  4363. print(z + (- y))
  4364. \end{lstlisting}
  4365. \fi}
  4366. \end{minipage}
  4367. \begin{minipage}{0.45\textwidth}
  4368. After instruction selection:
  4369. {\if\edition\racketEd
  4370. \begin{lstlisting}
  4371. locals-types:
  4372. x : Integer, y : Integer,
  4373. z : Integer, t : Integer,
  4374. v : Integer, w : Integer
  4375. start:
  4376. movq $1, v
  4377. movq $42, w
  4378. movq v, x
  4379. addq $7, x
  4380. movq x, y
  4381. movq x, z
  4382. addq w, z
  4383. movq y, t
  4384. negq t
  4385. movq z, %rax
  4386. addq t, %rax
  4387. jmp conclusion
  4388. \end{lstlisting}
  4389. \fi}
  4390. {\if\edition\pythonEd
  4391. \begin{lstlisting}
  4392. movq $1, v
  4393. movq $42, w
  4394. movq v, x
  4395. addq $7, x
  4396. movq x, y
  4397. movq x, z
  4398. addq w, z
  4399. movq y, tmp_0
  4400. negq tmp_0
  4401. movq z, tmp_1
  4402. addq tmp_0, tmp_1
  4403. movq tmp_1, %rdi
  4404. callq print_int
  4405. \end{lstlisting}
  4406. \fi}
  4407. \end{minipage}
  4408. \end{tcolorbox}
  4409. \caption{A running example for register allocation.}
  4410. \label{fig:reg-eg}
  4411. \end{figure}
  4412. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4413. compute where a variable is in use. Once we have that information, we
  4414. compute which variables are in use at the same time, i.e., which ones
  4415. \emph{interfere}\index{subject}{interfere} with each other, and
  4416. represent this relation as an undirected graph whose vertices are
  4417. variables and edges indicate when two variables interfere
  4418. (section~\ref{sec:build-interference}). We then model register
  4419. allocation as a graph coloring problem
  4420. (section~\ref{sec:graph-coloring}).
  4421. If we run out of registers despite these efforts, we place the
  4422. remaining variables on the stack, similarly to how we handled
  4423. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4424. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4425. location. The decision to spill a variable is handled as part of the
  4426. graph coloring process.
  4427. We make the simplifying assumption that each variable is assigned to
  4428. one location (a register or stack address). A more sophisticated
  4429. approach is to assign a variable to one or more locations in different
  4430. regions of the program. For example, if a variable is used many times
  4431. in short sequence and then used again only after many other
  4432. instructions, it could be more efficient to assign the variable to a
  4433. register during the initial sequence and then move it to the stack for
  4434. the rest of its lifetime. We refer the interested reader to
  4435. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4436. approach.
  4437. % discuss prioritizing variables based on how much they are used.
  4438. \section{Registers and Calling Conventions}
  4439. \label{sec:calling-conventions}
  4440. \index{subject}{calling conventions}
  4441. As we perform register allocation, we must be aware of the
  4442. \emph{calling conventions} \index{subject}{calling conventions} that
  4443. govern how functions calls are performed in x86.
  4444. %
  4445. Even though \LangVar{} does not include programmer-defined functions,
  4446. our generated code includes a \code{main} function that is called by
  4447. the operating system and our generated code contains calls to the
  4448. \code{read\_int} function.
  4449. Function calls require coordination between two pieces of code that
  4450. may be written by different programmers or generated by different
  4451. compilers. Here we follow the System V calling conventions that are
  4452. used by the GNU C compiler on Linux and
  4453. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4454. %
  4455. The calling conventions include rules about how functions share the
  4456. use of registers. In particular, the caller is responsible for freeing
  4457. some registers prior to the function call for use by the callee.
  4458. These are called the \emph{caller-saved registers}
  4459. \index{subject}{caller-saved registers}
  4460. and they are
  4461. \begin{lstlisting}
  4462. rax rcx rdx rsi rdi r8 r9 r10 r11
  4463. \end{lstlisting}
  4464. On the other hand, the callee is responsible for preserving the values
  4465. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4466. which are
  4467. \begin{lstlisting}
  4468. rsp rbp rbx r12 r13 r14 r15
  4469. \end{lstlisting}
  4470. We can think about this caller/callee convention from two points of
  4471. view, the caller view and the callee view, as follows:
  4472. \begin{itemize}
  4473. \item The caller should assume that all the caller-saved registers get
  4474. overwritten with arbitrary values by the callee. On the other hand,
  4475. the caller can safely assume that all the callee-saved registers
  4476. retain their original values.
  4477. \item The callee can freely use any of the caller-saved registers.
  4478. However, if the callee wants to use a callee-saved register, the
  4479. callee must arrange to put the original value back in the register
  4480. prior to returning to the caller. This can be accomplished by saving
  4481. the value to the stack in the prelude of the function and restoring
  4482. the value in the conclusion of the function.
  4483. \end{itemize}
  4484. In x86, registers are also used for passing arguments to a function
  4485. and for the return value. In particular, the first six arguments of a
  4486. function are passed in the following six registers, in this order.
  4487. \index{subject}{argument-passing registers}
  4488. \index{subject}{parameter-passing registers}
  4489. \begin{lstlisting}
  4490. rdi rsi rdx rcx r8 r9
  4491. \end{lstlisting}
  4492. If there are more than six arguments, the convention is to use
  4493. space on the frame of the caller for the rest of the
  4494. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  4495. need more than six arguments.
  4496. %
  4497. \racket{For now, the only function we care about is \code{read\_int},
  4498. which takes zero arguments.}
  4499. %
  4500. \python{For now, the only functions we care about are \code{read\_int}
  4501. and \code{print\_int}, which take zero and one argument, respectively.}
  4502. %
  4503. The register \code{rax} is used for the return value of a function.
  4504. The next question is how these calling conventions impact register
  4505. allocation. Consider the \LangVar{} program presented in
  4506. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4507. example from the caller point of view and then from the callee point
  4508. of view. We refer to a variable that is in use during a function call
  4509. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4510. The program makes two calls to \READOP{}. The variable \code{x} is
  4511. call-live because it is in use during the second call to \READOP{}; we
  4512. must ensure that the value in \code{x} does not get overwritten during
  4513. the call to \READOP{}. One obvious approach is to save all the values
  4514. that reside in caller-saved registers to the stack prior to each
  4515. function call and to restore them after each call. That way, if the
  4516. register allocator chooses to assign \code{x} to a caller-saved
  4517. register, its value will be preserved across the call to \READOP{}.
  4518. However, saving and restoring to the stack is relatively slow. If
  4519. \code{x} is not used many times, it may be better to assign \code{x}
  4520. to a stack location in the first place. Or better yet, if we can
  4521. arrange for \code{x} to be placed in a callee-saved register, then it
  4522. won't need to be saved and restored during function calls.
  4523. The approach that we recommend for call-live variables is either to
  4524. assign them to callee-saved registers or to spill them to the
  4525. stack. On the other hand, for variables that are not call-live, we try
  4526. the following alternatives in order: (1) look for an available
  4527. caller-saved register (to leave room for other variables in the
  4528. callee-saved register), (2) look for a callee-saved register, and (3)
  4529. spill the variable to the stack.
  4530. It is straightforward to implement this approach in a graph coloring
  4531. register allocator. First, we know which variables are call-live
  4532. because we already need to compute which variables are in use at every
  4533. instruction (section~\ref{sec:liveness-analysis-Lvar}). Second, when
  4534. we build the interference graph
  4535. (section~\ref{sec:build-interference}), we can place an edge between
  4536. each of the call-live variables and the caller-saved registers in the
  4537. interference graph. This will prevent the graph coloring algorithm
  4538. from assigning them to caller-saved registers.
  4539. Returning to the example in
  4540. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4541. generated x86 code on the right-hand side. Notice that variable
  4542. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  4543. is already in a safe place during the second call to
  4544. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  4545. \code{rcx}, a caller-saved register, because \code{y} is not a
  4546. call-live variable.
  4547. Next we analyze the example from the callee point of view, focusing on
  4548. the prelude and conclusion of the \code{main} function. As usual, the
  4549. prelude begins with saving the \code{rbp} register to the stack and
  4550. setting the \code{rbp} to the current stack pointer. We now know why
  4551. it is necessary to save the \code{rbp}: it is a callee-saved register.
  4552. The prelude then pushes \code{rbx} to the stack because (1) \code{rbx}
  4553. is a callee-saved register and (2) \code{rbx} is assigned to a variable
  4554. (\code{x}). The other callee-saved registers are not saved in the
  4555. prelude because they are not used. The prelude subtracts 8 bytes from
  4556. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4557. conclusion, we see that \code{rbx} is restored from the stack with a
  4558. \code{popq} instruction.
  4559. \index{subject}{prelude}\index{subject}{conclusion}
  4560. \begin{figure}[tp]
  4561. \begin{tcolorbox}[colback=white]
  4562. \begin{minipage}{0.45\textwidth}
  4563. Example \LangVar{} program:
  4564. %var_test_14.rkt
  4565. {\if\edition\racketEd
  4566. \begin{lstlisting}
  4567. (let ([x (read)])
  4568. (let ([y (read)])
  4569. (+ (+ x y) 42)))
  4570. \end{lstlisting}
  4571. \fi}
  4572. {\if\edition\pythonEd
  4573. \begin{lstlisting}
  4574. x = input_int()
  4575. y = input_int()
  4576. print((x + y) + 42)
  4577. \end{lstlisting}
  4578. \fi}
  4579. \end{minipage}
  4580. \begin{minipage}{0.45\textwidth}
  4581. Generated x86 assembly:
  4582. {\if\edition\racketEd
  4583. \begin{lstlisting}
  4584. start:
  4585. callq read_int
  4586. movq %rax, %rbx
  4587. callq read_int
  4588. movq %rax, %rcx
  4589. addq %rcx, %rbx
  4590. movq %rbx, %rax
  4591. addq $42, %rax
  4592. jmp _conclusion
  4593. .globl main
  4594. main:
  4595. pushq %rbp
  4596. movq %rsp, %rbp
  4597. pushq %rbx
  4598. subq $8, %rsp
  4599. jmp start
  4600. conclusion:
  4601. addq $8, %rsp
  4602. popq %rbx
  4603. popq %rbp
  4604. retq
  4605. \end{lstlisting}
  4606. \fi}
  4607. {\if\edition\pythonEd
  4608. \begin{lstlisting}
  4609. .globl main
  4610. main:
  4611. pushq %rbp
  4612. movq %rsp, %rbp
  4613. pushq %rbx
  4614. subq $8, %rsp
  4615. callq read_int
  4616. movq %rax, %rbx
  4617. callq read_int
  4618. movq %rax, %rcx
  4619. movq %rbx, %rdx
  4620. addq %rcx, %rdx
  4621. movq %rdx, %rcx
  4622. addq $42, %rcx
  4623. movq %rcx, %rdi
  4624. callq print_int
  4625. addq $8, %rsp
  4626. popq %rbx
  4627. popq %rbp
  4628. retq
  4629. \end{lstlisting}
  4630. \fi}
  4631. \end{minipage}
  4632. \end{tcolorbox}
  4633. \caption{An example with function calls.}
  4634. \label{fig:example-calling-conventions}
  4635. \end{figure}
  4636. %\clearpage
  4637. \section{Liveness Analysis}
  4638. \label{sec:liveness-analysis-Lvar}
  4639. \index{subject}{liveness analysis}
  4640. The \code{uncover\_live} \racket{pass}\python{function} performs
  4641. \emph{liveness analysis}; that is, it discovers which variables are
  4642. in use in different regions of a program.
  4643. %
  4644. A variable or register is \emph{live} at a program point if its
  4645. current value is used at some later point in the program. We refer to
  4646. variables, stack locations, and registers collectively as
  4647. \emph{locations}.
  4648. %
  4649. Consider the following code fragment in which there are two writes to
  4650. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4651. time?
  4652. \begin{center}
  4653. \begin{minipage}{0.96\textwidth}
  4654. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4655. movq $5, a
  4656. movq $30, b
  4657. movq a, c
  4658. movq $10, b
  4659. addq b, c
  4660. \end{lstlisting}
  4661. \end{minipage}
  4662. \end{center}
  4663. The answer is no, because \code{a} is live from line 1 to 3 and
  4664. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4665. line 2 is never used because it is overwritten (line 4) before the
  4666. next read (line 5).
  4667. The live locations for each instruction can be computed by traversing
  4668. the instruction sequence back to front (i.e., backward in execution
  4669. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4670. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4671. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4672. locations before instruction $I_k$. \racket{We recommend representing
  4673. these sets with the Racket \code{set} data structure described in
  4674. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4675. with the Python
  4676. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4677. data structure.}
  4678. {\if\edition\racketEd
  4679. \begin{figure}[tp]
  4680. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4681. \small
  4682. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4683. A \emph{set} is an unordered collection of elements without duplicates.
  4684. Here are some of the operations defined on sets.
  4685. \index{subject}{set}
  4686. \begin{description}
  4687. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4688. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4689. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4690. difference of the two sets.
  4691. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4692. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4693. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4694. \end{description}
  4695. \end{tcolorbox}
  4696. %\end{wrapfigure}
  4697. \caption{The \code{set} data structure.}
  4698. \label{fig:set}
  4699. \end{figure}
  4700. \fi}
  4701. The live locations after an instruction are always the same as the
  4702. live locations before the next instruction.
  4703. \index{subject}{live-after} \index{subject}{live-before}
  4704. \begin{equation} \label{eq:live-after-before-next}
  4705. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4706. \end{equation}
  4707. To start things off, there are no live locations after the last
  4708. instruction, so
  4709. \begin{equation}\label{eq:live-last-empty}
  4710. L_{\mathsf{after}}(n) = \emptyset
  4711. \end{equation}
  4712. We then apply the following rule repeatedly, traversing the
  4713. instruction sequence back to front.
  4714. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4715. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4716. \end{equation}
  4717. where $W(k)$ are the locations written to by instruction $I_k$, and
  4718. $R(k)$ are the locations read by instruction $I_k$.
  4719. {\if\edition\racketEd
  4720. %
  4721. There is a special case for \code{jmp} instructions. The locations
  4722. that are live before a \code{jmp} should be the locations in
  4723. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4724. maintaining an alist named \code{label->live} that maps each label to
  4725. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4726. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4727. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4728. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4729. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4730. %
  4731. \fi}
  4732. Let us walk through the previous example, applying these formulas
  4733. starting with the instruction on line 5 of the code fragment. We
  4734. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4735. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4736. $\emptyset$ because it is the last instruction
  4737. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4738. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4739. variables \code{b} and \code{c}
  4740. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4741. \[
  4742. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4743. \]
  4744. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4745. the live-before set from line 5 to be the live-after set for this
  4746. instruction (formula~\eqref{eq:live-after-before-next}).
  4747. \[
  4748. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4749. \]
  4750. This move instruction writes to \code{b} and does not read from any
  4751. variables, so we have the following live-before set
  4752. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4753. \[
  4754. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4755. \]
  4756. The live-before for instruction \code{movq a, c}
  4757. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4758. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4759. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4760. variable that is not live and does not read from a variable.
  4761. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4762. because it writes to variable \code{a}.
  4763. \begin{figure}[tbp]
  4764. \centering
  4765. \begin{tcolorbox}[colback=white]
  4766. \hspace{10pt}
  4767. \begin{minipage}{0.4\textwidth}
  4768. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4769. movq $5, a
  4770. movq $30, b
  4771. movq a, c
  4772. movq $10, b
  4773. addq b, c
  4774. \end{lstlisting}
  4775. \end{minipage}
  4776. \vrule\hspace{10pt}
  4777. \begin{minipage}{0.45\textwidth}
  4778. \begin{align*}
  4779. L_{\mathsf{before}}(1)= \emptyset,
  4780. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4781. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4782. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4783. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4784. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4785. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4786. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4787. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4788. L_{\mathsf{after}}(5)= \emptyset
  4789. \end{align*}
  4790. \end{minipage}
  4791. \end{tcolorbox}
  4792. \caption{Example output of liveness analysis on a short example.}
  4793. \label{fig:liveness-example-0}
  4794. \end{figure}
  4795. \begin{exercise}\normalfont\normalsize
  4796. Perform liveness analysis by hand on the running example in
  4797. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4798. sets for each instruction. Compare your answers to the solution
  4799. shown in figure~\ref{fig:live-eg}.
  4800. \end{exercise}
  4801. \begin{figure}[tp]
  4802. \hspace{20pt}
  4803. \begin{minipage}{0.55\textwidth}
  4804. \begin{tcolorbox}[colback=white]
  4805. {\if\edition\racketEd
  4806. \begin{lstlisting}
  4807. |$\{\ttm{rsp}\}$|
  4808. movq $1, v
  4809. |$\{\ttm{v},\ttm{rsp}\}$|
  4810. movq $42, w
  4811. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4812. movq v, x
  4813. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4814. addq $7, x
  4815. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4816. movq x, y
  4817. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4818. movq x, z
  4819. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4820. addq w, z
  4821. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4822. movq y, t
  4823. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4824. negq t
  4825. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4826. movq z, %rax
  4827. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4828. addq t, %rax
  4829. |$\{\ttm{rax},\ttm{rsp}\}$|
  4830. jmp conclusion
  4831. \end{lstlisting}
  4832. \fi}
  4833. {\if\edition\pythonEd
  4834. \begin{lstlisting}
  4835. movq $1, v
  4836. |$\{\ttm{v}\}$|
  4837. movq $42, w
  4838. |$\{\ttm{w}, \ttm{v}\}$|
  4839. movq v, x
  4840. |$\{\ttm{w}, \ttm{x}\}$|
  4841. addq $7, x
  4842. |$\{\ttm{w}, \ttm{x}\}$|
  4843. movq x, y
  4844. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4845. movq x, z
  4846. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4847. addq w, z
  4848. |$\{\ttm{y}, \ttm{z}\}$|
  4849. movq y, tmp_0
  4850. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4851. negq tmp_0
  4852. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4853. movq z, tmp_1
  4854. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4855. addq tmp_0, tmp_1
  4856. |$\{\ttm{tmp\_1}\}$|
  4857. movq tmp_1, %rdi
  4858. |$\{\ttm{rdi}\}$|
  4859. callq print_int
  4860. |$\{\}$|
  4861. \end{lstlisting}
  4862. \fi}
  4863. \end{tcolorbox}
  4864. \end{minipage}
  4865. \caption{The running example annotated with live-after sets.}
  4866. \label{fig:live-eg}
  4867. \end{figure}
  4868. \begin{exercise}\normalfont\normalsize
  4869. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4870. %
  4871. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4872. field of the \code{Block} structure.}
  4873. %
  4874. \python{Return a dictionary that maps each instruction to its
  4875. live-after set.}
  4876. %
  4877. \racket{We recommend creating an auxiliary function that takes a list
  4878. of instructions and an initial live-after set (typically empty) and
  4879. returns the list of live-after sets.}
  4880. %
  4881. We recommend creating auxiliary functions to (1) compute the set
  4882. of locations that appear in an \Arg{}, (2) compute the locations read
  4883. by an instruction (the $R$ function), and (3) the locations written by
  4884. an instruction (the $W$ function). The \code{callq} instruction should
  4885. include all the caller-saved registers in its write set $W$ because
  4886. the calling convention says that those registers may be written to
  4887. during the function call. Likewise, the \code{callq} instruction
  4888. should include the appropriate argument-passing registers in its
  4889. read set $R$, depending on the arity of the function being
  4890. called. (This is why the abstract syntax for \code{callq} includes the
  4891. arity.)
  4892. \end{exercise}
  4893. %\clearpage
  4894. \section{Build the Interference Graph}
  4895. \label{sec:build-interference}
  4896. {\if\edition\racketEd
  4897. \begin{figure}[tp]
  4898. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4899. \small
  4900. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4901. A \emph{graph} is a collection of vertices and edges where each
  4902. edge connects two vertices. A graph is \emph{directed} if each
  4903. edge points from a source to a target. Otherwise the graph is
  4904. \emph{undirected}.
  4905. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4906. \begin{description}
  4907. %% We currently don't use directed graphs. We instead use
  4908. %% directed multi-graphs. -Jeremy
  4909. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4910. directed graph from a list of edges. Each edge is a list
  4911. containing the source and target vertex.
  4912. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4913. undirected graph from a list of edges. Each edge is represented by
  4914. a list containing two vertices.
  4915. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4916. inserts a vertex into the graph.
  4917. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4918. inserts an edge between the two vertices.
  4919. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4920. returns a sequence of vertices adjacent to the vertex.
  4921. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4922. returns a sequence of all vertices in the graph.
  4923. \end{description}
  4924. \end{tcolorbox}
  4925. %\end{wrapfigure}
  4926. \caption{The Racket \code{graph} package.}
  4927. \label{fig:graph}
  4928. \end{figure}
  4929. \fi}
  4930. On the basis of the liveness analysis, we know where each location is
  4931. live. However, during register allocation, we need to answer
  4932. questions of the specific form: are locations $u$ and $v$ live at the
  4933. same time? (If so, they cannot be assigned to the same register.) To
  4934. make this question more efficient to answer, we create an explicit
  4935. data structure, an \emph{interference
  4936. graph}\index{subject}{interference graph}. An interference graph is
  4937. an undirected graph that has an edge between two locations if they are
  4938. live at the same time, that is, if they interfere with each other.
  4939. %
  4940. \racket{We recommend using the Racket \code{graph} package
  4941. (figure~\ref{fig:graph}) to represent the interference graph.}
  4942. %
  4943. \python{We provide implementations of directed and undirected graph
  4944. data structures in the file \code{graph.py} of the support code.}
  4945. A straightforward way to compute the interference graph is to look at
  4946. the set of live locations between each instruction and add an edge to
  4947. the graph for every pair of variables in the same set. This approach
  4948. is less than ideal for two reasons. First, it can be expensive because
  4949. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4950. locations. Second, in the special case in which two locations hold the
  4951. same value (because one was assigned to the other), they can be live
  4952. at the same time without interfering with each other.
  4953. A better way to compute the interference graph is to focus on
  4954. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4955. must not overwrite something in a live location. So for each
  4956. instruction, we create an edge between the locations being written to
  4957. and the live locations. (However, a location never interferes with
  4958. itself.) For the \key{callq} instruction, we consider all the
  4959. caller-saved registers to have been written to, so an edge is added
  4960. between every live variable and every caller-saved register. Also, for
  4961. \key{movq} there is the special case of two variables holding the same
  4962. value. If a live variable $v$ is the same as the source of the
  4963. \key{movq}, then there is no need to add an edge between $v$ and the
  4964. destination, because they both hold the same value.
  4965. %
  4966. Hence we have the following two rules:
  4967. \begin{enumerate}
  4968. \item If instruction $I_k$ is a move instruction of the form
  4969. \key{movq} $s$\key{,} $d$, then for every $v \in
  4970. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4971. $(d,v)$.
  4972. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4973. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4974. $(d,v)$.
  4975. \end{enumerate}
  4976. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  4977. these rules to each instruction. We highlight a few of the
  4978. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  4979. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4980. so \code{v} interferes with \code{rsp}.}
  4981. %
  4982. \python{The first instruction is \lstinline{movq $1, v}, and the
  4983. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4984. no interference because $\ttm{v}$ is the destination of the move.}
  4985. %
  4986. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  4987. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4988. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4989. %
  4990. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  4991. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4992. $\ttm{x}$ interferes with \ttm{w}.}
  4993. %
  4994. \racket{The next instruction is \lstinline{movq x, y}, and the
  4995. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4996. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4997. \ttm{x} because \ttm{x} is the source of the move and therefore
  4998. \ttm{x} and \ttm{y} hold the same value.}
  4999. %
  5000. \python{The next instruction is \lstinline{movq x, y}, and the
  5001. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5002. applies, so \ttm{y} interferes with \ttm{w} but not
  5003. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5004. \ttm{x} and \ttm{y} hold the same value.}
  5005. %
  5006. Figure~\ref{fig:interference-results} lists the interference results
  5007. for all the instructions, and the resulting interference graph is
  5008. shown in figure~\ref{fig:interfere}.
  5009. \begin{figure}[tbp]
  5010. \begin{tcolorbox}[colback=white]
  5011. \begin{quote}
  5012. {\if\edition\racketEd
  5013. \begin{tabular}{ll}
  5014. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5015. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5016. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5017. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5018. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5019. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5020. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5021. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5022. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5023. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5024. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5025. \lstinline!jmp conclusion!& no interference.
  5026. \end{tabular}
  5027. \fi}
  5028. {\if\edition\pythonEd
  5029. \begin{tabular}{ll}
  5030. \lstinline!movq $1, v!& no interference\\
  5031. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5032. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5033. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5034. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5035. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5036. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5037. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5038. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5039. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5040. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5041. \lstinline!movq tmp_1, %rdi! & no interference \\
  5042. \lstinline!callq print_int!& no interference.
  5043. \end{tabular}
  5044. \fi}
  5045. \end{quote}
  5046. \end{tcolorbox}
  5047. \caption{Interference results for the running example.}
  5048. \label{fig:interference-results}
  5049. \end{figure}
  5050. \begin{figure}[tbp]
  5051. \begin{tcolorbox}[colback=white]
  5052. \large
  5053. {\if\edition\racketEd
  5054. \[
  5055. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5056. \node (rax) at (0,0) {$\ttm{rax}$};
  5057. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5058. \node (t1) at (0,2) {$\ttm{t}$};
  5059. \node (z) at (3,2) {$\ttm{z}$};
  5060. \node (x) at (6,2) {$\ttm{x}$};
  5061. \node (y) at (3,0) {$\ttm{y}$};
  5062. \node (w) at (6,0) {$\ttm{w}$};
  5063. \node (v) at (9,0) {$\ttm{v}$};
  5064. \draw (t1) to (rax);
  5065. \draw (t1) to (z);
  5066. \draw (z) to (y);
  5067. \draw (z) to (w);
  5068. \draw (x) to (w);
  5069. \draw (y) to (w);
  5070. \draw (v) to (w);
  5071. \draw (v) to (rsp);
  5072. \draw (w) to (rsp);
  5073. \draw (x) to (rsp);
  5074. \draw (y) to (rsp);
  5075. \path[-.,bend left=15] (z) edge node {} (rsp);
  5076. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5077. \draw (rax) to (rsp);
  5078. \end{tikzpicture}
  5079. \]
  5080. \fi}
  5081. {\if\edition\pythonEd
  5082. \[
  5083. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5084. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5085. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5086. \node (z) at (3,2) {$\ttm{z}$};
  5087. \node (x) at (6,2) {$\ttm{x}$};
  5088. \node (y) at (3,0) {$\ttm{y}$};
  5089. \node (w) at (6,0) {$\ttm{w}$};
  5090. \node (v) at (9,0) {$\ttm{v}$};
  5091. \draw (t0) to (t1);
  5092. \draw (t0) to (z);
  5093. \draw (z) to (y);
  5094. \draw (z) to (w);
  5095. \draw (x) to (w);
  5096. \draw (y) to (w);
  5097. \draw (v) to (w);
  5098. \end{tikzpicture}
  5099. \]
  5100. \fi}
  5101. \end{tcolorbox}
  5102. \caption{The interference graph of the example program.}
  5103. \label{fig:interfere}
  5104. \end{figure}
  5105. %% Our next concern is to choose a data structure for representing the
  5106. %% interference graph. There are many choices for how to represent a
  5107. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  5108. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  5109. %% data structure is to study the algorithm that uses the data structure,
  5110. %% determine what operations need to be performed, and then choose the
  5111. %% data structure that provide the most efficient implementations of
  5112. %% those operations. Often times the choice of data structure can have an
  5113. %% effect on the time complexity of the algorithm, as it does here. If
  5114. %% you skim the next section, you will see that the register allocation
  5115. %% algorithm needs to ask the graph for all its vertices and, given a
  5116. %% vertex, it needs to known all the adjacent vertices. Thus, the
  5117. %% correct choice of graph representation is that of an adjacency
  5118. %% list. There are helper functions in \code{utilities.rkt} for
  5119. %% representing graphs using the adjacency list representation:
  5120. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  5121. %% (Appendix~\ref{appendix:utilities}).
  5122. %% %
  5123. %% \margincomment{\footnotesize To do: change to use the
  5124. %% Racket graph library. \\ --Jeremy}
  5125. %% %
  5126. %% In particular, those functions use a hash table to map each vertex to
  5127. %% the set of adjacent vertices, and the sets are represented using
  5128. %% Racket's \key{set}, which is also a hash table.
  5129. \begin{exercise}\normalfont\normalsize
  5130. \racket{Implement the compiler pass named \code{build\_interference} according
  5131. to the algorithm suggested here. We recommend using the Racket
  5132. \code{graph} package to create and inspect the interference graph.
  5133. The output graph of this pass should be stored in the $\itm{info}$ field of
  5134. the program, under the key \code{conflicts}.}
  5135. %
  5136. \python{Implement a function named \code{build\_interference}
  5137. according to the algorithm suggested above that
  5138. returns the interference graph.}
  5139. \end{exercise}
  5140. \section{Graph Coloring via Sudoku}
  5141. \label{sec:graph-coloring}
  5142. \index{subject}{graph coloring}
  5143. \index{subject}{sudoku}
  5144. \index{subject}{color}
  5145. We come to the main event discussed in this chapter, mapping variables
  5146. to registers and stack locations. Variables that interfere with each
  5147. other must be mapped to different locations. In terms of the
  5148. interference graph, this means that adjacent vertices must be mapped
  5149. to different locations. If we think of locations as colors, the
  5150. register allocation problem becomes the graph coloring
  5151. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5152. The reader may be more familiar with the graph coloring problem than he
  5153. or she realizes; the popular game of sudoku is an instance of the
  5154. graph coloring problem. The following describes how to build a graph
  5155. out of an initial sudoku board.
  5156. \begin{itemize}
  5157. \item There is one vertex in the graph for each sudoku square.
  5158. \item There is an edge between two vertices if the corresponding squares
  5159. are in the same row, in the same column, or in the same $3\times 3$ region.
  5160. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5161. \item On the basis of the initial assignment of numbers to squares on the
  5162. sudoku board, assign the corresponding colors to the corresponding
  5163. vertices in the graph.
  5164. \end{itemize}
  5165. If you can color the remaining vertices in the graph with the nine
  5166. colors, then you have also solved the corresponding game of sudoku.
  5167. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5168. the corresponding graph with colored vertices. Here we use a
  5169. monochrome representation of colors, mapping the sudoku number 1 to
  5170. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5171. of the vertices (the colored ones) because showing edges for all the
  5172. vertices would make the graph unreadable.
  5173. \begin{figure}[tbp]
  5174. \begin{tcolorbox}[colback=white]
  5175. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5176. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5177. \end{tcolorbox}
  5178. \caption{A sudoku game board and the corresponding colored graph.}
  5179. \label{fig:sudoku-graph}
  5180. \end{figure}
  5181. Some techniques for playing sudoku correspond to heuristics used in
  5182. graph coloring algorithms. For example, one of the basic techniques
  5183. for sudoku is called Pencil Marks. The idea is to use a process of
  5184. elimination to determine what numbers are no longer available for a
  5185. square and to write those numbers in the square (writing very
  5186. small). For example, if the number $1$ is assigned to a square, then
  5187. write the pencil mark $1$ in all the squares in the same row, column,
  5188. and region to indicate that $1$ is no longer an option for those other
  5189. squares.
  5190. %
  5191. The Pencil Marks technique corresponds to the notion of
  5192. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5193. saturation of a vertex, in sudoku terms, is the set of numbers that
  5194. are no longer available. In graph terminology, we have the following
  5195. definition:
  5196. \begin{equation*}
  5197. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5198. \text{ and } \mathrm{color}(v) = c \}
  5199. \end{equation*}
  5200. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5201. edge with $u$.
  5202. The Pencil Marks technique leads to a simple strategy for filling in
  5203. numbers: if there is a square with only one possible number left, then
  5204. choose that number! But what if there are no squares with only one
  5205. possibility left? One brute-force approach is to try them all: choose
  5206. the first one, and if that ultimately leads to a solution, great. If
  5207. not, backtrack and choose the next possibility. One good thing about
  5208. Pencil Marks is that it reduces the degree of branching in the search
  5209. tree. Nevertheless, backtracking can be terribly time consuming. One
  5210. way to reduce the amount of backtracking is to use the
  5211. most-constrained-first heuristic (aka minimum remaining
  5212. values)~\citep{Russell2003}. That is, in choosing a square, always
  5213. choose one with the fewest possibilities left (the vertex with the
  5214. highest saturation). The idea is that choosing highly constrained
  5215. squares earlier rather than later is better, because later on there may
  5216. not be any possibilities left in the highly saturated squares.
  5217. However, register allocation is easier than sudoku, because the
  5218. register allocator can fall back to assigning variables to stack
  5219. locations when the registers run out. Thus, it makes sense to replace
  5220. backtracking with greedy search: make the best choice at the time and
  5221. keep going. We still wish to minimize the number of colors needed, so
  5222. we use the most-constrained-first heuristic in the greedy search.
  5223. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5224. algorithm for register allocation based on saturation and the
  5225. most-constrained-first heuristic. It is roughly equivalent to the
  5226. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  5227. Just as in sudoku, the algorithm represents colors with integers. The
  5228. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  5229. for register allocation. The integers $k$ and larger correspond to
  5230. stack locations. The registers that are not used for register
  5231. allocation, such as \code{rax}, are assigned to negative integers. In
  5232. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  5233. %% One might wonder why we include registers at all in the liveness
  5234. %% analysis and interference graph. For example, we never allocate a
  5235. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5236. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5237. %% to use register for passing arguments to functions, it will be
  5238. %% necessary for those registers to appear in the interference graph
  5239. %% because those registers will also be assigned to variables, and we
  5240. %% don't want those two uses to encroach on each other. Regarding
  5241. %% registers such as \code{rax} and \code{rsp} that are not used for
  5242. %% variables, we could omit them from the interference graph but that
  5243. %% would require adding special cases to our algorithm, which would
  5244. %% complicate the logic for little gain.
  5245. \begin{figure}[btp]
  5246. \begin{tcolorbox}[colback=white]
  5247. \centering
  5248. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5249. Algorithm: DSATUR
  5250. Input: A graph |$G$|
  5251. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5252. |$W \gets \mathrm{vertices}(G)$|
  5253. while |$W \neq \emptyset$| do
  5254. pick a vertex |$u$| from |$W$| with the highest saturation,
  5255. breaking ties randomly
  5256. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5257. |$\mathrm{color}[u] \gets c$|
  5258. |$W \gets W - \{u\}$|
  5259. \end{lstlisting}
  5260. \end{tcolorbox}
  5261. \caption{The saturation-based greedy graph coloring algorithm.}
  5262. \label{fig:satur-algo}
  5263. \end{figure}
  5264. {\if\edition\racketEd
  5265. With the DSATUR algorithm in hand, let us return to the running
  5266. example and consider how to color the interference graph shown in
  5267. figure~\ref{fig:interfere}.
  5268. %
  5269. We start by assigning each register node to its own color. For
  5270. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  5271. assigned $-2$. The variables are not yet colored, so they are
  5272. annotated with a dash. We then update the saturation for vertices that
  5273. are adjacent to a register, obtaining the following annotated
  5274. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  5275. it interferes with both \code{rax} and \code{rsp}.
  5276. \[
  5277. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5278. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5279. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5280. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5281. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5282. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5283. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5284. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5285. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5286. \draw (t1) to (rax);
  5287. \draw (t1) to (z);
  5288. \draw (z) to (y);
  5289. \draw (z) to (w);
  5290. \draw (x) to (w);
  5291. \draw (y) to (w);
  5292. \draw (v) to (w);
  5293. \draw (v) to (rsp);
  5294. \draw (w) to (rsp);
  5295. \draw (x) to (rsp);
  5296. \draw (y) to (rsp);
  5297. \path[-.,bend left=15] (z) edge node {} (rsp);
  5298. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5299. \draw (rax) to (rsp);
  5300. \end{tikzpicture}
  5301. \]
  5302. The algorithm says to select a maximally saturated vertex. So, we pick
  5303. $\ttm{t}$ and color it with the first available integer, which is
  5304. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5305. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5306. \[
  5307. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5308. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5309. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5310. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5311. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5312. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5313. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5314. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5315. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5316. \draw (t1) to (rax);
  5317. \draw (t1) to (z);
  5318. \draw (z) to (y);
  5319. \draw (z) to (w);
  5320. \draw (x) to (w);
  5321. \draw (y) to (w);
  5322. \draw (v) to (w);
  5323. \draw (v) to (rsp);
  5324. \draw (w) to (rsp);
  5325. \draw (x) to (rsp);
  5326. \draw (y) to (rsp);
  5327. \path[-.,bend left=15] (z) edge node {} (rsp);
  5328. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5329. \draw (rax) to (rsp);
  5330. \end{tikzpicture}
  5331. \]
  5332. We repeat the process, selecting a maximally saturated vertex,
  5333. choosing \code{z}, and coloring it with the first available number, which
  5334. is $1$. We add $1$ to the saturation for the neighboring vertices
  5335. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5336. \[
  5337. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5338. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5339. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5340. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5341. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5342. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5343. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5344. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5345. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5346. \draw (t1) to (rax);
  5347. \draw (t1) to (z);
  5348. \draw (z) to (y);
  5349. \draw (z) to (w);
  5350. \draw (x) to (w);
  5351. \draw (y) to (w);
  5352. \draw (v) to (w);
  5353. \draw (v) to (rsp);
  5354. \draw (w) to (rsp);
  5355. \draw (x) to (rsp);
  5356. \draw (y) to (rsp);
  5357. \path[-.,bend left=15] (z) edge node {} (rsp);
  5358. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5359. \draw (rax) to (rsp);
  5360. \end{tikzpicture}
  5361. \]
  5362. The most saturated vertices are now \code{w} and \code{y}. We color
  5363. \code{w} with the first available color, which is $0$.
  5364. \[
  5365. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5366. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5367. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5368. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5369. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5370. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5371. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5372. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5373. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5374. \draw (t1) to (rax);
  5375. \draw (t1) to (z);
  5376. \draw (z) to (y);
  5377. \draw (z) to (w);
  5378. \draw (x) to (w);
  5379. \draw (y) to (w);
  5380. \draw (v) to (w);
  5381. \draw (v) to (rsp);
  5382. \draw (w) to (rsp);
  5383. \draw (x) to (rsp);
  5384. \draw (y) to (rsp);
  5385. \path[-.,bend left=15] (z) edge node {} (rsp);
  5386. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5387. \draw (rax) to (rsp);
  5388. \end{tikzpicture}
  5389. \]
  5390. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5391. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5392. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5393. and \code{z}, whose colors are $0$ and $1$ respectively.
  5394. \[
  5395. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5396. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5397. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5398. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5399. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5400. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5401. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5402. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5403. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5404. \draw (t1) to (rax);
  5405. \draw (t1) to (z);
  5406. \draw (z) to (y);
  5407. \draw (z) to (w);
  5408. \draw (x) to (w);
  5409. \draw (y) to (w);
  5410. \draw (v) to (w);
  5411. \draw (v) to (rsp);
  5412. \draw (w) to (rsp);
  5413. \draw (x) to (rsp);
  5414. \draw (y) to (rsp);
  5415. \path[-.,bend left=15] (z) edge node {} (rsp);
  5416. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5417. \draw (rax) to (rsp);
  5418. \end{tikzpicture}
  5419. \]
  5420. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5421. \[
  5422. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5423. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5424. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5425. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5426. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5427. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5428. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5429. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5430. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5431. \draw (t1) to (rax);
  5432. \draw (t1) to (z);
  5433. \draw (z) to (y);
  5434. \draw (z) to (w);
  5435. \draw (x) to (w);
  5436. \draw (y) to (w);
  5437. \draw (v) to (w);
  5438. \draw (v) to (rsp);
  5439. \draw (w) to (rsp);
  5440. \draw (x) to (rsp);
  5441. \draw (y) to (rsp);
  5442. \path[-.,bend left=15] (z) edge node {} (rsp);
  5443. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5444. \draw (rax) to (rsp);
  5445. \end{tikzpicture}
  5446. \]
  5447. In the last step of the algorithm, we color \code{x} with $1$.
  5448. \[
  5449. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5450. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5451. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5452. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5453. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5454. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5455. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5456. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5457. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5458. \draw (t1) to (rax);
  5459. \draw (t1) to (z);
  5460. \draw (z) to (y);
  5461. \draw (z) to (w);
  5462. \draw (x) to (w);
  5463. \draw (y) to (w);
  5464. \draw (v) to (w);
  5465. \draw (v) to (rsp);
  5466. \draw (w) to (rsp);
  5467. \draw (x) to (rsp);
  5468. \draw (y) to (rsp);
  5469. \path[-.,bend left=15] (z) edge node {} (rsp);
  5470. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5471. \draw (rax) to (rsp);
  5472. \end{tikzpicture}
  5473. \]
  5474. So, we obtain the following coloring:
  5475. \[
  5476. \{
  5477. \ttm{rax} \mapsto -1,
  5478. \ttm{rsp} \mapsto -2,
  5479. \ttm{t} \mapsto 0,
  5480. \ttm{z} \mapsto 1,
  5481. \ttm{x} \mapsto 1,
  5482. \ttm{y} \mapsto 2,
  5483. \ttm{w} \mapsto 0,
  5484. \ttm{v} \mapsto 1
  5485. \}
  5486. \]
  5487. \fi}
  5488. %
  5489. {\if\edition\pythonEd
  5490. %
  5491. With the DSATUR algorithm in hand, let us return to the running
  5492. example and consider how to color the interference graph in
  5493. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5494. to indicate that it has not yet been assigned a color. The saturation
  5495. sets are also shown for each node; all of them start as the empty set.
  5496. (We do not include the register nodes in the graph below because there
  5497. were no interference edges involving registers in this program, but in
  5498. general there can be.)
  5499. %
  5500. \[
  5501. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5502. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5503. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5504. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5505. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5506. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5507. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5508. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5509. \draw (t0) to (t1);
  5510. \draw (t0) to (z);
  5511. \draw (z) to (y);
  5512. \draw (z) to (w);
  5513. \draw (x) to (w);
  5514. \draw (y) to (w);
  5515. \draw (v) to (w);
  5516. \end{tikzpicture}
  5517. \]
  5518. The algorithm says to select a maximally saturated vertex, but they
  5519. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5520. then color it with the first available integer, which is $0$. We mark
  5521. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5522. they interfere with $\ttm{tmp\_0}$.
  5523. \[
  5524. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5525. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5526. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5527. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5528. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5529. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5530. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5531. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5532. \draw (t0) to (t1);
  5533. \draw (t0) to (z);
  5534. \draw (z) to (y);
  5535. \draw (z) to (w);
  5536. \draw (x) to (w);
  5537. \draw (y) to (w);
  5538. \draw (v) to (w);
  5539. \end{tikzpicture}
  5540. \]
  5541. We repeat the process. The most saturated vertices are \code{z} and
  5542. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5543. available number, which is $1$. We add $1$ to the saturation for the
  5544. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5545. \[
  5546. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5547. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5548. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5549. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5550. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5551. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5552. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5553. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5554. \draw (t0) to (t1);
  5555. \draw (t0) to (z);
  5556. \draw (z) to (y);
  5557. \draw (z) to (w);
  5558. \draw (x) to (w);
  5559. \draw (y) to (w);
  5560. \draw (v) to (w);
  5561. \end{tikzpicture}
  5562. \]
  5563. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5564. \code{y}. We color \code{w} with the first available color, which
  5565. is $0$.
  5566. \[
  5567. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5568. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5569. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5570. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5571. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5572. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5573. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5574. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5575. \draw (t0) to (t1);
  5576. \draw (t0) to (z);
  5577. \draw (z) to (y);
  5578. \draw (z) to (w);
  5579. \draw (x) to (w);
  5580. \draw (y) to (w);
  5581. \draw (v) to (w);
  5582. \end{tikzpicture}
  5583. \]
  5584. Now \code{y} is the most saturated, so we color it with $2$.
  5585. \[
  5586. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5587. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5588. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5589. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5590. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5591. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5592. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5593. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5594. \draw (t0) to (t1);
  5595. \draw (t0) to (z);
  5596. \draw (z) to (y);
  5597. \draw (z) to (w);
  5598. \draw (x) to (w);
  5599. \draw (y) to (w);
  5600. \draw (v) to (w);
  5601. \end{tikzpicture}
  5602. \]
  5603. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5604. We choose to color \code{v} with $1$.
  5605. \[
  5606. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5607. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5608. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5609. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5610. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5611. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5612. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5613. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5614. \draw (t0) to (t1);
  5615. \draw (t0) to (z);
  5616. \draw (z) to (y);
  5617. \draw (z) to (w);
  5618. \draw (x) to (w);
  5619. \draw (y) to (w);
  5620. \draw (v) to (w);
  5621. \end{tikzpicture}
  5622. \]
  5623. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5624. \[
  5625. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5626. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5627. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5628. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5629. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5630. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5631. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5632. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5633. \draw (t0) to (t1);
  5634. \draw (t0) to (z);
  5635. \draw (z) to (y);
  5636. \draw (z) to (w);
  5637. \draw (x) to (w);
  5638. \draw (y) to (w);
  5639. \draw (v) to (w);
  5640. \end{tikzpicture}
  5641. \]
  5642. So, we obtain the following coloring:
  5643. \[
  5644. \{ \ttm{tmp\_0} \mapsto 0,
  5645. \ttm{tmp\_1} \mapsto 1,
  5646. \ttm{z} \mapsto 1,
  5647. \ttm{x} \mapsto 1,
  5648. \ttm{y} \mapsto 2,
  5649. \ttm{w} \mapsto 0,
  5650. \ttm{v} \mapsto 1 \}
  5651. \]
  5652. \fi}
  5653. We recommend creating an auxiliary function named \code{color\_graph}
  5654. that takes an interference graph and a list of all the variables in
  5655. the program. This function should return a mapping of variables to
  5656. their colors (represented as natural numbers). By creating this helper
  5657. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5658. when we add support for functions.
  5659. To prioritize the processing of highly saturated nodes inside the
  5660. \code{color\_graph} function, we recommend using the priority queue
  5661. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5662. addition, you will need to maintain a mapping from variables to their
  5663. handles in the priority queue so that you can notify the priority
  5664. queue when their saturation changes.}
  5665. {\if\edition\racketEd
  5666. \begin{figure}[tp]
  5667. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5668. \small
  5669. \begin{tcolorbox}[title=Priority Queue]
  5670. A \emph{priority queue} is a collection of items in which the
  5671. removal of items is governed by priority. In a min queue,
  5672. lower priority items are removed first. An implementation is in
  5673. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5674. queue} \index{subject}{minimum priority queue}
  5675. \begin{description}
  5676. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5677. priority queue that uses the $\itm{cmp}$ predicate to determine
  5678. whether its first argument has lower or equal priority to its
  5679. second argument.
  5680. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5681. items in the queue.
  5682. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5683. the item into the queue and returns a handle for the item in the
  5684. queue.
  5685. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5686. the lowest priority.
  5687. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5688. notifies the queue that the priority has decreased for the item
  5689. associated with the given handle.
  5690. \end{description}
  5691. \end{tcolorbox}
  5692. %\end{wrapfigure}
  5693. \caption{The priority queue data structure.}
  5694. \label{fig:priority-queue}
  5695. \end{figure}
  5696. \fi}
  5697. With the coloring complete, we finalize the assignment of variables to
  5698. registers and stack locations. We map the first $k$ colors to the $k$
  5699. registers and the rest of the colors to stack locations. Suppose for
  5700. the moment that we have just one register to use for register
  5701. allocation, \key{rcx}. Then we have the following map from colors to
  5702. locations.
  5703. \[
  5704. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5705. \]
  5706. Composing this mapping with the coloring, we arrive at the following
  5707. assignment of variables to locations.
  5708. {\if\edition\racketEd
  5709. \begin{gather*}
  5710. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5711. \ttm{w} \mapsto \key{\%rcx}, \,
  5712. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5713. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5714. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5715. \ttm{t} \mapsto \key{\%rcx} \}
  5716. \end{gather*}
  5717. \fi}
  5718. {\if\edition\pythonEd
  5719. \begin{gather*}
  5720. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5721. \ttm{w} \mapsto \key{\%rcx}, \,
  5722. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5723. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5724. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5725. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5726. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5727. \end{gather*}
  5728. \fi}
  5729. Adapt the code from the \code{assign\_homes} pass
  5730. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5731. assigned location. Applying this assignment to our running
  5732. example shown next, on the left, yields the program on the right.
  5733. % why frame size of 32? -JGS
  5734. \begin{center}
  5735. {\if\edition\racketEd
  5736. \begin{minipage}{0.3\textwidth}
  5737. \begin{lstlisting}
  5738. movq $1, v
  5739. movq $42, w
  5740. movq v, x
  5741. addq $7, x
  5742. movq x, y
  5743. movq x, z
  5744. addq w, z
  5745. movq y, t
  5746. negq t
  5747. movq z, %rax
  5748. addq t, %rax
  5749. jmp conclusion
  5750. \end{lstlisting}
  5751. \end{minipage}
  5752. $\Rightarrow\qquad$
  5753. \begin{minipage}{0.45\textwidth}
  5754. \begin{lstlisting}
  5755. movq $1, -8(%rbp)
  5756. movq $42, %rcx
  5757. movq -8(%rbp), -8(%rbp)
  5758. addq $7, -8(%rbp)
  5759. movq -8(%rbp), -16(%rbp)
  5760. movq -8(%rbp), -8(%rbp)
  5761. addq %rcx, -8(%rbp)
  5762. movq -16(%rbp), %rcx
  5763. negq %rcx
  5764. movq -8(%rbp), %rax
  5765. addq %rcx, %rax
  5766. jmp conclusion
  5767. \end{lstlisting}
  5768. \end{minipage}
  5769. \fi}
  5770. {\if\edition\pythonEd
  5771. \begin{minipage}{0.3\textwidth}
  5772. \begin{lstlisting}
  5773. movq $1, v
  5774. movq $42, w
  5775. movq v, x
  5776. addq $7, x
  5777. movq x, y
  5778. movq x, z
  5779. addq w, z
  5780. movq y, tmp_0
  5781. negq tmp_0
  5782. movq z, tmp_1
  5783. addq tmp_0, tmp_1
  5784. movq tmp_1, %rdi
  5785. callq print_int
  5786. \end{lstlisting}
  5787. \end{minipage}
  5788. $\Rightarrow\qquad$
  5789. \begin{minipage}{0.45\textwidth}
  5790. \begin{lstlisting}
  5791. movq $1, -8(%rbp)
  5792. movq $42, %rcx
  5793. movq -8(%rbp), -8(%rbp)
  5794. addq $7, -8(%rbp)
  5795. movq -8(%rbp), -16(%rbp)
  5796. movq -8(%rbp), -8(%rbp)
  5797. addq %rcx, -8(%rbp)
  5798. movq -16(%rbp), %rcx
  5799. negq %rcx
  5800. movq -8(%rbp), -8(%rbp)
  5801. addq %rcx, -8(%rbp)
  5802. movq -8(%rbp), %rdi
  5803. callq print_int
  5804. \end{lstlisting}
  5805. \end{minipage}
  5806. \fi}
  5807. \end{center}
  5808. \begin{exercise}\normalfont\normalsize
  5809. Implement the \code{allocate\_registers} pass.
  5810. Create five programs that exercise all aspects of the register
  5811. allocation algorithm, including spilling variables to the stack.
  5812. %
  5813. {\if\edition\racketEd
  5814. Replace \code{assign\_homes} in the list of \code{passes} in the
  5815. \code{run-tests.rkt} script with the three new passes:
  5816. \code{uncover\_live}, \code{build\_interference}, and
  5817. \code{allocate\_registers}.
  5818. Temporarily remove the call to \code{compiler-tests}.
  5819. Run the script to test the register allocator.
  5820. \fi}
  5821. %
  5822. {\if\edition\pythonEd
  5823. Run the \code{run-tests.py} script to to check whether the
  5824. output programs produce the same result as the input programs.
  5825. \fi}
  5826. \end{exercise}
  5827. \section{Patch Instructions}
  5828. \label{sec:patch-instructions}
  5829. The remaining step in the compilation to x86 is to ensure that the
  5830. instructions have at most one argument that is a memory access.
  5831. %
  5832. In the running example, the instruction \code{movq -8(\%rbp),
  5833. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  5834. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5835. then move \code{rax} into \code{-16(\%rbp)}.
  5836. %
  5837. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5838. problematic, but they can simply be deleted. In general, we recommend
  5839. deleting all the trivial moves whose source and destination are the
  5840. same location.
  5841. %
  5842. The following is the output of \code{patch\_instructions} on the
  5843. running example.
  5844. \begin{center}
  5845. {\if\edition\racketEd
  5846. \begin{minipage}{0.4\textwidth}
  5847. \begin{lstlisting}
  5848. movq $1, -8(%rbp)
  5849. movq $42, %rcx
  5850. movq -8(%rbp), -8(%rbp)
  5851. addq $7, -8(%rbp)
  5852. movq -8(%rbp), -16(%rbp)
  5853. movq -8(%rbp), -8(%rbp)
  5854. addq %rcx, -8(%rbp)
  5855. movq -16(%rbp), %rcx
  5856. negq %rcx
  5857. movq -8(%rbp), %rax
  5858. addq %rcx, %rax
  5859. jmp conclusion
  5860. \end{lstlisting}
  5861. \end{minipage}
  5862. $\Rightarrow\qquad$
  5863. \begin{minipage}{0.45\textwidth}
  5864. \begin{lstlisting}
  5865. movq $1, -8(%rbp)
  5866. movq $42, %rcx
  5867. addq $7, -8(%rbp)
  5868. movq -8(%rbp), %rax
  5869. movq %rax, -16(%rbp)
  5870. addq %rcx, -8(%rbp)
  5871. movq -16(%rbp), %rcx
  5872. negq %rcx
  5873. movq -8(%rbp), %rax
  5874. addq %rcx, %rax
  5875. jmp conclusion
  5876. \end{lstlisting}
  5877. \end{minipage}
  5878. \fi}
  5879. {\if\edition\pythonEd
  5880. \begin{minipage}{0.4\textwidth}
  5881. \begin{lstlisting}
  5882. movq $1, -8(%rbp)
  5883. movq $42, %rcx
  5884. movq -8(%rbp), -8(%rbp)
  5885. addq $7, -8(%rbp)
  5886. movq -8(%rbp), -16(%rbp)
  5887. movq -8(%rbp), -8(%rbp)
  5888. addq %rcx, -8(%rbp)
  5889. movq -16(%rbp), %rcx
  5890. negq %rcx
  5891. movq -8(%rbp), -8(%rbp)
  5892. addq %rcx, -8(%rbp)
  5893. movq -8(%rbp), %rdi
  5894. callq print_int
  5895. \end{lstlisting}
  5896. \end{minipage}
  5897. $\Rightarrow\qquad$
  5898. \begin{minipage}{0.45\textwidth}
  5899. \begin{lstlisting}
  5900. movq $1, -8(%rbp)
  5901. movq $42, %rcx
  5902. addq $7, -8(%rbp)
  5903. movq -8(%rbp), %rax
  5904. movq %rax, -16(%rbp)
  5905. addq %rcx, -8(%rbp)
  5906. movq -16(%rbp), %rcx
  5907. negq %rcx
  5908. addq %rcx, -8(%rbp)
  5909. movq -8(%rbp), %rdi
  5910. callq print_int
  5911. \end{lstlisting}
  5912. \end{minipage}
  5913. \fi}
  5914. \end{center}
  5915. \begin{exercise}\normalfont\normalsize
  5916. %
  5917. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5918. %
  5919. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5920. %in the \code{run-tests.rkt} script.
  5921. %
  5922. Run the script to test the \code{patch\_instructions} pass.
  5923. \end{exercise}
  5924. \section{Prelude and Conclusion}
  5925. \label{sec:print-x86-reg-alloc}
  5926. \index{subject}{calling conventions}
  5927. \index{subject}{prelude}\index{subject}{conclusion}
  5928. Recall that this pass generates the prelude and conclusion
  5929. instructions to satisfy the x86 calling conventions
  5930. (section~\ref{sec:calling-conventions}). With the addition of the
  5931. register allocator, the callee-saved registers used by the register
  5932. allocator must be saved in the prelude and restored in the conclusion.
  5933. In the \code{allocate\_registers} pass,
  5934. %
  5935. \racket{add an entry to the \itm{info}
  5936. of \code{X86Program} named \code{used\_callee}}
  5937. %
  5938. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5939. %
  5940. that stores the set of callee-saved registers that were assigned to
  5941. variables. The \code{prelude\_and\_conclusion} pass can then access
  5942. this information to decide which callee-saved registers need to be
  5943. saved and restored.
  5944. %
  5945. When calculating the amount to adjust the \code{rsp} in the prelude,
  5946. make sure to take into account the space used for saving the
  5947. callee-saved registers. Also, remember that the frame needs to be a
  5948. multiple of 16 bytes! We recommend using the following equation for
  5949. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5950. of spilled variables and $C$ be the number of callee-saved registers
  5951. that were allocated to variables. The $\itm{align}$ function rounds a
  5952. number up to the nearest 16 bytes.
  5953. \[
  5954. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5955. \]
  5956. The reason we subtract $8\itm{C}$ in this equation is that the
  5957. prelude uses \code{pushq} to save each of the callee-saved registers,
  5958. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5959. \racket{An overview of all the passes involved in register
  5960. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  5961. {\if\edition\racketEd
  5962. \begin{figure}[tbp]
  5963. \begin{tcolorbox}[colback=white]
  5964. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5965. \node (Lvar) at (0,2) {\large \LangVar{}};
  5966. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5967. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  5968. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  5969. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  5970. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  5971. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  5972. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  5973. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  5974. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  5975. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5976. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  5977. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5978. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  5979. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5980. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  5981. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  5982. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  5983. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  5984. \end{tikzpicture}
  5985. \end{tcolorbox}
  5986. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5987. \label{fig:reg-alloc-passes}
  5988. \end{figure}
  5989. \fi}
  5990. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5991. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  5992. use of registers and the stack, we limit the register allocator for
  5993. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5994. the prelude\index{subject}{prelude} of the \code{main} function, we
  5995. push \code{rbx} onto the stack because it is a callee-saved register
  5996. and it was assigned to a variable by the register allocator. We
  5997. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5998. reserve space for the one spilled variable. After that subtraction,
  5999. the \code{rsp} is aligned to 16 bytes.
  6000. Moving on to the program proper, we see how the registers were
  6001. allocated.
  6002. %
  6003. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  6004. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  6005. %
  6006. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6007. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  6008. were assigned to \code{rbx}.}
  6009. %
  6010. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  6011. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6012. callee-save register \code{rbx} onto the stack. The spilled variables
  6013. must be placed lower on the stack than the saved callee-save
  6014. registers, so in this case \racket{\code{w}}\python{z} is placed at
  6015. \code{-16(\%rbp)}.
  6016. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6017. done in the prelude. We move the stack pointer up by \code{8} bytes
  6018. (the room for spilled variables), then pop the old values of
  6019. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6020. \code{retq} to return control to the operating system.
  6021. \begin{figure}[tbp]
  6022. \begin{minipage}{0.55\textwidth}
  6023. \begin{tcolorbox}[colback=white]
  6024. % var_test_28.rkt
  6025. % (use-minimal-set-of-registers! #t)
  6026. % and only rbx rcx
  6027. % tmp 0 rbx
  6028. % z 1 rcx
  6029. % y 0 rbx
  6030. % w 2 16(%rbp)
  6031. % v 0 rbx
  6032. % x 0 rbx
  6033. {\if\edition\racketEd
  6034. \begin{lstlisting}
  6035. start:
  6036. movq $1, %rbx
  6037. movq $42, -16(%rbp)
  6038. addq $7, %rbx
  6039. movq %rbx, %rcx
  6040. addq -16(%rbp), %rcx
  6041. negq %rbx
  6042. movq %rcx, %rax
  6043. addq %rbx, %rax
  6044. jmp conclusion
  6045. .globl main
  6046. main:
  6047. pushq %rbp
  6048. movq %rsp, %rbp
  6049. pushq %rbx
  6050. subq $8, %rsp
  6051. jmp start
  6052. conclusion:
  6053. addq $8, %rsp
  6054. popq %rbx
  6055. popq %rbp
  6056. retq
  6057. \end{lstlisting}
  6058. \fi}
  6059. {\if\edition\pythonEd
  6060. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6061. \begin{lstlisting}
  6062. .globl main
  6063. main:
  6064. pushq %rbp
  6065. movq %rsp, %rbp
  6066. pushq %rbx
  6067. subq $8, %rsp
  6068. movq $1, %rcx
  6069. movq $42, %rbx
  6070. addq $7, %rcx
  6071. movq %rcx, -16(%rbp)
  6072. addq %rbx, -16(%rbp)
  6073. negq %rcx
  6074. movq -16(%rbp), %rbx
  6075. addq %rcx, %rbx
  6076. movq %rbx, %rdi
  6077. callq print_int
  6078. addq $8, %rsp
  6079. popq %rbx
  6080. popq %rbp
  6081. retq
  6082. \end{lstlisting}
  6083. \fi}
  6084. \end{tcolorbox}
  6085. \end{minipage}
  6086. \caption{The x86 output from the running example
  6087. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6088. and \code{rcx}.}
  6089. \label{fig:running-example-x86}
  6090. \end{figure}
  6091. \begin{exercise}\normalfont\normalsize
  6092. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6093. %
  6094. \racket{
  6095. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6096. list of passes and the call to \code{compiler-tests}.}
  6097. %
  6098. Run the script to test the complete compiler for \LangVar{} that
  6099. performs register allocation.
  6100. \end{exercise}
  6101. \section{Challenge: Move Biasing}
  6102. \label{sec:move-biasing}
  6103. \index{subject}{move biasing}
  6104. This section describes an enhancement to the register allocator,
  6105. called move biasing, for students who are looking for an extra
  6106. challenge.
  6107. {\if\edition\racketEd
  6108. To motivate the need for move biasing we return to the running example,
  6109. but this time we use all the general purpose registers. So, we have
  6110. the following mapping of color numbers to registers.
  6111. \[
  6112. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6113. \]
  6114. Using the same assignment of variables to color numbers that was
  6115. produced by the register allocator described in the last section, we
  6116. get the following program.
  6117. \begin{center}
  6118. \begin{minipage}{0.3\textwidth}
  6119. \begin{lstlisting}
  6120. movq $1, v
  6121. movq $42, w
  6122. movq v, x
  6123. addq $7, x
  6124. movq x, y
  6125. movq x, z
  6126. addq w, z
  6127. movq y, t
  6128. negq t
  6129. movq z, %rax
  6130. addq t, %rax
  6131. jmp conclusion
  6132. \end{lstlisting}
  6133. \end{minipage}
  6134. $\Rightarrow\qquad$
  6135. \begin{minipage}{0.45\textwidth}
  6136. \begin{lstlisting}
  6137. movq $1, %rdx
  6138. movq $42, %rcx
  6139. movq %rdx, %rdx
  6140. addq $7, %rdx
  6141. movq %rdx, %rsi
  6142. movq %rdx, %rdx
  6143. addq %rcx, %rdx
  6144. movq %rsi, %rcx
  6145. negq %rcx
  6146. movq %rdx, %rax
  6147. addq %rcx, %rax
  6148. jmp conclusion
  6149. \end{lstlisting}
  6150. \end{minipage}
  6151. \end{center}
  6152. In this output code there are two \key{movq} instructions that
  6153. can be removed because their source and target are the same. However,
  6154. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6155. register, we could instead remove three \key{movq} instructions. We
  6156. can accomplish this by taking into account which variables appear in
  6157. \key{movq} instructions with which other variables.
  6158. \fi}
  6159. {\if\edition\pythonEd
  6160. %
  6161. To motivate the need for move biasing we return to the running example
  6162. and recall that in section~\ref{sec:patch-instructions} we were able to
  6163. remove three trivial move instructions from the running
  6164. example. However, we could remove another trivial move if we were able
  6165. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6166. We say that two variables $p$ and $q$ are \emph{move
  6167. related}\index{subject}{move related} if they participate together in
  6168. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6169. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  6170. if there are multiple variables with the same saturation, prefer
  6171. variables that can be assigned to a color that is the same as the
  6172. color of a move-related variable. Furthermore, when the register
  6173. allocator chooses a color for a variable, it should prefer a color
  6174. that has already been used for a move-related variable (assuming that
  6175. they do not interfere). Of course, this preference should not override
  6176. the preference for registers over stack locations. So, this preference
  6177. should be used as a tie breaker in choosing between registers and
  6178. in choosing between stack locations.
  6179. We recommend representing the move relationships in a graph, similarly
  6180. to how we represented interference. The following is the \emph{move
  6181. graph} for our running example.
  6182. {\if\edition\racketEd
  6183. \[
  6184. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6185. \node (rax) at (0,0) {$\ttm{rax}$};
  6186. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6187. \node (t) at (0,2) {$\ttm{t}$};
  6188. \node (z) at (3,2) {$\ttm{z}$};
  6189. \node (x) at (6,2) {$\ttm{x}$};
  6190. \node (y) at (3,0) {$\ttm{y}$};
  6191. \node (w) at (6,0) {$\ttm{w}$};
  6192. \node (v) at (9,0) {$\ttm{v}$};
  6193. \draw (v) to (x);
  6194. \draw (x) to (y);
  6195. \draw (x) to (z);
  6196. \draw (y) to (t);
  6197. \end{tikzpicture}
  6198. \]
  6199. \fi}
  6200. %
  6201. {\if\edition\pythonEd
  6202. \[
  6203. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6204. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6205. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6206. \node (z) at (3,2) {$\ttm{z}$};
  6207. \node (x) at (6,2) {$\ttm{x}$};
  6208. \node (y) at (3,0) {$\ttm{y}$};
  6209. \node (w) at (6,0) {$\ttm{w}$};
  6210. \node (v) at (9,0) {$\ttm{v}$};
  6211. \draw (y) to (t0);
  6212. \draw (z) to (x);
  6213. \draw (z) to (t1);
  6214. \draw (x) to (y);
  6215. \draw (x) to (v);
  6216. \end{tikzpicture}
  6217. \]
  6218. \fi}
  6219. {\if\edition\racketEd
  6220. Now we replay the graph coloring, pausing to see the coloring of
  6221. \code{y}. Recall the following configuration. The most saturated vertices
  6222. were \code{w} and \code{y}.
  6223. \[
  6224. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6225. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6226. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6227. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6228. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6229. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6230. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6231. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6232. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6233. \draw (t1) to (rax);
  6234. \draw (t1) to (z);
  6235. \draw (z) to (y);
  6236. \draw (z) to (w);
  6237. \draw (x) to (w);
  6238. \draw (y) to (w);
  6239. \draw (v) to (w);
  6240. \draw (v) to (rsp);
  6241. \draw (w) to (rsp);
  6242. \draw (x) to (rsp);
  6243. \draw (y) to (rsp);
  6244. \path[-.,bend left=15] (z) edge node {} (rsp);
  6245. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6246. \draw (rax) to (rsp);
  6247. \end{tikzpicture}
  6248. \]
  6249. %
  6250. The last time, we chose to color \code{w} with $0$. This time, we see
  6251. that \code{w} is not move-related to any vertex, but \code{y} is
  6252. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6253. the same color as \code{t}.
  6254. \[
  6255. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6256. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6257. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6258. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6259. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6260. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6261. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6262. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6263. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6264. \draw (t1) to (rax);
  6265. \draw (t1) to (z);
  6266. \draw (z) to (y);
  6267. \draw (z) to (w);
  6268. \draw (x) to (w);
  6269. \draw (y) to (w);
  6270. \draw (v) to (w);
  6271. \draw (v) to (rsp);
  6272. \draw (w) to (rsp);
  6273. \draw (x) to (rsp);
  6274. \draw (y) to (rsp);
  6275. \path[-.,bend left=15] (z) edge node {} (rsp);
  6276. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6277. \draw (rax) to (rsp);
  6278. \end{tikzpicture}
  6279. \]
  6280. Now \code{w} is the most saturated, so we color it $2$.
  6281. \[
  6282. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6283. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6284. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6285. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6286. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6287. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6288. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6289. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6290. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6291. \draw (t1) to (rax);
  6292. \draw (t1) to (z);
  6293. \draw (z) to (y);
  6294. \draw (z) to (w);
  6295. \draw (x) to (w);
  6296. \draw (y) to (w);
  6297. \draw (v) to (w);
  6298. \draw (v) to (rsp);
  6299. \draw (w) to (rsp);
  6300. \draw (x) to (rsp);
  6301. \draw (y) to (rsp);
  6302. \path[-.,bend left=15] (z) edge node {} (rsp);
  6303. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6304. \draw (rax) to (rsp);
  6305. \end{tikzpicture}
  6306. \]
  6307. At this point, vertices \code{x} and \code{v} are most saturated, but
  6308. \code{x} is move related to \code{y} and \code{z}, so we color
  6309. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6310. \[
  6311. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6312. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6313. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6314. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6315. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6316. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6317. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6318. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6319. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6320. \draw (t1) to (rax);
  6321. \draw (t) to (z);
  6322. \draw (z) to (y);
  6323. \draw (z) to (w);
  6324. \draw (x) to (w);
  6325. \draw (y) to (w);
  6326. \draw (v) to (w);
  6327. \draw (v) to (rsp);
  6328. \draw (w) to (rsp);
  6329. \draw (x) to (rsp);
  6330. \draw (y) to (rsp);
  6331. \path[-.,bend left=15] (z) edge node {} (rsp);
  6332. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6333. \draw (rax) to (rsp);
  6334. \end{tikzpicture}
  6335. \]
  6336. \fi}
  6337. %
  6338. {\if\edition\pythonEd
  6339. Now we replay the graph coloring, pausing before the coloring of
  6340. \code{w}. Recall the following configuration. The most saturated vertices
  6341. were \code{tmp\_1}, \code{w}, and \code{y}.
  6342. \[
  6343. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6344. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6345. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6346. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6347. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6348. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6349. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6350. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6351. \draw (t0) to (t1);
  6352. \draw (t0) to (z);
  6353. \draw (z) to (y);
  6354. \draw (z) to (w);
  6355. \draw (x) to (w);
  6356. \draw (y) to (w);
  6357. \draw (v) to (w);
  6358. \end{tikzpicture}
  6359. \]
  6360. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6361. or \code{y}, but note that \code{w} is not move related to any
  6362. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6363. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6364. \code{y} and color it $0$, we can delete another move instruction.
  6365. \[
  6366. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6367. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6368. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6369. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6370. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6371. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6372. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6373. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6374. \draw (t0) to (t1);
  6375. \draw (t0) to (z);
  6376. \draw (z) to (y);
  6377. \draw (z) to (w);
  6378. \draw (x) to (w);
  6379. \draw (y) to (w);
  6380. \draw (v) to (w);
  6381. \end{tikzpicture}
  6382. \]
  6383. Now \code{w} is the most saturated, so we color it $2$.
  6384. \[
  6385. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6386. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6387. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6388. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6389. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6390. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6391. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6392. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6393. \draw (t0) to (t1);
  6394. \draw (t0) to (z);
  6395. \draw (z) to (y);
  6396. \draw (z) to (w);
  6397. \draw (x) to (w);
  6398. \draw (y) to (w);
  6399. \draw (v) to (w);
  6400. \end{tikzpicture}
  6401. \]
  6402. To finish the coloring, \code{x} and \code{v} get $0$ and
  6403. \code{tmp\_1} gets $1$.
  6404. \[
  6405. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6406. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6407. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6408. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6409. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6410. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6411. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6412. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6413. \draw (t0) to (t1);
  6414. \draw (t0) to (z);
  6415. \draw (z) to (y);
  6416. \draw (z) to (w);
  6417. \draw (x) to (w);
  6418. \draw (y) to (w);
  6419. \draw (v) to (w);
  6420. \end{tikzpicture}
  6421. \]
  6422. \fi}
  6423. So, we have the following assignment of variables to registers.
  6424. {\if\edition\racketEd
  6425. \begin{gather*}
  6426. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6427. \ttm{w} \mapsto \key{\%rsi}, \,
  6428. \ttm{x} \mapsto \key{\%rcx}, \,
  6429. \ttm{y} \mapsto \key{\%rcx}, \,
  6430. \ttm{z} \mapsto \key{\%rdx}, \,
  6431. \ttm{t} \mapsto \key{\%rcx} \}
  6432. \end{gather*}
  6433. \fi}
  6434. {\if\edition\pythonEd
  6435. \begin{gather*}
  6436. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6437. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6438. \ttm{x} \mapsto \key{\%rcx}, \,
  6439. \ttm{y} \mapsto \key{\%rcx}, \\
  6440. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6441. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6442. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6443. \end{gather*}
  6444. \fi}
  6445. %
  6446. We apply this register assignment to the running example shown next,
  6447. on the left, to obtain the code in the middle. The
  6448. \code{patch\_instructions} then deletes the trivial moves to obtain
  6449. the code on the right.
  6450. {\if\edition\racketEd
  6451. \begin{minipage}{0.25\textwidth}
  6452. \begin{lstlisting}
  6453. movq $1, v
  6454. movq $42, w
  6455. movq v, x
  6456. addq $7, x
  6457. movq x, y
  6458. movq x, z
  6459. addq w, z
  6460. movq y, t
  6461. negq t
  6462. movq z, %rax
  6463. addq t, %rax
  6464. jmp conclusion
  6465. \end{lstlisting}
  6466. \end{minipage}
  6467. $\Rightarrow\qquad$
  6468. \begin{minipage}{0.25\textwidth}
  6469. \begin{lstlisting}
  6470. movq $1, %rcx
  6471. movq $42, %rsi
  6472. movq %rcx, %rcx
  6473. addq $7, %rcx
  6474. movq %rcx, %rcx
  6475. movq %rcx, %rdx
  6476. addq %rsi, %rdx
  6477. movq %rcx, %rcx
  6478. negq %rcx
  6479. movq %rdx, %rax
  6480. addq %rcx, %rax
  6481. jmp conclusion
  6482. \end{lstlisting}
  6483. \end{minipage}
  6484. $\Rightarrow\qquad$
  6485. \begin{minipage}{0.25\textwidth}
  6486. \begin{lstlisting}
  6487. movq $1, %rcx
  6488. movq $42, %rsi
  6489. addq $7, %rcx
  6490. movq %rcx, %rdx
  6491. addq %rsi, %rdx
  6492. negq %rcx
  6493. movq %rdx, %rax
  6494. addq %rcx, %rax
  6495. jmp conclusion
  6496. \end{lstlisting}
  6497. \end{minipage}
  6498. \fi}
  6499. {\if\edition\pythonEd
  6500. \begin{minipage}{0.20\textwidth}
  6501. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6502. movq $1, v
  6503. movq $42, w
  6504. movq v, x
  6505. addq $7, x
  6506. movq x, y
  6507. movq x, z
  6508. addq w, z
  6509. movq y, tmp_0
  6510. negq tmp_0
  6511. movq z, tmp_1
  6512. addq tmp_0, tmp_1
  6513. movq tmp_1, %rdi
  6514. callq _print_int
  6515. \end{lstlisting}
  6516. \end{minipage}
  6517. ${\Rightarrow\qquad}$
  6518. \begin{minipage}{0.30\textwidth}
  6519. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6520. movq $1, %rcx
  6521. movq $42, -16(%rbp)
  6522. movq %rcx, %rcx
  6523. addq $7, %rcx
  6524. movq %rcx, %rcx
  6525. movq %rcx, -8(%rbp)
  6526. addq -16(%rbp), -8(%rbp)
  6527. movq %rcx, %rcx
  6528. negq %rcx
  6529. movq -8(%rbp), -8(%rbp)
  6530. addq %rcx, -8(%rbp)
  6531. movq -8(%rbp), %rdi
  6532. callq _print_int
  6533. \end{lstlisting}
  6534. \end{minipage}
  6535. ${\Rightarrow\qquad}$
  6536. \begin{minipage}{0.20\textwidth}
  6537. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6538. movq $1, %rcx
  6539. movq $42, -16(%rbp)
  6540. addq $7, %rcx
  6541. movq %rcx, -8(%rbp)
  6542. movq -16(%rbp), %rax
  6543. addq %rax, -8(%rbp)
  6544. negq %rcx
  6545. addq %rcx, -8(%rbp)
  6546. movq -8(%rbp), %rdi
  6547. callq print_int
  6548. \end{lstlisting}
  6549. \end{minipage}
  6550. \fi}
  6551. \begin{exercise}\normalfont\normalsize
  6552. Change your implementation of \code{allocate\_registers} to take move
  6553. biasing into account. Create two new tests that include at least one
  6554. opportunity for move biasing, and visually inspect the output x86
  6555. programs to make sure that your move biasing is working properly. Make
  6556. sure that your compiler still passes all the tests.
  6557. \end{exercise}
  6558. %To do: another neat challenge would be to do
  6559. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6560. %% \subsection{Output of the Running Example}
  6561. %% \label{sec:reg-alloc-output}
  6562. % challenge: prioritize variables based on execution frequencies
  6563. % and the number of uses of a variable
  6564. % challenge: enhance the coloring algorithm using Chaitin's
  6565. % approach of prioritizing high-degree variables
  6566. % by removing low-degree variables (coloring them later)
  6567. % from the interference graph
  6568. \section{Further Reading}
  6569. \label{sec:register-allocation-further-reading}
  6570. Early register allocation algorithms were developed for Fortran
  6571. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6572. of graph coloring began in the late 1970s and early 1980s with the
  6573. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6574. algorithm is based on the following observation of
  6575. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6576. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6577. $v$ removed is also $k$ colorable. To see why, suppose that the
  6578. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6579. different colors, but because there are fewer than $k$ neighbors, there
  6580. will be one or more colors left over to use for coloring $v$ in $G$.
  6581. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6582. less than $k$ from the graph and recursively colors the rest of the
  6583. graph. Upon returning from the recursion, it colors $v$ with one of
  6584. the available colors and returns. \citet{Chaitin:1982vn} augments
  6585. this algorithm to handle spilling as follows. If there are no vertices
  6586. of degree lower than $k$ then pick a vertex at random, spill it,
  6587. remove it from the graph, and proceed recursively to color the rest of
  6588. the graph.
  6589. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6590. move-related and that don't interfere with each other, in a process
  6591. called \emph{coalescing}. Although coalescing decreases the number of
  6592. moves, it can make the graph more difficult to
  6593. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6594. which two variables are merged only if they have fewer than $k$
  6595. neighbors of high degree. \citet{George:1996aa} observed that
  6596. conservative coalescing is sometimes too conservative and made it more
  6597. aggressive by iterating the coalescing with the removal of low-degree
  6598. vertices.
  6599. %
  6600. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6601. also proposed \emph{biased coloring}, in which a variable is assigned to
  6602. the same color as another move-related variable if possible, as
  6603. discussed in section~\ref{sec:move-biasing}.
  6604. %
  6605. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6606. performs coalescing, graph coloring, and spill code insertion until
  6607. all variables have been assigned a location.
  6608. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6609. spilled variables that don't have to be: a high-degree variable can be
  6610. colorable if many of its neighbors are assigned the same color.
  6611. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6612. high-degree vertex is not immediately spilled. Instead the decision is
  6613. deferred until after the recursive call, at which point it is apparent
  6614. whether there is actually an available color or not. We observe that
  6615. this algorithm is equivalent to the smallest-last ordering
  6616. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6617. be registers and the rest to be stack locations.
  6618. %% biased coloring
  6619. Earlier editions of the compiler course at Indiana University
  6620. \citep{Dybvig:2010aa} were based on the algorithm of
  6621. \citet{Briggs:1994kx}.
  6622. The smallest-last ordering algorithm is one of many \emph{greedy}
  6623. coloring algorithms. A greedy coloring algorithm visits all the
  6624. vertices in a particular order and assigns each one the first
  6625. available color. An \emph{offline} greedy algorithm chooses the
  6626. ordering up front, prior to assigning colors. The algorithm of
  6627. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6628. ordering does not depend on the colors assigned. Other orderings are
  6629. possible. For example, \citet{Chow:1984ys} ordered variables according
  6630. to an estimate of runtime cost.
  6631. An \emph{online} greedy coloring algorithm uses information about the
  6632. current assignment of colors to influence the order in which the
  6633. remaining vertices are colored. The saturation-based algorithm
  6634. described in this chapter is one such algorithm. We choose to use
  6635. saturation-based coloring because it is fun to introduce graph
  6636. coloring via sudoku!
  6637. A register allocator may choose to map each variable to just one
  6638. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6639. variable to one or more locations. The latter can be achieved by
  6640. \emph{live range splitting}, where a variable is replaced by several
  6641. variables that each handle part of its live
  6642. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6643. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6644. %% replacement algorithm, bottom-up local
  6645. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6646. %% Cooper: top-down (priority bassed), bottom-up
  6647. %% top-down
  6648. %% order variables by priority (estimated cost)
  6649. %% caveat: split variables into two groups:
  6650. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6651. %% color the constrained ones first
  6652. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6653. %% cite J. Cocke for an algorithm that colors variables
  6654. %% in a high-degree first ordering
  6655. %Register Allocation via Usage Counts, Freiburghouse CACM
  6656. \citet{Palsberg:2007si} observed that many of the interference graphs
  6657. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6658. that is, every cycle with four or more edges has an edge that is not
  6659. part of the cycle but that connects two vertices on the cycle. Such
  6660. graphs can be optimally colored by the greedy algorithm with a vertex
  6661. ordering determined by maximum cardinality search.
  6662. In situations in which compile time is of utmost importance, such as
  6663. in just-in-time compilers, graph coloring algorithms can be too
  6664. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6665. be more appropriate.
  6666. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6667. \chapter{Booleans and Conditionals}
  6668. \label{ch:Lif}
  6669. \index{subject}{Boolean}
  6670. \index{subject}{control flow}
  6671. \index{subject}{conditional expression}
  6672. \setcounter{footnote}{0}
  6673. The \LangVar{} language has only a single kind of value, the
  6674. integers. In this chapter we add a second kind of value, the Booleans,
  6675. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6676. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6677. and \FALSE{}, respectively. The \LangIf{} language includes several
  6678. operations that involve Booleans (\key{and}, \key{not},
  6679. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6680. expression \python{and statement}. With the addition of \key{if},
  6681. programs can have nontrivial control flow which
  6682. %
  6683. \racket{impacts \code{explicate\_control} and liveness analysis}
  6684. %
  6685. \python{impacts liveness analysis and motivates a new pass named
  6686. \code{explicate\_control}}.
  6687. %
  6688. Also, because we now have two kinds of values, we need to handle
  6689. programs that apply an operation to the wrong kind of value, such as
  6690. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6691. There are two language design options for such situations. One option
  6692. is to signal an error and the other is to provide a wider
  6693. interpretation of the operation. \racket{The Racket
  6694. language}\python{Python} uses a mixture of these two options,
  6695. depending on the operation and the kind of value. For example, the
  6696. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6697. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6698. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6699. %
  6700. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6701. in Racket because \code{car} expects a pair.}
  6702. %
  6703. \python{On the other hand, \code{1[0]} results in a runtime error
  6704. in Python because an ``\code{int} object is not subscriptable''.}
  6705. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6706. design choices as \racket{Racket}\python{Python}, except that much of the
  6707. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6708. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6709. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6710. \python{MyPy} reports a compile-time error
  6711. %
  6712. \racket{because Racket expects the type of the argument to be of the form
  6713. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6714. %
  6715. \python{stating that a ``value of type \code{int} is not indexable''.}
  6716. The \LangIf{} language performs type checking during compilation just as
  6717. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6718. the alternative choice, that is, a dynamically typed language like
  6719. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6720. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6721. restrictive, for example, rejecting \racket{\code{(not
  6722. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6723. fairly simple because the focus of this book is on compilation and not
  6724. type systems, about which there are already several excellent
  6725. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6726. This chapter is organized as follows. We begin by defining the syntax
  6727. and interpreter for the \LangIf{} language
  6728. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6729. checking and define a type checker for \LangIf{}
  6730. (section~\ref{sec:type-check-Lif}).
  6731. %
  6732. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6733. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6734. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6735. %
  6736. The remaining sections of this chapter discuss how Booleans and
  6737. conditional control flow require changes to the existing compiler
  6738. passes and the addition of new ones. We introduce the \code{shrink}
  6739. pass to translate some operators into others, thereby reducing the
  6740. number of operators that need to be handled in later passes.
  6741. %
  6742. The main event of this chapter is the \code{explicate\_control} pass
  6743. that is responsible for translating \code{if}s into conditional
  6744. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6745. %
  6746. Regarding register allocation, there is the interesting question of
  6747. how to handle conditional \code{goto}s during liveness analysis.
  6748. \section{The \LangIf{} Language}
  6749. \label{sec:lang-if}
  6750. Definitions of the concrete syntax and abstract syntax of the
  6751. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  6752. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6753. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6754. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6755. %
  6756. \python{, and the \code{if} statement}. We expand the set of
  6757. operators to include
  6758. \begin{enumerate}
  6759. \item the logical operators \key{and}, \key{or}, and \key{not},
  6760. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6761. for comparing integers or Booleans for equality, and
  6762. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6763. comparing integers.
  6764. \end{enumerate}
  6765. \racket{We reorganize the abstract syntax for the primitive
  6766. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  6767. rule for all of them. This means that the grammar no longer checks
  6768. whether the arity of an operators matches the number of
  6769. arguments. That responsibility is moved to the type checker for
  6770. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6771. \newcommand{\LifGrammarRacket}{
  6772. \begin{array}{lcl}
  6773. \Type &::=& \key{Boolean} \\
  6774. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6775. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6776. \Exp &::=& \itm{bool}
  6777. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6778. \MID (\key{not}\;\Exp) \\
  6779. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6780. \end{array}
  6781. }
  6782. \newcommand{\LifASTRacket}{
  6783. \begin{array}{lcl}
  6784. \Type &::=& \key{Boolean} \\
  6785. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6786. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6787. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6788. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6789. \end{array}
  6790. }
  6791. \newcommand{\LintOpAST}{
  6792. \begin{array}{rcl}
  6793. \Type &::=& \key{Integer} \\
  6794. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6795. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6796. \end{array}
  6797. }
  6798. \newcommand{\LifGrammarPython}{
  6799. \begin{array}{rcl}
  6800. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6801. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6802. \MID \key{not}~\Exp \\
  6803. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6804. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6805. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6806. \end{array}
  6807. }
  6808. \newcommand{\LifASTPython}{
  6809. \begin{array}{lcl}
  6810. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6811. \itm{unaryop} &::=& \code{Not()} \\
  6812. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6813. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6814. \Exp &::=& \BOOL{\itm{bool}}
  6815. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6816. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6817. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6818. \end{array}
  6819. }
  6820. \begin{figure}[tp]
  6821. \centering
  6822. \begin{tcolorbox}[colback=white]
  6823. {\if\edition\racketEd
  6824. \[
  6825. \begin{array}{l}
  6826. \gray{\LintGrammarRacket{}} \\ \hline
  6827. \gray{\LvarGrammarRacket{}} \\ \hline
  6828. \LifGrammarRacket{} \\
  6829. \begin{array}{lcl}
  6830. \LangIfM{} &::=& \Exp
  6831. \end{array}
  6832. \end{array}
  6833. \]
  6834. \fi}
  6835. {\if\edition\pythonEd
  6836. \[
  6837. \begin{array}{l}
  6838. \gray{\LintGrammarPython} \\ \hline
  6839. \gray{\LvarGrammarPython} \\ \hline
  6840. \LifGrammarPython \\
  6841. \begin{array}{rcl}
  6842. \LangIfM{} &::=& \Stmt^{*}
  6843. \end{array}
  6844. \end{array}
  6845. \]
  6846. \fi}
  6847. \end{tcolorbox}
  6848. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6849. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6850. \label{fig:Lif-concrete-syntax}
  6851. \end{figure}
  6852. \begin{figure}[tp]
  6853. %\begin{minipage}{0.66\textwidth}
  6854. \begin{tcolorbox}[colback=white]
  6855. \centering
  6856. {\if\edition\racketEd
  6857. \[
  6858. \begin{array}{l}
  6859. \gray{\LintOpAST} \\ \hline
  6860. \gray{\LvarASTRacket{}} \\ \hline
  6861. \LifASTRacket{} \\
  6862. \begin{array}{lcl}
  6863. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6864. \end{array}
  6865. \end{array}
  6866. \]
  6867. \fi}
  6868. {\if\edition\pythonEd
  6869. \[
  6870. \begin{array}{l}
  6871. \gray{\LintASTPython} \\ \hline
  6872. \gray{\LvarASTPython} \\ \hline
  6873. \LifASTPython \\
  6874. \begin{array}{lcl}
  6875. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6876. \end{array}
  6877. \end{array}
  6878. \]
  6879. \fi}
  6880. \end{tcolorbox}
  6881. %\end{minipage}
  6882. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  6883. \index{subject}{IfExp@\IFNAME{}}
  6884. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  6885. \index{subject}{and@\ANDNAME{}}
  6886. \index{subject}{or@\ORNAME{}}
  6887. \index{subject}{not@\NOTNAME{}}
  6888. \index{subject}{equal@\EQNAME{}}
  6889. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  6890. \racket{
  6891. \index{subject}{lessthan@\texttt{<}}
  6892. \index{subject}{lessthaneq@\texttt{<=}}
  6893. \index{subject}{greaterthan@\texttt{>}}
  6894. \index{subject}{greaterthaneq@\texttt{>=}}
  6895. }
  6896. \python{
  6897. \index{subject}{BoolOp@\texttt{BoolOp}}
  6898. \index{subject}{Compare@\texttt{Compare}}
  6899. \index{subject}{Lt@\texttt{Lt}}
  6900. \index{subject}{LtE@\texttt{LtE}}
  6901. \index{subject}{Gt@\texttt{Gt}}
  6902. \index{subject}{GtE@\texttt{GtE}}
  6903. }
  6904. \caption{The abstract syntax of \LangIf{}.}
  6905. \label{fig:Lif-syntax}
  6906. \end{figure}
  6907. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  6908. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  6909. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6910. evaluate to the corresponding Boolean values. The conditional
  6911. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  6912. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  6913. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  6914. \code{or}, and \code{not} behave according to propositional logic. In
  6915. addition, the \code{and} and \code{or} operations perform
  6916. \emph{short-circuit evaluation}.
  6917. %
  6918. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6919. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6920. %
  6921. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6922. evaluated if $e_1$ evaluates to \TRUE{}.
  6923. \racket{With the increase in the number of primitive operations, the
  6924. interpreter would become repetitive without some care. We refactor
  6925. the case for \code{Prim}, moving the code that differs with each
  6926. operation into the \code{interp\_op} method shown in
  6927. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6928. \code{or} operations separately because of their short-circuiting
  6929. behavior.}
  6930. \begin{figure}[tbp]
  6931. \begin{tcolorbox}[colback=white]
  6932. {\if\edition\racketEd
  6933. \begin{lstlisting}
  6934. (define interp-Lif-class
  6935. (class interp-Lvar-class
  6936. (super-new)
  6937. (define/public (interp_op op) ...)
  6938. (define/override ((interp_exp env) e)
  6939. (define recur (interp_exp env))
  6940. (match e
  6941. [(Bool b) b]
  6942. [(If cnd thn els)
  6943. (match (recur cnd)
  6944. [#t (recur thn)]
  6945. [#f (recur els)])]
  6946. [(Prim 'and (list e1 e2))
  6947. (match (recur e1)
  6948. [#t (match (recur e2) [#t #t] [#f #f])]
  6949. [#f #f])]
  6950. [(Prim 'or (list e1 e2))
  6951. (define v1 (recur e1))
  6952. (match v1
  6953. [#t #t]
  6954. [#f (match (recur e2) [#t #t] [#f #f])])]
  6955. [(Prim op args)
  6956. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6957. [else ((super interp_exp env) e)]))
  6958. ))
  6959. (define (interp_Lif p)
  6960. (send (new interp-Lif-class) interp_program p))
  6961. \end{lstlisting}
  6962. \fi}
  6963. {\if\edition\pythonEd
  6964. \begin{lstlisting}
  6965. class InterpLif(InterpLvar):
  6966. def interp_exp(self, e, env):
  6967. match e:
  6968. case IfExp(test, body, orelse):
  6969. if self.interp_exp(test, env):
  6970. return self.interp_exp(body, env)
  6971. else:
  6972. return self.interp_exp(orelse, env)
  6973. case UnaryOp(Not(), v):
  6974. return not self.interp_exp(v, env)
  6975. case BoolOp(And(), values):
  6976. if self.interp_exp(values[0], env):
  6977. return self.interp_exp(values[1], env)
  6978. else:
  6979. return False
  6980. case BoolOp(Or(), values):
  6981. if self.interp_exp(values[0], env):
  6982. return True
  6983. else:
  6984. return self.interp_exp(values[1], env)
  6985. case Compare(left, [cmp], [right]):
  6986. l = self.interp_exp(left, env)
  6987. r = self.interp_exp(right, env)
  6988. return self.interp_cmp(cmp)(l, r)
  6989. case _:
  6990. return super().interp_exp(e, env)
  6991. def interp_stmts(self, ss, env):
  6992. if len(ss) == 0:
  6993. return
  6994. match ss[0]:
  6995. case If(test, body, orelse):
  6996. if self.interp_exp(test, env):
  6997. return self.interp_stmts(body + ss[1:], env)
  6998. else:
  6999. return self.interp_stmts(orelse + ss[1:], env)
  7000. case _:
  7001. return super().interp_stmts(ss, env)
  7002. ...
  7003. \end{lstlisting}
  7004. \fi}
  7005. \end{tcolorbox}
  7006. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7007. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7008. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7009. \label{fig:interp-Lif}
  7010. \end{figure}
  7011. {\if\edition\racketEd
  7012. \begin{figure}[tbp]
  7013. \begin{tcolorbox}[colback=white]
  7014. \begin{lstlisting}
  7015. (define/public (interp_op op)
  7016. (match op
  7017. ['+ fx+]
  7018. ['- fx-]
  7019. ['read read-fixnum]
  7020. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7021. ['eq? (lambda (v1 v2)
  7022. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7023. (and (boolean? v1) (boolean? v2))
  7024. (and (vector? v1) (vector? v2)))
  7025. (eq? v1 v2)]))]
  7026. ['< (lambda (v1 v2)
  7027. (cond [(and (fixnum? v1) (fixnum? v2))
  7028. (< v1 v2)]))]
  7029. ['<= (lambda (v1 v2)
  7030. (cond [(and (fixnum? v1) (fixnum? v2))
  7031. (<= v1 v2)]))]
  7032. ['> (lambda (v1 v2)
  7033. (cond [(and (fixnum? v1) (fixnum? v2))
  7034. (> v1 v2)]))]
  7035. ['>= (lambda (v1 v2)
  7036. (cond [(and (fixnum? v1) (fixnum? v2))
  7037. (>= v1 v2)]))]
  7038. [else (error 'interp_op "unknown operator")]))
  7039. \end{lstlisting}
  7040. \end{tcolorbox}
  7041. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7042. \label{fig:interp-op-Lif}
  7043. \end{figure}
  7044. \fi}
  7045. {\if\edition\pythonEd
  7046. \begin{figure}
  7047. \begin{tcolorbox}[colback=white]
  7048. \begin{lstlisting}
  7049. class InterpLif(InterpLvar):
  7050. ...
  7051. def interp_cmp(self, cmp):
  7052. match cmp:
  7053. case Lt():
  7054. return lambda x, y: x < y
  7055. case LtE():
  7056. return lambda x, y: x <= y
  7057. case Gt():
  7058. return lambda x, y: x > y
  7059. case GtE():
  7060. return lambda x, y: x >= y
  7061. case Eq():
  7062. return lambda x, y: x == y
  7063. case NotEq():
  7064. return lambda x, y: x != y
  7065. \end{lstlisting}
  7066. \end{tcolorbox}
  7067. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7068. \label{fig:interp-cmp-Lif}
  7069. \end{figure}
  7070. \fi}
  7071. \section{Type Checking \LangIf{} Programs}
  7072. \label{sec:type-check-Lif}
  7073. \index{subject}{type checking}
  7074. \index{subject}{semantic analysis}
  7075. It is helpful to think about type checking in two complementary
  7076. ways. A type checker predicts the type of value that will be produced
  7077. by each expression in the program. For \LangIf{}, we have just two types,
  7078. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  7079. {\if\edition\racketEd
  7080. \begin{lstlisting}
  7081. (+ 10 (- (+ 12 20)))
  7082. \end{lstlisting}
  7083. \fi}
  7084. {\if\edition\pythonEd
  7085. \begin{lstlisting}
  7086. 10 + -(12 + 20)
  7087. \end{lstlisting}
  7088. \fi}
  7089. \noindent produces a value of type \INTTY{}, whereas
  7090. {\if\edition\racketEd
  7091. \begin{lstlisting}
  7092. (and (not #f) #t)
  7093. \end{lstlisting}
  7094. \fi}
  7095. {\if\edition\pythonEd
  7096. \begin{lstlisting}
  7097. (not False) and True
  7098. \end{lstlisting}
  7099. \fi}
  7100. \noindent produces a value of type \BOOLTY{}.
  7101. A second way to think about type checking is that it enforces a set of
  7102. rules about which operators can be applied to which kinds of
  7103. values. For example, our type checker for \LangIf{} signals an error
  7104. for the following expression:
  7105. %
  7106. {\if\edition\racketEd
  7107. \begin{lstlisting}
  7108. (not (+ 10 (- (+ 12 20))))
  7109. \end{lstlisting}
  7110. \fi}
  7111. {\if\edition\pythonEd
  7112. \begin{lstlisting}
  7113. not (10 + -(12 + 20))
  7114. \end{lstlisting}
  7115. \fi}
  7116. \noindent The subexpression
  7117. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7118. \python{\code{(10 + -(12 + 20))}}
  7119. has type \INTTY{}, but the type checker enforces the rule that the
  7120. argument of \code{not} must be an expression of type \BOOLTY{}.
  7121. We implement type checking using classes and methods because they
  7122. provide the open recursion needed to reuse code as we extend the type
  7123. checker in subsequent chapters, analogous to the use of classes and methods
  7124. for the interpreters (section~\ref{sec:extensible-interp}).
  7125. We separate the type checker for the \LangVar{} subset into its own
  7126. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7127. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7128. from the type checker for \LangVar{}. These type checkers are in the
  7129. files
  7130. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7131. and
  7132. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7133. of the support code.
  7134. %
  7135. Each type checker is a structurally recursive function over the AST.
  7136. Given an input expression \code{e}, the type checker either signals an
  7137. error or returns \racket{an expression and} its type.
  7138. %
  7139. \racket{It returns an expression because there are situations in which
  7140. we want to change or update the expression.}
  7141. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7142. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7143. constant is \INTTY{}. To handle variables, the type checker uses the
  7144. environment \code{env} to map variables to types.
  7145. %
  7146. \racket{Consider the case for \key{let}. We type check the
  7147. initializing expression to obtain its type \key{T} and then
  7148. associate type \code{T} with the variable \code{x} in the
  7149. environment used to type check the body of the \key{let}. Thus,
  7150. when the type checker encounters a use of variable \code{x}, it can
  7151. find its type in the environment.}
  7152. %
  7153. \python{Consider the case for assignment. We type check the
  7154. initializing expression to obtain its type \key{t}. If the variable
  7155. \code{lhs.id} is already in the environment because there was a
  7156. prior assignment, we check that this initializer has the same type
  7157. as the prior one. If this is the first assignment to the variable,
  7158. we associate type \code{t} with the variable \code{lhs.id} in the
  7159. environment. Thus, when the type checker encounters a use of
  7160. variable \code{x}, it can find its type in the environment.}
  7161. %
  7162. \racket{Regarding primitive operators, we recursively analyze the
  7163. arguments and then invoke \code{type\_check\_op} to check whether
  7164. the argument types are allowed.}
  7165. %
  7166. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7167. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7168. \racket{Several auxiliary methods are used in the type checker. The
  7169. method \code{operator-types} defines a dictionary that maps the
  7170. operator names to their parameter and return types. The
  7171. \code{type-equal?} method determines whether two types are equal,
  7172. which for now simply dispatches to \code{equal?} (deep
  7173. equality). The \code{check-type-equal?} method triggers an error if
  7174. the two types are not equal. The \code{type-check-op} method looks
  7175. up the operator in the \code{operator-types} dictionary and then
  7176. checks whether the argument types are equal to the parameter types.
  7177. The result is the return type of the operator.}
  7178. %
  7179. \python{The auxiliary method \code{check\_type\_equal} triggers
  7180. an error if the two types are not equal.}
  7181. \begin{figure}[tbp]
  7182. \begin{tcolorbox}[colback=white]
  7183. {\if\edition\racketEd
  7184. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7185. (define type-check-Lvar-class
  7186. (class object%
  7187. (super-new)
  7188. (define/public (operator-types)
  7189. '((+ . ((Integer Integer) . Integer))
  7190. (- . ((Integer Integer) . Integer))
  7191. (read . (() . Integer))))
  7192. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7193. (define/public (check-type-equal? t1 t2 e)
  7194. (unless (type-equal? t1 t2)
  7195. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7196. (define/public (type-check-op op arg-types e)
  7197. (match (dict-ref (operator-types) op)
  7198. [`(,param-types . ,return-type)
  7199. (for ([at arg-types] [pt param-types])
  7200. (check-type-equal? at pt e))
  7201. return-type]
  7202. [else (error 'type-check-op "unrecognized ~a" op)]))
  7203. (define/public (type-check-exp env)
  7204. (lambda (e)
  7205. (match e
  7206. [(Int n) (values (Int n) 'Integer)]
  7207. [(Var x) (values (Var x) (dict-ref env x))]
  7208. [(Let x e body)
  7209. (define-values (e^ Te) ((type-check-exp env) e))
  7210. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7211. (values (Let x e^ b) Tb)]
  7212. [(Prim op es)
  7213. (define-values (new-es ts)
  7214. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7215. (values (Prim op new-es) (type-check-op op ts e))]
  7216. [else (error 'type-check-exp "couldn't match" e)])))
  7217. (define/public (type-check-program e)
  7218. (match e
  7219. [(Program info body)
  7220. (define-values (body^ Tb) ((type-check-exp '()) body))
  7221. (check-type-equal? Tb 'Integer body)
  7222. (Program info body^)]
  7223. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7224. ))
  7225. (define (type-check-Lvar p)
  7226. (send (new type-check-Lvar-class) type-check-program p))
  7227. \end{lstlisting}
  7228. \fi}
  7229. {\if\edition\pythonEd
  7230. \begin{lstlisting}[escapechar=`]
  7231. class TypeCheckLvar:
  7232. def check_type_equal(self, t1, t2, e):
  7233. if t1 != t2:
  7234. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7235. raise Exception(msg)
  7236. def type_check_exp(self, e, env):
  7237. match e:
  7238. case BinOp(left, (Add() | Sub()), right):
  7239. l = self.type_check_exp(left, env)
  7240. check_type_equal(l, int, left)
  7241. r = self.type_check_exp(right, env)
  7242. check_type_equal(r, int, right)
  7243. return int
  7244. case UnaryOp(USub(), v):
  7245. t = self.type_check_exp(v, env)
  7246. check_type_equal(t, int, v)
  7247. return int
  7248. case Name(id):
  7249. return env[id]
  7250. case Constant(value) if isinstance(value, int):
  7251. return int
  7252. case Call(Name('input_int'), []):
  7253. return int
  7254. def type_check_stmts(self, ss, env):
  7255. if len(ss) == 0:
  7256. return
  7257. match ss[0]:
  7258. case Assign([lhs], value):
  7259. t = self.type_check_exp(value, env)
  7260. if lhs.id in env:
  7261. check_type_equal(env[lhs.id], t, value)
  7262. else:
  7263. env[lhs.id] = t
  7264. return self.type_check_stmts(ss[1:], env)
  7265. case Expr(Call(Name('print'), [arg])):
  7266. t = self.type_check_exp(arg, env)
  7267. check_type_equal(t, int, arg)
  7268. return self.type_check_stmts(ss[1:], env)
  7269. case Expr(value):
  7270. self.type_check_exp(value, env)
  7271. return self.type_check_stmts(ss[1:], env)
  7272. def type_check_P(self, p):
  7273. match p:
  7274. case Module(body):
  7275. self.type_check_stmts(body, {})
  7276. \end{lstlisting}
  7277. \fi}
  7278. \end{tcolorbox}
  7279. \caption{Type checker for the \LangVar{} language.}
  7280. \label{fig:type-check-Lvar}
  7281. \end{figure}
  7282. \begin{figure}[tbp]
  7283. \begin{tcolorbox}[colback=white]
  7284. {\if\edition\racketEd
  7285. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7286. (define type-check-Lif-class
  7287. (class type-check-Lvar-class
  7288. (super-new)
  7289. (inherit check-type-equal?)
  7290. (define/override (operator-types)
  7291. (append '((and . ((Boolean Boolean) . Boolean))
  7292. (or . ((Boolean Boolean) . Boolean))
  7293. (< . ((Integer Integer) . Boolean))
  7294. (<= . ((Integer Integer) . Boolean))
  7295. (> . ((Integer Integer) . Boolean))
  7296. (>= . ((Integer Integer) . Boolean))
  7297. (not . ((Boolean) . Boolean)))
  7298. (super operator-types)))
  7299. (define/override (type-check-exp env)
  7300. (lambda (e)
  7301. (match e
  7302. [(Bool b) (values (Bool b) 'Boolean)]
  7303. [(Prim 'eq? (list e1 e2))
  7304. (define-values (e1^ T1) ((type-check-exp env) e1))
  7305. (define-values (e2^ T2) ((type-check-exp env) e2))
  7306. (check-type-equal? T1 T2 e)
  7307. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7308. [(If cnd thn els)
  7309. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7310. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7311. (define-values (els^ Te) ((type-check-exp env) els))
  7312. (check-type-equal? Tc 'Boolean e)
  7313. (check-type-equal? Tt Te e)
  7314. (values (If cnd^ thn^ els^) Te)]
  7315. [else ((super type-check-exp env) e)])))
  7316. ))
  7317. (define (type-check-Lif p)
  7318. (send (new type-check-Lif-class) type-check-program p))
  7319. \end{lstlisting}
  7320. \fi}
  7321. {\if\edition\pythonEd
  7322. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7323. class TypeCheckLif(TypeCheckLvar):
  7324. def type_check_exp(self, e, env):
  7325. match e:
  7326. case Constant(value) if isinstance(value, bool):
  7327. return bool
  7328. case BinOp(left, Sub(), right):
  7329. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7330. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7331. return int
  7332. case UnaryOp(Not(), v):
  7333. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7334. return bool
  7335. case BoolOp(op, values):
  7336. left = values[0] ; right = values[1]
  7337. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7338. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7339. return bool
  7340. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7341. or isinstance(cmp, NotEq):
  7342. l = self.type_check_exp(left, env)
  7343. r = self.type_check_exp(right, env)
  7344. check_type_equal(l, r, e)
  7345. return bool
  7346. case Compare(left, [cmp], [right]):
  7347. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7348. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7349. return bool
  7350. case IfExp(test, body, orelse):
  7351. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7352. b = self.type_check_exp(body, env)
  7353. o = self.type_check_exp(orelse, env)
  7354. check_type_equal(b, o, e)
  7355. return b
  7356. case _:
  7357. return super().type_check_exp(e, env)
  7358. def type_check_stmts(self, ss, env):
  7359. if len(ss) == 0:
  7360. return
  7361. match ss[0]:
  7362. case If(test, body, orelse):
  7363. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7364. b = self.type_check_stmts(body, env)
  7365. o = self.type_check_stmts(orelse, env)
  7366. check_type_equal(b, o, ss[0])
  7367. return self.type_check_stmts(ss[1:], env)
  7368. case _:
  7369. return super().type_check_stmts(ss, env)
  7370. \end{lstlisting}
  7371. \fi}
  7372. \end{tcolorbox}
  7373. \caption{Type checker for the \LangIf{} language.}
  7374. \label{fig:type-check-Lif}
  7375. \end{figure}
  7376. The definition of the type checker for \LangIf{} is shown in
  7377. figure~\ref{fig:type-check-Lif}.
  7378. %
  7379. The type of a Boolean constant is \BOOLTY{}.
  7380. %
  7381. \racket{The \code{operator-types} function adds dictionary entries for
  7382. the new operators.}
  7383. %
  7384. \python{Logical not requires its argument to be a \BOOLTY{} and
  7385. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  7386. %
  7387. The equality operator requires the two arguments to have the same type,
  7388. and therefore we handle it separately from the other operators.
  7389. %
  7390. \python{The other comparisons (less-than, etc.) require their
  7391. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  7392. %
  7393. The condition of an \code{if} must
  7394. be of \BOOLTY{} type, and the two branches must have the same type.
  7395. \begin{exercise}\normalfont\normalsize
  7396. Create ten new test programs in \LangIf{}. Half the programs should
  7397. have a type error. For those programs, create an empty file with the
  7398. same base name and with file extension \code{.tyerr}. For example, if
  7399. the test
  7400. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7401. is expected to error, then create
  7402. an empty file named \code{cond\_test\_14.tyerr}.
  7403. %
  7404. \racket{This indicates to \code{interp-tests} and
  7405. \code{compiler-tests} that a type error is expected. }
  7406. %
  7407. The other half of the test programs should not have type errors.
  7408. %
  7409. \racket{In the \code{run-tests.rkt} script, change the second argument
  7410. of \code{interp-tests} and \code{compiler-tests} to
  7411. \code{type-check-Lif}, which causes the type checker to run prior to
  7412. the compiler passes. Temporarily change the \code{passes} to an
  7413. empty list and run the script, thereby checking that the new test
  7414. programs either type check or do not, as intended.}
  7415. %
  7416. Run the test script to check that these test programs type check as
  7417. expected.
  7418. \end{exercise}
  7419. \clearpage
  7420. \section{The \LangCIf{} Intermediate Language}
  7421. \label{sec:Cif}
  7422. {\if\edition\racketEd
  7423. %
  7424. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7425. comparison operators to the \Exp{} nonterminal and the literals
  7426. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7427. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7428. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7429. comparison operation and the branches are \code{goto} statements,
  7430. making it straightforward to compile \code{if} statements to x86. The
  7431. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7432. expressions. A \code{goto} statement transfers control to the $\Tail$
  7433. expression corresponding to its label.
  7434. %
  7435. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7436. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7437. defines its abstract syntax.
  7438. %
  7439. \fi}
  7440. %
  7441. {\if\edition\pythonEd
  7442. %
  7443. The output of \key{explicate\_control} is a language similar to the
  7444. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7445. \code{goto} statements, so we name it \LangCIf{}.
  7446. %
  7447. The \LangCIf{} language supports the same operators as \LangIf{} but
  7448. the arguments of operators are restricted to atomic expressions. The
  7449. \LangCIf{} language does not include \code{if} expressions but it does
  7450. include a restricted form of \code{if} statement. The condition must be
  7451. a comparison and the two branches may only contain \code{goto}
  7452. statements. These restrictions make it easier to translate \code{if}
  7453. statements to x86. The \LangCIf{} language also adds a \code{return}
  7454. statement to finish the program with a specified value.
  7455. %
  7456. The \key{CProgram} construct contains a dictionary mapping labels to
  7457. lists of statements that end with a \code{return} statement, a
  7458. \code{goto}, or a conditional \code{goto}.
  7459. %% Statement lists of this
  7460. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  7461. %% is a control transfer at the end and control only enters at the
  7462. %% beginning of the list, which is marked by the label.
  7463. %
  7464. A \code{goto} statement transfers control to the sequence of statements
  7465. associated with its label.
  7466. %
  7467. The concrete syntax for \LangCIf{} is defined in
  7468. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  7469. in figure~\ref{fig:c1-syntax}.
  7470. %
  7471. \fi}
  7472. %
  7473. \newcommand{\CifGrammarRacket}{
  7474. \begin{array}{lcl}
  7475. \Atm &::=& \itm{bool} \\
  7476. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7477. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7478. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7479. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7480. \end{array}
  7481. }
  7482. \newcommand{\CifASTRacket}{
  7483. \begin{array}{lcl}
  7484. \Atm &::=& \BOOL{\itm{bool}} \\
  7485. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7486. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7487. \Tail &::= & \GOTO{\itm{label}} \\
  7488. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7489. \end{array}
  7490. }
  7491. \newcommand{\CifGrammarPython}{
  7492. \begin{array}{lcl}
  7493. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7494. \Exp &::= & \Atm \MID \CREAD{}
  7495. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7496. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7497. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7498. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  7499. &\MID& \CASSIGN{\Var}{\Exp}
  7500. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7501. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7502. \end{array}
  7503. }
  7504. \newcommand{\CifASTPython}{
  7505. \begin{array}{lcl}
  7506. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7507. \Exp &::= & \Atm \MID \READ{} \\
  7508. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7509. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7510. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7511. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7512. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  7513. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7514. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7515. \end{array}
  7516. }
  7517. \begin{figure}[tbp]
  7518. \begin{tcolorbox}[colback=white]
  7519. \small
  7520. {\if\edition\racketEd
  7521. \[
  7522. \begin{array}{l}
  7523. \gray{\CvarGrammarRacket} \\ \hline
  7524. \CifGrammarRacket \\
  7525. \begin{array}{lcl}
  7526. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7527. \end{array}
  7528. \end{array}
  7529. \]
  7530. \fi}
  7531. {\if\edition\pythonEd
  7532. \[
  7533. \begin{array}{l}
  7534. \CifGrammarPython \\
  7535. \begin{array}{lcl}
  7536. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  7537. \end{array}
  7538. \end{array}
  7539. \]
  7540. \fi}
  7541. \end{tcolorbox}
  7542. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7543. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7544. \label{fig:c1-concrete-syntax}
  7545. \end{figure}
  7546. \begin{figure}[tp]
  7547. \begin{tcolorbox}[colback=white]
  7548. \small
  7549. {\if\edition\racketEd
  7550. \[
  7551. \begin{array}{l}
  7552. \gray{\CvarASTRacket} \\ \hline
  7553. \CifASTRacket \\
  7554. \begin{array}{lcl}
  7555. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7556. \end{array}
  7557. \end{array}
  7558. \]
  7559. \fi}
  7560. {\if\edition\pythonEd
  7561. \[
  7562. \begin{array}{l}
  7563. \CifASTPython \\
  7564. \begin{array}{lcl}
  7565. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  7566. \end{array}
  7567. \end{array}
  7568. \]
  7569. \fi}
  7570. \end{tcolorbox}
  7571. \racket{
  7572. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7573. }
  7574. \index{subject}{Goto@\texttt{Goto}}
  7575. \index{subject}{Return@\texttt{Return}}
  7576. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7577. (figure~\ref{fig:c0-syntax})}.}
  7578. \label{fig:c1-syntax}
  7579. \end{figure}
  7580. \section{The \LangXIf{} Language}
  7581. \label{sec:x86-if}
  7582. \index{subject}{x86} To implement the new logical operations, the
  7583. comparison operations, and the \key{if} expression\python{ and
  7584. statement}, we delve further into the x86
  7585. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7586. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7587. subset of x86, which includes instructions for logical operations,
  7588. comparisons, and \racket{conditional} jumps.
  7589. %
  7590. \python{The abstract syntax for an \LangXIf{} program contains a
  7591. dictionary mapping labels to sequences of instructions, each of
  7592. which we refer to as a \emph{basic block}\index{subject}{basic
  7593. block}.}
  7594. One challenge is that x86 does not provide an instruction that
  7595. directly implements logical negation (\code{not} in \LangIf{} and
  7596. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7597. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7598. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7599. bit of its arguments, and writes the results into its second argument.
  7600. Recall the following truth table for exclusive-or:
  7601. \begin{center}
  7602. \begin{tabular}{l|cc}
  7603. & 0 & 1 \\ \hline
  7604. 0 & 0 & 1 \\
  7605. 1 & 1 & 0
  7606. \end{tabular}
  7607. \end{center}
  7608. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7609. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7610. for the bit $1$, the result is the opposite of the second bit. Thus,
  7611. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7612. the first argument, as follows, where $\Arg$ is the translation of
  7613. $\Atm$ to x86:
  7614. \[
  7615. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7616. \qquad\Rightarrow\qquad
  7617. \begin{array}{l}
  7618. \key{movq}~ \Arg\key{,} \Var\\
  7619. \key{xorq}~ \key{\$1,} \Var
  7620. \end{array}
  7621. \]
  7622. \newcommand{\GrammarXIf}{
  7623. \begin{array}{lcl}
  7624. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7625. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7626. \Arg &::=& \key{\%}\itm{bytereg}\\
  7627. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7628. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7629. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7630. \MID \key{set}cc~\Arg
  7631. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7632. &\MID& \key{j}cc~\itm{label} \\
  7633. \end{array}
  7634. }
  7635. \begin{figure}[tp]
  7636. \begin{tcolorbox}[colback=white]
  7637. \[
  7638. \begin{array}{l}
  7639. \gray{\GrammarXInt} \\ \hline
  7640. \GrammarXIf \\
  7641. \begin{array}{lcl}
  7642. \LangXIfM{} &::= & \key{.globl main} \\
  7643. & & \key{main:} \; \Instr\ldots
  7644. \end{array}
  7645. \end{array}
  7646. \]
  7647. \end{tcolorbox}
  7648. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7649. \label{fig:x86-1-concrete}
  7650. \end{figure}
  7651. \newcommand{\ASTXIfRacket}{
  7652. \begin{array}{lcl}
  7653. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7654. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7655. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7656. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7657. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7658. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7659. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7660. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7661. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7662. \end{array}
  7663. }
  7664. \begin{figure}[tp]
  7665. \begin{tcolorbox}[colback=white]
  7666. \small
  7667. {\if\edition\racketEd
  7668. \[\arraycolsep=3pt
  7669. \begin{array}{l}
  7670. \gray{\ASTXIntRacket} \\ \hline
  7671. \ASTXIfRacket \\
  7672. \begin{array}{lcl}
  7673. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7674. \end{array}
  7675. \end{array}
  7676. \]
  7677. \fi}
  7678. %
  7679. {\if\edition\pythonEd
  7680. \[
  7681. \begin{array}{lcl}
  7682. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7683. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7684. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7685. \MID \BYTEREG{\itm{bytereg}} \\
  7686. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7687. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7688. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7689. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7690. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7691. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7692. \MID \PUSHQ{\Arg}} \\
  7693. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7694. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7695. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7696. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7697. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7698. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7699. \Block &::= & \Instr^{+} \\
  7700. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7701. \end{array}
  7702. \]
  7703. \fi}
  7704. \end{tcolorbox}
  7705. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7706. \label{fig:x86-1}
  7707. \end{figure}
  7708. Next we consider the x86 instructions that are relevant for compiling
  7709. the comparison operations. The \key{cmpq} instruction compares its two
  7710. arguments to determine whether one argument is less than, equal to, or
  7711. greater than the other argument. The \key{cmpq} instruction is unusual
  7712. regarding the order of its arguments and where the result is
  7713. placed. The argument order is backward: if you want to test whether
  7714. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7715. \key{cmpq} is placed in the special EFLAGS register. This register
  7716. cannot be accessed directly, but it can be queried by a number of
  7717. instructions, including the \key{set} instruction. The instruction
  7718. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  7719. depending on whether the contents of the EFLAGS register matches the
  7720. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7721. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7722. The \key{set} instruction has a quirk in that its destination argument
  7723. must be single-byte register, such as \code{al} (\code{l} for lower bits) or
  7724. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  7725. register. Thankfully, the \key{movzbq} instruction can be used to
  7726. move from a single-byte register to a normal 64-bit register. The
  7727. abstract syntax for the \code{set} instruction differs from the
  7728. concrete syntax in that it separates the instruction name from the
  7729. condition code.
  7730. \python{The x86 instructions for jumping are relevant to the
  7731. compilation of \key{if} expressions.}
  7732. %
  7733. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7734. counter to the address of the instruction after the specified
  7735. label.}
  7736. %
  7737. \racket{The x86 instruction for conditional jump is relevant to the
  7738. compilation of \key{if} expressions.}
  7739. %
  7740. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7741. counter to point to the instruction after \itm{label}, depending on
  7742. whether the result in the EFLAGS register matches the condition code
  7743. \itm{cc}; otherwise, the jump instruction falls through to the next
  7744. instruction. Like the abstract syntax for \code{set}, the abstract
  7745. syntax for conditional jump separates the instruction name from the
  7746. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7747. corresponds to \code{jle foo}. Because the conditional jump instruction
  7748. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7749. a \key{cmpq} instruction to set the EFLAGS register.
  7750. \section{Shrink the \LangIf{} Language}
  7751. \label{sec:shrink-Lif}
  7752. The \LangIf{} language includes several features that are easily
  7753. expressible with other features. For example, \code{and} and \code{or}
  7754. are expressible using \code{if} as follows.
  7755. \begin{align*}
  7756. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7757. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7758. \end{align*}
  7759. By performing these translations in the front end of the compiler,
  7760. subsequent passes of the compiler do not need to deal with these features,
  7761. thus making the passes shorter.
  7762. On the other hand, translations sometimes reduce the efficiency of the
  7763. generated code by increasing the number of instructions. For example,
  7764. expressing subtraction in terms of negation
  7765. \[
  7766. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7767. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7768. \]
  7769. produces code with two x86 instructions (\code{negq} and \code{addq})
  7770. instead of just one (\code{subq}).
  7771. \begin{exercise}\normalfont\normalsize
  7772. %
  7773. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7774. the language by translating them to \code{if} expressions in \LangIf{}.
  7775. %
  7776. Create four test programs that involve these operators.
  7777. %
  7778. {\if\edition\racketEd
  7779. In the \code{run-tests.rkt} script, add the following entry for
  7780. \code{shrink} to the list of passes (it should be the only pass at
  7781. this point).
  7782. \begin{lstlisting}
  7783. (list "shrink" shrink interp_Lif type-check-Lif)
  7784. \end{lstlisting}
  7785. This instructs \code{interp-tests} to run the interpreter
  7786. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7787. output of \code{shrink}.
  7788. \fi}
  7789. %
  7790. Run the script to test your compiler on all the test programs.
  7791. \end{exercise}
  7792. {\if\edition\racketEd
  7793. \section{Uniquify Variables}
  7794. \label{sec:uniquify-Lif}
  7795. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7796. \code{if} expressions.
  7797. \begin{exercise}\normalfont\normalsize
  7798. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7799. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  7800. \begin{lstlisting}
  7801. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7802. \end{lstlisting}
  7803. Run the script to test your compiler.
  7804. \end{exercise}
  7805. \fi}
  7806. \section{Remove Complex Operands}
  7807. \label{sec:remove-complex-opera-Lif}
  7808. The output language of \code{remove\_complex\_operands} is
  7809. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  7810. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  7811. but the \code{if} expression is not. All three subexpressions of an
  7812. \code{if} are allowed to be complex expressions, but the operands of
  7813. the \code{not} operator and comparison operators must be atomic.
  7814. %
  7815. \python{We add a new language form, the \code{Begin} expression, to aid
  7816. in the translation of \code{if} expressions. When we recursively
  7817. process the two branches of the \code{if}, we generate temporary
  7818. variables and their initializing expressions. However, these
  7819. expressions may contain side effects and should only be executed
  7820. when the condition of the \code{if} is true (for the ``then''
  7821. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7822. a way to initialize the temporary variables within the two branches
  7823. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7824. form execute the statements $ss$ and then returns the result of
  7825. expression $e$.}
  7826. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7827. the new features in \LangIf{}. In recursively processing
  7828. subexpressions, recall that you should invoke \code{rco\_atom} when
  7829. the output needs to be an \Atm{} (as specified in the grammar for
  7830. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7831. \Exp{}. Regarding \code{if}, it is particularly important
  7832. \textbf{not} to replace its condition with a temporary variable, because
  7833. that would interfere with the generation of high-quality output in the
  7834. upcoming \code{explicate\_control} pass.
  7835. \newcommand{\LifMonadASTRacket}{
  7836. \begin{array}{rcl}
  7837. \Atm &::=& \BOOL{\itm{bool}}\\
  7838. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7839. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7840. \MID \IF{\Exp}{\Exp}{\Exp}
  7841. \end{array}
  7842. }
  7843. \newcommand{\LifMonadASTPython}{
  7844. \begin{array}{rcl}
  7845. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7846. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7847. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7848. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7849. \Atm &::=& \BOOL{\itm{bool}}\\
  7850. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7851. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7852. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7853. \end{array}
  7854. }
  7855. \begin{figure}[tp]
  7856. \centering
  7857. \begin{tcolorbox}[colback=white]
  7858. {\if\edition\racketEd
  7859. \[
  7860. \begin{array}{l}
  7861. \gray{\LvarMonadASTRacket} \\ \hline
  7862. \LifMonadASTRacket \\
  7863. \begin{array}{rcl}
  7864. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7865. \end{array}
  7866. \end{array}
  7867. \]
  7868. \fi}
  7869. {\if\edition\pythonEd
  7870. \[
  7871. \begin{array}{l}
  7872. \gray{\LvarMonadASTPython} \\ \hline
  7873. \LifMonadASTPython \\
  7874. \begin{array}{rcl}
  7875. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7876. \end{array}
  7877. \end{array}
  7878. \]
  7879. \fi}
  7880. \end{tcolorbox}
  7881. \python{\index{subject}{Begin@\texttt{Begin}}}
  7882. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7883. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  7884. \label{fig:Lif-anf-syntax}
  7885. \end{figure}
  7886. \begin{exercise}\normalfont\normalsize
  7887. %
  7888. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7889. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7890. %
  7891. Create three new \LangIf{} programs that exercise the interesting
  7892. code in this pass.
  7893. %
  7894. {\if\edition\racketEd
  7895. In the \code{run-tests.rkt} script, add the following entry to the
  7896. list of \code{passes} and then run the script to test your compiler.
  7897. \begin{lstlisting}
  7898. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7899. \end{lstlisting}
  7900. \fi}
  7901. \end{exercise}
  7902. \section{Explicate Control}
  7903. \label{sec:explicate-control-Lif}
  7904. \racket{Recall that the purpose of \code{explicate\_control} is to
  7905. make the order of evaluation explicit in the syntax of the program.
  7906. With the addition of \key{if}, this becomes more interesting.}
  7907. %
  7908. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7909. %
  7910. The main challenge to overcome is that the condition of an \key{if}
  7911. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  7912. condition must be a comparison.
  7913. As a motivating example, consider the following program that has an
  7914. \key{if} expression nested in the condition of another \key{if}:%
  7915. \python{\footnote{Programmers rarely write nested \code{if}
  7916. expressions, but it is not uncommon for the condition of an
  7917. \code{if} statement to be a call of a function that also contains an
  7918. \code{if} statement. When such a function is inlined, the result is
  7919. a nested \code{if} that requires the techniques discussed in this
  7920. section.}}
  7921. % cond_test_41.rkt, if_lt_eq.py
  7922. \begin{center}
  7923. \begin{minipage}{0.96\textwidth}
  7924. {\if\edition\racketEd
  7925. \begin{lstlisting}
  7926. (let ([x (read)])
  7927. (let ([y (read)])
  7928. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7929. (+ y 2)
  7930. (+ y 10))))
  7931. \end{lstlisting}
  7932. \fi}
  7933. {\if\edition\pythonEd
  7934. \begin{lstlisting}
  7935. x = input_int()
  7936. y = input_int()
  7937. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7938. \end{lstlisting}
  7939. \fi}
  7940. \end{minipage}
  7941. \end{center}
  7942. %
  7943. The naive way to compile \key{if} and the comparison operations would
  7944. be to handle each of them in isolation, regardless of their context.
  7945. Each comparison would be translated into a \key{cmpq} instruction
  7946. followed by several instructions to move the result from the EFLAGS
  7947. register into a general purpose register or stack location. Each
  7948. \key{if} would be translated into a \key{cmpq} instruction followed by
  7949. a conditional jump. The generated code for the inner \key{if} in this
  7950. example would be as follows:
  7951. \begin{center}
  7952. \begin{minipage}{0.96\textwidth}
  7953. \begin{lstlisting}
  7954. cmpq $1, x
  7955. setl %al
  7956. movzbq %al, tmp
  7957. cmpq $1, tmp
  7958. je then_branch_1
  7959. jmp else_branch_1
  7960. \end{lstlisting}
  7961. \end{minipage}
  7962. \end{center}
  7963. Notice that the three instructions starting with \code{setl} are
  7964. redundant: the conditional jump could come immediately after the first
  7965. \code{cmpq}.
  7966. Our goal is to compile \key{if} expressions so that the relevant
  7967. comparison instruction appears directly before the conditional jump.
  7968. For example, we want to generate the following code for the inner
  7969. \code{if}:
  7970. \begin{center}
  7971. \begin{minipage}{0.96\textwidth}
  7972. \begin{lstlisting}
  7973. cmpq $1, x
  7974. jl then_branch_1
  7975. jmp else_branch_1
  7976. \end{lstlisting}
  7977. \end{minipage}
  7978. \end{center}
  7979. One way to achieve this goal is to reorganize the code at the level of
  7980. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7981. the following code:
  7982. \begin{center}
  7983. \begin{minipage}{0.96\textwidth}
  7984. {\if\edition\racketEd
  7985. \begin{lstlisting}
  7986. (let ([x (read)])
  7987. (let ([y (read)])
  7988. (if (< x 1)
  7989. (if (eq? x 0)
  7990. (+ y 2)
  7991. (+ y 10))
  7992. (if (eq? x 2)
  7993. (+ y 2)
  7994. (+ y 10)))))
  7995. \end{lstlisting}
  7996. \fi}
  7997. {\if\edition\pythonEd
  7998. \begin{lstlisting}
  7999. x = input_int()
  8000. y = input_int()
  8001. print(((y + 2) if x == 0 else (y + 10)) \
  8002. if (x < 1) \
  8003. else ((y + 2) if (x == 2) else (y + 10)))
  8004. \end{lstlisting}
  8005. \fi}
  8006. \end{minipage}
  8007. \end{center}
  8008. Unfortunately, this approach duplicates the two branches from the
  8009. outer \code{if}, and a compiler must never duplicate code! After all,
  8010. the two branches could be very large expressions.
  8011. How can we apply this transformation without duplicating code? In
  8012. other words, how can two different parts of a program refer to one
  8013. piece of code?
  8014. %
  8015. The answer is that we must move away from abstract syntax \emph{trees}
  8016. and instead use \emph{graphs}.
  8017. %
  8018. At the level of x86 assembly, this is straightforward because we can
  8019. label the code for each branch and insert jumps in all the places that
  8020. need to execute the branch. In this way, jump instructions are edges
  8021. in the graph and the basic blocks are the nodes.
  8022. %
  8023. Likewise, our language \LangCIf{} provides the ability to label a
  8024. sequence of statements and to jump to a label via \code{goto}.
  8025. As a preview of what \code{explicate\_control} will do,
  8026. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8027. \code{explicate\_control} on this example. Note how the condition of
  8028. every \code{if} is a comparison operation and that we have not
  8029. duplicated any code but instead have used labels and \code{goto} to
  8030. enable sharing of code.
  8031. \begin{figure}[tbp]
  8032. \begin{tcolorbox}[colback=white]
  8033. {\if\edition\racketEd
  8034. \begin{tabular}{lll}
  8035. \begin{minipage}{0.4\textwidth}
  8036. % cond_test_41.rkt
  8037. \begin{lstlisting}
  8038. (let ([x (read)])
  8039. (let ([y (read)])
  8040. (if (if (< x 1)
  8041. (eq? x 0)
  8042. (eq? x 2))
  8043. (+ y 2)
  8044. (+ y 10))))
  8045. \end{lstlisting}
  8046. \end{minipage}
  8047. &
  8048. $\Rightarrow$
  8049. &
  8050. \begin{minipage}{0.55\textwidth}
  8051. \begin{lstlisting}
  8052. start:
  8053. x = (read);
  8054. y = (read);
  8055. if (< x 1)
  8056. goto block_4;
  8057. else
  8058. goto block_5;
  8059. block_4:
  8060. if (eq? x 0)
  8061. goto block_2;
  8062. else
  8063. goto block_3;
  8064. block_5:
  8065. if (eq? x 2)
  8066. goto block_2;
  8067. else
  8068. goto block_3;
  8069. block_2:
  8070. return (+ y 2);
  8071. block_3:
  8072. return (+ y 10);
  8073. \end{lstlisting}
  8074. \end{minipage}
  8075. \end{tabular}
  8076. \fi}
  8077. {\if\edition\pythonEd
  8078. \begin{tabular}{lll}
  8079. \begin{minipage}{0.4\textwidth}
  8080. % cond_test_41.rkt
  8081. \begin{lstlisting}
  8082. x = input_int()
  8083. y = input_int()
  8084. print(y + 2 \
  8085. if (x == 0 \
  8086. if x < 1 \
  8087. else x == 2) \
  8088. else y + 10)
  8089. \end{lstlisting}
  8090. \end{minipage}
  8091. &
  8092. $\Rightarrow$
  8093. &
  8094. \begin{minipage}{0.55\textwidth}
  8095. \begin{lstlisting}
  8096. start:
  8097. x = input_int()
  8098. y = input_int()
  8099. if x < 1:
  8100. goto block_8
  8101. else:
  8102. goto block_9
  8103. block_8:
  8104. if x == 0:
  8105. goto block_4
  8106. else:
  8107. goto block_5
  8108. block_9:
  8109. if x == 2:
  8110. goto block_6
  8111. else:
  8112. goto block_7
  8113. block_4:
  8114. goto block_2
  8115. block_5:
  8116. goto block_3
  8117. block_6:
  8118. goto block_2
  8119. block_7:
  8120. goto block_3
  8121. block_2:
  8122. tmp_0 = y + 2
  8123. goto block_1
  8124. block_3:
  8125. tmp_0 = y + 10
  8126. goto block_1
  8127. block_1:
  8128. print(tmp_0)
  8129. return 0
  8130. \end{lstlisting}
  8131. \end{minipage}
  8132. \end{tabular}
  8133. \fi}
  8134. \end{tcolorbox}
  8135. \caption{Translation from \LangIf{} to \LangCIf{}
  8136. via the \code{explicate\_control}.}
  8137. \label{fig:explicate-control-s1-38}
  8138. \end{figure}
  8139. {\if\edition\racketEd
  8140. %
  8141. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8142. \code{explicate\_control} for \LangVar{} using two recursive
  8143. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8144. former function translates expressions in tail position, whereas the
  8145. latter function translates expressions on the right-hand side of a
  8146. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8147. have a new kind of position to deal with: the predicate position of
  8148. the \key{if}. We need another function, \code{explicate\_pred}, that
  8149. decides how to compile an \key{if} by analyzing its condition. So,
  8150. \code{explicate\_pred} takes an \LangIf{} expression and two
  8151. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8152. and outputs a tail. In the following paragraphs we discuss specific
  8153. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8154. \code{explicate\_pred} functions.
  8155. %
  8156. \fi}
  8157. %
  8158. {\if\edition\pythonEd
  8159. %
  8160. We recommend implementing \code{explicate\_control} using the
  8161. following four auxiliary functions.
  8162. \begin{description}
  8163. \item[\code{explicate\_effect}] generates code for expressions as
  8164. statements, so their result is ignored and only their side effects
  8165. matter.
  8166. \item[\code{explicate\_assign}] generates code for expressions
  8167. on the right-hand side of an assignment.
  8168. \item[\code{explicate\_pred}] generates code for an \code{if}
  8169. expression or statement by analyzing the condition expression.
  8170. \item[\code{explicate\_stmt}] generates code for statements.
  8171. \end{description}
  8172. These four functions should build the dictionary of basic blocks. The
  8173. following auxiliary function can be used to create a new basic block
  8174. from a list of statements. It returns a \code{goto} statement that
  8175. jumps to the new basic block.
  8176. \begin{center}
  8177. \begin{minipage}{\textwidth}
  8178. \begin{lstlisting}
  8179. def create_block(stmts, basic_blocks):
  8180. label = label_name(generate_name('block'))
  8181. basic_blocks[label] = stmts
  8182. return Goto(label)
  8183. \end{lstlisting}
  8184. \end{minipage}
  8185. \end{center}
  8186. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8187. \code{explicate\_control} pass.
  8188. The \code{explicate\_effect} function has three parameters: 1) the
  8189. expression to be compiled, 2) the already-compiled code for this
  8190. expression's \emph{continuation}, that is, the list of statements that
  8191. should execute after this expression, and 3) the dictionary of
  8192. generated basic blocks. The \code{explicate\_effect} function returns
  8193. a list of \LangCIf{} statements and it may add to the dictionary of
  8194. basic blocks.
  8195. %
  8196. Let's consider a few of the cases for the expression to be compiled.
  8197. If the expression to be compiled is a constant, then it can be
  8198. discarded because it has no side effects. If it's a \CREAD{}, then it
  8199. has a side-effect and should be preserved. So the expression should be
  8200. translated into a statement using the \code{Expr} AST class. If the
  8201. expression to be compiled is an \code{if} expression, we translate the
  8202. two branches using \code{explicate\_effect} and then translate the
  8203. condition expression using \code{explicate\_pred}, which generates
  8204. code for the entire \code{if}.
  8205. The \code{explicate\_assign} function has four parameters: 1) the
  8206. right-hand side of the assignment, 2) the left-hand side of the
  8207. assignment (the variable), 3) the continuation, and 4) the dictionary
  8208. of basic blocks. The \code{explicate\_assign} function returns a list
  8209. of \LangCIf{} statements and it may add to the dictionary of basic
  8210. blocks.
  8211. When the right-hand side is an \code{if} expression, there is some
  8212. work to do. In particular, the two branches should be translated using
  8213. \code{explicate\_assign} and the condition expression should be
  8214. translated using \code{explicate\_pred}. Otherwise we can simply
  8215. generate an assignment statement, with the given left and right-hand
  8216. sides, concatenated with its continuation.
  8217. \begin{figure}[tbp]
  8218. \begin{tcolorbox}[colback=white]
  8219. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8220. def explicate_effect(e, cont, basic_blocks):
  8221. match e:
  8222. case IfExp(test, body, orelse):
  8223. ...
  8224. case Call(func, args):
  8225. ...
  8226. case Begin(body, result):
  8227. ...
  8228. case _:
  8229. ...
  8230. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8231. match rhs:
  8232. case IfExp(test, body, orelse):
  8233. ...
  8234. case Begin(body, result):
  8235. ...
  8236. case _:
  8237. return [Assign([lhs], rhs)] + cont
  8238. def explicate_pred(cnd, thn, els, basic_blocks):
  8239. match cnd:
  8240. case Compare(left, [op], [right]):
  8241. goto_thn = create_block(thn, basic_blocks)
  8242. goto_els = create_block(els, basic_blocks)
  8243. return [If(cnd, [goto_thn], [goto_els])]
  8244. case Constant(True):
  8245. return thn;
  8246. case Constant(False):
  8247. return els;
  8248. case UnaryOp(Not(), operand):
  8249. ...
  8250. case IfExp(test, body, orelse):
  8251. ...
  8252. case Begin(body, result):
  8253. ...
  8254. case _:
  8255. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8256. [create_block(els, basic_blocks)],
  8257. [create_block(thn, basic_blocks)])]
  8258. def explicate_stmt(s, cont, basic_blocks):
  8259. match s:
  8260. case Assign([lhs], rhs):
  8261. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8262. case Expr(value):
  8263. return explicate_effect(value, cont, basic_blocks)
  8264. case If(test, body, orelse):
  8265. ...
  8266. def explicate_control(p):
  8267. match p:
  8268. case Module(body):
  8269. new_body = [Return(Constant(0))]
  8270. basic_blocks = {}
  8271. for s in reversed(body):
  8272. new_body = explicate_stmt(s, new_body, basic_blocks)
  8273. basic_blocks[label_name('start')] = new_body
  8274. return CProgram(basic_blocks)
  8275. \end{lstlisting}
  8276. \end{tcolorbox}
  8277. \caption{Skeleton for the \code{explicate\_control} pass.}
  8278. \label{fig:explicate-control-Lif}
  8279. \end{figure}
  8280. \fi}
  8281. {\if\edition\racketEd
  8282. \subsection{Explicate Tail and Assign}
  8283. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8284. additional cases for Boolean constants and \key{if}. The cases for
  8285. \code{if} should recursively compile the two branches using either
  8286. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8287. cases should then invoke \code{explicate\_pred} on the condition
  8288. expression, passing in the generated code for the two branches. For
  8289. example, consider the following program with an \code{if} in tail
  8290. position.
  8291. % cond_test_6.rkt
  8292. \begin{lstlisting}
  8293. (let ([x (read)])
  8294. (if (eq? x 0) 42 777))
  8295. \end{lstlisting}
  8296. The two branches are recursively compiled to return statements. We
  8297. then delegate to \code{explicate\_pred}, passing the condition
  8298. \code{(eq? x 0)} and the two return statements. We return to this
  8299. example shortly when we discuss \code{explicate\_pred}.
  8300. Next let us consider a program with an \code{if} on the right-hand
  8301. side of a \code{let}.
  8302. \begin{lstlisting}
  8303. (let ([y (read)])
  8304. (let ([x (if (eq? y 0) 40 777)])
  8305. (+ x 2)))
  8306. \end{lstlisting}
  8307. Note that the body of the inner \code{let} will have already been
  8308. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8309. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8310. to recursively process both branches of the \code{if}, and we do not
  8311. want to duplicate code, so we generate the following block using an
  8312. auxiliary function named \code{create\_block}, discussed in the next
  8313. section.
  8314. \begin{lstlisting}
  8315. block_6:
  8316. return (+ x 2)
  8317. \end{lstlisting}
  8318. We then use \code{goto block\_6;} as the \code{cont} argument for
  8319. compiling the branches. So the two branches compile to
  8320. \begin{center}
  8321. \begin{minipage}{0.2\textwidth}
  8322. \begin{lstlisting}
  8323. x = 40;
  8324. goto block_6;
  8325. \end{lstlisting}
  8326. \end{minipage}
  8327. \hspace{0.5in} and \hspace{0.5in}
  8328. \begin{minipage}{0.2\textwidth}
  8329. \begin{lstlisting}
  8330. x = 777;
  8331. goto block_6;
  8332. \end{lstlisting}
  8333. \end{minipage}
  8334. \end{center}
  8335. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8336. \code{(eq? y 0)} and the previously presented code for the branches.
  8337. \subsection{Create Block}
  8338. We recommend implementing the \code{create\_block} auxiliary function
  8339. as follows, using a global variable \code{basic-blocks} to store a
  8340. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8341. that \code{create\_block} generates a new label and then associates
  8342. the given \code{tail} with the new label in the \code{basic-blocks}
  8343. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8344. new label. However, if the given \code{tail} is already a \code{Goto},
  8345. then there is no need to generate a new label and entry in
  8346. \code{basic-blocks}; we can simply return that \code{Goto}.
  8347. %
  8348. \begin{lstlisting}
  8349. (define (create_block tail)
  8350. (match tail
  8351. [(Goto label) (Goto label)]
  8352. [else
  8353. (let ([label (gensym 'block)])
  8354. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8355. (Goto label))]))
  8356. \end{lstlisting}
  8357. \fi}
  8358. {\if\edition\racketEd
  8359. \subsection{Explicate Predicate}
  8360. \begin{figure}[tbp]
  8361. \begin{tcolorbox}[colback=white]
  8362. \begin{lstlisting}
  8363. (define (explicate_pred cnd thn els)
  8364. (match cnd
  8365. [(Var x) ___]
  8366. [(Let x rhs body) ___]
  8367. [(Prim 'not (list e)) ___]
  8368. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8369. (IfStmt (Prim op es) (create_block thn)
  8370. (create_block els))]
  8371. [(Bool b) (if b thn els)]
  8372. [(If cnd^ thn^ els^) ___]
  8373. [else (error "explicate_pred unhandled case" cnd)]))
  8374. \end{lstlisting}
  8375. \end{tcolorbox}
  8376. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8377. \label{fig:explicate-pred}
  8378. \end{figure}
  8379. \fi}
  8380. \racket{The skeleton for the \code{explicate\_pred} function is given
  8381. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  8382. (1) \code{cnd}, the condition expression of the \code{if};
  8383. (2) \code{thn}, the code generated by explicate for the \emph{then} branch;
  8384. and (3) \code{els}, the code generated by
  8385. explicate for the \emph{else} branch. The \code{explicate\_pred}
  8386. function should match on \code{cnd} with a case for
  8387. every kind of expression that can have type \BOOLTY{}.}
  8388. %
  8389. \python{The \code{explicate\_pred} function has four parameters: 1)
  8390. the condition expression, 2) the generated statements for the
  8391. ``then'' branch, 3) the generated statements for the ``else''
  8392. branch, and 4) the dictionary of basic blocks. The
  8393. \code{explicate\_pred} function returns a list of \LangCIf{}
  8394. statements and it may add to the dictionary of basic blocks.}
  8395. Consider the case for comparison operators. We translate the
  8396. comparison to an \code{if} statement whose branches are \code{goto}
  8397. statements created by applying \code{create\_block} to the code
  8398. generated for the \code{thn} and \code{els} branches. Let us
  8399. illustrate this translation by returning to the program with an
  8400. \code{if} expression in tail position, shown next. We invoke
  8401. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  8402. \python{\code{x == 0}}.
  8403. %
  8404. {\if\edition\racketEd
  8405. \begin{lstlisting}
  8406. (let ([x (read)])
  8407. (if (eq? x 0) 42 777))
  8408. \end{lstlisting}
  8409. \fi}
  8410. %
  8411. {\if\edition\pythonEd
  8412. \begin{lstlisting}
  8413. x = input_int()
  8414. 42 if x == 0 else 777
  8415. \end{lstlisting}
  8416. \fi}
  8417. %
  8418. \noindent The two branches \code{42} and \code{777} were already
  8419. compiled to \code{return} statements, from which we now create the
  8420. following blocks:
  8421. %
  8422. \begin{center}
  8423. \begin{minipage}{\textwidth}
  8424. \begin{lstlisting}
  8425. block_1:
  8426. return 42;
  8427. block_2:
  8428. return 777;
  8429. \end{lstlisting}
  8430. \end{minipage}
  8431. \end{center}
  8432. %
  8433. After that, \code{explicate\_pred} compiles the comparison
  8434. \racket{\code{(eq? x 0)}}
  8435. \python{\code{x == 0}}
  8436. to the following \code{if} statement:
  8437. %
  8438. {\if\edition\racketEd
  8439. \begin{center}
  8440. \begin{minipage}{\textwidth}
  8441. \begin{lstlisting}
  8442. if (eq? x 0)
  8443. goto block_1;
  8444. else
  8445. goto block_2;
  8446. \end{lstlisting}
  8447. \end{minipage}
  8448. \end{center}
  8449. \fi}
  8450. {\if\edition\pythonEd
  8451. \begin{center}
  8452. \begin{minipage}{\textwidth}
  8453. \begin{lstlisting}
  8454. if x == 0:
  8455. goto block_1;
  8456. else
  8457. goto block_2;
  8458. \end{lstlisting}
  8459. \end{minipage}
  8460. \end{center}
  8461. \fi}
  8462. Next consider the case for Boolean constants. We perform a kind of
  8463. partial evaluation\index{subject}{partial evaluation} and output
  8464. either the \code{thn} or \code{els} branch, depending on whether the
  8465. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8466. following program:
  8467. {\if\edition\racketEd
  8468. \begin{lstlisting}
  8469. (if #t 42 777)
  8470. \end{lstlisting}
  8471. \fi}
  8472. {\if\edition\pythonEd
  8473. \begin{lstlisting}
  8474. 42 if True else 777
  8475. \end{lstlisting}
  8476. \fi}
  8477. %
  8478. \noindent Again, the two branches \code{42} and \code{777} were
  8479. compiled to \code{return} statements, so \code{explicate\_pred}
  8480. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8481. code for the \emph{then} branch.
  8482. \begin{lstlisting}
  8483. return 42;
  8484. \end{lstlisting}
  8485. This case demonstrates that we sometimes discard the \code{thn} or
  8486. \code{els} blocks that are input to \code{explicate\_pred}.
  8487. The case for \key{if} expressions in \code{explicate\_pred} is
  8488. particularly illuminating because it deals with the challenges
  8489. discussed previously regarding nested \key{if} expressions
  8490. (figure~\ref{fig:explicate-control-s1-38}). The
  8491. \racket{\lstinline{thn^}}\python{\code{body}} and
  8492. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8493. \key{if} inherit their context from the current one, that is,
  8494. predicate context. So, you should recursively apply
  8495. \code{explicate\_pred} to the
  8496. \racket{\lstinline{thn^}}\python{\code{body}} and
  8497. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8498. those recursive calls, pass \code{thn} and \code{els} as the extra
  8499. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8500. inside each recursive call. As discussed previously, to avoid
  8501. duplicating code, we need to add them to the dictionary of basic
  8502. blocks so that we can instead refer to them by name and execute them
  8503. with a \key{goto}.
  8504. {\if\edition\pythonEd
  8505. %
  8506. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8507. three parameters: 1) the statement to be compiled, 2) the code for its
  8508. continuation, and 3) the dictionary of basic blocks. The
  8509. \code{explicate\_stmt} returns a list of statements and it may add to
  8510. the dictionary of basic blocks. The cases for assignment and an
  8511. expression-statement are given in full in the skeleton code: they
  8512. simply dispatch to \code{explicate\_assign} and
  8513. \code{explicate\_effect}, respectively. The case for \code{if}
  8514. statements is not given, and is similar to the case for \code{if}
  8515. expressions.
  8516. The \code{explicate\_control} function itself is given in
  8517. figure~\ref{fig:explicate-control-Lif}. It applies
  8518. \code{explicate\_stmt} to each statement in the program, from back to
  8519. front. Thus, the result so-far, stored in \code{new\_body}, can be
  8520. used as the continuation parameter in the next call to
  8521. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8522. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8523. the dictionary of basic blocks, labeling it as the ``start'' block.
  8524. %
  8525. \fi}
  8526. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8527. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8528. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8529. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8530. %% results from the two recursive calls. We complete the case for
  8531. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8532. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8533. %% the result $B_5$.
  8534. %% \[
  8535. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8536. %% \quad\Rightarrow\quad
  8537. %% B_5
  8538. %% \]
  8539. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8540. %% inherit the current context, so they are in tail position. Thus, the
  8541. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8542. %% \code{explicate\_tail}.
  8543. %% %
  8544. %% We need to pass $B_0$ as the accumulator argument for both of these
  8545. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8546. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8547. %% to the control-flow graph and obtain a promised goto $G_0$.
  8548. %% %
  8549. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8550. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8551. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8552. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8553. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8554. %% \[
  8555. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8556. %% \]
  8557. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8558. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8559. %% should not be confused with the labels for the blocks that appear in
  8560. %% the generated code. We initially construct unlabeled blocks; we only
  8561. %% attach labels to blocks when we add them to the control-flow graph, as
  8562. %% we see in the next case.
  8563. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8564. %% function. The context of the \key{if} is an assignment to some
  8565. %% variable $x$ and then the control continues to some promised block
  8566. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8567. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8568. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8569. %% branches of the \key{if} inherit the current context, so they are in
  8570. %% assignment positions. Let $B_2$ be the result of applying
  8571. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8572. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8573. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8574. %% the result of applying \code{explicate\_pred} to the predicate
  8575. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8576. %% translates to the promise $B_4$.
  8577. %% \[
  8578. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8579. %% \]
  8580. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8581. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8582. \code{remove\_complex\_operands} pass and then the
  8583. \code{explicate\_control} pass on the example program. We walk through
  8584. the output program.
  8585. %
  8586. Following the order of evaluation in the output of
  8587. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8588. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8589. in the predicate of the inner \key{if}. In the output of
  8590. \code{explicate\_control}, in the
  8591. block labeled \code{start}, two assignment statements are followed by an
  8592. \code{if} statement that branches to \code{block\_4} or
  8593. \code{block\_5}. The blocks associated with those labels contain the
  8594. translations of the code
  8595. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8596. and
  8597. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8598. respectively. In particular, we start \code{block\_4} with the
  8599. comparison
  8600. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8601. and then branch to \code{block\_2} or \code{block\_3},
  8602. which correspond to the two branches of the outer \key{if}, that is,
  8603. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8604. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8605. %
  8606. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8607. %
  8608. \python{The \code{block\_1} corresponds to the \code{print} statement
  8609. at the end of the program.}
  8610. {\if\edition\racketEd
  8611. \subsection{Interactions between Explicate and Shrink}
  8612. The way in which the \code{shrink} pass transforms logical operations
  8613. such as \code{and} and \code{or} can impact the quality of code
  8614. generated by \code{explicate\_control}. For example, consider the
  8615. following program:
  8616. % cond_test_21.rkt, and_eq_input.py
  8617. \begin{lstlisting}
  8618. (if (and (eq? (read) 0) (eq? (read) 1))
  8619. 0
  8620. 42)
  8621. \end{lstlisting}
  8622. The \code{and} operation should transform into something that the
  8623. \code{explicate\_pred} function can analyze and descend through to
  8624. reach the underlying \code{eq?} conditions. Ideally, for this program
  8625. your \code{explicate\_control} pass should generate code similar to
  8626. the following:
  8627. \begin{center}
  8628. \begin{minipage}{\textwidth}
  8629. \begin{lstlisting}
  8630. start:
  8631. tmp1 = (read);
  8632. if (eq? tmp1 0) goto block40;
  8633. else goto block39;
  8634. block40:
  8635. tmp2 = (read);
  8636. if (eq? tmp2 1) goto block38;
  8637. else goto block39;
  8638. block38:
  8639. return 0;
  8640. block39:
  8641. return 42;
  8642. \end{lstlisting}
  8643. \end{minipage}
  8644. \end{center}
  8645. \fi}
  8646. \begin{exercise}\normalfont\normalsize
  8647. \racket{
  8648. Implement the pass \code{explicate\_control} by adding the cases for
  8649. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8650. \code{explicate\_assign} functions. Implement the auxiliary function
  8651. \code{explicate\_pred} for predicate contexts.}
  8652. \python{Implement \code{explicate\_control} pass with its
  8653. four auxiliary functions.}
  8654. %
  8655. Create test cases that exercise all the new cases in the code for
  8656. this pass.
  8657. %
  8658. {\if\edition\racketEd
  8659. Add the following entry to the list of \code{passes} in
  8660. \code{run-tests.rkt}:
  8661. \begin{lstlisting}
  8662. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8663. \end{lstlisting}
  8664. and then run \code{run-tests.rkt} to test your compiler.
  8665. \fi}
  8666. \end{exercise}
  8667. \section{Select Instructions}
  8668. \label{sec:select-Lif}
  8669. \index{subject}{instruction selection}
  8670. The \code{select\_instructions} pass translates \LangCIf{} to
  8671. \LangXIfVar{}.
  8672. %
  8673. \racket{Recall that we implement this pass using three auxiliary
  8674. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8675. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8676. %
  8677. \racket{For $\Atm$, we have new cases for the Booleans.}
  8678. %
  8679. \python{We begin with the Boolean constants.}
  8680. We take the usual approach of encoding them as integers.
  8681. \[
  8682. \TRUE{} \quad\Rightarrow\quad \key{1}
  8683. \qquad\qquad
  8684. \FALSE{} \quad\Rightarrow\quad \key{0}
  8685. \]
  8686. For translating statements, we discuss some of the cases. The
  8687. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8688. discussed at the beginning of this section. Given an assignment, if
  8689. the left-hand-side variable is the same as the argument of \code{not},
  8690. then just the \code{xorq} instruction suffices.
  8691. \[
  8692. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8693. \quad\Rightarrow\quad
  8694. \key{xorq}~\key{\$}1\key{,}~\Var
  8695. \]
  8696. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8697. semantics of x86. In the following translation, let $\Arg$ be the
  8698. result of translating $\Atm$ to x86.
  8699. \[
  8700. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8701. \quad\Rightarrow\quad
  8702. \begin{array}{l}
  8703. \key{movq}~\Arg\key{,}~\Var\\
  8704. \key{xorq}~\key{\$}1\key{,}~\Var
  8705. \end{array}
  8706. \]
  8707. Next consider the cases for equality comparisons. Translating this
  8708. operation to x86 is slightly involved due to the unusual nature of the
  8709. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8710. We recommend translating an assignment with an equality on the
  8711. right-hand side into a sequence of three instructions. \\
  8712. \begin{tabular}{lll}
  8713. \begin{minipage}{0.4\textwidth}
  8714. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8715. \end{minipage}
  8716. &
  8717. $\Rightarrow$
  8718. &
  8719. \begin{minipage}{0.4\textwidth}
  8720. \begin{lstlisting}
  8721. cmpq |$\Arg_2$|, |$\Arg_1$|
  8722. sete %al
  8723. movzbq %al, |$\Var$|
  8724. \end{lstlisting}
  8725. \end{minipage}
  8726. \end{tabular} \\
  8727. The translations for the other comparison operators are similar to
  8728. this but use different condition codes for the \code{set} instruction.
  8729. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8730. \key{goto} and \key{if} statements. Both are straightforward to
  8731. translate to x86.}
  8732. %
  8733. A \key{goto} statement becomes a jump instruction.
  8734. \[
  8735. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8736. \]
  8737. %
  8738. An \key{if} statement becomes a compare instruction followed by a
  8739. conditional jump (for the \emph{then} branch), and the fall-through is to
  8740. a regular jump (for the \emph{else} branch).\\
  8741. \begin{tabular}{lll}
  8742. \begin{minipage}{0.4\textwidth}
  8743. \begin{lstlisting}
  8744. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8745. goto |$\ell_1$||$\racket{\key{;}}$|
  8746. else|$\python{\key{:}}$|
  8747. goto |$\ell_2$||$\racket{\key{;}}$|
  8748. \end{lstlisting}
  8749. \end{minipage}
  8750. &
  8751. $\Rightarrow$
  8752. &
  8753. \begin{minipage}{0.4\textwidth}
  8754. \begin{lstlisting}
  8755. cmpq |$\Arg_2$|, |$\Arg_1$|
  8756. je |$\ell_1$|
  8757. jmp |$\ell_2$|
  8758. \end{lstlisting}
  8759. \end{minipage}
  8760. \end{tabular} \\
  8761. Again, the translations for the other comparison operators are similar to this
  8762. but use different condition codes for the conditional jump instruction.
  8763. \python{Regarding the \key{return} statement, we recommend treating it
  8764. as an assignment to the \key{rax} register followed by a jump to the
  8765. conclusion of the \code{main} function.}
  8766. \begin{exercise}\normalfont\normalsize
  8767. Expand your \code{select\_instructions} pass to handle the new
  8768. features of the \LangCIf{} language.
  8769. %
  8770. {\if\edition\racketEd
  8771. Add the following entry to the list of \code{passes} in
  8772. \code{run-tests.rkt}
  8773. \begin{lstlisting}
  8774. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8775. \end{lstlisting}
  8776. \fi}
  8777. %
  8778. Run the script to test your compiler on all the test programs.
  8779. \end{exercise}
  8780. \section{Register Allocation}
  8781. \label{sec:register-allocation-Lif}
  8782. \index{subject}{register allocation}
  8783. The changes required for compiling \LangIf{} affect liveness analysis,
  8784. building the interference graph, and assigning homes, but the graph
  8785. coloring algorithm itself does not change.
  8786. \subsection{Liveness Analysis}
  8787. \label{sec:liveness-analysis-Lif}
  8788. \index{subject}{liveness analysis}
  8789. Recall that for \LangVar{} we implemented liveness analysis for a
  8790. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  8791. the addition of \key{if} expressions to \LangIf{},
  8792. \code{explicate\_control} produces many basic blocks.
  8793. %% We recommend that you create a new auxiliary function named
  8794. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8795. %% control-flow graph.
  8796. The first question is, in what order should we process the basic blocks?
  8797. Recall that to perform liveness analysis on a basic block we need to
  8798. know the live-after set for the last instruction in the block. If a
  8799. basic block has no successors (i.e., contains no jumps to other
  8800. blocks), then it has an empty live-after set and we can immediately
  8801. apply liveness analysis to it. If a basic block has some successors,
  8802. then we need to complete liveness analysis on those blocks
  8803. first. These ordering constraints are the reverse of a
  8804. \emph{topological order}\index{subject}{topological order} on a graph
  8805. representation of the program. In particular, the \emph{control flow
  8806. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8807. of a program has a node for each basic block and an edge for each jump
  8808. from one block to another. It is straightforward to generate a CFG
  8809. from the dictionary of basic blocks. One then transposes the CFG and
  8810. applies the topological sort algorithm.
  8811. %
  8812. %
  8813. \racket{We recommend using the \code{tsort} and \code{transpose}
  8814. functions of the Racket \code{graph} package to accomplish this.}
  8815. %
  8816. \python{We provide implementations of \code{topological\_sort} and
  8817. \code{transpose} in the file \code{graph.py} of the support code.}
  8818. %
  8819. As an aside, a topological ordering is only guaranteed to exist if the
  8820. graph does not contain any cycles. This is the case for the
  8821. control-flow graphs that we generate from \LangIf{} programs.
  8822. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8823. and learn how to handle cycles in the control-flow graph.
  8824. \racket{You need to construct a directed graph to represent the
  8825. control-flow graph. Do not use the \code{directed-graph} of the
  8826. \code{graph} package because that allows at most one edge
  8827. between each pair of vertices, whereas a control-flow graph may have
  8828. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8829. file in the support code implements a graph representation that
  8830. allows multiple edges between a pair of vertices.}
  8831. {\if\edition\racketEd
  8832. The next question is how to analyze jump instructions. Recall that in
  8833. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8834. \code{label->live} that maps each label to the set of live locations
  8835. at the beginning of its block. We use \code{label->live} to determine
  8836. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8837. that we have many basic blocks, \code{label->live} needs to be updated
  8838. as we process the blocks. In particular, after performing liveness
  8839. analysis on a block, we take the live-before set of its first
  8840. instruction and associate that with the block's label in the
  8841. \code{label->live} alist.
  8842. \fi}
  8843. %
  8844. {\if\edition\pythonEd
  8845. %
  8846. The next question is how to analyze jump instructions. The locations
  8847. that are live before a \code{jmp} should be the locations in
  8848. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  8849. maintaining a dictionary named \code{live\_before\_block} that maps each
  8850. label to the $L_{\mathsf{before}}$ for the first instruction in its
  8851. block. After performing liveness analysis on each block, we take the
  8852. live-before set of its first instruction and associate that with the
  8853. block's label in the \code{live\_before\_block} dictionary.
  8854. %
  8855. \fi}
  8856. In \LangXIfVar{} we also have the conditional jump
  8857. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8858. this instruction is particularly interesting because during
  8859. compilation, we do not know which way a conditional jump will go. Thus
  8860. we do not know whether to use the live-before set for the block
  8861. associated with the $\itm{label}$ or the live-before set for the
  8862. following instruction. However, there is no harm to the correctness
  8863. of the generated code if we classify more locations as live than the
  8864. ones that are truly live during one particular execution of the
  8865. instruction. Thus, we can take the union of the live-before sets from
  8866. the following instruction and from the mapping for $\itm{label}$ in
  8867. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8868. The auxiliary functions for computing the variables in an
  8869. instruction's argument and for computing the variables read-from ($R$)
  8870. or written-to ($W$) by an instruction need to be updated to handle the
  8871. new kinds of arguments and instructions in \LangXIfVar{}.
  8872. \begin{exercise}\normalfont\normalsize
  8873. {\if\edition\racketEd
  8874. %
  8875. Update the \code{uncover\_live} pass to apply liveness analysis to
  8876. every basic block in the program.
  8877. %
  8878. Add the following entry to the list of \code{passes} in the
  8879. \code{run-tests.rkt} script:
  8880. \begin{lstlisting}
  8881. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8882. \end{lstlisting}
  8883. \fi}
  8884. {\if\edition\pythonEd
  8885. %
  8886. Update the \code{uncover\_live} function to perform liveness analysis,
  8887. in reverse topological order, on all the basic blocks in the
  8888. program.
  8889. %
  8890. \fi}
  8891. % Check that the live-after sets that you generate for
  8892. % example X matches the following... -Jeremy
  8893. \end{exercise}
  8894. \subsection{Build the Interference Graph}
  8895. \label{sec:build-interference-Lif}
  8896. Many of the new instructions in \LangXIfVar{} can be handled in the
  8897. same way as the instructions in \LangXVar{}.
  8898. % Thus, if your code was
  8899. % already quite general, it will not need to be changed to handle the
  8900. % new instructions. If your code is not general enough, we recommend that
  8901. % you change your code to be more general. For example, you can factor
  8902. % out the computing of the the read and write sets for each kind of
  8903. % instruction into auxiliary functions.
  8904. %
  8905. Some instructions, such as the \key{movzbq} instruction, require special care,
  8906. similar to the \key{movq} instruction. Refer to rule number 1 in
  8907. section~\ref{sec:build-interference}.
  8908. \begin{exercise}\normalfont\normalsize
  8909. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8910. {\if\edition\racketEd
  8911. Add the following entries to the list of \code{passes} in the
  8912. \code{run-tests.rkt} script:
  8913. \begin{lstlisting}
  8914. (list "build_interference" build_interference interp-pseudo-x86-1)
  8915. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8916. \end{lstlisting}
  8917. \fi}
  8918. % Check that the interference graph that you generate for
  8919. % example X matches the following graph G... -Jeremy
  8920. \end{exercise}
  8921. \section{Patch Instructions}
  8922. The new instructions \key{cmpq} and \key{movzbq} have some special
  8923. restrictions that need to be handled in the \code{patch\_instructions}
  8924. pass.
  8925. %
  8926. The second argument of the \key{cmpq} instruction must not be an
  8927. immediate value (such as an integer). So, if you are comparing two
  8928. immediates, we recommend inserting a \key{movq} instruction to put the
  8929. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8930. one memory reference.
  8931. %
  8932. The second argument of the \key{movzbq} must be a register.
  8933. \begin{exercise}\normalfont\normalsize
  8934. %
  8935. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8936. %
  8937. {\if\edition\racketEd
  8938. Add the following entry to the list of \code{passes} in
  8939. \code{run-tests.rkt}, and then run this script to test your compiler.
  8940. \begin{lstlisting}
  8941. (list "patch_instructions" patch_instructions interp-x86-1)
  8942. \end{lstlisting}
  8943. \fi}
  8944. \end{exercise}
  8945. {\if\edition\pythonEd
  8946. \section{Prelude and Conclusion}
  8947. \label{sec:prelude-conclusion-cond}
  8948. The generation of the \code{main} function with its prelude and
  8949. conclusion must change to accommodate how the program now consists of
  8950. one or more basic blocks. After the prelude in \code{main}, jump to
  8951. the \code{start} block. Place the conclusion in a basic block labeled
  8952. with \code{conclusion}.
  8953. \fi}
  8954. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8955. \LangIf{} translated to x86, showing the results of
  8956. \code{explicate\_control}, \code{select\_instructions}, and the final
  8957. x86 assembly.
  8958. \begin{figure}[tbp]
  8959. \begin{tcolorbox}[colback=white]
  8960. {\if\edition\racketEd
  8961. \begin{tabular}{lll}
  8962. \begin{minipage}{0.4\textwidth}
  8963. % cond_test_20.rkt, eq_input.py
  8964. \begin{lstlisting}
  8965. (if (eq? (read) 1) 42 0)
  8966. \end{lstlisting}
  8967. $\Downarrow$
  8968. \begin{lstlisting}
  8969. start:
  8970. tmp7951 = (read);
  8971. if (eq? tmp7951 1)
  8972. goto block7952;
  8973. else
  8974. goto block7953;
  8975. block7952:
  8976. return 42;
  8977. block7953:
  8978. return 0;
  8979. \end{lstlisting}
  8980. $\Downarrow$
  8981. \begin{lstlisting}
  8982. start:
  8983. callq read_int
  8984. movq %rax, tmp7951
  8985. cmpq $1, tmp7951
  8986. je block7952
  8987. jmp block7953
  8988. block7953:
  8989. movq $0, %rax
  8990. jmp conclusion
  8991. block7952:
  8992. movq $42, %rax
  8993. jmp conclusion
  8994. \end{lstlisting}
  8995. \end{minipage}
  8996. &
  8997. $\Rightarrow\qquad$
  8998. \begin{minipage}{0.4\textwidth}
  8999. \begin{lstlisting}
  9000. start:
  9001. callq read_int
  9002. movq %rax, %rcx
  9003. cmpq $1, %rcx
  9004. je block7952
  9005. jmp block7953
  9006. block7953:
  9007. movq $0, %rax
  9008. jmp conclusion
  9009. block7952:
  9010. movq $42, %rax
  9011. jmp conclusion
  9012. .globl main
  9013. main:
  9014. pushq %rbp
  9015. movq %rsp, %rbp
  9016. pushq %r13
  9017. pushq %r12
  9018. pushq %rbx
  9019. pushq %r14
  9020. subq $0, %rsp
  9021. jmp start
  9022. conclusion:
  9023. addq $0, %rsp
  9024. popq %r14
  9025. popq %rbx
  9026. popq %r12
  9027. popq %r13
  9028. popq %rbp
  9029. retq
  9030. \end{lstlisting}
  9031. \end{minipage}
  9032. \end{tabular}
  9033. \fi}
  9034. {\if\edition\pythonEd
  9035. \begin{tabular}{lll}
  9036. \begin{minipage}{0.4\textwidth}
  9037. % cond_test_20.rkt, eq_input.py
  9038. \begin{lstlisting}
  9039. print(42 if input_int() == 1 else 0)
  9040. \end{lstlisting}
  9041. $\Downarrow$
  9042. \begin{lstlisting}
  9043. start:
  9044. tmp_0 = input_int()
  9045. if tmp_0 == 1:
  9046. goto block_3
  9047. else:
  9048. goto block_4
  9049. block_3:
  9050. tmp_1 = 42
  9051. goto block_2
  9052. block_4:
  9053. tmp_1 = 0
  9054. goto block_2
  9055. block_2:
  9056. print(tmp_1)
  9057. return 0
  9058. \end{lstlisting}
  9059. $\Downarrow$
  9060. \begin{lstlisting}
  9061. start:
  9062. callq read_int
  9063. movq %rax, tmp_0
  9064. cmpq 1, tmp_0
  9065. je block_3
  9066. jmp block_4
  9067. block_3:
  9068. movq 42, tmp_1
  9069. jmp block_2
  9070. block_4:
  9071. movq 0, tmp_1
  9072. jmp block_2
  9073. block_2:
  9074. movq tmp_1, %rdi
  9075. callq print_int
  9076. movq 0, %rax
  9077. jmp conclusion
  9078. \end{lstlisting}
  9079. \end{minipage}
  9080. &
  9081. $\Rightarrow\qquad$
  9082. \begin{minipage}{0.4\textwidth}
  9083. \begin{lstlisting}
  9084. .globl main
  9085. main:
  9086. pushq %rbp
  9087. movq %rsp, %rbp
  9088. subq $0, %rsp
  9089. jmp start
  9090. start:
  9091. callq read_int
  9092. movq %rax, %rcx
  9093. cmpq $1, %rcx
  9094. je block_3
  9095. jmp block_4
  9096. block_3:
  9097. movq $42, %rcx
  9098. jmp block_2
  9099. block_4:
  9100. movq $0, %rcx
  9101. jmp block_2
  9102. block_2:
  9103. movq %rcx, %rdi
  9104. callq print_int
  9105. movq $0, %rax
  9106. jmp conclusion
  9107. conclusion:
  9108. addq $0, %rsp
  9109. popq %rbp
  9110. retq
  9111. \end{lstlisting}
  9112. \end{minipage}
  9113. \end{tabular}
  9114. \fi}
  9115. \end{tcolorbox}
  9116. \caption{Example compilation of an \key{if} expression to x86, showing
  9117. the results of \code{explicate\_control},
  9118. \code{select\_instructions}, and the final x86 assembly code. }
  9119. \label{fig:if-example-x86}
  9120. \end{figure}
  9121. \begin{figure}[tbp]
  9122. \begin{tcolorbox}[colback=white]
  9123. {\if\edition\racketEd
  9124. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9125. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9126. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9127. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9128. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9129. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9130. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9131. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9132. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9133. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9134. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9135. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9136. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9137. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9138. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9139. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  9140. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9141. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9142. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9143. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9144. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9145. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9146. \end{tikzpicture}
  9147. \fi}
  9148. {\if\edition\pythonEd
  9149. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9150. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9151. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9152. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9153. \node (C-1) at (0,0) {\large \LangCIf{}};
  9154. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9155. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9156. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9157. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9158. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9159. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9160. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  9161. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9162. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9163. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9164. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9165. \end{tikzpicture}
  9166. \fi}
  9167. \end{tcolorbox}
  9168. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9169. \label{fig:Lif-passes}
  9170. \end{figure}
  9171. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9172. compilation of \LangIf{}.
  9173. \section{Challenge: Optimize Blocks and Remove Jumps}
  9174. \label{sec:opt-jumps}
  9175. We discuss two optional challenges that involve optimizing the
  9176. control-flow of the program.
  9177. \subsection{Optimize Blocks}
  9178. The algorithm for \code{explicate\_control} that we discussed in
  9179. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9180. blocks. It creates a basic block whenever a continuation \emph{might}
  9181. get used more than once (e.g., whenever the \code{cont} parameter is
  9182. passed into two or more recursive calls). However, some continuation
  9183. arguments may not be used at all. For example, consider the case for
  9184. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  9185. \code{els} continuation.
  9186. %
  9187. {\if\edition\racketEd
  9188. The following example program falls into this
  9189. case, and it creates two unused blocks.
  9190. \begin{center}
  9191. \begin{tabular}{lll}
  9192. \begin{minipage}{0.4\textwidth}
  9193. % cond_test_82.rkt
  9194. \begin{lstlisting}
  9195. (let ([y (if #t
  9196. (read)
  9197. (if (eq? (read) 0)
  9198. 777
  9199. (let ([x (read)])
  9200. (+ 1 x))))])
  9201. (+ y 2))
  9202. \end{lstlisting}
  9203. \end{minipage}
  9204. &
  9205. $\Rightarrow$
  9206. &
  9207. \begin{minipage}{0.55\textwidth}
  9208. \begin{lstlisting}
  9209. start:
  9210. y = (read);
  9211. goto block_5;
  9212. block_5:
  9213. return (+ y 2);
  9214. block_6:
  9215. y = 777;
  9216. goto block_5;
  9217. block_7:
  9218. x = (read);
  9219. y = (+ 1 x2);
  9220. goto block_5;
  9221. \end{lstlisting}
  9222. \end{minipage}
  9223. \end{tabular}
  9224. \end{center}
  9225. \fi}
  9226. The question is, how can we decide whether to create a basic block?
  9227. \emph{Lazy evaluation}\index{subject}{lazy
  9228. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9229. delaying the creation of a basic block until the point in time at which
  9230. we know that it will be used.
  9231. %
  9232. {\if\edition\racketEd
  9233. %
  9234. Racket provides support for
  9235. lazy evaluation with the
  9236. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9237. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9238. \index{subject}{delay} creates a
  9239. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9240. expressions is postponed. When \key{(force}
  9241. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9242. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9243. result of $e_n$ is cached in the promise and returned. If \code{force}
  9244. is applied again to the same promise, then the cached result is
  9245. returned. If \code{force} is applied to an argument that is not a
  9246. promise, \code{force} simply returns the argument.
  9247. %
  9248. \fi}
  9249. %
  9250. {\if\edition\pythonEd
  9251. %
  9252. While Python does not provide direct support for lazy evaluation, it
  9253. is easy to mimic. We can \emph{delay} the evaluation of a computation
  9254. by wrapping it inside a function with no parameters. We can
  9255. \emph{force} its evaluation by calling the function. However, in some
  9256. cases of \code{explicate\_pred}, etc., we will return a list of
  9257. statements and in other cases we will return a function that computes
  9258. a list of statements. We use the term \emph{promise} to refer to a
  9259. value that may be delayed. To uniformly deal with
  9260. promises, we define the following \code{force} function that checks
  9261. whether its input is delayed (i.e., whether it is a function) and then
  9262. either 1) calls the function, or 2) returns the input.
  9263. \begin{lstlisting}
  9264. def force(promise):
  9265. if isinstance(promise, types.FunctionType):
  9266. return promise()
  9267. else:
  9268. return promise
  9269. \end{lstlisting}
  9270. %
  9271. \fi}
  9272. We use promises for the input and output of the functions
  9273. \code{explicate\_pred}, \code{explicate\_assign},
  9274. %
  9275. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9276. %
  9277. So, instead of taking and returning \racket{$\Tail$
  9278. expressions}\python{lists of statements}, they take and return
  9279. promises. Furthermore, when we come to a situation in which a
  9280. continuation might be used more than once, as in the case for
  9281. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9282. that creates a basic block for each continuation (if there is not
  9283. already one) and then returns a \code{goto} statement to that basic
  9284. block. When we come to a situation in which we have a promise but need an
  9285. actual piece of code, for example, to create a larger piece of code with a
  9286. constructor such as \code{Seq}, then insert a call to \code{force}.
  9287. %
  9288. {\if\edition\racketEd
  9289. %
  9290. Also, we must modify the \code{create\_block} function to begin with
  9291. \code{delay} to create a promise. When forced, this promise forces the
  9292. original promise. If that returns a \code{Goto} (because the block was
  9293. already added to \code{basic-blocks}), then we return the
  9294. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9295. return a \code{Goto} to the new label.
  9296. \begin{center}
  9297. \begin{minipage}{\textwidth}
  9298. \begin{lstlisting}
  9299. (define (create_block tail)
  9300. (delay
  9301. (define t (force tail))
  9302. (match t
  9303. [(Goto label) (Goto label)]
  9304. [else
  9305. (let ([label (gensym 'block)])
  9306. (set! basic-blocks (cons (cons label t) basic-blocks))
  9307. (Goto label))]))
  9308. \end{lstlisting}
  9309. \end{minipage}
  9310. \end{center}
  9311. \fi}
  9312. {\if\edition\pythonEd
  9313. %
  9314. Here is the new version of the \code{create\_block} auxiliary function
  9315. that works on promises and that checks whether the block consists of a
  9316. solitary \code{goto} statement.\\
  9317. \begin{minipage}{\textwidth}
  9318. \begin{lstlisting}
  9319. def create_block(promise, basic_blocks):
  9320. stmts = force(promise)
  9321. match stmts:
  9322. case [Goto(l)]:
  9323. return Goto(l)
  9324. case _:
  9325. label = label_name(generate_name('block'))
  9326. basic_blocks[label] = stmts
  9327. return Goto(label)
  9328. \end{lstlisting}
  9329. \end{minipage}
  9330. \fi}
  9331. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9332. improved \code{explicate\_control} on this example. As you can
  9333. see, the number of basic blocks has been reduced from four blocks (see
  9334. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9335. \begin{figure}[tbp]
  9336. \begin{tcolorbox}[colback=white]
  9337. {\if\edition\racketEd
  9338. \begin{tabular}{lll}
  9339. \begin{minipage}{0.4\textwidth}
  9340. % cond_test_82.rkt
  9341. \begin{lstlisting}
  9342. (let ([y (if #t
  9343. (read)
  9344. (if (eq? (read) 0)
  9345. 777
  9346. (let ([x (read)])
  9347. (+ 1 x))))])
  9348. (+ y 2))
  9349. \end{lstlisting}
  9350. \end{minipage}
  9351. &
  9352. $\Rightarrow$
  9353. &
  9354. \begin{minipage}{0.55\textwidth}
  9355. \begin{lstlisting}
  9356. start:
  9357. y = (read);
  9358. goto block_5;
  9359. block_5:
  9360. return (+ y 2);
  9361. \end{lstlisting}
  9362. \end{minipage}
  9363. \end{tabular}
  9364. \fi}
  9365. {\if\edition\pythonEd
  9366. \begin{tabular}{lll}
  9367. \begin{minipage}{0.4\textwidth}
  9368. % cond_test_41.rkt
  9369. \begin{lstlisting}
  9370. x = input_int()
  9371. y = input_int()
  9372. print(y + 2 \
  9373. if (x == 0 \
  9374. if x < 1 \
  9375. else x == 2) \
  9376. else y + 10)
  9377. \end{lstlisting}
  9378. \end{minipage}
  9379. &
  9380. $\Rightarrow$
  9381. &
  9382. \begin{minipage}{0.55\textwidth}
  9383. \begin{lstlisting}
  9384. start:
  9385. x = input_int()
  9386. y = input_int()
  9387. if x < 1:
  9388. goto block_4
  9389. else:
  9390. goto block_5
  9391. block_4:
  9392. if x == 0:
  9393. goto block_2
  9394. else:
  9395. goto block_3
  9396. block_5:
  9397. if x == 2:
  9398. goto block_2
  9399. else:
  9400. goto block_3
  9401. block_2:
  9402. tmp_0 = y + 2
  9403. goto block_1
  9404. block_3:
  9405. tmp_0 = y + 10
  9406. goto block_1
  9407. block_1:
  9408. print(tmp_0)
  9409. return 0
  9410. \end{lstlisting}
  9411. \end{minipage}
  9412. \end{tabular}
  9413. \fi}
  9414. \end{tcolorbox}
  9415. \caption{Translation from \LangIf{} to \LangCIf{}
  9416. via the improved \code{explicate\_control}.}
  9417. \label{fig:explicate-control-challenge}
  9418. \end{figure}
  9419. %% Recall that in the example output of \code{explicate\_control} in
  9420. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9421. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9422. %% block. The first goal of this challenge assignment is to remove those
  9423. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9424. %% \code{explicate\_control} on the left and shows the result of bypassing
  9425. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9426. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9427. %% \code{block55}. The optimized code on the right of
  9428. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9429. %% \code{then} branch jumping directly to \code{block55}. The story is
  9430. %% similar for the \code{else} branch, as well as for the two branches in
  9431. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9432. %% have been optimized in this way, there are no longer any jumps to
  9433. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9434. %% \begin{figure}[tbp]
  9435. %% \begin{tabular}{lll}
  9436. %% \begin{minipage}{0.4\textwidth}
  9437. %% \begin{lstlisting}
  9438. %% block62:
  9439. %% tmp54 = (read);
  9440. %% if (eq? tmp54 2) then
  9441. %% goto block59;
  9442. %% else
  9443. %% goto block60;
  9444. %% block61:
  9445. %% tmp53 = (read);
  9446. %% if (eq? tmp53 0) then
  9447. %% goto block57;
  9448. %% else
  9449. %% goto block58;
  9450. %% block60:
  9451. %% goto block56;
  9452. %% block59:
  9453. %% goto block55;
  9454. %% block58:
  9455. %% goto block56;
  9456. %% block57:
  9457. %% goto block55;
  9458. %% block56:
  9459. %% return (+ 700 77);
  9460. %% block55:
  9461. %% return (+ 10 32);
  9462. %% start:
  9463. %% tmp52 = (read);
  9464. %% if (eq? tmp52 1) then
  9465. %% goto block61;
  9466. %% else
  9467. %% goto block62;
  9468. %% \end{lstlisting}
  9469. %% \end{minipage}
  9470. %% &
  9471. %% $\Rightarrow$
  9472. %% &
  9473. %% \begin{minipage}{0.55\textwidth}
  9474. %% \begin{lstlisting}
  9475. %% block62:
  9476. %% tmp54 = (read);
  9477. %% if (eq? tmp54 2) then
  9478. %% goto block55;
  9479. %% else
  9480. %% goto block56;
  9481. %% block61:
  9482. %% tmp53 = (read);
  9483. %% if (eq? tmp53 0) then
  9484. %% goto block55;
  9485. %% else
  9486. %% goto block56;
  9487. %% block56:
  9488. %% return (+ 700 77);
  9489. %% block55:
  9490. %% return (+ 10 32);
  9491. %% start:
  9492. %% tmp52 = (read);
  9493. %% if (eq? tmp52 1) then
  9494. %% goto block61;
  9495. %% else
  9496. %% goto block62;
  9497. %% \end{lstlisting}
  9498. %% \end{minipage}
  9499. %% \end{tabular}
  9500. %% \caption{Optimize jumps by removing trivial blocks.}
  9501. %% \label{fig:optimize-jumps}
  9502. %% \end{figure}
  9503. %% The name of this pass is \code{optimize-jumps}. We recommend
  9504. %% implementing this pass in two phases. The first phrase builds a hash
  9505. %% table that maps labels to possibly improved labels. The second phase
  9506. %% changes the target of each \code{goto} to use the improved label. If
  9507. %% the label is for a trivial block, then the hash table should map the
  9508. %% label to the first non-trivial block that can be reached from this
  9509. %% label by jumping through trivial blocks. If the label is for a
  9510. %% non-trivial block, then the hash table should map the label to itself;
  9511. %% we do not want to change jumps to non-trivial blocks.
  9512. %% The first phase can be accomplished by constructing an empty hash
  9513. %% table, call it \code{short-cut}, and then iterating over the control
  9514. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9515. %% then update the hash table, mapping the block's source to the target
  9516. %% of the \code{goto}. Also, the hash table may already have mapped some
  9517. %% labels to the block's source, to you must iterate through the hash
  9518. %% table and update all of those so that they instead map to the target
  9519. %% of the \code{goto}.
  9520. %% For the second phase, we recommend iterating through the $\Tail$ of
  9521. %% each block in the program, updating the target of every \code{goto}
  9522. %% according to the mapping in \code{short-cut}.
  9523. \begin{exercise}\normalfont\normalsize
  9524. Implement the improvements to the \code{explicate\_control} pass.
  9525. Check that it removes trivial blocks in a few example programs. Then
  9526. check that your compiler still passes all your tests.
  9527. \end{exercise}
  9528. \subsection{Remove Jumps}
  9529. There is an opportunity for removing jumps that is apparent in the
  9530. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9531. ends with a jump to \code{block\_5}, and there are no other jumps to
  9532. \code{block\_5} in the rest of the program. In this situation we can
  9533. avoid the runtime overhead of this jump by merging \code{block\_5}
  9534. into the preceding block, which in this case is the \code{start} block.
  9535. Figure~\ref{fig:remove-jumps} shows the output of
  9536. \code{allocate\_registers} on the left and the result of this
  9537. optimization on the right.
  9538. \begin{figure}[tbp]
  9539. \begin{tcolorbox}[colback=white]
  9540. {\if\edition\racketEd
  9541. \begin{tabular}{lll}
  9542. \begin{minipage}{0.5\textwidth}
  9543. % cond_test_82.rkt
  9544. \begin{lstlisting}
  9545. start:
  9546. callq read_int
  9547. movq %rax, %rcx
  9548. jmp block_5
  9549. block_5:
  9550. movq %rcx, %rax
  9551. addq $2, %rax
  9552. jmp conclusion
  9553. \end{lstlisting}
  9554. \end{minipage}
  9555. &
  9556. $\Rightarrow\qquad$
  9557. \begin{minipage}{0.4\textwidth}
  9558. \begin{lstlisting}
  9559. start:
  9560. callq read_int
  9561. movq %rax, %rcx
  9562. movq %rcx, %rax
  9563. addq $2, %rax
  9564. jmp conclusion
  9565. \end{lstlisting}
  9566. \end{minipage}
  9567. \end{tabular}
  9568. \fi}
  9569. {\if\edition\pythonEd
  9570. \begin{tabular}{lll}
  9571. \begin{minipage}{0.5\textwidth}
  9572. % cond_test_20.rkt
  9573. \begin{lstlisting}
  9574. start:
  9575. callq read_int
  9576. movq %rax, tmp_0
  9577. cmpq 1, tmp_0
  9578. je block_3
  9579. jmp block_4
  9580. block_3:
  9581. movq 42, tmp_1
  9582. jmp block_2
  9583. block_4:
  9584. movq 0, tmp_1
  9585. jmp block_2
  9586. block_2:
  9587. movq tmp_1, %rdi
  9588. callq print_int
  9589. movq 0, %rax
  9590. jmp conclusion
  9591. \end{lstlisting}
  9592. \end{minipage}
  9593. &
  9594. $\Rightarrow\qquad$
  9595. \begin{minipage}{0.4\textwidth}
  9596. \begin{lstlisting}
  9597. start:
  9598. callq read_int
  9599. movq %rax, tmp_0
  9600. cmpq 1, tmp_0
  9601. je block_3
  9602. movq 0, tmp_1
  9603. jmp block_2
  9604. block_3:
  9605. movq 42, tmp_1
  9606. jmp block_2
  9607. block_2:
  9608. movq tmp_1, %rdi
  9609. callq print_int
  9610. movq 0, %rax
  9611. jmp conclusion
  9612. \end{lstlisting}
  9613. \end{minipage}
  9614. \end{tabular}
  9615. \fi}
  9616. \end{tcolorbox}
  9617. \caption{Merging basic blocks by removing unnecessary jumps.}
  9618. \label{fig:remove-jumps}
  9619. \end{figure}
  9620. \begin{exercise}\normalfont\normalsize
  9621. %
  9622. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9623. into their preceding basic block, when there is only one preceding
  9624. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9625. %
  9626. {\if\edition\racketEd
  9627. In the \code{run-tests.rkt} script, add the following entry to the
  9628. list of \code{passes} between \code{allocate\_registers}
  9629. and \code{patch\_instructions}:
  9630. \begin{lstlisting}
  9631. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9632. \end{lstlisting}
  9633. \fi}
  9634. %
  9635. Run the script to test your compiler.
  9636. %
  9637. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9638. blocks on several test programs.
  9639. \end{exercise}
  9640. \section{Further Reading}
  9641. \label{sec:cond-further-reading}
  9642. The algorithm for the \code{explicate\_control} pass is based on the
  9643. \code{expose-basic-blocks} pass in the course notes of
  9644. \citet{Dybvig:2010aa}.
  9645. %
  9646. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9647. \citet{Appel:2003fk}, and is related to translations into continuation
  9648. passing
  9649. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9650. %
  9651. The treatment of conditionals in the \code{explicate\_control} pass is
  9652. similar to short-cut boolean
  9653. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9654. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9655. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9656. \chapter{Loops and Dataflow Analysis}
  9657. \label{ch:Lwhile}
  9658. \setcounter{footnote}{0}
  9659. % TODO: define R'_8
  9660. % TODO: multi-graph
  9661. {\if\edition\racketEd
  9662. %
  9663. In this chapter we study two features that are the hallmarks of
  9664. imperative programming languages: loops and assignments to local
  9665. variables. The following example demonstrates these new features by
  9666. computing the sum of the first five positive integers:
  9667. % similar to loop_test_1.rkt
  9668. \begin{lstlisting}
  9669. (let ([sum 0])
  9670. (let ([i 5])
  9671. (begin
  9672. (while (> i 0)
  9673. (begin
  9674. (set! sum (+ sum i))
  9675. (set! i (- i 1))))
  9676. sum)))
  9677. \end{lstlisting}
  9678. The \code{while} loop consists of a condition and a
  9679. body.\footnote{The \code{while} loop is not a built-in
  9680. feature of the Racket language, but Racket includes many looping
  9681. constructs and it is straightforward to define \code{while} as a
  9682. macro.} The body is evaluated repeatedly so long as the condition
  9683. remains true.
  9684. %
  9685. The \code{set!} consists of a variable and a right-hand side
  9686. expression. The \code{set!} updates value of the variable to the
  9687. value of the right-hand side.
  9688. %
  9689. The primary purpose of both the \code{while} loop and \code{set!} is
  9690. to cause side effects, so they do not give a meaningful result
  9691. value. Instead, their result is the \code{\#<void>} value. The
  9692. expression \code{(void)} is an explicit way to create the
  9693. \code{\#<void>} value, and it has type \code{Void}. The
  9694. \code{\#<void>} value can be passed around just like other values
  9695. inside an \LangLoop{} program, and it can be compared for equality with
  9696. another \code{\#<void>} value. However, there are no other operations
  9697. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9698. Racket defines the \code{void?} predicate that returns \code{\#t}
  9699. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9700. %
  9701. \footnote{Racket's \code{Void} type corresponds to what is often
  9702. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9703. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9704. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9705. %
  9706. With the addition of side effect-producing features such as
  9707. \code{while} loop and \code{set!}, it is helpful to include a language
  9708. feature for sequencing side effects: the \code{begin} expression. It
  9709. consists of one or more subexpressions that are evaluated
  9710. left to right.
  9711. %
  9712. \fi}
  9713. {\if\edition\pythonEd
  9714. %
  9715. In this chapter we study loops, one of the hallmarks of imperative
  9716. programming languages. The following example demonstrates the
  9717. \code{while} loop by computing the sum of the first five positive
  9718. integers.
  9719. \begin{lstlisting}
  9720. sum = 0
  9721. i = 5
  9722. while i > 0:
  9723. sum = sum + i
  9724. i = i - 1
  9725. print(sum)
  9726. \end{lstlisting}
  9727. The \code{while} loop consists of a condition expression and a body (a
  9728. sequence of statements). The body is evaluated repeatedly so long as
  9729. the condition remains true.
  9730. %
  9731. \fi}
  9732. \section{The \LangLoop{} Language}
  9733. \newcommand{\LwhileGrammarRacket}{
  9734. \begin{array}{lcl}
  9735. \Type &::=& \key{Void}\\
  9736. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9737. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9738. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9739. \end{array}
  9740. }
  9741. \newcommand{\LwhileASTRacket}{
  9742. \begin{array}{lcl}
  9743. \Type &::=& \key{Void}\\
  9744. \Exp &::=& \SETBANG{\Var}{\Exp}
  9745. \MID \BEGIN{\Exp^{*}}{\Exp}
  9746. \MID \WHILE{\Exp}{\Exp}
  9747. \MID \VOID{}
  9748. \end{array}
  9749. }
  9750. \newcommand{\LwhileGrammarPython}{
  9751. \begin{array}{rcl}
  9752. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9753. \end{array}
  9754. }
  9755. \newcommand{\LwhileASTPython}{
  9756. \begin{array}{lcl}
  9757. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9758. \end{array}
  9759. }
  9760. \begin{figure}[tp]
  9761. \centering
  9762. \begin{tcolorbox}[colback=white]
  9763. \small
  9764. {\if\edition\racketEd
  9765. \[
  9766. \begin{array}{l}
  9767. \gray{\LintGrammarRacket{}} \\ \hline
  9768. \gray{\LvarGrammarRacket{}} \\ \hline
  9769. \gray{\LifGrammarRacket{}} \\ \hline
  9770. \LwhileGrammarRacket \\
  9771. \begin{array}{lcl}
  9772. \LangLoopM{} &::=& \Exp
  9773. \end{array}
  9774. \end{array}
  9775. \]
  9776. \fi}
  9777. {\if\edition\pythonEd
  9778. \[
  9779. \begin{array}{l}
  9780. \gray{\LintGrammarPython} \\ \hline
  9781. \gray{\LvarGrammarPython} \\ \hline
  9782. \gray{\LifGrammarPython} \\ \hline
  9783. \LwhileGrammarPython \\
  9784. \begin{array}{rcl}
  9785. \LangLoopM{} &::=& \Stmt^{*}
  9786. \end{array}
  9787. \end{array}
  9788. \]
  9789. \fi}
  9790. \end{tcolorbox}
  9791. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  9792. \label{fig:Lwhile-concrete-syntax}
  9793. \end{figure}
  9794. \begin{figure}[tp]
  9795. \centering
  9796. \begin{tcolorbox}[colback=white]
  9797. \small
  9798. {\if\edition\racketEd
  9799. \[
  9800. \begin{array}{l}
  9801. \gray{\LintOpAST} \\ \hline
  9802. \gray{\LvarASTRacket{}} \\ \hline
  9803. \gray{\LifASTRacket{}} \\ \hline
  9804. \LwhileASTRacket{} \\
  9805. \begin{array}{lcl}
  9806. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9807. \end{array}
  9808. \end{array}
  9809. \]
  9810. \fi}
  9811. {\if\edition\pythonEd
  9812. \[
  9813. \begin{array}{l}
  9814. \gray{\LintASTPython} \\ \hline
  9815. \gray{\LvarASTPython} \\ \hline
  9816. \gray{\LifASTPython} \\ \hline
  9817. \LwhileASTPython \\
  9818. \begin{array}{lcl}
  9819. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9820. \end{array}
  9821. \end{array}
  9822. \]
  9823. \fi}
  9824. \end{tcolorbox}
  9825. \python{
  9826. \index{subject}{While@\texttt{While}}
  9827. }
  9828. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  9829. \label{fig:Lwhile-syntax}
  9830. \end{figure}
  9831. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  9832. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  9833. shows the definition of its abstract syntax.
  9834. %
  9835. The definitional interpreter for \LangLoop{} is shown in
  9836. figure~\ref{fig:interp-Lwhile}.
  9837. %
  9838. {\if\edition\racketEd
  9839. %
  9840. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9841. and \code{Void}, and we make changes to the cases for \code{Var} and
  9842. \code{Let} regarding variables. To support assignment to variables and
  9843. to make their lifetimes indefinite (see the second example in
  9844. section~\ref{sec:assignment-scoping}), we box the value that is bound
  9845. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9846. value.
  9847. %
  9848. Now we discuss the new cases. For \code{SetBang}, we find the
  9849. variable in the environment to obtain a boxed value, and then we change
  9850. it using \code{set-box!} to the result of evaluating the right-hand
  9851. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9852. %
  9853. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  9854. if the result is true, (2) evaluate the body.
  9855. The result value of a \code{while} loop is also \code{\#<void>}.
  9856. %
  9857. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9858. subexpressions \itm{es} for their effects and then evaluates
  9859. and returns the result from \itm{body}.
  9860. %
  9861. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9862. %
  9863. \fi}
  9864. {\if\edition\pythonEd
  9865. %
  9866. We add a new case for \code{While} in the \code{interp\_stmts}
  9867. function, where we repeatedly interpret the \code{body} so long as the
  9868. \code{test} expression remains true.
  9869. %
  9870. \fi}
  9871. \begin{figure}[tbp]
  9872. \begin{tcolorbox}[colback=white]
  9873. {\if\edition\racketEd
  9874. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9875. (define interp-Lwhile-class
  9876. (class interp-Lif-class
  9877. (super-new)
  9878. (define/override ((interp-exp env) e)
  9879. (define recur (interp-exp env))
  9880. (match e
  9881. [(Let x e body)
  9882. (define new-env (dict-set env x (box (recur e))))
  9883. ((interp-exp new-env) body)]
  9884. [(Var x) (unbox (dict-ref env x))]
  9885. [(SetBang x rhs)
  9886. (set-box! (dict-ref env x) (recur rhs))]
  9887. [(WhileLoop cnd body)
  9888. (define (loop)
  9889. (cond [(recur cnd) (recur body) (loop)]
  9890. [else (void)]))
  9891. (loop)]
  9892. [(Begin es body)
  9893. (for ([e es]) (recur e))
  9894. (recur body)]
  9895. [(Void) (void)]
  9896. [else ((super interp-exp env) e)]))
  9897. ))
  9898. (define (interp-Lwhile p)
  9899. (send (new interp-Lwhile-class) interp-program p))
  9900. \end{lstlisting}
  9901. \fi}
  9902. {\if\edition\pythonEd
  9903. \begin{lstlisting}
  9904. class InterpLwhile(InterpLif):
  9905. def interp_stmts(self, ss, env):
  9906. if len(ss) == 0:
  9907. return
  9908. match ss[0]:
  9909. case While(test, body, []):
  9910. while self.interp_exp(test, env):
  9911. self.interp_stmts(body, env)
  9912. return self.interp_stmts(ss[1:], env)
  9913. case _:
  9914. return super().interp_stmts(ss, env)
  9915. \end{lstlisting}
  9916. \fi}
  9917. \end{tcolorbox}
  9918. \caption{Interpreter for \LangLoop{}.}
  9919. \label{fig:interp-Lwhile}
  9920. \end{figure}
  9921. The definition of the type checker for \LangLoop{} is shown in
  9922. figure~\ref{fig:type-check-Lwhile}.
  9923. %
  9924. {\if\edition\racketEd
  9925. %
  9926. The type checking of the \code{SetBang} expression requires the type
  9927. of the variable and the right-hand side to agree. The result type is
  9928. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9929. and the result type is \code{Void}. For \code{Begin}, the result type
  9930. is the type of its last subexpression.
  9931. %
  9932. \fi}
  9933. %
  9934. {\if\edition\pythonEd
  9935. %
  9936. A \code{while} loop is well typed if the type of the \code{test}
  9937. expression is \code{bool} and the statements in the \code{body} are
  9938. well typed.
  9939. %
  9940. \fi}
  9941. \begin{figure}[tbp]
  9942. \begin{tcolorbox}[colback=white]
  9943. {\if\edition\racketEd
  9944. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9945. (define type-check-Lwhile-class
  9946. (class type-check-Lif-class
  9947. (super-new)
  9948. (inherit check-type-equal?)
  9949. (define/override (type-check-exp env)
  9950. (lambda (e)
  9951. (define recur (type-check-exp env))
  9952. (match e
  9953. [(SetBang x rhs)
  9954. (define-values (rhs^ rhsT) (recur rhs))
  9955. (define varT (dict-ref env x))
  9956. (check-type-equal? rhsT varT e)
  9957. (values (SetBang x rhs^) 'Void)]
  9958. [(WhileLoop cnd body)
  9959. (define-values (cnd^ Tc) (recur cnd))
  9960. (check-type-equal? Tc 'Boolean e)
  9961. (define-values (body^ Tbody) ((type-check-exp env) body))
  9962. (values (WhileLoop cnd^ body^) 'Void)]
  9963. [(Begin es body)
  9964. (define-values (es^ ts)
  9965. (for/lists (l1 l2) ([e es]) (recur e)))
  9966. (define-values (body^ Tbody) (recur body))
  9967. (values (Begin es^ body^) Tbody)]
  9968. [else ((super type-check-exp env) e)])))
  9969. ))
  9970. (define (type-check-Lwhile p)
  9971. (send (new type-check-Lwhile-class) type-check-program p))
  9972. \end{lstlisting}
  9973. \fi}
  9974. {\if\edition\pythonEd
  9975. \begin{lstlisting}
  9976. class TypeCheckLwhile(TypeCheckLif):
  9977. def type_check_stmts(self, ss, env):
  9978. if len(ss) == 0:
  9979. return
  9980. match ss[0]:
  9981. case While(test, body, []):
  9982. test_t = self.type_check_exp(test, env)
  9983. check_type_equal(bool, test_t, test)
  9984. body_t = self.type_check_stmts(body, env)
  9985. return self.type_check_stmts(ss[1:], env)
  9986. case _:
  9987. return super().type_check_stmts(ss, env)
  9988. \end{lstlisting}
  9989. \fi}
  9990. \end{tcolorbox}
  9991. \caption{Type checker for the \LangLoop{} language.}
  9992. \label{fig:type-check-Lwhile}
  9993. \end{figure}
  9994. {\if\edition\racketEd
  9995. %
  9996. At first glance, the translation of these language features to x86
  9997. seems straightforward because the \LangCIf{} intermediate language
  9998. already supports all the ingredients that we need: assignment,
  9999. \code{goto}, conditional branching, and sequencing. However, there are
  10000. complications that arise, which we discuss in the next section. After
  10001. that we introduce the changes necessary to the existing passes.
  10002. %
  10003. \fi}
  10004. {\if\edition\pythonEd
  10005. %
  10006. At first glance, the translation of \code{while} loops to x86 seems
  10007. straightforward because the \LangCIf{} intermediate language already
  10008. supports \code{goto} and conditional branching. However, there are
  10009. complications that arise which we discuss in the next section. After
  10010. that we introduce the changes necessary to the existing passes.
  10011. %
  10012. \fi}
  10013. \section{Cyclic Control Flow and Dataflow Analysis}
  10014. \label{sec:dataflow-analysis}
  10015. Up until this point, the programs generated in
  10016. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10017. \code{while} loop introduces a cycle. Does that matter?
  10018. %
  10019. Indeed, it does. Recall that for register allocation, the compiler
  10020. performs liveness analysis to determine which variables can share the
  10021. same register. To accomplish this, we analyzed the control-flow graph
  10022. in reverse topological order
  10023. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10024. well defined only for acyclic graphs.
  10025. Let us return to the example of computing the sum of the first five
  10026. positive integers. Here is the program after instruction selection but
  10027. before register allocation.
  10028. \begin{center}
  10029. {\if\edition\racketEd
  10030. \begin{minipage}{0.45\textwidth}
  10031. \begin{lstlisting}
  10032. (define (main) : Integer
  10033. mainstart:
  10034. movq $0, sum
  10035. movq $5, i
  10036. jmp block5
  10037. block5:
  10038. movq i, tmp3
  10039. cmpq tmp3, $0
  10040. jl block7
  10041. jmp block8
  10042. \end{lstlisting}
  10043. \end{minipage}
  10044. \begin{minipage}{0.45\textwidth}
  10045. \begin{lstlisting}
  10046. block7:
  10047. addq i, sum
  10048. movq $1, tmp4
  10049. negq tmp4
  10050. addq tmp4, i
  10051. jmp block5
  10052. block8:
  10053. movq $27, %rax
  10054. addq sum, %rax
  10055. jmp mainconclusion
  10056. )
  10057. \end{lstlisting}
  10058. \end{minipage}
  10059. \fi}
  10060. {\if\edition\pythonEd
  10061. \begin{minipage}{0.45\textwidth}
  10062. \begin{lstlisting}
  10063. mainstart:
  10064. movq $0, sum
  10065. movq $5, i
  10066. jmp block5
  10067. block5:
  10068. cmpq $0, i
  10069. jg block7
  10070. jmp block8
  10071. \end{lstlisting}
  10072. \end{minipage}
  10073. \begin{minipage}{0.45\textwidth}
  10074. \begin{lstlisting}
  10075. block7:
  10076. addq i, sum
  10077. subq $1, i
  10078. jmp block5
  10079. block8:
  10080. movq sum, %rdi
  10081. callq print_int
  10082. movq $0, %rax
  10083. jmp mainconclusion
  10084. \end{lstlisting}
  10085. \end{minipage}
  10086. \fi}
  10087. \end{center}
  10088. Recall that liveness analysis works backward, starting at the end
  10089. of each function. For this example we could start with \code{block8}
  10090. because we know what is live at the beginning of the conclusion:
  10091. only \code{rax} and \code{rsp}. So the live-before set
  10092. for \code{block8} is \code{\{rsp,sum\}}.
  10093. %
  10094. Next we might try to analyze \code{block5} or \code{block7}, but
  10095. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10096. we are stuck.
  10097. The way out of this impasse is to realize that we can compute an
  10098. underapproximation of each live-before set by starting with empty
  10099. live-after sets. By \emph{underapproximation}, we mean that the set
  10100. contains only variables that are live for some execution of the
  10101. program, but the set may be missing some variables that are live.
  10102. Next, the underapproximations for each block can be improved by (1)
  10103. updating the live-after set for each block using the approximate
  10104. live-before sets from the other blocks, and (2) performing liveness
  10105. analysis again on each block. In fact, by iterating this process, the
  10106. underapproximations eventually become the correct solutions!
  10107. %
  10108. This approach of iteratively analyzing a control-flow graph is
  10109. applicable to many static analysis problems and goes by the name
  10110. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10111. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10112. Washington.
  10113. Let us apply this approach to the previously presented example. We use
  10114. the empty set for the initial live-before set for each block. Let
  10115. $m_0$ be the following mapping from label names to sets of locations
  10116. (variables and registers):
  10117. \begin{center}
  10118. \begin{lstlisting}
  10119. mainstart: {}, block5: {}, block7: {}, block8: {}
  10120. \end{lstlisting}
  10121. \end{center}
  10122. Using the above live-before approximations, we determine the
  10123. live-after for each block and then apply liveness analysis to each
  10124. block. This produces our next approximation $m_1$ of the live-before
  10125. sets.
  10126. \begin{center}
  10127. \begin{lstlisting}
  10128. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10129. \end{lstlisting}
  10130. \end{center}
  10131. For the second round, the live-after for \code{mainstart} is the
  10132. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10133. the liveness analysis for \code{mainstart} computes the empty set. The
  10134. live-after for \code{block5} is the union of the live-before sets for
  10135. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  10136. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  10137. sum\}}. The live-after for \code{block7} is the live-before for
  10138. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10139. So the liveness analysis for \code{block7} remains \code{\{i,
  10140. sum\}}. Together these yield the following approximation $m_2$ of
  10141. the live-before sets:
  10142. \begin{center}
  10143. \begin{lstlisting}
  10144. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10145. \end{lstlisting}
  10146. \end{center}
  10147. In the preceding iteration, only \code{block5} changed, so we can
  10148. limit our attention to \code{mainstart} and \code{block7}, the two
  10149. blocks that jump to \code{block5}. As a result, the live-before sets
  10150. for \code{mainstart} and \code{block7} are updated to include
  10151. \code{rsp}, yielding the following approximation $m_3$:
  10152. \begin{center}
  10153. \begin{lstlisting}
  10154. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10155. \end{lstlisting}
  10156. \end{center}
  10157. Because \code{block7} changed, we analyze \code{block5} once more, but
  10158. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10159. our approximations have converged, so $m_3$ is the solution.
  10160. This iteration process is guaranteed to converge to a solution by the
  10161. Kleene fixed-point theorem, a general theorem about functions on
  10162. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10163. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10164. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10165. join operator
  10166. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  10167. ordering}\index{subject}{join}\footnote{Technically speaking, we
  10168. will be working with join semilattices.} When two elements are
  10169. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10170. as much information as $m_i$, so we can think of $m_j$ as a
  10171. better-than-or-equal-to approximation in relation to $m_i$. The
  10172. bottom element $\bot$ represents the complete lack of information,
  10173. that is, the worst approximation. The join operator takes two lattice
  10174. elements and combines their information; that is, it produces the
  10175. least upper bound of the two.\index{subject}{least upper bound}
  10176. A dataflow analysis typically involves two lattices: one lattice to
  10177. represent abstract states and another lattice that aggregates the
  10178. abstract states of all the blocks in the control-flow graph. For
  10179. liveness analysis, an abstract state is a set of locations. We form
  10180. the lattice $L$ by taking its elements to be sets of locations, the
  10181. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10182. set, and the join operator to be set union.
  10183. %
  10184. We form a second lattice $M$ by taking its elements to be mappings
  10185. from the block labels to sets of locations (elements of $L$). We
  10186. order the mappings point-wise, using the ordering of $L$. So, given any
  10187. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10188. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10189. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10190. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10191. We can think of one iteration of liveness analysis applied to the
  10192. whole program as being a function $f$ on the lattice $M$. It takes a
  10193. mapping as input and computes a new mapping.
  10194. \[
  10195. f(m_i) = m_{i+1}
  10196. \]
  10197. Next let us think for a moment about what a final solution $m_s$
  10198. should look like. If we perform liveness analysis using the solution
  10199. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10200. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10201. \[
  10202. f(m_s) = m_s
  10203. \]
  10204. Furthermore, the solution should include only locations that are
  10205. forced to be there by performing liveness analysis on the program, so
  10206. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10207. The Kleene fixed-point theorem states that if a function $f$ is
  10208. monotone (better inputs produce better outputs), then the least fixed
  10209. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10210. chain} obtained by starting at $\bot$ and iterating $f$, as
  10211. follows:\index{subject}{Kleene fixed-point theorem}
  10212. \[
  10213. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10214. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10215. \]
  10216. When a lattice contains only finitely long ascending chains, then
  10217. every Kleene chain tops out at some fixed point after some number of
  10218. iterations of $f$.
  10219. \[
  10220. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10221. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10222. \]
  10223. The liveness analysis is indeed a monotone function and the lattice
  10224. $M$ has finitely long ascending chains because there are only a
  10225. finite number of variables and blocks in the program. Thus we are
  10226. guaranteed that iteratively applying liveness analysis to all blocks
  10227. in the program will eventually produce the least fixed point solution.
  10228. Next let us consider dataflow analysis in general and discuss the
  10229. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10230. %
  10231. The algorithm has four parameters: the control-flow graph \code{G}, a
  10232. function \code{transfer} that applies the analysis to one block, and the
  10233. \code{bottom} and \code{join} operators for the lattice of abstract
  10234. states. The \code{analyze\_dataflow} function is formulated as a
  10235. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10236. function come from the predecessor nodes in the control-flow
  10237. graph. However, liveness analysis is a \emph{backward} dataflow
  10238. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10239. function with the transpose of the control-flow graph.
  10240. The algorithm begins by creating the bottom mapping, represented by a
  10241. hash table. It then pushes all the nodes in the control-flow graph
  10242. onto the work list (a queue). The algorithm repeats the \code{while}
  10243. loop as long as there are items in the work list. In each iteration, a
  10244. node is popped from the work list and processed. The \code{input} for
  10245. the node is computed by taking the join of the abstract states of all
  10246. the predecessor nodes. The \code{transfer} function is then applied to
  10247. obtain the \code{output} abstract state. If the output differs from
  10248. the previous state for this block, the mapping for this block is
  10249. updated and its successor nodes are pushed onto the work list.
  10250. \begin{figure}[tb]
  10251. \begin{tcolorbox}[colback=white]
  10252. {\if\edition\racketEd
  10253. \begin{lstlisting}
  10254. (define (analyze_dataflow G transfer bottom join)
  10255. (define mapping (make-hash))
  10256. (for ([v (in-vertices G)])
  10257. (dict-set! mapping v bottom))
  10258. (define worklist (make-queue))
  10259. (for ([v (in-vertices G)])
  10260. (enqueue! worklist v))
  10261. (define trans-G (transpose G))
  10262. (while (not (queue-empty? worklist))
  10263. (define node (dequeue! worklist))
  10264. (define input (for/fold ([state bottom])
  10265. ([pred (in-neighbors trans-G node)])
  10266. (join state (dict-ref mapping pred))))
  10267. (define output (transfer node input))
  10268. (cond [(not (equal? output (dict-ref mapping node)))
  10269. (dict-set! mapping node output)
  10270. (for ([v (in-neighbors G node)])
  10271. (enqueue! worklist v))]))
  10272. mapping)
  10273. \end{lstlisting}
  10274. \fi}
  10275. {\if\edition\pythonEd
  10276. \begin{lstlisting}
  10277. def analyze_dataflow(G, transfer, bottom, join):
  10278. trans_G = transpose(G)
  10279. mapping = dict((v, bottom) for v in G.vertices())
  10280. worklist = deque(G.vertices)
  10281. while worklist:
  10282. node = worklist.pop()
  10283. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10284. input = reduce(join, inputs, bottom)
  10285. output = transfer(node, input)
  10286. if output != mapping[node]:
  10287. mapping[node] = output
  10288. worklist.extend(G.adjacent(node))
  10289. \end{lstlisting}
  10290. \fi}
  10291. \end{tcolorbox}
  10292. \caption{Generic work list algorithm for dataflow analysis}
  10293. \label{fig:generic-dataflow}
  10294. \end{figure}
  10295. {\if\edition\racketEd
  10296. \section{Mutable Variables and Remove Complex Operands}
  10297. There is a subtle interaction between the
  10298. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10299. and the left-to-right order of evaluation of Racket. Consider the
  10300. following example:
  10301. \begin{lstlisting}
  10302. (let ([x 2])
  10303. (+ x (begin (set! x 40) x)))
  10304. \end{lstlisting}
  10305. The result of this program is \code{42} because the first read from
  10306. \code{x} produces \code{2} and the second produces \code{40}. However,
  10307. if we naively apply the \code{remove\_complex\_operands} pass to this
  10308. example we obtain the following program whose result is \code{80}!
  10309. \begin{lstlisting}
  10310. (let ([x 2])
  10311. (let ([tmp (begin (set! x 40) x)])
  10312. (+ x tmp)))
  10313. \end{lstlisting}
  10314. The problem is that with mutable variables, the ordering between
  10315. reads and writes is important, and the
  10316. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10317. before the first read of \code{x}.
  10318. We recommend solving this problem by giving special treatment to reads
  10319. from mutable variables, that is, variables that occur on the left-hand
  10320. side of a \code{set!}. We mark each read from a mutable variable with
  10321. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10322. that the read operation is effectful in that it can produce different
  10323. results at different points in time. Let's apply this idea to the
  10324. following variation that also involves a variable that is not mutated:
  10325. % loop_test_24.rkt
  10326. \begin{lstlisting}
  10327. (let ([x 2])
  10328. (let ([y 0])
  10329. (+ y (+ x (begin (set! x 40) x)))))
  10330. \end{lstlisting}
  10331. We first analyze this program to discover that variable \code{x}
  10332. is mutable but \code{y} is not. We then transform the program as
  10333. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10334. \begin{lstlisting}
  10335. (let ([x 2])
  10336. (let ([y 0])
  10337. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10338. \end{lstlisting}
  10339. Now that we have a clear distinction between reads from mutable and
  10340. immutable variables, we can apply the \code{remove\_complex\_operands}
  10341. pass, where reads from immutable variables are still classified as
  10342. atomic expressions but reads from mutable variables are classified as
  10343. complex. Thus, \code{remove\_complex\_operands} yields the following
  10344. program:\\
  10345. \begin{minipage}{\textwidth}
  10346. \begin{lstlisting}
  10347. (let ([x 2])
  10348. (let ([y 0])
  10349. (+ y (let ([t1 (get! x)])
  10350. (let ([t2 (begin (set! x 40) (get! x))])
  10351. (+ t1 t2))))))
  10352. \end{lstlisting}
  10353. \end{minipage}
  10354. The temporary variable \code{t1} gets the value of \code{x} before the
  10355. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10356. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10357. do not generate a temporary variable for the occurrence of \code{y}
  10358. because it's an immutable variable. We want to avoid such unnecessary
  10359. extra temporaries because they would needless increase the number of
  10360. variables, making it more likely for some of them to be spilled. The
  10361. result of this program is \code{42}, the same as the result prior to
  10362. \code{remove\_complex\_operands}.
  10363. The approach that we've sketched requires only a small
  10364. modification to \code{remove\_complex\_operands} to handle
  10365. \code{get!}. However, it requires a new pass, called
  10366. \code{uncover-get!}, that we discuss in
  10367. section~\ref{sec:uncover-get-bang}.
  10368. As an aside, this problematic interaction between \code{set!} and the
  10369. pass \code{remove\_complex\_operands} is particular to Racket and not
  10370. its predecessor, the Scheme language. The key difference is that
  10371. Scheme does not specify an order of evaluation for the arguments of an
  10372. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10373. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10374. would be correct results for the example program. Interestingly,
  10375. Racket is implemented on top of the Chez Scheme
  10376. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10377. presented in this section (using extra \code{let} bindings to control
  10378. the order of evaluation) is used in the translation from Racket to
  10379. Scheme~\citep{Flatt:2019tb}.
  10380. \fi} % racket
  10381. Having discussed the complications that arise from adding support for
  10382. assignment and loops, we turn to discussing the individual compilation
  10383. passes.
  10384. {\if\edition\racketEd
  10385. \section{Uncover \texttt{get!}}
  10386. \label{sec:uncover-get-bang}
  10387. The goal of this pass is to mark uses of mutable variables so that
  10388. \code{remove\_complex\_operands} can treat them as complex expressions
  10389. and thereby preserve their ordering relative to the side effects in
  10390. other operands. So, the first step is to collect all the mutable
  10391. variables. We recommend creating an auxiliary function for this,
  10392. named \code{collect-set!}, that recursively traverses expressions,
  10393. returning the set of all variables that occur on the left-hand side of a
  10394. \code{set!}. Here's an excerpt of its implementation.
  10395. \begin{center}
  10396. \begin{minipage}{\textwidth}
  10397. \begin{lstlisting}
  10398. (define (collect-set! e)
  10399. (match e
  10400. [(Var x) (set)]
  10401. [(Int n) (set)]
  10402. [(Let x rhs body)
  10403. (set-union (collect-set! rhs) (collect-set! body))]
  10404. [(SetBang var rhs)
  10405. (set-union (set var) (collect-set! rhs))]
  10406. ...))
  10407. \end{lstlisting}
  10408. \end{minipage}
  10409. \end{center}
  10410. By placing this pass after \code{uniquify}, we need not worry about
  10411. variable shadowing, and our logic for \code{Let} can remain simple, as
  10412. in this excerpt.
  10413. The second step is to mark the occurrences of the mutable variables
  10414. with the new \code{GetBang} AST node (\code{get!} in concrete
  10415. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10416. function, which takes two parameters: the set of mutable variables
  10417. \code{set!-vars} and the expression \code{e} to be processed. The
  10418. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10419. mutable variable or leaves it alone if not.
  10420. \begin{center}
  10421. \begin{minipage}{\textwidth}
  10422. \begin{lstlisting}
  10423. (define ((uncover-get!-exp set!-vars) e)
  10424. (match e
  10425. [(Var x)
  10426. (if (set-member? set!-vars x)
  10427. (GetBang x)
  10428. (Var x))]
  10429. ...))
  10430. \end{lstlisting}
  10431. \end{minipage}
  10432. \end{center}
  10433. To wrap things up, define the \code{uncover-get!} function for
  10434. processing a whole program, using \code{collect-set!} to obtain the
  10435. set of mutable variables and then \code{uncover-get!-exp} to replace
  10436. their occurrences with \code{GetBang}.
  10437. \fi}
  10438. \section{Remove Complex Operands}
  10439. \label{sec:rco-loop}
  10440. {\if\edition\racketEd
  10441. %
  10442. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10443. \code{while} are all complex expressions. The subexpressions of
  10444. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10445. %
  10446. \fi}
  10447. {\if\edition\pythonEd
  10448. %
  10449. The change needed for this pass is to add a case for the \code{while}
  10450. statement. The condition of a \code{while} loop is allowed to be a
  10451. complex expression, just like the condition of the \code{if}
  10452. statement.
  10453. %
  10454. \fi}
  10455. %
  10456. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10457. \LangLoopANF{} of this pass.
  10458. \newcommand{\LwhileMonadASTRacket}{
  10459. \begin{array}{rcl}
  10460. \Atm &::=& \VOID{} \\
  10461. \Exp &::=& \GETBANG{\Var}
  10462. \MID \SETBANG{\Var}{\Exp}
  10463. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10464. &\MID& \WHILE{\Exp}{\Exp}
  10465. \end{array}
  10466. }
  10467. \newcommand{\LwhileMonadASTPython}{
  10468. \begin{array}{rcl}
  10469. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10470. \end{array}
  10471. }
  10472. \begin{figure}[tp]
  10473. \centering
  10474. \begin{tcolorbox}[colback=white]
  10475. \small
  10476. {\if\edition\racketEd
  10477. \[
  10478. \begin{array}{l}
  10479. \gray{\LvarMonadASTRacket} \\ \hline
  10480. \gray{\LifMonadASTRacket} \\ \hline
  10481. \LwhileMonadASTRacket \\
  10482. \begin{array}{rcl}
  10483. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10484. \end{array}
  10485. \end{array}
  10486. \]
  10487. \fi}
  10488. {\if\edition\pythonEd
  10489. \[
  10490. \begin{array}{l}
  10491. \gray{\LvarMonadASTPython} \\ \hline
  10492. \gray{\LifMonadASTPython} \\ \hline
  10493. \LwhileMonadASTPython \\
  10494. \begin{array}{rcl}
  10495. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10496. \end{array}
  10497. \end{array}
  10498. %% \begin{array}{rcl}
  10499. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10500. %% \Exp &::=& \Atm \MID \READ{} \\
  10501. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10502. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10503. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10504. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10505. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10506. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10507. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10508. %% \end{array}
  10509. \]
  10510. \fi}
  10511. \end{tcolorbox}
  10512. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10513. \label{fig:Lwhile-anf-syntax}
  10514. \end{figure}
  10515. {\if\edition\racketEd
  10516. %
  10517. As usual, when a complex expression appears in a grammar position that
  10518. needs to be atomic, such as the argument of a primitive operator, we
  10519. must introduce a temporary variable and bind it to the complex
  10520. expression. This approach applies, unchanged, to handle the new
  10521. language forms. For example, in the following code there are two
  10522. \code{begin} expressions appearing as arguments to the \code{+}
  10523. operator. The output of \code{rco\_exp} is then shown, in which the
  10524. \code{begin} expressions have been bound to temporary
  10525. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10526. allowed to have arbitrary expressions in their right-hand side
  10527. expression, so it is fine to place \code{begin} there.
  10528. %
  10529. \begin{center}
  10530. \begin{tabular}{lcl}
  10531. \begin{minipage}{0.4\textwidth}
  10532. \begin{lstlisting}
  10533. (let ([x2 10])
  10534. (let ([y3 0])
  10535. (+ (+ (begin
  10536. (set! y3 (read))
  10537. (get! x2))
  10538. (begin
  10539. (set! x2 (read))
  10540. (get! y3)))
  10541. (get! x2))))
  10542. \end{lstlisting}
  10543. \end{minipage}
  10544. &
  10545. $\Rightarrow$
  10546. &
  10547. \begin{minipage}{0.4\textwidth}
  10548. \begin{lstlisting}
  10549. (let ([x2 10])
  10550. (let ([y3 0])
  10551. (let ([tmp4 (begin
  10552. (set! y3 (read))
  10553. x2)])
  10554. (let ([tmp5 (begin
  10555. (set! x2 (read))
  10556. y3)])
  10557. (let ([tmp6 (+ tmp4 tmp5)])
  10558. (let ([tmp7 x2])
  10559. (+ tmp6 tmp7)))))))
  10560. \end{lstlisting}
  10561. \end{minipage}
  10562. \end{tabular}
  10563. \end{center}
  10564. \fi}
  10565. \section{Explicate Control \racket{and \LangCLoop{}}}
  10566. \label{sec:explicate-loop}
  10567. \newcommand{\CloopASTRacket}{
  10568. \begin{array}{lcl}
  10569. \Atm &::=& \VOID \\
  10570. \Stmt &::=& \READ{}
  10571. \end{array}
  10572. }
  10573. {\if\edition\racketEd
  10574. Recall that in the \code{explicate\_control} pass we define one helper
  10575. function for each kind of position in the program. For the \LangVar{}
  10576. language of integers and variables, we needed assignment and tail
  10577. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10578. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10579. another kind of position: effect position. Except for the last
  10580. subexpression, the subexpressions inside a \code{begin} are evaluated
  10581. only for their effect. Their result values are discarded. We can
  10582. generate better code by taking this fact into account.
  10583. The output language of \code{explicate\_control} is \LangCLoop{}
  10584. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10585. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10586. and that \code{read} may appear as a statement. The most significant
  10587. difference between the programs generated by \code{explicate\_control}
  10588. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10589. chapter is that the control-flow graphs of the latter may contain
  10590. cycles.
  10591. \begin{figure}[tp]
  10592. \begin{tcolorbox}[colback=white]
  10593. \small
  10594. \[
  10595. \begin{array}{l}
  10596. \gray{\CvarASTRacket} \\ \hline
  10597. \gray{\CifASTRacket} \\ \hline
  10598. \CloopASTRacket \\
  10599. \begin{array}{lcl}
  10600. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10601. \end{array}
  10602. \end{array}
  10603. \]
  10604. \end{tcolorbox}
  10605. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10606. \label{fig:c7-syntax}
  10607. \end{figure}
  10608. The new auxiliary function \code{explicate\_effect} takes an
  10609. expression (in an effect position) and the code for its
  10610. continuation. The function returns a $\Tail$ that includes the
  10611. generated code for the input expression followed by the
  10612. continuation. If the expression is obviously pure, that is, never
  10613. causes side effects, then the expression can be removed, so the result
  10614. is just the continuation.
  10615. %
  10616. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10617. interesting; the generated code is depicted in the following diagram:
  10618. \begin{center}
  10619. \begin{minipage}{0.3\textwidth}
  10620. \xymatrix{
  10621. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10622. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10623. & *+[F]{\txt{\itm{cont}}} \\
  10624. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10625. }
  10626. \end{minipage}
  10627. \end{center}
  10628. We start by creating a fresh label $\itm{loop}$ for the top of the
  10629. loop. Next, recursively process the \itm{body} (in effect position)
  10630. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10631. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10632. \itm{body'} as the \emph{then} branch and the continuation block as the
  10633. \emph{else} branch. The result should be added to the dictionary of
  10634. \code{basic-blocks} with the label \itm{loop}. The result for the
  10635. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10636. The auxiliary functions for tail, assignment, and predicate positions
  10637. need to be updated. The three new language forms, \code{while},
  10638. \code{set!}, and \code{begin}, can appear in assignment and tail
  10639. positions. Only \code{begin} may appear in predicate positions; the
  10640. other two have result type \code{Void}.
  10641. \fi}
  10642. %
  10643. {\if\edition\pythonEd
  10644. %
  10645. The output of this pass is the language \LangCIf{}. No new language
  10646. features are needed in the output because a \code{while} loop can be
  10647. expressed in terms of \code{goto} and \code{if} statements, which are
  10648. already in \LangCIf{}.
  10649. %
  10650. Add a case for the \code{while} statement to the
  10651. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10652. the condition expression.
  10653. %
  10654. \fi}
  10655. {\if\edition\racketEd
  10656. \section{Select Instructions}
  10657. \label{sec:select-instructions-loop}
  10658. Only two small additions are needed in the \code{select\_instructions}
  10659. pass to handle the changes to \LangCLoop{}. First, to handle the
  10660. addition of \VOID{} we simply translate it to \code{0}. Second,
  10661. \code{read} may appear as a stand-alone statement instead of
  10662. appearing only on the right-hand side of an assignment statement. The code
  10663. generation is nearly identical to the one for assignment; just leave
  10664. off the instruction for moving the result into the left-hand side.
  10665. \fi}
  10666. \section{Register Allocation}
  10667. \label{sec:register-allocation-loop}
  10668. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10669. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10670. which complicates the liveness analysis needed for register
  10671. allocation.
  10672. %
  10673. We recommend using the generic \code{analyze\_dataflow} function that
  10674. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10675. perform liveness analysis, replacing the code in
  10676. \code{uncover\_live} that processed the basic blocks in topological
  10677. order (section~\ref{sec:liveness-analysis-Lif}).
  10678. The \code{analyze\_dataflow} function has the following four parameters.
  10679. \begin{enumerate}
  10680. \item The first parameter \code{G} should be passed the transpose
  10681. of the control-flow graph.
  10682. \item The second parameter \code{transfer} should be passed a function
  10683. that applies liveness analysis to a basic block. It takes two
  10684. parameters: the label for the block to analyze and the live-after
  10685. set for that block. The transfer function should return the
  10686. live-before set for the block.
  10687. %
  10688. \racket{Also, as a side effect, it should update the block's
  10689. $\itm{info}$ with the liveness information for each instruction.}
  10690. %
  10691. \python{Also, as a side-effect, it should update the live-before and
  10692. live-after sets for each instruction.}
  10693. %
  10694. To implement the \code{transfer} function, you should be able to
  10695. reuse the code you already have for analyzing basic blocks.
  10696. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10697. \code{bottom} and \code{join} for the lattice of abstract states,
  10698. that is, sets of locations. For liveness analysis, the bottom of the
  10699. lattice is the empty set, and the join operator is set union.
  10700. \end{enumerate}
  10701. \begin{figure}[p]
  10702. \begin{tcolorbox}[colback=white]
  10703. {\if\edition\racketEd
  10704. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10705. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10706. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10707. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10708. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10709. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10710. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10711. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10712. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10713. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10714. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10715. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10716. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  10717. \path[->,bend left=15] (Lfun) edge [above] node
  10718. {\ttfamily\footnotesize shrink} (Lfun-2);
  10719. \path[->,bend left=15] (Lfun-2) edge [above] node
  10720. {\ttfamily\footnotesize uniquify} (F1-4);
  10721. \path[->,bend left=15] (F1-4) edge [above] node
  10722. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10723. \path[->,bend left=15] (F1-5) edge [left] node
  10724. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10725. \path[->,bend left=10] (F1-6) edge [above] node
  10726. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10727. \path[->,bend left=15] (C3-2) edge [right] node
  10728. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10729. \path[->,bend right=15] (x86-2) edge [right] node
  10730. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10731. \path[->,bend right=15] (x86-2-1) edge [below] node
  10732. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  10733. \path[->,bend right=15] (x86-2-2) edge [right] node
  10734. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  10735. \path[->,bend left=15] (x86-3) edge [above] node
  10736. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10737. \path[->,bend left=15] (x86-4) edge [right] node
  10738. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10739. \end{tikzpicture}
  10740. \fi}
  10741. {\if\edition\pythonEd
  10742. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10743. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10744. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  10745. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  10746. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10747. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10748. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10749. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10750. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  10751. \path[->,bend left=15] (Lfun) edge [above] node
  10752. {\ttfamily\footnotesize shrink} (Lfun-2);
  10753. \path[->,bend left=15] (Lfun-2) edge [above] node
  10754. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10755. \path[->,bend left=10] (F1-6) edge [right] node
  10756. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10757. \path[->,bend right=15] (C3-2) edge [right] node
  10758. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10759. \path[->,bend right=15] (x86-2) edge [below] node
  10760. {\ttfamily\footnotesize assign\_homes} (x86-3);
  10761. \path[->,bend left=15] (x86-3) edge [above] node
  10762. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10763. \path[->,bend right=15] (x86-4) edge [below] node
  10764. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10765. \end{tikzpicture}
  10766. \fi}
  10767. \end{tcolorbox}
  10768. \caption{Diagram of the passes for \LangLoop{}.}
  10769. \label{fig:Lwhile-passes}
  10770. \end{figure}
  10771. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10772. for the compilation of \LangLoop{}.
  10773. % Further Reading: dataflow analysis
  10774. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10775. \chapter{Tuples and Garbage Collection}
  10776. \label{ch:Lvec}
  10777. \index{subject}{tuple}
  10778. \index{subject}{vector}
  10779. \index{subject}{allocate}
  10780. \index{subject}{heap allocate}
  10781. \setcounter{footnote}{0}
  10782. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10783. %% all the IR grammars are spelled out! \\ --Jeremy}
  10784. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10785. %% the root stack. \\ --Jeremy}
  10786. In this chapter we study the implementation of tuples\racket{, called
  10787. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10788. in which each element may have a different type.
  10789. %
  10790. This language feature is the first to use the computer's
  10791. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  10792. indefinite; that is, a tuple lives forever from the programmer's
  10793. viewpoint. Of course, from an implementer's viewpoint, it is important
  10794. to reclaim the space associated with a tuple when it is no longer
  10795. needed, which is why we also study \emph{garbage collection}
  10796. \index{subject}{garbage collection} techniques in this chapter.
  10797. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  10798. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10799. language (chapter~\ref{ch:Lwhile}) with tuples.
  10800. %
  10801. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10802. copying live tuples back and forth between two halves of the heap. The
  10803. garbage collector requires coordination with the compiler so that it
  10804. can find all the live tuples.
  10805. %
  10806. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10807. discuss the necessary changes and additions to the compiler passes,
  10808. including a new compiler pass named \code{expose\_allocation}.
  10809. \section{The \LangVec{} Language}
  10810. \label{sec:r3}
  10811. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  10812. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  10813. the definition of the abstract syntax.
  10814. %
  10815. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10816. creating a tuple, \code{vector-ref} for reading an element of a
  10817. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10818. \code{vector-length} for obtaining the number of elements of a
  10819. tuple.}
  10820. %
  10821. \python{The \LangVec{} language adds 1) tuple creation via a
  10822. comma-separated list of expressions, 2) accessing an element of a
  10823. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10824. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10825. operator, and 4) obtaining the number of elements (the length) of a
  10826. tuple. In this chapter, we restrict access indices to constant
  10827. integers.}
  10828. %
  10829. The following program shows an example use of tuples. It creates a tuple
  10830. \code{t} containing the elements \code{40},
  10831. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10832. contains just \code{2}. The element at index $1$ of \code{t} is
  10833. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  10834. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10835. to which we add \code{2}, the element at index $0$ of the tuple.
  10836. The result of the program is \code{42}.
  10837. %
  10838. {\if\edition\racketEd
  10839. \begin{lstlisting}
  10840. (let ([t (vector 40 #t (vector 2))])
  10841. (if (vector-ref t 1)
  10842. (+ (vector-ref t 0)
  10843. (vector-ref (vector-ref t 2) 0))
  10844. 44))
  10845. \end{lstlisting}
  10846. \fi}
  10847. {\if\edition\pythonEd
  10848. \begin{lstlisting}
  10849. t = 40, True, (2,)
  10850. print( t[0] + t[2][0] if t[1] else 44 )
  10851. \end{lstlisting}
  10852. \fi}
  10853. \newcommand{\LtupGrammarRacket}{
  10854. \begin{array}{lcl}
  10855. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10856. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10857. \MID \LP\key{vector-length}\;\Exp\RP \\
  10858. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10859. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10860. \end{array}
  10861. }
  10862. \newcommand{\LtupASTRacket}{
  10863. \begin{array}{lcl}
  10864. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10865. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10866. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10867. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  10868. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10869. \end{array}
  10870. }
  10871. \newcommand{\LtupGrammarPython}{
  10872. \begin{array}{rcl}
  10873. \itm{cmp} &::= & \key{is} \\
  10874. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10875. \end{array}
  10876. }
  10877. \newcommand{\LtupASTPython}{
  10878. \begin{array}{lcl}
  10879. \itm{cmp} &::= & \code{Is()} \\
  10880. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10881. &\MID& \LEN{\Exp}
  10882. \end{array}
  10883. }
  10884. \begin{figure}[tbp]
  10885. \centering
  10886. \begin{tcolorbox}[colback=white]
  10887. \small
  10888. {\if\edition\racketEd
  10889. \[
  10890. \begin{array}{l}
  10891. \gray{\LintGrammarRacket{}} \\ \hline
  10892. \gray{\LvarGrammarRacket{}} \\ \hline
  10893. \gray{\LifGrammarRacket{}} \\ \hline
  10894. \gray{\LwhileGrammarRacket} \\ \hline
  10895. \LtupGrammarRacket \\
  10896. \begin{array}{lcl}
  10897. \LangVecM{} &::=& \Exp
  10898. \end{array}
  10899. \end{array}
  10900. \]
  10901. \fi}
  10902. {\if\edition\pythonEd
  10903. \[
  10904. \begin{array}{l}
  10905. \gray{\LintGrammarPython{}} \\ \hline
  10906. \gray{\LvarGrammarPython{}} \\ \hline
  10907. \gray{\LifGrammarPython{}} \\ \hline
  10908. \gray{\LwhileGrammarPython} \\ \hline
  10909. \LtupGrammarPython \\
  10910. \begin{array}{rcl}
  10911. \LangVecM{} &::=& \Stmt^{*}
  10912. \end{array}
  10913. \end{array}
  10914. \]
  10915. \fi}
  10916. \end{tcolorbox}
  10917. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10918. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  10919. \label{fig:Lvec-concrete-syntax}
  10920. \end{figure}
  10921. \begin{figure}[tp]
  10922. \centering
  10923. \begin{tcolorbox}[colback=white]
  10924. \small
  10925. {\if\edition\racketEd
  10926. \[
  10927. \begin{array}{l}
  10928. \gray{\LintOpAST} \\ \hline
  10929. \gray{\LvarASTRacket{}} \\ \hline
  10930. \gray{\LifASTRacket{}} \\ \hline
  10931. \gray{\LwhileASTRacket{}} \\ \hline
  10932. \LtupASTRacket{} \\
  10933. \begin{array}{lcl}
  10934. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10935. \end{array}
  10936. \end{array}
  10937. \]
  10938. \fi}
  10939. {\if\edition\pythonEd
  10940. \[
  10941. \begin{array}{l}
  10942. \gray{\LintASTPython} \\ \hline
  10943. \gray{\LvarASTPython} \\ \hline
  10944. \gray{\LifASTPython} \\ \hline
  10945. \gray{\LwhileASTPython} \\ \hline
  10946. \LtupASTPython \\
  10947. \begin{array}{lcl}
  10948. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10949. \end{array}
  10950. \end{array}
  10951. \]
  10952. \fi}
  10953. \end{tcolorbox}
  10954. \caption{The abstract syntax of \LangVec{}.}
  10955. \label{fig:Lvec-syntax}
  10956. \end{figure}
  10957. Tuples raise several interesting new issues. First, variable binding
  10958. performs a shallow copy in dealing with tuples, which means that
  10959. different variables can refer to the same tuple; that is, two
  10960. variables can be \emph{aliases}\index{subject}{alias} for the same
  10961. entity. Consider the following example, in which \code{t1} and
  10962. \code{t2} refer to the same tuple value and \code{t3} refers to a
  10963. different tuple value with equal elements. The result of the
  10964. program is \code{42}.
  10965. \begin{center}
  10966. \begin{minipage}{0.96\textwidth}
  10967. {\if\edition\racketEd
  10968. \begin{lstlisting}
  10969. (let ([t1 (vector 3 7)])
  10970. (let ([t2 t1])
  10971. (let ([t3 (vector 3 7)])
  10972. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10973. 42
  10974. 0))))
  10975. \end{lstlisting}
  10976. \fi}
  10977. {\if\edition\pythonEd
  10978. \begin{lstlisting}
  10979. t1 = 3, 7
  10980. t2 = t1
  10981. t3 = 3, 7
  10982. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10983. \end{lstlisting}
  10984. \fi}
  10985. \end{minipage}
  10986. \end{center}
  10987. {\if\edition\racketEd
  10988. Whether two variables are aliased or not affects what happens
  10989. when the underlying tuple is mutated\index{subject}{mutation}.
  10990. Consider the following example in which \code{t1} and \code{t2}
  10991. again refer to the same tuple value.
  10992. \begin{center}
  10993. \begin{minipage}{0.96\textwidth}
  10994. \begin{lstlisting}
  10995. (let ([t1 (vector 3 7)])
  10996. (let ([t2 t1])
  10997. (let ([_ (vector-set! t2 0 42)])
  10998. (vector-ref t1 0))))
  10999. \end{lstlisting}
  11000. \end{minipage}
  11001. \end{center}
  11002. The mutation through \code{t2} is visible in referencing the tuple
  11003. from \code{t1}, so the result of this program is \code{42}.
  11004. \fi}
  11005. The next issue concerns the lifetime of tuples. When does a tuple's
  11006. lifetime end? Notice that \LangVec{} does not include an operation
  11007. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11008. to any notion of static scoping.
  11009. %
  11010. {\if\edition\racketEd
  11011. %
  11012. For example, the following program returns \code{42} even though the
  11013. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11014. that reads from the vector to which it was bound.
  11015. \begin{center}
  11016. \begin{minipage}{0.96\textwidth}
  11017. \begin{lstlisting}
  11018. (let ([v (vector (vector 44))])
  11019. (let ([x (let ([w (vector 42)])
  11020. (let ([_ (vector-set! v 0 w)])
  11021. 0))])
  11022. (+ x (vector-ref (vector-ref v 0) 0))))
  11023. \end{lstlisting}
  11024. \end{minipage}
  11025. \end{center}
  11026. \fi}
  11027. %
  11028. {\if\edition\pythonEd
  11029. %
  11030. For example, the following program returns \code{42} even though the
  11031. variable \code{x} goes out of scope when the function returns, prior
  11032. to reading the tuple element at index zero. (We study the compilation
  11033. of functions in chapter~\ref{ch:Lfun}.)
  11034. %
  11035. \begin{center}
  11036. \begin{minipage}{0.96\textwidth}
  11037. \begin{lstlisting}
  11038. def f():
  11039. x = 42, 43
  11040. return x
  11041. t = f()
  11042. print( t[0] )
  11043. \end{lstlisting}
  11044. \end{minipage}
  11045. \end{center}
  11046. \fi}
  11047. %
  11048. From the perspective of programmer-observable behavior, tuples live
  11049. forever. However, if they really lived forever then many long-running
  11050. programs would run out of memory. To solve this problem, the
  11051. language's runtime system performs automatic garbage collection.
  11052. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11053. \LangVec{} language.
  11054. %
  11055. \racket{We define the \code{vector}, \code{vector-ref},
  11056. \code{vector-set!}, and \code{vector-length} operations for
  11057. \LangVec{} in terms of the corresponding operations in Racket. One
  11058. subtle point is that the \code{vector-set!} operation returns the
  11059. \code{\#<void>} value.}
  11060. %
  11061. \python{We represent tuples with Python lists in the interpreter
  11062. because we need to write to them
  11063. (section~\ref{sec:expose-allocation}). (Python tuples are
  11064. immutable.) We define element access, the \code{is} operator, and
  11065. the \code{len} operator for \LangVec{} in terms of the corresponding
  11066. operations in Python.}
  11067. \begin{figure}[tbp]
  11068. \begin{tcolorbox}[colback=white]
  11069. {\if\edition\racketEd
  11070. \begin{lstlisting}
  11071. (define interp-Lvec-class
  11072. (class interp-Lwhile-class
  11073. (super-new)
  11074. (define/override (interp-op op)
  11075. (match op
  11076. ['eq? (lambda (v1 v2)
  11077. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11078. (and (boolean? v1) (boolean? v2))
  11079. (and (vector? v1) (vector? v2))
  11080. (and (void? v1) (void? v2)))
  11081. (eq? v1 v2)]))]
  11082. ['vector vector]
  11083. ['vector-length vector-length]
  11084. ['vector-ref vector-ref]
  11085. ['vector-set! vector-set!]
  11086. [else (super interp-op op)]
  11087. ))
  11088. (define/override ((interp-exp env) e)
  11089. (match e
  11090. [(HasType e t) ((interp-exp env) e)]
  11091. [else ((super interp-exp env) e)]
  11092. ))
  11093. ))
  11094. (define (interp-Lvec p)
  11095. (send (new interp-Lvec-class) interp-program p))
  11096. \end{lstlisting}
  11097. \fi}
  11098. %
  11099. {\if\edition\pythonEd
  11100. \begin{lstlisting}
  11101. class InterpLtup(InterpLwhile):
  11102. def interp_cmp(self, cmp):
  11103. match cmp:
  11104. case Is():
  11105. return lambda x, y: x is y
  11106. case _:
  11107. return super().interp_cmp(cmp)
  11108. def interp_exp(self, e, env):
  11109. match e:
  11110. case Tuple(es, Load()):
  11111. return tuple([self.interp_exp(e, env) for e in es])
  11112. case Subscript(tup, index, Load()):
  11113. t = self.interp_exp(tup, env)
  11114. n = self.interp_exp(index, env)
  11115. return t[n]
  11116. case _:
  11117. return super().interp_exp(e, env)
  11118. \end{lstlisting}
  11119. \fi}
  11120. \end{tcolorbox}
  11121. \caption{Interpreter for the \LangVec{} language.}
  11122. \label{fig:interp-Lvec}
  11123. \end{figure}
  11124. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11125. \LangVec{}.
  11126. %
  11127. The type of a tuple is a
  11128. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11129. type for each of its elements.
  11130. %
  11131. \racket{To create the s-expression for the \code{Vector} type, we use the
  11132. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11133. operator} \code{,@} to insert the list \code{t*} without its usual
  11134. start and end parentheses. \index{subject}{unquote-splicing}}
  11135. %
  11136. The type of accessing the ith element of a tuple is the ith element
  11137. type of the tuple's type, if there is one. If not, an error is
  11138. signaled. Note that the index \code{i} is required to be a constant
  11139. integer (and not, for example, a call to
  11140. \racket{\code{read}}\python{input\_int}) so that the type checker
  11141. can determine the element's type given the tuple type.
  11142. %
  11143. \racket{
  11144. Regarding writing an element to a tuple, the element's type must
  11145. be equal to the ith element type of the tuple's type.
  11146. The result type is \code{Void}.}
  11147. %% When allocating a tuple,
  11148. %% we need to know which elements of the tuple are themselves tuples for
  11149. %% the purposes of garbage collection. We can obtain this information
  11150. %% during type checking. The type checker shown in
  11151. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11152. %% expression; it also
  11153. %% %
  11154. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11155. %% where $T$ is the tuple's type.
  11156. %
  11157. %records the type of each tuple expression in a new field named \code{has\_type}.
  11158. \begin{figure}[tp]
  11159. \begin{tcolorbox}[colback=white]
  11160. {\if\edition\racketEd
  11161. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11162. (define type-check-Lvec-class
  11163. (class type-check-Lif-class
  11164. (super-new)
  11165. (inherit check-type-equal?)
  11166. (define/override (type-check-exp env)
  11167. (lambda (e)
  11168. (define recur (type-check-exp env))
  11169. (match e
  11170. [(Prim 'vector es)
  11171. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11172. (define t `(Vector ,@t*))
  11173. (values (Prim 'vector e*) t)]
  11174. [(Prim 'vector-ref (list e1 (Int i)))
  11175. (define-values (e1^ t) (recur e1))
  11176. (match t
  11177. [`(Vector ,ts ...)
  11178. (unless (and (0 . <= . i) (i . < . (length ts)))
  11179. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11180. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11181. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11182. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11183. (define-values (e-vec t-vec) (recur e1))
  11184. (define-values (e-elt^ t-elt) (recur elt))
  11185. (match t-vec
  11186. [`(Vector ,ts ...)
  11187. (unless (and (0 . <= . i) (i . < . (length ts)))
  11188. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11189. (check-type-equal? (list-ref ts i) t-elt e)
  11190. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11191. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11192. [(Prim 'vector-length (list e))
  11193. (define-values (e^ t) (recur e))
  11194. (match t
  11195. [`(Vector ,ts ...)
  11196. (values (Prim 'vector-length (list e^)) 'Integer)]
  11197. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11198. [(Prim 'eq? (list arg1 arg2))
  11199. (define-values (e1 t1) (recur arg1))
  11200. (define-values (e2 t2) (recur arg2))
  11201. (match* (t1 t2)
  11202. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11203. [(other wise) (check-type-equal? t1 t2 e)])
  11204. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11205. [else ((super type-check-exp env) e)]
  11206. )))
  11207. ))
  11208. (define (type-check-Lvec p)
  11209. (send (new type-check-Lvec-class) type-check-program p))
  11210. \end{lstlisting}
  11211. \fi}
  11212. {\if\edition\pythonEd
  11213. \begin{lstlisting}
  11214. class TypeCheckLtup(TypeCheckLwhile):
  11215. def type_check_exp(self, e, env):
  11216. match e:
  11217. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11218. l = self.type_check_exp(left, env)
  11219. r = self.type_check_exp(right, env)
  11220. check_type_equal(l, r, e)
  11221. return bool
  11222. case Tuple(es, Load()):
  11223. ts = [self.type_check_exp(e, env) for e in es]
  11224. e.has_type = TupleType(ts)
  11225. return e.has_type
  11226. case Subscript(tup, Constant(i), Load()):
  11227. tup_ty = self.type_check_exp(tup, env)
  11228. i_ty = self.type_check_exp(Constant(i), env)
  11229. check_type_equal(i_ty, int, i)
  11230. match tup_ty:
  11231. case TupleType(ts):
  11232. return ts[i]
  11233. case _:
  11234. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11235. case _:
  11236. return super().type_check_exp(e, env)
  11237. \end{lstlisting}
  11238. \fi}
  11239. \end{tcolorbox}
  11240. \caption{Type checker for the \LangVec{} language.}
  11241. \label{fig:type-check-Lvec}
  11242. \end{figure}
  11243. \section{Garbage Collection}
  11244. \label{sec:GC}
  11245. Garbage collection is a runtime technique for reclaiming space on the
  11246. heap that will not be used in the future of the running program. We
  11247. use the term \emph{object}\index{subject}{object} to refer to any
  11248. value that is stored in the heap, which for now includes only
  11249. tuples.%
  11250. %
  11251. \footnote{The term \emph{object} as it is used in the context of
  11252. object-oriented programming has a more specific meaning than the
  11253. way in which we use the term here.}
  11254. %
  11255. Unfortunately, it is impossible to know precisely which objects will
  11256. be accessed in the future and which will not. Instead, garbage
  11257. collectors overapproximate the set of objects that will be accessed by
  11258. identifying which objects can possibly be accessed. The running
  11259. program can directly access objects that are in registers and on the
  11260. procedure call stack. It can also transitively access the elements of
  11261. tuples, starting with a tuple whose address is in a register or on the
  11262. procedure call stack. We define the \emph{root
  11263. set}\index{subject}{root set} to be all the tuple addresses that are
  11264. in registers or on the procedure call stack. We define the \emph{live
  11265. objects}\index{subject}{live objects} to be the objects that are
  11266. reachable from the root set. Garbage collectors reclaim the space that
  11267. is allocated to objects that are no longer live. That means that some
  11268. objects may not get reclaimed as soon as they could be, but at least
  11269. garbage collectors do not reclaim the space dedicated to objects that
  11270. will be accessed in the future! The programmer can influence which
  11271. objects get reclaimed by causing them to become unreachable.
  11272. So the goal of the garbage collector is twofold:
  11273. \begin{enumerate}
  11274. \item to preserve all the live objects, and
  11275. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11276. \end{enumerate}
  11277. \subsection{Two-Space Copying Collector}
  11278. Here we study a relatively simple algorithm for garbage collection
  11279. that is the basis of many state-of-the-art garbage
  11280. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11281. particular, we describe a two-space copying
  11282. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11283. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11284. collector} \index{subject}{two-space copying collector}
  11285. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11286. what happens in a two-space collector, showing two time steps, prior
  11287. to garbage collection (on the top) and after garbage collection (on
  11288. the bottom). In a two-space collector, the heap is divided into two
  11289. parts named the FromSpace\index{subject}{FromSpace} and the
  11290. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11291. FromSpace until there is not enough room for the next allocation
  11292. request. At that point, the garbage collector goes to work to make
  11293. room for the next allocation.
  11294. A copying collector makes more room by copying all the live objects
  11295. from the FromSpace into the ToSpace and then performs a sleight of
  11296. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11297. as the new ToSpace. In the example shown in
  11298. figure~\ref{fig:copying-collector}, the root set consists of three
  11299. pointers, one in a register and two on the stack. All the live
  11300. objects have been copied to the ToSpace (the right-hand side of
  11301. figure~\ref{fig:copying-collector}) in a way that preserves the
  11302. pointer relationships. For example, the pointer in the register still
  11303. points to a tuple that in turn points to two other tuples. There are
  11304. four tuples that are not reachable from the root set and therefore do
  11305. not get copied into the ToSpace.
  11306. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11307. created by a well-typed program in \LangVec{} because it contains a
  11308. cycle. However, creating cycles will be possible once we get to
  11309. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11310. to deal with cycles to begin with, so we will not need to revisit this
  11311. issue.
  11312. \begin{figure}[tbp]
  11313. \centering
  11314. \begin{tcolorbox}[colback=white]
  11315. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11316. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11317. \\[5ex]
  11318. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11319. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11320. \end{tcolorbox}
  11321. \caption{A copying collector in action.}
  11322. \label{fig:copying-collector}
  11323. \end{figure}
  11324. \subsection{Graph Copying via Cheney's Algorithm}
  11325. \label{sec:cheney}
  11326. \index{subject}{Cheney's algorithm}
  11327. Let us take a closer look at the copying of the live objects. The
  11328. allocated objects and pointers can be viewed as a graph, and we need to
  11329. copy the part of the graph that is reachable from the root set. To
  11330. make sure that we copy all the reachable vertices in the graph, we need
  11331. an exhaustive graph traversal algorithm, such as depth-first search or
  11332. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  11333. such algorithms take into account the possibility of cycles by marking
  11334. which vertices have already been visited, so to ensure termination
  11335. of the algorithm. These search algorithms also use a data structure
  11336. such as a stack or queue as a to-do list to keep track of the vertices
  11337. that need to be visited. We use breadth-first search and a trick
  11338. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  11339. and copying tuples into the ToSpace.
  11340. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11341. copy progresses. The queue is represented by a chunk of contiguous
  11342. memory at the beginning of the ToSpace, using two pointers to track
  11343. the front and the back of the queue, called the \emph{free pointer}
  11344. and the \emph{scan pointer}, respectively. The algorithm starts by
  11345. copying all tuples that are immediately reachable from the root set
  11346. into the ToSpace to form the initial queue. When we copy a tuple, we
  11347. mark the old tuple to indicate that it has been visited. We discuss
  11348. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11349. that any pointers inside the copied tuples in the queue still point
  11350. back to the FromSpace. Once the initial queue has been created, the
  11351. algorithm enters a loop in which it repeatedly processes the tuple at
  11352. the front of the queue and pops it off the queue. To process a tuple,
  11353. the algorithm copies all the objects that are directly reachable from it
  11354. to the ToSpace, placing them at the back of the queue. The algorithm
  11355. then updates the pointers in the popped tuple so that they point to the
  11356. newly copied objects.
  11357. \begin{figure}[tbp]
  11358. \centering
  11359. \begin{tcolorbox}[colback=white]
  11360. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  11361. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  11362. \end{tcolorbox}
  11363. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11364. \label{fig:cheney}
  11365. \end{figure}
  11366. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11367. tuple whose second element is $42$ to the back of the queue. The other
  11368. pointer goes to a tuple that has already been copied, so we do not
  11369. need to copy it again, but we do need to update the pointer to the new
  11370. location. This can be accomplished by storing a \emph{forwarding
  11371. pointer}\index{subject}{forwarding pointer} to the new location in the
  11372. old tuple, when we initially copied the tuple into the
  11373. ToSpace. This completes one step of the algorithm. The algorithm
  11374. continues in this way until the queue is empty; that is, when the scan
  11375. pointer catches up with the free pointer.
  11376. \subsection{Data Representation}
  11377. \label{sec:data-rep-gc}
  11378. The garbage collector places some requirements on the data
  11379. representations used by our compiler. First, the garbage collector
  11380. needs to distinguish between pointers and other kinds of data such as
  11381. integers. The following are several ways to accomplish this:
  11382. \begin{enumerate}
  11383. \item Attach a tag to each object that identifies what type of
  11384. object it is~\citep{McCarthy:1960dz}.
  11385. \item Store different types of objects in different
  11386. regions~\citep{Steele:1977ab}.
  11387. \item Use type information from the program to either (a) generate
  11388. type-specific code for collecting, or (b) generate tables that
  11389. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11390. \end{enumerate}
  11391. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11392. need to tag objects in any case, so option 1 is a natural choice for those
  11393. languages. However, \LangVec{} is a statically typed language, so it
  11394. would be unfortunate to require tags on every object, especially small
  11395. and pervasive objects like integers and Booleans. Option 3 is the
  11396. best-performing choice for statically typed languages, but it comes with
  11397. a relatively high implementation complexity. To keep this chapter
  11398. within a reasonable scope of complexity, we recommend a combination of options
  11399. 1 and 2, using separate strategies for the stack and the heap.
  11400. Regarding the stack, we recommend using a separate stack for pointers,
  11401. which we call the \emph{root stack}\index{subject}{root stack}
  11402. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11403. That is, when a local variable needs to be spilled and is of type
  11404. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11405. root stack instead of putting it on the procedure call
  11406. stack. Furthermore, we always spill tuple-typed variables if they are
  11407. live during a call to the collector, thereby ensuring that no pointers
  11408. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11409. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11410. contrasts it with the data layout using a root stack. The root stack
  11411. contains the two pointers from the regular stack and also the pointer
  11412. in the second register.
  11413. \begin{figure}[tbp]
  11414. \centering
  11415. \begin{tcolorbox}[colback=white]
  11416. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11417. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11418. \end{tcolorbox}
  11419. \caption{Maintaining a root stack to facilitate garbage collection.}
  11420. \label{fig:shadow-stack}
  11421. \end{figure}
  11422. The problem of distinguishing between pointers and other kinds of data
  11423. also arises inside each tuple on the heap. We solve this problem by
  11424. attaching a tag, an extra 64 bits, to each
  11425. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11426. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11427. Note that we have drawn the bits in a big-endian way, from right to left,
  11428. with bit location 0 (the least significant bit) on the far right,
  11429. which corresponds to the direction of the x86 shifting instructions
  11430. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11431. is dedicated to specifying which elements of the tuple are pointers,
  11432. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11433. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11434. data. The pointer mask starts at bit location 7. We limit tuples to a
  11435. maximum size of fifty elements, so we need 50 bits for the pointer
  11436. mask.%
  11437. %
  11438. \footnote{A production-quality compiler would handle
  11439. arbitrarily sized tuples and use a more complex approach.}
  11440. %
  11441. The tag also contains two other pieces of information. The length of
  11442. the tuple (number of elements) is stored in bits at locations 1 through
  11443. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11444. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11445. has not yet been copied. If the bit has value 0, then the entire tag
  11446. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11447. zero in any case, because our tuples are 8-byte aligned.)
  11448. \begin{figure}[tbp]
  11449. \centering
  11450. \begin{tcolorbox}[colback=white]
  11451. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11452. \end{tcolorbox}
  11453. \caption{Representation of tuples in the heap.}
  11454. \label{fig:tuple-rep}
  11455. \end{figure}
  11456. \subsection{Implementation of the Garbage Collector}
  11457. \label{sec:organize-gz}
  11458. \index{subject}{prelude}
  11459. An implementation of the copying collector is provided in the
  11460. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11461. interface to the garbage collector that is used by the compiler. The
  11462. \code{initialize} function creates the FromSpace, ToSpace, and root
  11463. stack and should be called in the prelude of the \code{main}
  11464. function. The arguments of \code{initialize} are the root stack size
  11465. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11466. good choice for both. The \code{initialize} function puts the address
  11467. of the beginning of the FromSpace into the global variable
  11468. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11469. the address that is one past the last element of the FromSpace. We use
  11470. half-open intervals to represent chunks of
  11471. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11472. points to the first element of the root stack.
  11473. As long as there is room left in the FromSpace, your generated code
  11474. can allocate tuples simply by moving the \code{free\_ptr} forward.
  11475. %
  11476. The amount of room left in the FromSpace is the difference between the
  11477. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11478. function should be called when there is not enough room left in the
  11479. FromSpace for the next allocation. The \code{collect} function takes
  11480. a pointer to the current top of the root stack (one past the last item
  11481. that was pushed) and the number of bytes that need to be
  11482. allocated. The \code{collect} function performs the copying collection
  11483. and leaves the heap in a state such that there is enough room for the
  11484. next allocation.
  11485. \begin{figure}[tbp]
  11486. \begin{tcolorbox}[colback=white]
  11487. \begin{lstlisting}
  11488. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11489. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11490. int64_t* free_ptr;
  11491. int64_t* fromspace_begin;
  11492. int64_t* fromspace_end;
  11493. int64_t** rootstack_begin;
  11494. \end{lstlisting}
  11495. \end{tcolorbox}
  11496. \caption{The compiler's interface to the garbage collector.}
  11497. \label{fig:gc-header}
  11498. \end{figure}
  11499. %% \begin{exercise}
  11500. %% In the file \code{runtime.c} you will find the implementation of
  11501. %% \code{initialize} and a partial implementation of \code{collect}.
  11502. %% The \code{collect} function calls another function, \code{cheney},
  11503. %% to perform the actual copy, and that function is left to the reader
  11504. %% to implement. The following is the prototype for \code{cheney}.
  11505. %% \begin{lstlisting}
  11506. %% static void cheney(int64_t** rootstack_ptr);
  11507. %% \end{lstlisting}
  11508. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11509. %% rootstack (which is an array of pointers). The \code{cheney} function
  11510. %% also communicates with \code{collect} through the global
  11511. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11512. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11513. %% the ToSpace:
  11514. %% \begin{lstlisting}
  11515. %% static int64_t* tospace_begin;
  11516. %% static int64_t* tospace_end;
  11517. %% \end{lstlisting}
  11518. %% The job of the \code{cheney} function is to copy all the live
  11519. %% objects (reachable from the root stack) into the ToSpace, update
  11520. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11521. %% update the root stack so that it points to the objects in the
  11522. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11523. %% and ToSpace.
  11524. %% \end{exercise}
  11525. The introduction of garbage collection has a nontrivial impact on our
  11526. compiler passes. We introduce a new compiler pass named
  11527. \code{expose\_allocation} that elaborates the code for allocating
  11528. tuples. We also make significant changes to
  11529. \code{select\_instructions}, \code{build\_interference},
  11530. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11531. make minor changes in several more passes.
  11532. The following program serves as our running example. It creates
  11533. two tuples, one nested inside the other. Both tuples have length
  11534. one. The program accesses the element in the inner tuple.
  11535. % tests/vectors_test_17.rkt
  11536. {\if\edition\racketEd
  11537. \begin{lstlisting}
  11538. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11539. \end{lstlisting}
  11540. \fi}
  11541. {\if\edition\pythonEd
  11542. \begin{lstlisting}
  11543. print( ((42,),)[0][0] )
  11544. \end{lstlisting}
  11545. \fi}
  11546. %% {\if\edition\racketEd
  11547. %% \section{Shrink}
  11548. %% \label{sec:shrink-Lvec}
  11549. %% Recall that the \code{shrink} pass translates the primitives operators
  11550. %% into a smaller set of primitives.
  11551. %% %
  11552. %% This pass comes after type checking, and the type checker adds a
  11553. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11554. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11555. %% \fi}
  11556. \section{Expose Allocation}
  11557. \label{sec:expose-allocation}
  11558. The pass \code{expose\_allocation} lowers tuple creation into making a
  11559. conditional call to the collector followed by allocating the
  11560. appropriate amount of memory and initializing it. We choose to place
  11561. the \code{expose\_allocation} pass before
  11562. \code{remove\_complex\_operands} because it generates
  11563. code that contains complex operands.
  11564. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11565. that replaces tuple creation with new lower-level forms that we use in the
  11566. translation of tuple creation.
  11567. %
  11568. {\if\edition\racketEd
  11569. \[
  11570. \begin{array}{lcl}
  11571. \Exp &::=& \cdots
  11572. \MID (\key{collect} \,\itm{int})
  11573. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11574. \MID (\key{global-value} \,\itm{name})
  11575. \end{array}
  11576. \]
  11577. \fi}
  11578. {\if\edition\pythonEd
  11579. \[
  11580. \begin{array}{lcl}
  11581. \Exp &::=& \cdots\\
  11582. &\MID& \key{collect}(\itm{int})
  11583. \MID \key{allocate}(\itm{int},\itm{type})
  11584. \MID \key{global\_value}(\itm{name}) \\
  11585. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  11586. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11587. \end{array}
  11588. \]
  11589. \fi}
  11590. %
  11591. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11592. make sure that there are $n$ bytes ready to be allocated. During
  11593. instruction selection, the \CCOLLECT{$n$} form will become a call to
  11594. the \code{collect} function in \code{runtime.c}.
  11595. %
  11596. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11597. space at the front for the 64-bit tag), but the elements are not
  11598. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11599. of the tuple:
  11600. %
  11601. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11602. %
  11603. where $\Type_i$ is the type of the $i$th element.
  11604. %
  11605. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11606. variable, such as \code{free\_ptr}.
  11607. %
  11608. \python{The \code{begin} form is an expression that executes a
  11609. sequence of statements and then produces the value of the expression
  11610. at the end.}
  11611. \racket{
  11612. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11613. can be obtained by running the
  11614. \code{type-check-Lvec-has-type} type checker immediately before the
  11615. \code{expose\_allocation} pass. This version of the type checker
  11616. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11617. around each tuple creation. The concrete syntax
  11618. for \code{HasType} is \code{has-type}.}
  11619. The following shows the transformation of tuple creation into (1) a
  11620. sequence of temporary variable bindings for the initializing
  11621. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11622. \code{allocate}, and (4) the initialization of the tuple. The
  11623. \itm{len} placeholder refers to the length of the tuple, and
  11624. \itm{bytes} is the total number of bytes that need to be allocated for
  11625. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11626. %
  11627. \python{The \itm{type} needed for the second argument of the
  11628. \code{allocate} form can be obtained from the \code{has\_type} field
  11629. of the tuple AST node, which is stored there by running the type
  11630. checker for \LangVec{} immediately before this pass.}
  11631. %
  11632. \begin{center}
  11633. \begin{minipage}{\textwidth}
  11634. {\if\edition\racketEd
  11635. \begin{lstlisting}
  11636. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11637. |$\Longrightarrow$|
  11638. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11639. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11640. (global-value fromspace_end))
  11641. (void)
  11642. (collect |\itm{bytes}|))])
  11643. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11644. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11645. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11646. |$v$|) ... )))) ...)
  11647. \end{lstlisting}
  11648. \fi}
  11649. {\if\edition\pythonEd
  11650. \begin{lstlisting}
  11651. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11652. |$\Longrightarrow$|
  11653. begin:
  11654. |$x_0$| = |$e_0$|
  11655. |$\vdots$|
  11656. |$x_{n-1}$| = |$e_{n-1}$|
  11657. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11658. 0
  11659. else:
  11660. collect(|\itm{bytes}|)
  11661. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11662. |$v$|[0] = |$x_0$|
  11663. |$\vdots$|
  11664. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11665. |$v$|
  11666. \end{lstlisting}
  11667. \fi}
  11668. \end{minipage}
  11669. \end{center}
  11670. %
  11671. \noindent The sequencing of the initializing expressions
  11672. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, because
  11673. they may trigger garbage collection and we cannot have an allocated
  11674. but uninitialized tuple on the heap during a collection.
  11675. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11676. \code{expose\_allocation} pass on our running example.
  11677. \begin{figure}[tbp]
  11678. \begin{tcolorbox}[colback=white]
  11679. % tests/s2_17.rkt
  11680. {\if\edition\racketEd
  11681. \begin{lstlisting}
  11682. (vector-ref
  11683. (vector-ref
  11684. (let ([vecinit6
  11685. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11686. (global-value fromspace_end))
  11687. (void)
  11688. (collect 16))])
  11689. (let ([alloc2 (allocate 1 (Vector Integer))])
  11690. (let ([_3 (vector-set! alloc2 0 42)])
  11691. alloc2)))])
  11692. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11693. (global-value fromspace_end))
  11694. (void)
  11695. (collect 16))])
  11696. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11697. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11698. alloc5))))
  11699. 0)
  11700. 0)
  11701. \end{lstlisting}
  11702. \fi}
  11703. {\if\edition\pythonEd
  11704. \begin{lstlisting}
  11705. print( |$T_1$|[0][0] )
  11706. \end{lstlisting}
  11707. where $T_1$ is
  11708. \begin{lstlisting}
  11709. begin:
  11710. tmp.1 = |$T_2$|
  11711. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11712. 0
  11713. else:
  11714. collect(16)
  11715. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11716. tmp.2[0] = tmp.1
  11717. tmp.2
  11718. \end{lstlisting}
  11719. and $T_2$ is
  11720. \begin{lstlisting}
  11721. begin:
  11722. tmp.3 = 42
  11723. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11724. 0
  11725. else:
  11726. collect(16)
  11727. tmp.4 = allocate(1, TupleType([int]))
  11728. tmp.4[0] = tmp.3
  11729. tmp.4
  11730. \end{lstlisting}
  11731. \fi}
  11732. \end{tcolorbox}
  11733. \caption{Output of the \code{expose\_allocation} pass.}
  11734. \label{fig:expose-alloc-output}
  11735. \end{figure}
  11736. \section{Remove Complex Operands}
  11737. \label{sec:remove-complex-opera-Lvec}
  11738. {\if\edition\racketEd
  11739. %
  11740. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11741. should be treated as complex operands.
  11742. %
  11743. \fi}
  11744. %
  11745. {\if\edition\pythonEd
  11746. %
  11747. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11748. and tuple access should be treated as complex operands. The
  11749. sub-expressions of tuple access must be atomic.
  11750. %
  11751. \fi}
  11752. %% A new case for
  11753. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11754. %% handled carefully to prevent the \code{Prim} node from being separated
  11755. %% from its enclosing \code{HasType}.
  11756. Figure~\ref{fig:Lvec-anf-syntax}
  11757. shows the grammar for the output language \LangAllocANF{} of this
  11758. pass, which is \LangAlloc{} in monadic normal form.
  11759. \newcommand{\LtupMonadASTRacket}{
  11760. \begin{array}{rcl}
  11761. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11762. \MID \GLOBALVALUE{\Var}
  11763. \end{array}
  11764. }
  11765. \newcommand{\LtupMonadASTPython}{
  11766. \begin{array}{rcl}
  11767. \Exp &::=& \GET{\Atm}{\Atm} \\
  11768. &\MID& \LEN{\Atm}\\
  11769. &\MID& \ALLOCATE{\Int}{\Type}
  11770. \MID \GLOBALVALUE{\Var} \\
  11771. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11772. &\MID& \COLLECT{\Int}
  11773. \end{array}
  11774. }
  11775. \begin{figure}[tp]
  11776. \centering
  11777. \begin{tcolorbox}[colback=white]
  11778. \small
  11779. {\if\edition\racketEd
  11780. \[
  11781. \begin{array}{l}
  11782. \gray{\LvarMonadASTRacket} \\ \hline
  11783. \gray{\LifMonadASTRacket} \\ \hline
  11784. \gray{\LwhileMonadASTRacket} \\ \hline
  11785. \LtupMonadASTRacket \\
  11786. \begin{array}{rcl}
  11787. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11788. \end{array}
  11789. \end{array}
  11790. \]
  11791. \fi}
  11792. {\if\edition\pythonEd
  11793. \[
  11794. \begin{array}{l}
  11795. \gray{\LvarMonadASTPython} \\ \hline
  11796. \gray{\LifMonadASTPython} \\ \hline
  11797. \gray{\LwhileMonadASTPython} \\ \hline
  11798. \LtupMonadASTPython \\
  11799. \begin{array}{rcl}
  11800. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11801. \end{array}
  11802. \end{array}
  11803. \]
  11804. \fi}
  11805. \end{tcolorbox}
  11806. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11807. \label{fig:Lvec-anf-syntax}
  11808. \end{figure}
  11809. \section{Explicate Control and the \LangCVec{} language}
  11810. \label{sec:explicate-control-r3}
  11811. \newcommand{\CtupASTRacket}{
  11812. \begin{array}{lcl}
  11813. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11814. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11815. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11816. &\MID& \VECLEN{\Atm} \\
  11817. &\MID& \GLOBALVALUE{\Var} \\
  11818. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11819. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11820. \end{array}
  11821. }
  11822. \newcommand{\CtupASTPython}{
  11823. \begin{array}{lcl}
  11824. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11825. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11826. \Stmt &::=& \COLLECT{\Int} \\
  11827. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11828. \end{array}
  11829. }
  11830. \begin{figure}[tp]
  11831. \begin{tcolorbox}[colback=white]
  11832. \small
  11833. {\if\edition\racketEd
  11834. \[
  11835. \begin{array}{l}
  11836. \gray{\CvarASTRacket} \\ \hline
  11837. \gray{\CifASTRacket} \\ \hline
  11838. \gray{\CloopASTRacket} \\ \hline
  11839. \CtupASTRacket \\
  11840. \begin{array}{lcl}
  11841. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11842. \end{array}
  11843. \end{array}
  11844. \]
  11845. \fi}
  11846. {\if\edition\pythonEd
  11847. \[
  11848. \begin{array}{l}
  11849. \gray{\CifASTPython} \\ \hline
  11850. \CtupASTPython \\
  11851. \begin{array}{lcl}
  11852. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11853. \end{array}
  11854. \end{array}
  11855. \]
  11856. \fi}
  11857. \end{tcolorbox}
  11858. \caption{The abstract syntax of \LangCVec{}, extending
  11859. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11860. (figure~\ref{fig:c1-syntax})}.}
  11861. \label{fig:c2-syntax}
  11862. \end{figure}
  11863. The output of \code{explicate\_control} is a program in the
  11864. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  11865. shows the definition of the abstract syntax.
  11866. %
  11867. %% \racket{(The concrete syntax is defined in
  11868. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11869. %
  11870. The new expressions of \LangCVec{} include \key{allocate},
  11871. %
  11872. \racket{\key{vector-ref}, and \key{vector-set!},}
  11873. %
  11874. \python{accessing tuple elements,}
  11875. %
  11876. and \key{global\_value}.
  11877. %
  11878. \python{\LangCVec{} also includes the \code{collect} statement and
  11879. assignment to a tuple element.}
  11880. %
  11881. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11882. %
  11883. The \code{explicate\_control} pass can treat these new forms much like
  11884. the other forms that we've already encountered. The output of the
  11885. \code{explicate\_control} pass on the running example is shown on the
  11886. left side of figure~\ref{fig:select-instr-output-gc} in the next
  11887. section.
  11888. \section{Select Instructions and the \LangXGlobal{} Language}
  11889. \label{sec:select-instructions-gc}
  11890. \index{subject}{instruction selection}
  11891. %% void (rep as zero)
  11892. %% allocate
  11893. %% collect (callq collect)
  11894. %% vector-ref
  11895. %% vector-set!
  11896. %% vector-length
  11897. %% global (postpone)
  11898. In this pass we generate x86 code for most of the new operations that
  11899. were needed to compile tuples, including \code{Allocate},
  11900. \code{Collect}, and accessing tuple elements.
  11901. %
  11902. We compile \code{GlobalValue} to \code{Global} because the latter has a
  11903. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  11904. \ref{fig:x86-2}). \index{subject}{x86}
  11905. The tuple read and write forms translate into \code{movq}
  11906. instructions. (The $+1$ in the offset serves to move past the tag at the
  11907. beginning of the tuple representation.)
  11908. %
  11909. \begin{center}
  11910. \begin{minipage}{\textwidth}
  11911. {\if\edition\racketEd
  11912. \begin{lstlisting}
  11913. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11914. |$\Longrightarrow$|
  11915. movq |$\itm{tup}'$|, %r11
  11916. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11917. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11918. |$\Longrightarrow$|
  11919. movq |$\itm{tup}'$|, %r11
  11920. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11921. movq $0, |$\itm{lhs'}$|
  11922. \end{lstlisting}
  11923. \fi}
  11924. {\if\edition\pythonEd
  11925. \begin{lstlisting}
  11926. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11927. |$\Longrightarrow$|
  11928. movq |$\itm{tup}'$|, %r11
  11929. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11930. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11931. |$\Longrightarrow$|
  11932. movq |$\itm{tup}'$|, %r11
  11933. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11934. \end{lstlisting}
  11935. \fi}
  11936. \end{minipage}
  11937. \end{center}
  11938. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11939. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11940. are obtained by translating from \LangCVec{} to x86.
  11941. %
  11942. The move of $\itm{tup}'$ to
  11943. register \code{r11} ensures that offset expression
  11944. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11945. removing \code{r11} from consideration by the register allocating.
  11946. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  11947. \code{rax}. Then the generated code for tuple assignment would be
  11948. \begin{lstlisting}
  11949. movq |$\itm{tup}'$|, %rax
  11950. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11951. \end{lstlisting}
  11952. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11953. \code{patch\_instructions} would insert a move through \code{rax}
  11954. as follows:
  11955. \begin{lstlisting}
  11956. movq |$\itm{tup}'$|, %rax
  11957. movq |$\itm{rhs}'$|, %rax
  11958. movq %rax, |$8(n+1)$|(%rax)
  11959. \end{lstlisting}
  11960. However, this sequence of instructions does not work, because we're
  11961. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11962. $\itm{rhs}'$) at the same time!
  11963. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11964. be translated into a sequence of instructions that read the tag of the
  11965. tuple and extract the 6 bits that represent the tuple length, which
  11966. are the bits starting at index 1 and going up to and including bit 6.
  11967. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11968. (shift right) can be used to accomplish this.
  11969. We compile the \code{allocate} form to operations on the
  11970. \code{free\_ptr}, as shown next. This approach is called
  11971. \emph{inline allocation} because it implements allocation without a
  11972. function call by simply incrementing the allocation pointer. It is much
  11973. more efficient than calling a function for each allocation. The
  11974. address in the \code{free\_ptr} is the next free address in the
  11975. FromSpace, so we copy it into \code{r11} and then move it forward by
  11976. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11977. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11978. the tag. We then initialize the \itm{tag} and finally copy the
  11979. address in \code{r11} to the left-hand side. Refer to
  11980. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11981. %
  11982. \racket{We recommend using the Racket operations
  11983. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11984. during compilation.}
  11985. %
  11986. \python{We recommend using the bitwise-or operator \code{|} and the
  11987. shift-left operator \code{<<} to compute the tag during
  11988. compilation.}
  11989. %
  11990. The type annotation in the \code{allocate} form is used to determine
  11991. the pointer mask region of the tag.
  11992. %
  11993. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11994. address of the \code{free\_ptr} global variable using a special
  11995. instruction-pointer-relative addressing mode of the x86-64 processor.
  11996. In particular, the assembler computes the distance $d$ between the
  11997. address of \code{free\_ptr} and where the \code{rip} would be at that
  11998. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11999. \code{$d$(\%rip)}, which at runtime will compute the address of
  12000. \code{free\_ptr}.
  12001. %
  12002. {\if\edition\racketEd
  12003. \begin{lstlisting}
  12004. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12005. |$\Longrightarrow$|
  12006. movq free_ptr(%rip), %r11
  12007. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12008. movq $|$\itm{tag}$|, 0(%r11)
  12009. movq %r11, |$\itm{lhs}'$|
  12010. \end{lstlisting}
  12011. \fi}
  12012. {\if\edition\pythonEd
  12013. \begin{lstlisting}
  12014. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12015. |$\Longrightarrow$|
  12016. movq free_ptr(%rip), %r11
  12017. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12018. movq $|$\itm{tag}$|, 0(%r11)
  12019. movq %r11, |$\itm{lhs}'$|
  12020. \end{lstlisting}
  12021. \fi}
  12022. %
  12023. The \code{collect} form is compiled to a call to the \code{collect}
  12024. function in the runtime. The arguments to \code{collect} are (1) the
  12025. top of the root stack, and (2) the number of bytes that need to be
  12026. allocated. We use another dedicated register, \code{r15}, to store
  12027. the pointer to the top of the root stack. Therefore \code{r15} is not
  12028. available for use by the register allocator.
  12029. %
  12030. {\if\edition\racketEd
  12031. \begin{lstlisting}
  12032. (collect |$\itm{bytes}$|)
  12033. |$\Longrightarrow$|
  12034. movq %r15, %rdi
  12035. movq $|\itm{bytes}|, %rsi
  12036. callq collect
  12037. \end{lstlisting}
  12038. \fi}
  12039. {\if\edition\pythonEd
  12040. \begin{lstlisting}
  12041. collect(|$\itm{bytes}$|)
  12042. |$\Longrightarrow$|
  12043. movq %r15, %rdi
  12044. movq $|\itm{bytes}|, %rsi
  12045. callq collect
  12046. \end{lstlisting}
  12047. \fi}
  12048. \newcommand{\GrammarXGlobal}{
  12049. \begin{array}{lcl}
  12050. \Arg &::=& \itm{label} \key{(\%rip)}
  12051. \end{array}
  12052. }
  12053. \newcommand{\ASTXGlobalRacket}{
  12054. \begin{array}{lcl}
  12055. \Arg &::=& \GLOBAL{\itm{label}}
  12056. \end{array}
  12057. }
  12058. \begin{figure}[tp]
  12059. \begin{tcolorbox}[colback=white]
  12060. \[
  12061. \begin{array}{l}
  12062. \gray{\GrammarXInt} \\ \hline
  12063. \gray{\GrammarXIf} \\ \hline
  12064. \GrammarXGlobal \\
  12065. \begin{array}{lcl}
  12066. \LangXGlobalM{} &::= & \key{.globl main} \\
  12067. & & \key{main:} \; \Instr^{*}
  12068. \end{array}
  12069. \end{array}
  12070. \]
  12071. \end{tcolorbox}
  12072. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12073. \label{fig:x86-2-concrete}
  12074. \end{figure}
  12075. \begin{figure}[tp]
  12076. \begin{tcolorbox}[colback=white]
  12077. \small
  12078. \[
  12079. \begin{array}{l}
  12080. \gray{\ASTXIntRacket} \\ \hline
  12081. \gray{\ASTXIfRacket} \\ \hline
  12082. \ASTXGlobalRacket \\
  12083. \begin{array}{lcl}
  12084. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12085. \end{array}
  12086. \end{array}
  12087. \]
  12088. \end{tcolorbox}
  12089. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12090. \label{fig:x86-2}
  12091. \end{figure}
  12092. The definitions of the concrete and abstract syntax of the
  12093. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12094. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12095. of global variables.
  12096. %
  12097. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12098. \code{select\_instructions} pass on the running example.
  12099. \begin{figure}[tbp]
  12100. \centering
  12101. \begin{tcolorbox}[colback=white]
  12102. % tests/s2_17.rkt
  12103. \begin{tabular}{lll}
  12104. \begin{minipage}{0.5\textwidth}
  12105. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12106. start:
  12107. tmp9 = (global-value free_ptr);
  12108. tmp0 = (+ tmp9 16);
  12109. tmp1 = (global-value fromspace_end);
  12110. if (< tmp0 tmp1)
  12111. goto block0;
  12112. else
  12113. goto block1;
  12114. block0:
  12115. _4 = (void);
  12116. goto block9;
  12117. block1:
  12118. (collect 16)
  12119. goto block9;
  12120. block9:
  12121. alloc2 = (allocate 1 (Vector Integer));
  12122. _3 = (vector-set! alloc2 0 42);
  12123. vecinit6 = alloc2;
  12124. tmp2 = (global-value free_ptr);
  12125. tmp3 = (+ tmp2 16);
  12126. tmp4 = (global-value fromspace_end);
  12127. if (< tmp3 tmp4)
  12128. goto block7;
  12129. else
  12130. goto block8;
  12131. block7:
  12132. _8 = (void);
  12133. goto block6;
  12134. block8:
  12135. (collect 16)
  12136. goto block6;
  12137. block6:
  12138. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12139. _7 = (vector-set! alloc5 0 vecinit6);
  12140. tmp5 = (vector-ref alloc5 0);
  12141. return (vector-ref tmp5 0);
  12142. \end{lstlisting}
  12143. \end{minipage}
  12144. &$\Rightarrow$&
  12145. \begin{minipage}{0.4\textwidth}
  12146. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12147. start:
  12148. movq free_ptr(%rip), tmp9
  12149. movq tmp9, tmp0
  12150. addq $16, tmp0
  12151. movq fromspace_end(%rip), tmp1
  12152. cmpq tmp1, tmp0
  12153. jl block0
  12154. jmp block1
  12155. block0:
  12156. movq $0, _4
  12157. jmp block9
  12158. block1:
  12159. movq %r15, %rdi
  12160. movq $16, %rsi
  12161. callq collect
  12162. jmp block9
  12163. block9:
  12164. movq free_ptr(%rip), %r11
  12165. addq $16, free_ptr(%rip)
  12166. movq $3, 0(%r11)
  12167. movq %r11, alloc2
  12168. movq alloc2, %r11
  12169. movq $42, 8(%r11)
  12170. movq $0, _3
  12171. movq alloc2, vecinit6
  12172. movq free_ptr(%rip), tmp2
  12173. movq tmp2, tmp3
  12174. addq $16, tmp3
  12175. movq fromspace_end(%rip), tmp4
  12176. cmpq tmp4, tmp3
  12177. jl block7
  12178. jmp block8
  12179. block7:
  12180. movq $0, _8
  12181. jmp block6
  12182. block8:
  12183. movq %r15, %rdi
  12184. movq $16, %rsi
  12185. callq collect
  12186. jmp block6
  12187. block6:
  12188. movq free_ptr(%rip), %r11
  12189. addq $16, free_ptr(%rip)
  12190. movq $131, 0(%r11)
  12191. movq %r11, alloc5
  12192. movq alloc5, %r11
  12193. movq vecinit6, 8(%r11)
  12194. movq $0, _7
  12195. movq alloc5, %r11
  12196. movq 8(%r11), tmp5
  12197. movq tmp5, %r11
  12198. movq 8(%r11), %rax
  12199. jmp conclusion
  12200. \end{lstlisting}
  12201. \end{minipage}
  12202. \end{tabular}
  12203. \end{tcolorbox}
  12204. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  12205. \code{select\_instructions} (\emph{right}) passes on the running
  12206. example.}
  12207. \label{fig:select-instr-output-gc}
  12208. \end{figure}
  12209. \clearpage
  12210. \section{Register Allocation}
  12211. \label{sec:reg-alloc-gc}
  12212. \index{subject}{register allocation}
  12213. As discussed previously in this chapter, the garbage collector needs to
  12214. access all the pointers in the root set, that is, all variables that
  12215. are tuples. It will be the responsibility of the register allocator
  12216. to make sure that
  12217. \begin{enumerate}
  12218. \item the root stack is used for spilling tuple-typed variables, and
  12219. \item if a tuple-typed variable is live during a call to the
  12220. collector, it must be spilled to ensure that it is visible to the
  12221. collector.
  12222. \end{enumerate}
  12223. The latter responsibility can be handled during construction of the
  12224. interference graph, by adding interference edges between the call-live
  12225. tuple-typed variables and all the callee-saved registers. (They
  12226. already interfere with the caller-saved registers.)
  12227. %
  12228. \racket{The type information for variables is in the \code{Program}
  12229. form, so we recommend adding another parameter to the
  12230. \code{build\_interference} function to communicate this alist.}
  12231. %
  12232. \python{The type information for variables is generated by the type
  12233. checker for \LangCVec{}, stored a field named \code{var\_types} in
  12234. the \code{CProgram} AST mode. You'll need to propagate that
  12235. information so that it is available in this pass.}
  12236. The spilling of tuple-typed variables to the root stack can be handled
  12237. after graph coloring, in choosing how to assign the colors
  12238. (integers) to registers and stack locations. The
  12239. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12240. changes to also record the number of spills to the root stack.
  12241. % build-interference
  12242. %
  12243. % callq
  12244. % extra parameter for var->type assoc. list
  12245. % update 'program' and 'if'
  12246. % allocate-registers
  12247. % allocate spilled vectors to the rootstack
  12248. % don't change color-graph
  12249. % TODO:
  12250. %\section{Patch Instructions}
  12251. %[mention that global variables are memory references]
  12252. \section{Prelude and Conclusion}
  12253. \label{sec:print-x86-gc}
  12254. \label{sec:prelude-conclusion-x86-gc}
  12255. \index{subject}{prelude}\index{subject}{conclusion}
  12256. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12257. \code{prelude\_and\_conclusion} pass on the running example. In the
  12258. prelude of the \code{main} function, we allocate space
  12259. on the root stack to make room for the spills of tuple-typed
  12260. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12261. taking care that the root stack grows up instead of down. For the
  12262. running example, there was just one spill, so we increment \code{r15}
  12263. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12264. One issue that deserves special care is that there may be a call to
  12265. \code{collect} prior to the initializing assignments for all the
  12266. variables in the root stack. We do not want the garbage collector to
  12267. mistakenly determine that some uninitialized variable is a pointer that
  12268. needs to be followed. Thus, we zero out all locations on the root
  12269. stack in the prelude of \code{main}. In
  12270. figure~\ref{fig:print-x86-output-gc}, the instruction
  12271. %
  12272. \lstinline{movq $0, 0(%r15)}
  12273. %
  12274. is sufficient to accomplish this task because there is only one spill.
  12275. In general, we have to clear as many words as there are spills of
  12276. tuple-typed variables. The garbage collector tests each root to see
  12277. if it is null prior to dereferencing it.
  12278. \begin{figure}[htbp]
  12279. % TODO: Python Version -Jeremy
  12280. \begin{tcolorbox}[colback=white]
  12281. \begin{minipage}[t]{0.5\textwidth}
  12282. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12283. .globl main
  12284. main:
  12285. pushq %rbp
  12286. movq %rsp, %rbp
  12287. subq $0, %rsp
  12288. movq $65536, %rdi
  12289. movq $65536, %rsi
  12290. callq initialize
  12291. movq rootstack_begin(%rip), %r15
  12292. movq $0, 0(%r15)
  12293. addq $8, %r15
  12294. jmp start
  12295. conclusion:
  12296. subq $8, %r15
  12297. addq $0, %rsp
  12298. popq %rbp
  12299. retq
  12300. \end{lstlisting}
  12301. \end{minipage}
  12302. \end{tcolorbox}
  12303. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  12304. \label{fig:print-x86-output-gc}
  12305. \end{figure}
  12306. \begin{figure}[tbp]
  12307. \begin{tcolorbox}[colback=white]
  12308. {\if\edition\racketEd
  12309. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12310. \node (Lvec) at (0,2) {\large \LangVec{}};
  12311. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12312. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12313. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12314. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12315. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12316. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12317. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12318. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12319. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12320. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12321. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12322. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12323. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12324. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12325. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12326. \path[->,bend left=15] (Lvec-4) edge [right] node
  12327. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12328. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12329. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12330. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12331. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12332. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12333. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12334. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12335. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12336. \end{tikzpicture}
  12337. \fi}
  12338. {\if\edition\pythonEd
  12339. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12340. \node (Lvec) at (0,2) {\large \LangVec{}};
  12341. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12342. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12343. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12344. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12345. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12346. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12347. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12348. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12349. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12350. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12351. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12352. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12353. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12354. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12355. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12356. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12357. \end{tikzpicture}
  12358. \fi}
  12359. \end{tcolorbox}
  12360. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12361. \label{fig:Lvec-passes}
  12362. \end{figure}
  12363. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12364. for the compilation of \LangVec{}.
  12365. \clearpage
  12366. {\if\edition\racketEd
  12367. \section{Challenge: Simple Structures}
  12368. \label{sec:simple-structures}
  12369. \index{subject}{struct}
  12370. \index{subject}{structure}
  12371. The language \LangStruct{} extends \LangVec{} with support for simple
  12372. structures. The definition of its concrete syntax is shown in
  12373. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12374. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12375. in Typed Racket is a user-defined data type that contains named fields
  12376. and that is heap allocated, similarly to a vector. The following is an
  12377. example of a structure definition, in this case the definition of a
  12378. \code{point} type:
  12379. \begin{lstlisting}
  12380. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12381. \end{lstlisting}
  12382. \newcommand{\LstructGrammarRacket}{
  12383. \begin{array}{lcl}
  12384. \Type &::=& \Var \\
  12385. \Exp &::=& (\Var\;\Exp \ldots)\\
  12386. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12387. \end{array}
  12388. }
  12389. \newcommand{\LstructASTRacket}{
  12390. \begin{array}{lcl}
  12391. \Type &::=& \VAR{\Var} \\
  12392. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12393. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12394. \end{array}
  12395. }
  12396. \begin{figure}[tbp]
  12397. \centering
  12398. \begin{tcolorbox}[colback=white]
  12399. \[
  12400. \begin{array}{l}
  12401. \gray{\LintGrammarRacket{}} \\ \hline
  12402. \gray{\LvarGrammarRacket{}} \\ \hline
  12403. \gray{\LifGrammarRacket{}} \\ \hline
  12404. \gray{\LwhileGrammarRacket} \\ \hline
  12405. \gray{\LtupGrammarRacket} \\ \hline
  12406. \LstructGrammarRacket \\
  12407. \begin{array}{lcl}
  12408. \LangStruct{} &::=& \Def \ldots \; \Exp
  12409. \end{array}
  12410. \end{array}
  12411. \]
  12412. \end{tcolorbox}
  12413. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12414. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12415. \label{fig:Lstruct-concrete-syntax}
  12416. \end{figure}
  12417. \begin{figure}[tbp]
  12418. \centering
  12419. \begin{tcolorbox}[colback=white]
  12420. \small
  12421. \[
  12422. \begin{array}{l}
  12423. \gray{\LintASTRacket{}} \\ \hline
  12424. \gray{\LvarASTRacket{}} \\ \hline
  12425. \gray{\LifASTRacket{}} \\ \hline
  12426. \gray{\LwhileASTRacket} \\ \hline
  12427. \gray{\LtupASTRacket} \\ \hline
  12428. \LstructASTRacket \\
  12429. \begin{array}{lcl}
  12430. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12431. \end{array}
  12432. \end{array}
  12433. \]
  12434. \end{tcolorbox}
  12435. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12436. (figure~\ref{fig:Lvec-syntax}).}
  12437. \label{fig:Lstruct-syntax}
  12438. \end{figure}
  12439. An instance of a structure is created using function-call syntax, with
  12440. the name of the structure in the function position, as follows:
  12441. \begin{lstlisting}
  12442. (point 7 12)
  12443. \end{lstlisting}
  12444. Function-call syntax is also used to read a field of a structure. The
  12445. function name is formed by the structure name, a dash, and the field
  12446. name. The following example uses \code{point-x} and \code{point-y} to
  12447. access the \code{x} and \code{y} fields of two point instances:
  12448. \begin{center}
  12449. \begin{lstlisting}
  12450. (let ([pt1 (point 7 12)])
  12451. (let ([pt2 (point 4 3)])
  12452. (+ (- (point-x pt1) (point-x pt2))
  12453. (- (point-y pt1) (point-y pt2)))))
  12454. \end{lstlisting}
  12455. \end{center}
  12456. Similarly, to write to a field of a structure, use its set function,
  12457. whose name starts with \code{set-}, followed by the structure name,
  12458. then a dash, then the field name, and finally with an exclamation
  12459. mark. The following example uses \code{set-point-x!} to change the
  12460. \code{x} field from \code{7} to \code{42}:
  12461. \begin{center}
  12462. \begin{lstlisting}
  12463. (let ([pt (point 7 12)])
  12464. (let ([_ (set-point-x! pt 42)])
  12465. (point-x pt)))
  12466. \end{lstlisting}
  12467. \end{center}
  12468. \begin{exercise}\normalfont\normalsize
  12469. Create a type checker for \LangStruct{} by extending the type
  12470. checker for \LangVec{}. Extend your compiler with support for simple
  12471. structures, compiling \LangStruct{} to x86 assembly code. Create
  12472. five new test cases that use structures and, test your compiler.
  12473. \end{exercise}
  12474. % TODO: create an interpreter for L_struct
  12475. \clearpage
  12476. \fi}
  12477. \section{Challenge: Arrays}
  12478. \label{sec:arrays}
  12479. % TODO mention trapped-error
  12480. In this chapter we have studied tuples, that is, heterogeneous
  12481. sequences of elements whose length is determined at compile time. This
  12482. challenge is also about sequences, but this time the length is
  12483. determined at runtime and all the elements have the same type (they
  12484. are homogeneous). We use the term \emph{array} for this latter kind of
  12485. sequence.
  12486. %
  12487. \racket{
  12488. The Racket language does not distinguish between tuples and arrays;
  12489. they are both represented by vectors. However, Typed Racket
  12490. distinguishes between tuples and arrays: the \code{Vector} type is for
  12491. tuples, and the \code{Vectorof} type is for arrays.}
  12492. \python{
  12493. Arrays correspond to the \code{list} type in Python language.
  12494. }
  12495. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12496. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  12497. presents the definition of the abstract syntax, extending \LangVec{}
  12498. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  12499. %
  12500. \racket{\code{make-vector} primitive operator for creating an array,
  12501. whose arguments are the length of the array and an initial value for
  12502. all the elements in the array.}
  12503. \python{bracket notation for creating an array literal.}
  12504. \racket{
  12505. The \code{vector-length},
  12506. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12507. for tuples become overloaded for use with arrays.}
  12508. \python{
  12509. The subscript operator becomes overloaded for use with arrays and tuples
  12510. and now may appear on the left-hand side of an assignment.
  12511. Note that the index of the subscript, when applied to an array, may be an
  12512. arbitrary expression and not just a constant integer.
  12513. The \code{len} function is also applicable to arrays.
  12514. }
  12515. %
  12516. We include integer multiplication in \LangArray{}, because it is
  12517. useful in many examples involving arrays such as computing the
  12518. inner product of two arrays (figure~\ref{fig:inner_product}).
  12519. \newcommand{\LarrayGrammarRacket}{
  12520. \begin{array}{lcl}
  12521. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12522. \Exp &::=& \CMUL{\Exp}{\Exp}
  12523. \MID \CMAKEVEC{\Exp}{\Exp}
  12524. \end{array}
  12525. }
  12526. \newcommand{\LarrayASTRacket}{
  12527. \begin{array}{lcl}
  12528. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12529. \Exp &::=& \MUL{\Exp}{\Exp}
  12530. \MID \MAKEVEC{\Exp}{\Exp}
  12531. \end{array}
  12532. }
  12533. \newcommand{\LarrayGrammarPython}{
  12534. \begin{array}{lcl}
  12535. \Type &::=& \key{list}\LS\Type\RS \\
  12536. \Exp &::=& \CMUL{\Exp}{\Exp}
  12537. \MID \CGET{\Exp}{\Exp}
  12538. \MID \LS \Exp \code{,} \ldots \RS \\
  12539. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  12540. \end{array}
  12541. }
  12542. \newcommand{\LarrayASTPython}{
  12543. \begin{array}{lcl}
  12544. \Type &::=& \key{ListType}\LP\Type\RP \\
  12545. \Exp &::=& \MUL{\Exp}{\Exp}
  12546. \MID \GET{\Exp}{\Exp} \\
  12547. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  12548. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  12549. \end{array}
  12550. }
  12551. \begin{figure}[tp]
  12552. \centering
  12553. \begin{tcolorbox}[colback=white]
  12554. \small
  12555. {\if\edition\racketEd
  12556. \[
  12557. \begin{array}{l}
  12558. \gray{\LintGrammarRacket{}} \\ \hline
  12559. \gray{\LvarGrammarRacket{}} \\ \hline
  12560. \gray{\LifGrammarRacket{}} \\ \hline
  12561. \gray{\LwhileGrammarRacket} \\ \hline
  12562. \gray{\LtupGrammarRacket} \\ \hline
  12563. \LarrayGrammarRacket \\
  12564. \begin{array}{lcl}
  12565. \LangArray{} &::=& \Exp
  12566. \end{array}
  12567. \end{array}
  12568. \]
  12569. \fi}
  12570. {\if\edition\pythonEd
  12571. \[
  12572. \begin{array}{l}
  12573. \gray{\LintGrammarPython{}} \\ \hline
  12574. \gray{\LvarGrammarPython{}} \\ \hline
  12575. \gray{\LifGrammarPython{}} \\ \hline
  12576. \gray{\LwhileGrammarPython} \\ \hline
  12577. \gray{\LtupGrammarPython} \\ \hline
  12578. \LarrayGrammarPython \\
  12579. \begin{array}{rcl}
  12580. \LangArrayM{} &::=& \Stmt^{*}
  12581. \end{array}
  12582. \end{array}
  12583. \]
  12584. \fi}
  12585. \end{tcolorbox}
  12586. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12587. \label{fig:Lvecof-concrete-syntax}
  12588. \end{figure}
  12589. \begin{figure}[tp]
  12590. \centering
  12591. \begin{tcolorbox}[colback=white]
  12592. \small
  12593. {\if\edition\racketEd
  12594. \[
  12595. \begin{array}{l}
  12596. \gray{\LintASTRacket{}} \\ \hline
  12597. \gray{\LvarASTRacket{}} \\ \hline
  12598. \gray{\LifASTRacket{}} \\ \hline
  12599. \gray{\LwhileASTRacket} \\ \hline
  12600. \gray{\LtupASTRacket} \\ \hline
  12601. \LarrayASTRacket \\
  12602. \begin{array}{lcl}
  12603. \LangArray{} &::=& \Exp
  12604. \end{array}
  12605. \end{array}
  12606. \]
  12607. \fi}
  12608. {\if\edition\pythonEd
  12609. \[
  12610. \begin{array}{l}
  12611. \gray{\LintASTPython{}} \\ \hline
  12612. \gray{\LvarASTPython{}} \\ \hline
  12613. \gray{\LifASTPython{}} \\ \hline
  12614. \gray{\LwhileASTPython} \\ \hline
  12615. \gray{\LtupASTPython} \\ \hline
  12616. \LarrayASTPython \\
  12617. \begin{array}{rcl}
  12618. \LangArrayM{} &::=& \Stmt^{*}
  12619. \end{array}
  12620. \end{array}
  12621. \]
  12622. \fi}
  12623. \end{tcolorbox}
  12624. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12625. \label{fig:Lvecof-syntax}
  12626. \end{figure}
  12627. \begin{figure}[tp]
  12628. \begin{tcolorbox}[colback=white]
  12629. {\if\edition\racketEd
  12630. % TODO: remove the function from the following example, like the python version -Jeremy
  12631. \begin{lstlisting}
  12632. (let ([A (make-vector 2 2)])
  12633. (let ([B (make-vector 2 3)])
  12634. (let ([i 0])
  12635. (let ([prod 0])
  12636. (begin
  12637. (while (< i n)
  12638. (begin
  12639. (set! prod (+ prod (* (vector-ref A i)
  12640. (vector-ref B i))))
  12641. (set! i (+ i 1))))
  12642. prod)))))
  12643. \end{lstlisting}
  12644. \fi}
  12645. {\if\edition\pythonEd
  12646. \begin{lstlisting}
  12647. A = [2, 2]
  12648. B = [3, 3]
  12649. i = 0
  12650. prod = 0
  12651. while i != len(A):
  12652. prod = prod + A[i] * B[i]
  12653. i = i + 1
  12654. print( prod )
  12655. \end{lstlisting}
  12656. \fi}
  12657. \end{tcolorbox}
  12658. \caption{Example program that computes the inner product.}
  12659. \label{fig:inner_product}
  12660. \end{figure}
  12661. {\if\edition\racketEd
  12662. %
  12663. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12664. checker for \LangArray{}. The result type of
  12665. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12666. of the initializing expression. The length expression is required to
  12667. have type \code{Integer}. The type checking of the operators
  12668. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12669. updated to handle the situation in which the vector has type
  12670. \code{Vectorof}. In these cases we translate the operators to their
  12671. \code{vectorof} form so that later passes can easily distinguish
  12672. between operations on tuples versus arrays. We override the
  12673. \code{operator-types} method to provide the type signature for
  12674. multiplication: it takes two integers and returns an integer. \fi}
  12675. {\if\edition\pythonEd
  12676. %
  12677. The type checker for \LangArray{} is defined in
  12678. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12679. is \code{list[T]} where \code{T} is the type of the initializing
  12680. expressions. The type checking of the \code{len} function and the
  12681. subscript operator is updated to handle lists. The type checker now
  12682. also handles a subscript on the left-hand side of an assignment.
  12683. Regarding multiplication, it takes two integers and returns an
  12684. integer.
  12685. %
  12686. \fi}
  12687. \begin{figure}[tbp]
  12688. \begin{tcolorbox}[colback=white]
  12689. {\if\edition\racketEd
  12690. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12691. (define type-check-Lvecof-class
  12692. (class type-check-Lvec-class
  12693. (super-new)
  12694. (inherit check-type-equal?)
  12695. (define/override (operator-types)
  12696. (append '((* . ((Integer Integer) . Integer)))
  12697. (super operator-types)))
  12698. (define/override (type-check-exp env)
  12699. (lambda (e)
  12700. (define recur (type-check-exp env))
  12701. (match e
  12702. [(Prim 'make-vector (list e1 e2))
  12703. (define-values (e1^ t1) (recur e1))
  12704. (define-values (e2^ elt-type) (recur e2))
  12705. (define vec-type `(Vectorof ,elt-type))
  12706. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  12707. [(Prim 'vector-ref (list e1 e2))
  12708. (define-values (e1^ t1) (recur e1))
  12709. (define-values (e2^ t2) (recur e2))
  12710. (match* (t1 t2)
  12711. [(`(Vectorof ,elt-type) 'Integer)
  12712. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12713. [(other wise) ((super type-check-exp env) e)])]
  12714. [(Prim 'vector-set! (list e1 e2 e3) )
  12715. (define-values (e-vec t-vec) (recur e1))
  12716. (define-values (e2^ t2) (recur e2))
  12717. (define-values (e-arg^ t-arg) (recur e3))
  12718. (match t-vec
  12719. [`(Vectorof ,elt-type)
  12720. (check-type-equal? elt-type t-arg e)
  12721. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12722. [else ((super type-check-exp env) e)])]
  12723. [(Prim 'vector-length (list e1))
  12724. (define-values (e1^ t1) (recur e1))
  12725. (match t1
  12726. [`(Vectorof ,t)
  12727. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12728. [else ((super type-check-exp env) e)])]
  12729. [else ((super type-check-exp env) e)])))
  12730. ))
  12731. (define (type-check-Lvecof p)
  12732. (send (new type-check-Lvecof-class) type-check-program p))
  12733. \end{lstlisting}
  12734. \fi}
  12735. {\if\edition\pythonEd
  12736. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12737. class TypeCheckLarray(TypeCheckLtup):
  12738. def type_check_exp(self, e, env):
  12739. match e:
  12740. case ast.List(es, Load()):
  12741. ts = [self.type_check_exp(e, env) for e in es]
  12742. elt_ty = ts[0]
  12743. for (ty, elt) in zip(ts, es):
  12744. self.check_type_equal(elt_ty, ty, elt)
  12745. e.has_type = ListType(elt_ty)
  12746. return e.has_type
  12747. case Call(Name('len'), [tup]):
  12748. tup_t = self.type_check_exp(tup, env)
  12749. tup.has_type = tup_t
  12750. match tup_t:
  12751. case TupleType(ts):
  12752. return IntType()
  12753. case ListType(ty):
  12754. return IntType()
  12755. case _:
  12756. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12757. case Subscript(tup, index, Load()):
  12758. tup_ty = self.type_check_exp(tup, env)
  12759. index_ty = self.type_check_exp(index, env)
  12760. self.check_type_equal(index_ty, IntType(), index)
  12761. match tup_ty:
  12762. case TupleType(ts):
  12763. match index:
  12764. case Constant(i):
  12765. return ts[i]
  12766. case _:
  12767. raise Exception('subscript required constant integer index')
  12768. case ListType(ty):
  12769. return ty
  12770. case _:
  12771. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12772. case BinOp(left, Mult(), right):
  12773. l = self.type_check_exp(left, env)
  12774. self.check_type_equal(l, IntType(), left)
  12775. r = self.type_check_exp(right, env)
  12776. self.check_type_equal(r, IntType(), right)
  12777. return IntType()
  12778. case _:
  12779. return super().type_check_exp(e, env)
  12780. def type_check_stmts(self, ss, env):
  12781. if len(ss) == 0:
  12782. return VoidType()
  12783. match ss[0]:
  12784. case Assign([Subscript(tup, index, Store())], value):
  12785. tup_t = self.type_check_exp(tup, env)
  12786. value_t = self.type_check_exp(value, env)
  12787. index_ty = self.type_check_exp(index, env)
  12788. self.check_type_equal(index_ty, IntType(), index)
  12789. match tup_t:
  12790. case ListType(ty):
  12791. self.check_type_equal(ty, value_t, ss[0])
  12792. case TupleType(ts):
  12793. return self.type_check_stmts(ss, env)
  12794. case _:
  12795. raise Exception('type_check_stmts: '
  12796. 'expected tuple or list, not ' + repr(tup_t))
  12797. return self.type_check_stmts(ss[1:], env)
  12798. case _:
  12799. return super().type_check_stmts(ss, env)
  12800. \end{lstlisting}
  12801. \fi}
  12802. \end{tcolorbox}
  12803. \caption{Type checker for the \LangArray{} language.}
  12804. \label{fig:type-check-Lvecof}
  12805. \end{figure}
  12806. The definition of the interpreter for \LangArray{} is shown in
  12807. figure~\ref{fig:interp-Lvecof}.
  12808. \racket{The \code{make-vector} operator is
  12809. interpreted using Racket's \code{make-vector} function,
  12810. and multiplication is interpreted using \code{fx*},
  12811. which is multiplication for \code{fixnum} integers.
  12812. In the \code{resolve} pass (Section~\ref{sec:array-resolution})
  12813. we translate array access operations
  12814. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  12815. which we interpret using \code{vector} operations with additional
  12816. bounds checks that signal a \code{trapped-error}.
  12817. }
  12818. %
  12819. \python{We implement list creation with a Python list comprehension
  12820. and multiplication is implemented with Python multiplication. We
  12821. add a case to handle a subscript on the left-hand side of
  12822. assignment. Other uses of subscript can be handled by the existing
  12823. code for tuples.}
  12824. \begin{figure}[tbp]
  12825. \begin{tcolorbox}[colback=white]
  12826. {\if\edition\racketEd
  12827. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12828. (define interp-Lvecof-class
  12829. (class interp-Lvec-class
  12830. (super-new)
  12831. (define/override (interp-op op)
  12832. (match op
  12833. ['make-vector make-vector]
  12834. ['vectorof-length vector-length]
  12835. ['vectorof-ref
  12836. (lambda (v i)
  12837. (if (< i (vector-length v))
  12838. (vector-ref v i)
  12839. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  12840. ['vectorof-set!
  12841. (lambda (v i e)
  12842. (if (< i (vector-length v))
  12843. (vector-set! v i e)
  12844. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  12845. [else (super interp-op op)]))
  12846. ))
  12847. (define (interp-Lvecof p)
  12848. (send (new interp-Lvecof-class) interp-program p))
  12849. \end{lstlisting}
  12850. \fi}
  12851. {\if\edition\pythonEd
  12852. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12853. class InterpLarray(InterpLtup):
  12854. def interp_exp(self, e, env):
  12855. match e:
  12856. case ast.List(es, Load()):
  12857. return [self.interp_exp(e, env) for e in es]
  12858. case BinOp(left, Mult(), right):
  12859. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  12860. return l * r
  12861. case _:
  12862. return super().interp_exp(e, env)
  12863. def interp_stmts(self, ss, env):
  12864. if len(ss) == 0:
  12865. return
  12866. match ss[0]:
  12867. case Assign([Subscript(lst, index)], value):
  12868. lst = self.interp_exp(lst, env)
  12869. index = self.interp_exp(index, env)
  12870. lst[index] = self.interp_exp(value, env)
  12871. return self.interp_stmts(ss[1:], env)
  12872. case _:
  12873. return super().interp_stmts(ss, env)
  12874. \end{lstlisting}
  12875. \fi}
  12876. \end{tcolorbox}
  12877. \caption{Interpreter for \LangArray{}.}
  12878. \label{fig:interp-Lvecof}
  12879. \end{figure}
  12880. \subsection{Data Representation}
  12881. \label{sec:array-rep}
  12882. Just as with tuples, we store arrays on the heap, which means that the
  12883. garbage collector will need to inspect arrays. An immediate thought is
  12884. to use the same representation for arrays that we use for tuples.
  12885. However, we limit tuples to a length of fifty so that their length and
  12886. pointer mask can fit into the 64-bit tag at the beginning of each
  12887. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12888. millions of elements, so we need more bits to store the length.
  12889. However, because arrays are homogeneous, we need only 1 bit for the
  12890. pointer mask instead of 1 bit per array element. Finally, the
  12891. garbage collector must be able to distinguish between tuples
  12892. and arrays, so we need to reserve one bit for that purpose. We
  12893. arrive at the following layout for the 64-bit tag at the beginning of
  12894. an array:
  12895. \begin{itemize}
  12896. \item The right-most bit is the forwarding bit, just as in a tuple.
  12897. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  12898. that it is not.
  12899. \item The next bit to the left is the pointer mask. A $0$ indicates
  12900. that none of the elements are pointers to the heap, and a $1$
  12901. indicates that all the elements are pointers.
  12902. \item The next $60$ bits store the length of the array.
  12903. \item The bit at position $62$ distinguishes between a tuple ($0$)
  12904. and an array ($1$).
  12905. \item The left-most bit is reserved as explained in
  12906. chapter~\ref{ch:Lgrad}.
  12907. \end{itemize}
  12908. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  12909. %% differentiate the kinds of values that have been injected into the
  12910. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12911. %% to indicate that the value is an array.
  12912. In the following subsections we provide hints regarding how to update
  12913. the passes to handle arrays.
  12914. \subsection{Overload Resolution}
  12915. \label{sec:array-resolution}
  12916. As noted previously, with the addition of arrays, several operators
  12917. have become \emph{overloaded}; that is, they can be applied to values
  12918. of more than one type. In this case, the element access and length
  12919. operators can be applied to both tuples and arrays. This kind of
  12920. overloading is quite common in programming languages, so many
  12921. compilers perform \emph{overload resolution}\index{subject}{overload
  12922. resolution} to handle it. The idea is to translate each overloaded
  12923. operator into different operators for the different types.
  12924. Implement a new pass named \code{resolve}.
  12925. Translate the reading of an array element
  12926. into a call to
  12927. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  12928. and the writing of an array element to
  12929. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  12930. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  12931. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  12932. When these operators are applied to tuples, leave them as is.
  12933. %
  12934. \python{The type checker for \LangArray{} adds a \code{has\_type}
  12935. field which can be inspected to determine whether the operator
  12936. is applied to a tuple or an array.}
  12937. \subsection{Bounds Checking}
  12938. Recall that the interpreter for \LangArray{} signals a
  12939. \code{trapped-error} when there is an array access that is out of
  12940. bounds. Therefore your compiler is obliged to also catch these errors
  12941. during execution and halt, signaling an error. We recommend inserting
  12942. a new pass named \code{check\_bounds} that inserts code around each
  12943. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  12944. \python{subscript} operation to ensure that the index is greater than
  12945. or equal to zero and less than the array's length. If not, the program
  12946. should halt, for which we recommend using a new primitive operation
  12947. named \code{exit}.
  12948. %% \subsection{Reveal Casts}
  12949. %% The array-access operators \code{vectorof-ref} and
  12950. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12951. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  12952. %% that the type checker cannot tell whether the index will be in bounds,
  12953. %% so the bounds check must be performed at run time. Recall that the
  12954. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  12955. %% an \code{If} around a vector reference for update to check whether
  12956. %% the index is less than the length. You should do the same for
  12957. %% \code{vectorof-ref} and \code{vectorof-set!} .
  12958. %% In addition, the handling of the \code{any-vector} operators in
  12959. %% \code{reveal-casts} needs to be updated to account for arrays that are
  12960. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  12961. %% generated code should test whether the tag is for tuples (\code{010})
  12962. %% or arrays (\code{110}) and then dispatch to either
  12963. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12964. %% we add a case in \code{select\_instructions} to generate the
  12965. %% appropriate instructions for accessing the array length from the
  12966. %% header of an array.
  12967. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12968. %% the generated code needs to check that the index is less than the
  12969. %% vector length, so like the code for \code{any-vector-length}, check
  12970. %% the tag to determine whether to use \code{any-vector-length} or
  12971. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12972. %% is complete, the generated code can use \code{any-vector-ref} and
  12973. %% \code{any-vector-set!} for both tuples and arrays because the
  12974. %% instructions used for those operators do not look at the tag at the
  12975. %% front of the tuple or array.
  12976. \subsection{Expose Allocation}
  12977. This pass should translate array creation into lower-level
  12978. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  12979. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  12980. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  12981. array. The \code{AllocateArray} AST node allocates an array of the
  12982. length specified by the $\Exp$ (of type \INTTY), but does not
  12983. initialize the elements of the array. Generate code in this pass to
  12984. initialize the elements analogous to the case for tuples.
  12985. {\if\edition\racketEd
  12986. \section{Uncover \texttt{get!}}
  12987. \label{sec:uncover-get-bang-vecof}
  12988. Add cases for \code{AllocateArray} to \code{collect-set!} and
  12989. \code{uncover-get!-exp}.
  12990. \fi}
  12991. \subsection{Remove Complex Operands}
  12992. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12993. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12994. complex, and its subexpression must be atomic.
  12995. \subsection{Explicate Control}
  12996. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12997. \code{explicate\_assign}.
  12998. \subsection{Select Instructions}
  12999. Generate instructions for \code{AllocateArray} similar to those for
  13000. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13001. except that the tag at the front of the array should instead use the
  13002. representation discussed in section~\ref{sec:array-rep}.
  13003. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13004. extract the length from the tag.
  13005. The instructions generated for accessing an element of an array differ
  13006. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13007. that the index is not a constant so you need to generate instructions
  13008. that compute the offset at runtime.
  13009. Compile the \code{exit} primitive into a call to the \code{exit}
  13010. function of the C standard library, with an argument of $255$.
  13011. %% Also, note that assignment to an array element may appear in
  13012. %% as a stand-alone statement, so make sure to handle that situation in
  13013. %% this pass.
  13014. %% Finally, the instructions for \code{any-vectorof-length} should be
  13015. %% similar to those for \code{vectorof-length}, except that one must
  13016. %% first project the array by writing zeroes into the $3$-bit tag
  13017. \begin{exercise}\normalfont\normalsize
  13018. Implement a compiler for the \LangArray{} language by extending your
  13019. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13020. programs, including the one shown in figure~\ref{fig:inner_product}
  13021. and also a program that multiplies two matrices. Note that although
  13022. matrices are two-dimensional arrays, they can be encoded into
  13023. one-dimensional arrays by laying out each row in the array, one after
  13024. the next.
  13025. \end{exercise}
  13026. {\if\edition\racketEd
  13027. \section{Challenge: Generational Collection}
  13028. The copying collector described in section~\ref{sec:GC} can incur
  13029. significant runtime overhead because the call to \code{collect} takes
  13030. time proportional to all the live data. One way to reduce this
  13031. overhead is to reduce how much data is inspected in each call to
  13032. \code{collect}. In particular, researchers have observed that recently
  13033. allocated data is more likely to become garbage then data that has
  13034. survived one or more previous calls to \code{collect}. This insight
  13035. motivated the creation of \emph{generational garbage collectors}
  13036. \index{subject}{generational garbage collector} that
  13037. (1) segregate data according to its age into two or more generations;
  13038. (2) allocate less space for younger generations, so collecting them is
  13039. faster, and more space for the older generations; and (3) perform
  13040. collection on the younger generations more frequently than on older
  13041. generations~\citep{Wilson:1992fk}.
  13042. For this challenge assignment, the goal is to adapt the copying
  13043. collector implemented in \code{runtime.c} to use two generations, one
  13044. for young data and one for old data. Each generation consists of a
  13045. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13046. \code{collect} function to use the two generations:
  13047. \begin{enumerate}
  13048. \item Copy the young generation's FromSpace to its ToSpace and then
  13049. switch the role of the ToSpace and FromSpace
  13050. \item If there is enough space for the requested number of bytes in
  13051. the young FromSpace, then return from \code{collect}.
  13052. \item If there is not enough space in the young FromSpace for the
  13053. requested bytes, then move the data from the young generation to the
  13054. old one with the following steps:
  13055. \begin{enumerate}
  13056. \item[a.] If there is enough room in the old FromSpace, copy the young
  13057. FromSpace to the old FromSpace and then return.
  13058. \item[b.] If there is not enough room in the old FromSpace, then collect
  13059. the old generation by copying the old FromSpace to the old ToSpace
  13060. and swap the roles of the old FromSpace and ToSpace.
  13061. \item[c.] If there is enough room now, copy the young FromSpace to the
  13062. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13063. and ToSpace for the old generation. Copy the young FromSpace and
  13064. the old FromSpace into the larger FromSpace for the old
  13065. generation and then return.
  13066. \end{enumerate}
  13067. \end{enumerate}
  13068. We recommend that you generalize the \code{cheney} function so that it
  13069. can be used for all the copies mentioned: between the young FromSpace
  13070. and ToSpace, between the old FromSpace and ToSpace, and between the
  13071. young FromSpace and old FromSpace. This can be accomplished by adding
  13072. parameters to \code{cheney} that replace its use of the global
  13073. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13074. \code{tospace\_begin}, and \code{tospace\_end}.
  13075. Note that the collection of the young generation does not traverse the
  13076. old generation. This introduces a potential problem: there may be
  13077. young data that is reachable only through pointers in the old
  13078. generation. If these pointers are not taken into account, the
  13079. collector could throw away young data that is live! One solution,
  13080. called \emph{pointer recording}, is to maintain a set of all the
  13081. pointers from the old generation into the new generation and consider
  13082. this set as part of the root set. To maintain this set, the compiler
  13083. must insert extra instructions around every \code{vector-set!}. If the
  13084. vector being modified is in the old generation, and if the value being
  13085. written is a pointer into the new generation, then that pointer must
  13086. be added to the set. Also, if the value being overwritten was a
  13087. pointer into the new generation, then that pointer should be removed
  13088. from the set.
  13089. \begin{exercise}\normalfont\normalsize
  13090. Adapt the \code{collect} function in \code{runtime.c} to implement
  13091. generational garbage collection, as outlined in this section.
  13092. Update the code generation for \code{vector-set!} to implement
  13093. pointer recording. Make sure that your new compiler and runtime
  13094. execute without error on your test suite.
  13095. \end{exercise}
  13096. \fi}
  13097. \section{Further Reading}
  13098. \citet{Appel90} describes many data representation approaches,
  13099. including the ones used in the compilation of Standard ML.
  13100. There are many alternatives to copying collectors (and their bigger
  13101. siblings, the generational collectors) with regard to garbage
  13102. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13103. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13104. collectors are that allocation is fast (just a comparison and pointer
  13105. increment), there is no fragmentation, cyclic garbage is collected,
  13106. and the time complexity of collection depends only on the amount of
  13107. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13108. main disadvantages of a two-space copying collector is that it uses a
  13109. lot of extra space and takes a long time to perform the copy, though
  13110. these problems are ameliorated in generational collectors.
  13111. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13112. small objects and generate a lot of garbage, so copying and
  13113. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13114. Garbage collection is an active research topic, especially concurrent
  13115. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13116. developing new techniques and revisiting old
  13117. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13118. meet every year at the International Symposium on Memory Management to
  13119. present these findings.
  13120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13121. \chapter{Functions}
  13122. \label{ch:Lfun}
  13123. \index{subject}{function}
  13124. \setcounter{footnote}{0}
  13125. This chapter studies the compilation of a subset of \racket{Typed
  13126. Racket}\python{Python} in which only top-level function definitions
  13127. are allowed. This kind of function appears in the C programming
  13128. language, and it serves as an important stepping-stone to implementing
  13129. lexically scoped functions in the form of \key{lambda} abstractions,
  13130. which is the topic of chapter~\ref{ch:Llambda}.
  13131. \section{The \LangFun{} Language}
  13132. The concrete syntax and abstract syntax for function definitions and
  13133. function application are shown in
  13134. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13135. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13136. with zero or more function definitions. The function names from these
  13137. definitions are in scope for the entire program, including all the
  13138. function definitions, and therefore the ordering of function
  13139. definitions does not matter.
  13140. %
  13141. \python{The abstract syntax for function parameters in
  13142. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  13143. consists of a parameter name and its type. This design differs from
  13144. Python's \code{ast} module, which has a more complex structure for
  13145. function parameters to handle keyword parameters,
  13146. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13147. complex Python abstract syntax into the simpler syntax of
  13148. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13149. \code{FunctionDef} constructor are for decorators and a type
  13150. comment, neither of which are used by our compiler. We recommend
  13151. replacing them with \code{None} in the \code{shrink} pass.
  13152. }
  13153. %
  13154. The concrete syntax for function application
  13155. \index{subject}{function application}
  13156. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13157. where the first expression
  13158. must evaluate to a function and the remaining expressions are the arguments. The
  13159. abstract syntax for function application is
  13160. $\APPLY{\Exp}{\Exp^*}$.
  13161. %% The syntax for function application does not include an explicit
  13162. %% keyword, which is error prone when using \code{match}. To alleviate
  13163. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13164. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13165. Functions are first-class in the sense that a function pointer
  13166. \index{subject}{function pointer} is data and can be stored in memory or passed
  13167. as a parameter to another function. Thus, there is a function
  13168. type, written
  13169. {\if\edition\racketEd
  13170. \begin{lstlisting}
  13171. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13172. \end{lstlisting}
  13173. \fi}
  13174. {\if\edition\pythonEd
  13175. \begin{lstlisting}
  13176. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13177. \end{lstlisting}
  13178. \fi}
  13179. %
  13180. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13181. through $\Type_n$ and whose return type is $\Type_R$. The main
  13182. limitation of these functions (with respect to
  13183. \racket{Racket}\python{Python} functions) is that they are not
  13184. lexically scoped. That is, the only external entities that can be
  13185. referenced from inside a function body are other globally defined
  13186. functions. The syntax of \LangFun{} prevents function definitions from
  13187. being nested inside each other.
  13188. \newcommand{\LfunGrammarRacket}{
  13189. \begin{array}{lcl}
  13190. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13191. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13192. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13193. \end{array}
  13194. }
  13195. \newcommand{\LfunASTRacket}{
  13196. \begin{array}{lcl}
  13197. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13198. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13199. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13200. \end{array}
  13201. }
  13202. \newcommand{\LfunGrammarPython}{
  13203. \begin{array}{lcl}
  13204. \Type &::=& \key{int}
  13205. \MID \key{bool} \MID \key{void}
  13206. \MID \key{tuple}\LS \Type^+ \RS
  13207. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13208. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13209. \Stmt &::=& \CRETURN{\Exp} \\
  13210. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13211. \end{array}
  13212. }
  13213. \newcommand{\LfunASTPython}{
  13214. \begin{array}{lcl}
  13215. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13216. \MID \key{TupleType}\LS\Type^+\RS\\
  13217. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13218. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13219. \Stmt &::=& \RETURN{\Exp} \\
  13220. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13221. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13222. \end{array}
  13223. }
  13224. \begin{figure}[tp]
  13225. \centering
  13226. \begin{tcolorbox}[colback=white]
  13227. \small
  13228. {\if\edition\racketEd
  13229. \[
  13230. \begin{array}{l}
  13231. \gray{\LintGrammarRacket{}} \\ \hline
  13232. \gray{\LvarGrammarRacket{}} \\ \hline
  13233. \gray{\LifGrammarRacket{}} \\ \hline
  13234. \gray{\LwhileGrammarRacket} \\ \hline
  13235. \gray{\LtupGrammarRacket} \\ \hline
  13236. \LfunGrammarRacket \\
  13237. \begin{array}{lcl}
  13238. \LangFunM{} &::=& \Def \ldots \; \Exp
  13239. \end{array}
  13240. \end{array}
  13241. \]
  13242. \fi}
  13243. {\if\edition\pythonEd
  13244. \[
  13245. \begin{array}{l}
  13246. \gray{\LintGrammarPython{}} \\ \hline
  13247. \gray{\LvarGrammarPython{}} \\ \hline
  13248. \gray{\LifGrammarPython{}} \\ \hline
  13249. \gray{\LwhileGrammarPython} \\ \hline
  13250. \gray{\LtupGrammarPython} \\ \hline
  13251. \LfunGrammarPython \\
  13252. \begin{array}{rcl}
  13253. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13254. \end{array}
  13255. \end{array}
  13256. \]
  13257. \fi}
  13258. \end{tcolorbox}
  13259. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13260. \label{fig:Lfun-concrete-syntax}
  13261. \end{figure}
  13262. \begin{figure}[tp]
  13263. \centering
  13264. \begin{tcolorbox}[colback=white]
  13265. \small
  13266. {\if\edition\racketEd
  13267. \[
  13268. \begin{array}{l}
  13269. \gray{\LintOpAST} \\ \hline
  13270. \gray{\LvarASTRacket{}} \\ \hline
  13271. \gray{\LifASTRacket{}} \\ \hline
  13272. \gray{\LwhileASTRacket{}} \\ \hline
  13273. \gray{\LtupASTRacket{}} \\ \hline
  13274. \LfunASTRacket \\
  13275. \begin{array}{lcl}
  13276. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13277. \end{array}
  13278. \end{array}
  13279. \]
  13280. \fi}
  13281. {\if\edition\pythonEd
  13282. \[
  13283. \begin{array}{l}
  13284. \gray{\LintASTPython{}} \\ \hline
  13285. \gray{\LvarASTPython{}} \\ \hline
  13286. \gray{\LifASTPython{}} \\ \hline
  13287. \gray{\LwhileASTPython} \\ \hline
  13288. \gray{\LtupASTPython} \\ \hline
  13289. \LfunASTPython \\
  13290. \begin{array}{rcl}
  13291. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13292. \end{array}
  13293. \end{array}
  13294. \]
  13295. \fi}
  13296. \end{tcolorbox}
  13297. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13298. \label{fig:Lfun-syntax}
  13299. \end{figure}
  13300. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13301. representative example of defining and using functions in \LangFun{}.
  13302. We define a function \code{map} that applies some other function
  13303. \code{f} to both elements of a tuple and returns a new tuple
  13304. containing the results. We also define a function \code{inc}. The
  13305. program applies \code{map} to \code{inc} and
  13306. %
  13307. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13308. %
  13309. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13310. %
  13311. from which we return \code{42}.
  13312. \begin{figure}[tbp]
  13313. \begin{tcolorbox}[colback=white]
  13314. {\if\edition\racketEd
  13315. \begin{lstlisting}
  13316. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13317. : (Vector Integer Integer)
  13318. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13319. (define (inc [x : Integer]) : Integer
  13320. (+ x 1))
  13321. (vector-ref (map inc (vector 0 41)) 1)
  13322. \end{lstlisting}
  13323. \fi}
  13324. {\if\edition\pythonEd
  13325. \begin{lstlisting}
  13326. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13327. return f(v[0]), f(v[1])
  13328. def inc(x : int) -> int:
  13329. return x + 1
  13330. print( map(inc, (0, 41))[1] )
  13331. \end{lstlisting}
  13332. \fi}
  13333. \end{tcolorbox}
  13334. \caption{Example of using functions in \LangFun{}.}
  13335. \label{fig:Lfun-function-example}
  13336. \end{figure}
  13337. The definitional interpreter for \LangFun{} is shown in
  13338. figure~\ref{fig:interp-Lfun}. The case for the
  13339. %
  13340. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13341. %
  13342. AST is responsible for setting up the mutual recursion between the
  13343. top-level function definitions.
  13344. %
  13345. \racket{We use the classic back-patching
  13346. \index{subject}{back-patching} approach that uses mutable variables
  13347. and makes two passes over the function
  13348. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13349. top-level environment using a mutable cons cell for each function
  13350. definition. Note that the \code{lambda} value for each function is
  13351. incomplete; it does not yet include the environment. Once the
  13352. top-level environment has been constructed, we iterate over it and
  13353. update the \code{lambda} values to use the top-level environment.}
  13354. %
  13355. \python{We create a dictionary named \code{env} and fill it in
  13356. by mapping each function name to a new \code{Function} value,
  13357. each of which stores a reference to the \code{env}.
  13358. (We define the class \code{Function} for this purpose.)}
  13359. %
  13360. To interpret a function \racket{application}\python{call}, we match
  13361. the result of the function expression to obtain a function value. We
  13362. then extend the function's environment with the mapping of parameters to
  13363. argument values. Finally, we interpret the body of the function in
  13364. this extended environment.
  13365. \begin{figure}[tp]
  13366. \begin{tcolorbox}[colback=white]
  13367. {\if\edition\racketEd
  13368. \begin{lstlisting}
  13369. (define interp-Lfun-class
  13370. (class interp-Lvec-class
  13371. (super-new)
  13372. (define/override ((interp-exp env) e)
  13373. (define recur (interp-exp env))
  13374. (match e
  13375. [(Apply fun args)
  13376. (define fun-val (recur fun))
  13377. (define arg-vals (for/list ([e args]) (recur e)))
  13378. (match fun-val
  13379. [`(function (,xs ...) ,body ,fun-env)
  13380. (define params-args (for/list ([x xs] [arg arg-vals])
  13381. (cons x (box arg))))
  13382. (define new-env (append params-args fun-env))
  13383. ((interp-exp new-env) body)]
  13384. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  13385. [else ((super interp-exp env) e)]
  13386. ))
  13387. (define/public (interp-def d)
  13388. (match d
  13389. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13390. (cons f (box `(function ,xs ,body ())))]))
  13391. (define/override (interp-program p)
  13392. (match p
  13393. [(ProgramDefsExp info ds body)
  13394. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13395. (for/list ([f (in-dict-values top-level)])
  13396. (set-box! f (match (unbox f)
  13397. [`(function ,xs ,body ())
  13398. `(function ,xs ,body ,top-level)])))
  13399. ((interp-exp top-level) body))]))
  13400. ))
  13401. (define (interp-Lfun p)
  13402. (send (new interp-Lfun-class) interp-program p))
  13403. \end{lstlisting}
  13404. \fi}
  13405. {\if\edition\pythonEd
  13406. \begin{lstlisting}
  13407. class InterpLfun(InterpLtup):
  13408. def apply_fun(self, fun, args, e):
  13409. match fun:
  13410. case Function(name, xs, body, env):
  13411. new_env = env.copy().update(zip(xs, args))
  13412. return self.interp_stmts(body, new_env)
  13413. case _:
  13414. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13415. def interp_exp(self, e, env):
  13416. match e:
  13417. case Call(Name('input_int'), []):
  13418. return super().interp_exp(e, env)
  13419. case Call(func, args):
  13420. f = self.interp_exp(func, env)
  13421. vs = [self.interp_exp(arg, env) for arg in args]
  13422. return self.apply_fun(f, vs, e)
  13423. case _:
  13424. return super().interp_exp(e, env)
  13425. def interp_stmts(self, ss, env):
  13426. if len(ss) == 0:
  13427. return
  13428. match ss[0]:
  13429. case Return(value):
  13430. return self.interp_exp(value, env)
  13431. case FunctionDef(name, params, bod, dl, returns, comment):
  13432. ps = [x for (x,t) in params]
  13433. env[name] = Function(name, ps, bod, env)
  13434. return self.interp_stmts(ss[1:], env)
  13435. case _:
  13436. return super().interp_stmts(ss, env)
  13437. def interp(self, p):
  13438. match p:
  13439. case Module(ss):
  13440. env = {}
  13441. self.interp_stmts(ss, env)
  13442. if 'main' in env.keys():
  13443. self.apply_fun(env['main'], [], None)
  13444. case _:
  13445. raise Exception('interp: unexpected ' + repr(p))
  13446. \end{lstlisting}
  13447. \fi}
  13448. \end{tcolorbox}
  13449. \caption{Interpreter for the \LangFun{} language.}
  13450. \label{fig:interp-Lfun}
  13451. \end{figure}
  13452. %\margincomment{TODO: explain type checker}
  13453. The type checker for \LangFun{} is shown in
  13454. figure~\ref{fig:type-check-Lfun}.
  13455. %
  13456. \python{(We omit the code that parses function parameters into the
  13457. simpler abstract syntax.)}
  13458. %
  13459. Similarly to the interpreter, the case for the
  13460. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13461. %
  13462. AST is responsible for setting up the mutual recursion between the
  13463. top-level function definitions. We begin by create a mapping
  13464. \code{env} from every function name to its type. We then type check
  13465. the program using this mapping.
  13466. %
  13467. In the case for function \racket{application}\python{call}, we match
  13468. the type of the function expression to a function type and check that
  13469. the types of the argument expressions are equal to the function's
  13470. parameter types. The type of the \racket{application}\python{call} as
  13471. a whole is the return type from the function type.
  13472. \begin{figure}[tp]
  13473. \begin{tcolorbox}[colback=white]
  13474. {\if\edition\racketEd
  13475. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13476. (define type-check-Lfun-class
  13477. (class type-check-Lvec-class
  13478. (super-new)
  13479. (inherit check-type-equal?)
  13480. (define/public (type-check-apply env e es)
  13481. (define-values (e^ ty) ((type-check-exp env) e))
  13482. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  13483. ((type-check-exp env) e)))
  13484. (match ty
  13485. [`(,ty^* ... -> ,rt)
  13486. (for ([arg-ty ty*] [param-ty ty^*])
  13487. (check-type-equal? arg-ty param-ty (Apply e es)))
  13488. (values e^ e* rt)]))
  13489. (define/override (type-check-exp env)
  13490. (lambda (e)
  13491. (match e
  13492. [(FunRef f n)
  13493. (values (FunRef f n) (dict-ref env f))]
  13494. [(Apply e es)
  13495. (define-values (e^ es^ rt) (type-check-apply env e es))
  13496. (values (Apply e^ es^) rt)]
  13497. [(Call e es)
  13498. (define-values (e^ es^ rt) (type-check-apply env e es))
  13499. (values (Call e^ es^) rt)]
  13500. [else ((super type-check-exp env) e)])))
  13501. (define/public (type-check-def env)
  13502. (lambda (e)
  13503. (match e
  13504. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  13505. (define new-env (append (map cons xs ps) env))
  13506. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13507. (check-type-equal? ty^ rt body)
  13508. (Def f p:t* rt info body^)])))
  13509. (define/public (fun-def-type d)
  13510. (match d
  13511. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  13512. (define/override (type-check-program e)
  13513. (match e
  13514. [(ProgramDefsExp info ds body)
  13515. (define env (for/list ([d ds])
  13516. (cons (Def-name d) (fun-def-type d))))
  13517. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  13518. (define-values (body^ ty) ((type-check-exp env) body))
  13519. (check-type-equal? ty 'Integer body)
  13520. (ProgramDefsExp info ds^ body^)]))))
  13521. (define (type-check-Lfun p)
  13522. (send (new type-check-Lfun-class) type-check-program p))
  13523. \end{lstlisting}
  13524. \fi}
  13525. {\if\edition\pythonEd
  13526. \begin{lstlisting}
  13527. class TypeCheckLfun(TypeCheckLtup):
  13528. def type_check_exp(self, e, env):
  13529. match e:
  13530. case Call(Name('input_int'), []):
  13531. return super().type_check_exp(e, env)
  13532. case Call(func, args):
  13533. func_t = self.type_check_exp(func, env)
  13534. args_t = [self.type_check_exp(arg, env) for arg in args]
  13535. match func_t:
  13536. case FunctionType(params_t, return_t):
  13537. for (arg_t, param_t) in zip(args_t, params_t):
  13538. check_type_equal(param_t, arg_t, e)
  13539. return return_t
  13540. case _:
  13541. raise Exception('type_check_exp: in call, unexpected ' +
  13542. repr(func_t))
  13543. case _:
  13544. return super().type_check_exp(e, env)
  13545. def type_check_stmts(self, ss, env):
  13546. if len(ss) == 0:
  13547. return
  13548. match ss[0]:
  13549. case FunctionDef(name, params, body, dl, returns, comment):
  13550. new_env = env.copy().update(params)
  13551. rt = self.type_check_stmts(body, new_env)
  13552. check_type_equal(returns, rt, ss[0])
  13553. return self.type_check_stmts(ss[1:], env)
  13554. case Return(value):
  13555. return self.type_check_exp(value, env)
  13556. case _:
  13557. return super().type_check_stmts(ss, env)
  13558. def type_check(self, p):
  13559. match p:
  13560. case Module(body):
  13561. env = {}
  13562. for s in body:
  13563. match s:
  13564. case FunctionDef(name, params, bod, dl, returns, comment):
  13565. if name in env:
  13566. raise Exception('type_check: function ' +
  13567. repr(name) + ' defined twice')
  13568. params_t = [t for (x,t) in params]
  13569. env[name] = FunctionType(params_t, returns)
  13570. self.type_check_stmts(body, env)
  13571. case _:
  13572. raise Exception('type_check: unexpected ' + repr(p))
  13573. \end{lstlisting}
  13574. \fi}
  13575. \end{tcolorbox}
  13576. \caption{Type checker for the \LangFun{} language.}
  13577. \label{fig:type-check-Lfun}
  13578. \end{figure}
  13579. \clearpage
  13580. \section{Functions in x86}
  13581. \label{sec:fun-x86}
  13582. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  13583. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  13584. %% \margincomment{\tiny Talk about the return address on the
  13585. %% stack and what callq and retq does.\\ --Jeremy }
  13586. The x86 architecture provides a few features to support the
  13587. implementation of functions. We have already seen that there are
  13588. labels in x86 so that one can refer to the location of an instruction,
  13589. as is needed for jump instructions. Labels can also be used to mark
  13590. the beginning of the instructions for a function. Going further, we
  13591. can obtain the address of a label by using the \key{leaq}
  13592. instruction. For example, the following puts the address of the
  13593. \code{inc} label into the \code{rbx} register:
  13594. \begin{lstlisting}
  13595. leaq inc(%rip), %rbx
  13596. \end{lstlisting}
  13597. Recall from section~\ref{sec:select-instructions-gc} that
  13598. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13599. addressing.
  13600. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13601. to functions whose locations were given by a label, such as
  13602. \code{read\_int}. To support function calls in this chapter we instead
  13603. jump to functions whose location are given by an address in
  13604. a register; that is, we use \emph{indirect function calls}. The
  13605. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13606. before the register name.\index{subject}{indirect function call}
  13607. \begin{lstlisting}
  13608. callq *%rbx
  13609. \end{lstlisting}
  13610. \subsection{Calling Conventions}
  13611. \label{sec:calling-conventions-fun}
  13612. \index{subject}{calling conventions}
  13613. The \code{callq} instruction provides partial support for implementing
  13614. functions: it pushes the return address on the stack and it jumps to
  13615. the target. However, \code{callq} does not handle
  13616. \begin{enumerate}
  13617. \item parameter passing,
  13618. \item pushing frames on the procedure call stack and popping them off,
  13619. or
  13620. \item determining how registers are shared by different functions.
  13621. \end{enumerate}
  13622. Regarding parameter passing, recall that the x86-64 calling
  13623. convention for Unix-based system uses the following six registers to
  13624. pass arguments to a function, in the given order.
  13625. \begin{lstlisting}
  13626. rdi rsi rdx rcx r8 r9
  13627. \end{lstlisting}
  13628. If there are more than six arguments, then the calling convention
  13629. mandates using space on the frame of the caller for the rest of the
  13630. arguments. However, to ease the implementation of efficient tail calls
  13631. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13632. arguments.
  13633. %
  13634. The return value of the function is stored in register \code{rax}.
  13635. \index{subject}{prelude}\index{subject}{conclusion}
  13636. Regarding frames \index{subject}{frame} and the procedure call stack,
  13637. \index{subject}{procedure call stack} recall from
  13638. section~\ref{sec:x86} that the stack grows down and each function call
  13639. uses a chunk of space on the stack called a frame. The caller sets the
  13640. stack pointer, register \code{rsp}, to the last data item in its
  13641. frame. The callee must not change anything in the caller's frame, that
  13642. is, anything that is at or above the stack pointer. The callee is free
  13643. to use locations that are below the stack pointer.
  13644. Recall that we store variables of tuple type on the root stack. So,
  13645. the prelude of a function needs to move the root stack pointer
  13646. \code{r15} up according to the number of variables of tuple type and
  13647. the conclusion needs to move the root stack pointer back down. Also,
  13648. the prelude must initialize to \code{0} this frame's slots in the root
  13649. stack to signal to the garbage collector that those slots do not yet
  13650. contain a valid pointer. Otherwise the garbage collector will
  13651. interpret the garbage bits in those slots as memory addresses and try
  13652. to traverse them, causing serious mayhem!
  13653. Regarding the sharing of registers between different functions, recall
  13654. from section~\ref{sec:calling-conventions} that the registers are
  13655. divided into two groups, the caller-saved registers and the
  13656. callee-saved registers. The caller should assume that all the
  13657. caller-saved registers are overwritten with arbitrary values by the
  13658. callee. For that reason we recommend in
  13659. section~\ref{sec:calling-conventions} that variables that are live
  13660. during a function call should not be assigned to caller-saved
  13661. registers.
  13662. On the flip side, if the callee wants to use a callee-saved register,
  13663. the callee must save the contents of those registers on their stack
  13664. frame and then put them back prior to returning to the caller. For
  13665. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13666. the register allocator assigns a variable to a callee-saved register,
  13667. then the prelude of the \code{main} function must save that register
  13668. to the stack and the conclusion of \code{main} must restore it. This
  13669. recommendation now generalizes to all functions.
  13670. Recall that the base pointer, register \code{rbp}, is used as a
  13671. point of reference within a frame, so that each local variable can be
  13672. accessed at a fixed offset from the base pointer
  13673. (section~\ref{sec:x86}).
  13674. %
  13675. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13676. and callee frames.
  13677. \begin{figure}[tbp]
  13678. \centering
  13679. \begin{tcolorbox}[colback=white]
  13680. \begin{tabular}{r|r|l|l} \hline
  13681. Caller View & Callee View & Contents & Frame \\ \hline
  13682. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13683. 0(\key{\%rbp}) & & old \key{rbp} \\
  13684. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13685. \ldots & & \ldots \\
  13686. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13687. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13688. \ldots & & \ldots \\
  13689. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13690. %% & & \\
  13691. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13692. %% & \ldots & \ldots \\
  13693. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13694. \hline
  13695. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13696. & 0(\key{\%rbp}) & old \key{rbp} \\
  13697. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13698. & \ldots & \ldots \\
  13699. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13700. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13701. & \ldots & \ldots \\
  13702. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13703. \end{tabular}
  13704. \end{tcolorbox}
  13705. \caption{Memory layout of caller and callee frames.}
  13706. \label{fig:call-frames}
  13707. \end{figure}
  13708. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13709. %% local variables and for storing the values of callee-saved registers
  13710. %% (we shall refer to all of these collectively as ``locals''), and that
  13711. %% at the beginning of a function we move the stack pointer \code{rsp}
  13712. %% down to make room for them.
  13713. %% We recommend storing the local variables
  13714. %% first and then the callee-saved registers, so that the local variables
  13715. %% can be accessed using \code{rbp} the same as before the addition of
  13716. %% functions.
  13717. %% To make additional room for passing arguments, we shall
  13718. %% move the stack pointer even further down. We count how many stack
  13719. %% arguments are needed for each function call that occurs inside the
  13720. %% body of the function and find their maximum. Adding this number to the
  13721. %% number of locals gives us how much the \code{rsp} should be moved at
  13722. %% the beginning of the function. In preparation for a function call, we
  13723. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13724. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13725. %% so on.
  13726. %% Upon calling the function, the stack arguments are retrieved by the
  13727. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13728. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13729. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13730. %% the layout of the caller and callee frames. Notice how important it is
  13731. %% that we correctly compute the maximum number of arguments needed for
  13732. %% function calls; if that number is too small then the arguments and
  13733. %% local variables will smash into each other!
  13734. \subsection{Efficient Tail Calls}
  13735. \label{sec:tail-call}
  13736. In general, the amount of stack space used by a program is determined
  13737. by the longest chain of nested function calls. That is, if function
  13738. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13739. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13740. large if functions are recursive. However, in some cases we can
  13741. arrange to use only a constant amount of space for a long chain of
  13742. nested function calls.
  13743. A \emph{tail call}\index{subject}{tail call} is a function call that
  13744. happens as the last action in a function body. For example, in the
  13745. following program, the recursive call to \code{tail\_sum} is a tail
  13746. call:
  13747. \begin{center}
  13748. {\if\edition\racketEd
  13749. \begin{lstlisting}
  13750. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13751. (if (eq? n 0)
  13752. r
  13753. (tail_sum (- n 1) (+ n r))))
  13754. (+ (tail_sum 3 0) 36)
  13755. \end{lstlisting}
  13756. \fi}
  13757. {\if\edition\pythonEd
  13758. \begin{lstlisting}
  13759. def tail_sum(n : int, r : int) -> int:
  13760. if n == 0:
  13761. return r
  13762. else:
  13763. return tail_sum(n - 1, n + r)
  13764. print( tail_sum(3, 0) + 36)
  13765. \end{lstlisting}
  13766. \fi}
  13767. \end{center}
  13768. At a tail call, the frame of the caller is no longer needed, so we can
  13769. pop the caller's frame before making the tail call. With this
  13770. approach, a recursive function that makes only tail calls ends up
  13771. using a constant amount of stack space. Functional languages like
  13772. Racket rely heavily on recursive functions, so the definition of
  13773. Racket \emph{requires} that all tail calls be optimized in this way.
  13774. \index{subject}{frame}
  13775. Some care is needed with regard to argument passing in tail calls. As
  13776. mentioned, for arguments beyond the sixth, the convention is to use
  13777. space in the caller's frame for passing arguments. However, for a
  13778. tail call we pop the caller's frame and can no longer use it. An
  13779. alternative is to use space in the callee's frame for passing
  13780. arguments. However, this option is also problematic because the caller
  13781. and callee's frames overlap in memory. As we begin to copy the
  13782. arguments from their sources in the caller's frame, the target
  13783. locations in the callee's frame might collide with the sources for
  13784. later arguments! We solve this problem by using the heap instead of
  13785. the stack for passing more than six arguments
  13786. (section~\ref{sec:limit-functions-r4}).
  13787. As mentioned, for a tail call we pop the caller's frame prior to
  13788. making the tail call. The instructions for popping a frame are the
  13789. instructions that we usually place in the conclusion of a
  13790. function. Thus, we also need to place such code immediately before
  13791. each tail call. These instructions include restoring the callee-saved
  13792. registers, so it is fortunate that the argument passing registers are
  13793. all caller-saved registers.
  13794. One note remains regarding which instruction to use to make the tail
  13795. call. When the callee is finished, it should not return to the current
  13796. function but instead return to the function that called the current
  13797. one. Thus, the return address that is already on the stack is the
  13798. right one, and we should not use \key{callq} to make the tail call
  13799. because that would overwrite the return address. Instead we simply use
  13800. the \key{jmp} instruction. As with the indirect function call, we write
  13801. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  13802. prefixed with an asterisk. We recommend using \code{rax} to hold the
  13803. jump target because the conclusion can overwrite just about everything
  13804. else.
  13805. \begin{lstlisting}
  13806. jmp *%rax
  13807. \end{lstlisting}
  13808. \section{Shrink \LangFun{}}
  13809. \label{sec:shrink-r4}
  13810. The \code{shrink} pass performs a minor modification to ease the
  13811. later passes. This pass introduces an explicit \code{main} function
  13812. that gobbles up all the top-level statements of the module.
  13813. %
  13814. \racket{It also changes the top \code{ProgramDefsExp} form to
  13815. \code{ProgramDefs}.}
  13816. {\if\edition\racketEd
  13817. \begin{lstlisting}
  13818. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  13819. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  13820. \end{lstlisting}
  13821. where $\itm{mainDef}$ is
  13822. \begin{lstlisting}
  13823. (Def 'main '() 'Integer '() |$\Exp'$|)
  13824. \end{lstlisting}
  13825. \fi}
  13826. {\if\edition\pythonEd
  13827. \begin{lstlisting}
  13828. Module(|$\Def\ldots\Stmt\ldots$|)
  13829. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  13830. \end{lstlisting}
  13831. where $\itm{mainDef}$ is
  13832. \begin{lstlisting}
  13833. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  13834. \end{lstlisting}
  13835. \fi}
  13836. \section{Reveal Functions and the \LangFunRef{} language}
  13837. \label{sec:reveal-functions-r4}
  13838. The syntax of \LangFun{} is inconvenient for purposes of compilation
  13839. in that it conflates the use of function names and local
  13840. variables. This is a problem because we need to compile the use of a
  13841. function name differently from the use of a local variable. In
  13842. particular, we use \code{leaq} to convert the function name (a label
  13843. in x86) to an address in a register. Thus, we create a new pass that
  13844. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  13845. $n$ is the arity of the function.\python{\footnote{The arity is not
  13846. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  13847. This pass is named \code{reveal\_functions} and the output language
  13848. is \LangFunRef{}.
  13849. %is defined in figure~\ref{fig:f1-syntax}.
  13850. %% The concrete syntax for a
  13851. %% function reference is $\CFUNREF{f}$.
  13852. %% \begin{figure}[tp]
  13853. %% \centering
  13854. %% \fbox{
  13855. %% \begin{minipage}{0.96\textwidth}
  13856. %% {\if\edition\racketEd
  13857. %% \[
  13858. %% \begin{array}{lcl}
  13859. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  13860. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13861. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  13862. %% \end{array}
  13863. %% \]
  13864. %% \fi}
  13865. %% {\if\edition\pythonEd
  13866. %% \[
  13867. %% \begin{array}{lcl}
  13868. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  13869. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  13870. %% \end{array}
  13871. %% \]
  13872. %% \fi}
  13873. %% \end{minipage}
  13874. %% }
  13875. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  13876. %% (figure~\ref{fig:Lfun-syntax}).}
  13877. %% \label{fig:f1-syntax}
  13878. %% \end{figure}
  13879. %% Distinguishing between calls in tail position and non-tail position
  13880. %% requires the pass to have some notion of context. We recommend using
  13881. %% two mutually recursive functions, one for processing expressions in
  13882. %% tail position and another for the rest.
  13883. \racket{Placing this pass after \code{uniquify} will make sure that
  13884. there are no local variables and functions that share the same
  13885. name.}
  13886. %
  13887. The \code{reveal\_functions} pass should come before the
  13888. \code{remove\_complex\_operands} pass because function references
  13889. should be categorized as complex expressions.
  13890. \section{Limit Functions}
  13891. \label{sec:limit-functions-r4}
  13892. Recall that we wish to limit the number of function parameters to six
  13893. so that we do not need to use the stack for argument passing, which
  13894. makes it easier to implement efficient tail calls. However, because
  13895. the input language \LangFun{} supports arbitrary numbers of function
  13896. arguments, we have some work to do! The \code{limit\_functions} pass
  13897. transforms functions and function calls that involve more than six
  13898. arguments to pass the first five arguments as usual, but it packs the
  13899. rest of the arguments into a tuple and passes it as the sixth
  13900. argument.\footnote{The implementation this pass can be postponed to
  13901. last because you can test the rest of the passes on functions with
  13902. six or fewer parameters.}
  13903. Each function definition with seven or more parameters is transformed as
  13904. follows.
  13905. {\if\edition\racketEd
  13906. \begin{lstlisting}
  13907. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  13908. |$\Rightarrow$|
  13909. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  13910. \end{lstlisting}
  13911. \fi}
  13912. {\if\edition\pythonEd
  13913. \begin{lstlisting}
  13914. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  13915. |$\Rightarrow$|
  13916. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  13917. |$T_r$|, None, |$\itm{body}'$|, None)
  13918. \end{lstlisting}
  13919. \fi}
  13920. %
  13921. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  13922. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  13923. the $k$th element of the tuple, where $k = i - 6$.
  13924. %
  13925. {\if\edition\racketEd
  13926. \begin{lstlisting}
  13927. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  13928. \end{lstlisting}
  13929. \fi}
  13930. {\if\edition\pythonEd
  13931. \begin{lstlisting}
  13932. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  13933. \end{lstlisting}
  13934. \fi}
  13935. For function calls with too many arguments, the \code{limit\_functions}
  13936. pass transforms them in the following way:
  13937. \begin{tabular}{lll}
  13938. \begin{minipage}{0.3\textwidth}
  13939. {\if\edition\racketEd
  13940. \begin{lstlisting}
  13941. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  13942. \end{lstlisting}
  13943. \fi}
  13944. {\if\edition\pythonEd
  13945. \begin{lstlisting}
  13946. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  13947. \end{lstlisting}
  13948. \fi}
  13949. \end{minipage}
  13950. &
  13951. $\Rightarrow$
  13952. &
  13953. \begin{minipage}{0.5\textwidth}
  13954. {\if\edition\racketEd
  13955. \begin{lstlisting}
  13956. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  13957. \end{lstlisting}
  13958. \fi}
  13959. {\if\edition\pythonEd
  13960. \begin{lstlisting}
  13961. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  13962. \end{lstlisting}
  13963. \fi}
  13964. \end{minipage}
  13965. \end{tabular}
  13966. \section{Remove Complex Operands}
  13967. \label{sec:rco-r4}
  13968. The primary decisions to make for this pass are whether to classify
  13969. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  13970. atomic or complex expressions. Recall that an atomic expression will
  13971. end up as an immediate argument of an x86 instruction. Function
  13972. application will be translated to a sequence of instructions, so
  13973. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  13974. complex expression. On the other hand, the arguments of
  13975. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  13976. expressions.
  13977. %
  13978. Regarding \code{FunRef}, as discussed previously, the function label
  13979. needs to be converted to an address using the \code{leaq}
  13980. instruction. Thus, even though \code{FunRef} seems rather simple, it
  13981. needs to be classified as a complex expression so that we generate an
  13982. assignment statement with a left-hand side that can serve as the
  13983. target of the \code{leaq}.
  13984. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  13985. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13986. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  13987. and augments programs to include a list of function definitions.
  13988. %
  13989. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13990. \newcommand{\LfunMonadASTRacket}{
  13991. \begin{array}{lcl}
  13992. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13993. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13994. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13995. \end{array}
  13996. }
  13997. \newcommand{\LfunMonadASTPython}{
  13998. \begin{array}{lcl}
  13999. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14000. \MID \key{TupleType}\LS\Type^+\RS\\
  14001. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14002. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14003. \Stmt &::=& \RETURN{\Exp} \\
  14004. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14005. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14006. \end{array}
  14007. }
  14008. \begin{figure}[tp]
  14009. \centering
  14010. \begin{tcolorbox}[colback=white]
  14011. \small
  14012. {\if\edition\racketEd
  14013. \[
  14014. \begin{array}{l}
  14015. \gray{\LvarMonadASTRacket} \\ \hline
  14016. \gray{\LifMonadASTRacket} \\ \hline
  14017. \gray{\LwhileMonadASTRacket} \\ \hline
  14018. \gray{\LtupMonadASTRacket} \\ \hline
  14019. \LfunMonadASTRacket \\
  14020. \begin{array}{rcl}
  14021. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14022. \end{array}
  14023. \end{array}
  14024. \]
  14025. \fi}
  14026. {\if\edition\pythonEd
  14027. \[
  14028. \begin{array}{l}
  14029. \gray{\LvarMonadASTPython} \\ \hline
  14030. \gray{\LifMonadASTPython} \\ \hline
  14031. \gray{\LwhileMonadASTPython} \\ \hline
  14032. \gray{\LtupMonadASTPython} \\ \hline
  14033. \LfunMonadASTPython \\
  14034. \begin{array}{rcl}
  14035. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14036. \end{array}
  14037. \end{array}
  14038. \]
  14039. \fi}
  14040. \end{tcolorbox}
  14041. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14042. \label{fig:Lfun-anf-syntax}
  14043. \end{figure}
  14044. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14045. %% \LangFunANF{} of this pass.
  14046. %% \begin{figure}[tp]
  14047. %% \centering
  14048. %% \fbox{
  14049. %% \begin{minipage}{0.96\textwidth}
  14050. %% \small
  14051. %% \[
  14052. %% \begin{array}{rcl}
  14053. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14054. %% \MID \VOID{} } \\
  14055. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14056. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14057. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14058. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14059. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14060. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14061. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14062. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14063. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14064. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14065. %% \end{array}
  14066. %% \]
  14067. %% \end{minipage}
  14068. %% }
  14069. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14070. %% \label{fig:Lfun-anf-syntax}
  14071. %% \end{figure}
  14072. \section{Explicate Control and the \LangCFun{} language}
  14073. \label{sec:explicate-control-r4}
  14074. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14075. output of \code{explicate\_control}.
  14076. %
  14077. %% \racket{(The concrete syntax is given in
  14078. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14079. %
  14080. The auxiliary functions for assignment\racket{ and tail contexts} should
  14081. be updated with cases for
  14082. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14083. function for predicate context should be updated for
  14084. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14085. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14086. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14087. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14088. auxiliary function for processing function definitions. This code is
  14089. similar to the case for \code{Program} in \LangVec{}. The top-level
  14090. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14091. form of \LangFun{} can then apply this new function to all the
  14092. function definitions.
  14093. {\if\edition\pythonEd
  14094. The translation of \code{Return} statements requires a new auxiliary
  14095. function to handle expressions in tail context, called
  14096. \code{explicate\_tail}. The function should take an expression and the
  14097. dictionary of basic blocks and produce a list of statements in the
  14098. \LangCFun{} language. The \code{explicate\_tail} function should
  14099. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  14100. and a default case for other kinds of expressions. The default case
  14101. should produce a \code{Return} statement. The case for \code{Call}
  14102. should change it into \code{TailCall}. The other cases should
  14103. recursively process their subexpressions and statements, choosing the
  14104. appropriate explicate functions for the various contexts.
  14105. \fi}
  14106. \newcommand{\CfunASTRacket}{
  14107. \begin{array}{lcl}
  14108. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14109. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14110. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14111. \end{array}
  14112. }
  14113. \newcommand{\CfunASTPython}{
  14114. \begin{array}{lcl}
  14115. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14116. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14117. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14118. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  14119. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14120. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14121. \end{array}
  14122. }
  14123. \begin{figure}[tp]
  14124. \begin{tcolorbox}[colback=white]
  14125. \small
  14126. {\if\edition\racketEd
  14127. \[
  14128. \begin{array}{l}
  14129. \gray{\CvarASTRacket} \\ \hline
  14130. \gray{\CifASTRacket} \\ \hline
  14131. \gray{\CloopASTRacket} \\ \hline
  14132. \gray{\CtupASTRacket} \\ \hline
  14133. \CfunASTRacket \\
  14134. \begin{array}{lcl}
  14135. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14136. \end{array}
  14137. \end{array}
  14138. \]
  14139. \fi}
  14140. {\if\edition\pythonEd
  14141. \[
  14142. \begin{array}{l}
  14143. \gray{\CifASTPython} \\ \hline
  14144. \gray{\CtupASTPython} \\ \hline
  14145. \CfunASTPython \\
  14146. \begin{array}{lcl}
  14147. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14148. \end{array}
  14149. \end{array}
  14150. \]
  14151. \fi}
  14152. \end{tcolorbox}
  14153. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14154. \label{fig:c3-syntax}
  14155. \end{figure}
  14156. \clearpage
  14157. \section{Select Instructions and the \LangXIndCall{} Language}
  14158. \label{sec:select-r4}
  14159. \index{subject}{instruction selection}
  14160. The output of select instructions is a program in the \LangXIndCall{}
  14161. language; the definition of its concrete syntax is shown in
  14162. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14163. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14164. directive on the labels of function definitions to make sure the
  14165. bottom three bits are zero, which we put to use in
  14166. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14167. this section. \index{subject}{x86}
  14168. \newcommand{\GrammarXIndCall}{
  14169. \begin{array}{lcl}
  14170. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14171. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14172. \Block &::= & \Instr^{+} \\
  14173. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14174. \end{array}
  14175. }
  14176. \newcommand{\ASTXIndCallRacket}{
  14177. \begin{array}{lcl}
  14178. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14179. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14180. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14181. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14182. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14183. \end{array}
  14184. }
  14185. \begin{figure}[tp]
  14186. \begin{tcolorbox}[colback=white]
  14187. \small
  14188. \[
  14189. \begin{array}{l}
  14190. \gray{\GrammarXInt} \\ \hline
  14191. \gray{\GrammarXIf} \\ \hline
  14192. \gray{\GrammarXGlobal} \\ \hline
  14193. \GrammarXIndCall \\
  14194. \begin{array}{lcl}
  14195. \LangXIndCallM{} &::= & \Def^{*}
  14196. \end{array}
  14197. \end{array}
  14198. \]
  14199. \end{tcolorbox}
  14200. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14201. \label{fig:x86-3-concrete}
  14202. \end{figure}
  14203. \begin{figure}[tp]
  14204. \begin{tcolorbox}[colback=white]
  14205. \small
  14206. {\if\edition\racketEd
  14207. \[\arraycolsep=3pt
  14208. \begin{array}{l}
  14209. \gray{\ASTXIntRacket} \\ \hline
  14210. \gray{\ASTXIfRacket} \\ \hline
  14211. \gray{\ASTXGlobalRacket} \\ \hline
  14212. \ASTXIndCallRacket \\
  14213. \begin{array}{lcl}
  14214. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14215. \end{array}
  14216. \end{array}
  14217. \]
  14218. \fi}
  14219. {\if\edition\pythonEd
  14220. \[
  14221. \begin{array}{lcl}
  14222. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14223. \MID \BYTEREG{\Reg} } \\
  14224. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14225. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14226. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14227. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14228. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14229. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14230. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14231. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14232. \end{array}
  14233. \]
  14234. \fi}
  14235. \end{tcolorbox}
  14236. \caption{The abstract syntax of \LangXIndCall{} (extends
  14237. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14238. \label{fig:x86-3}
  14239. \end{figure}
  14240. An assignment of a function reference to a variable becomes a
  14241. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14242. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14243. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14244. node, whose concrete syntax is instruction-pointer-relative
  14245. addressing.
  14246. \begin{center}
  14247. \begin{tabular}{lcl}
  14248. \begin{minipage}{0.35\textwidth}
  14249. {\if\edition\racketEd
  14250. \begin{lstlisting}
  14251. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14252. \end{lstlisting}
  14253. \fi}
  14254. {\if\edition\pythonEd
  14255. \begin{lstlisting}
  14256. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14257. \end{lstlisting}
  14258. \fi}
  14259. \end{minipage}
  14260. &
  14261. $\Rightarrow$\qquad\qquad
  14262. &
  14263. \begin{minipage}{0.3\textwidth}
  14264. \begin{lstlisting}
  14265. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14266. \end{lstlisting}
  14267. \end{minipage}
  14268. \end{tabular}
  14269. \end{center}
  14270. Regarding function definitions, we need to remove the parameters and
  14271. instead perform parameter passing using the conventions discussed in
  14272. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14273. registers. We recommend turning the parameters into local variables
  14274. and generating instructions at the beginning of the function to move
  14275. from the argument-passing registers
  14276. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14277. {\if\edition\racketEd
  14278. \begin{lstlisting}
  14279. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14280. |$\Rightarrow$|
  14281. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14282. \end{lstlisting}
  14283. \fi}
  14284. {\if\edition\pythonEd
  14285. \begin{lstlisting}
  14286. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14287. |$\Rightarrow$|
  14288. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14289. \end{lstlisting}
  14290. \fi}
  14291. The basic blocks $B'$ are the same as $B$ except that the
  14292. \code{start} block is modified to add the instructions for moving from
  14293. the argument registers to the parameter variables. So the \code{start}
  14294. block of $B$ shown on the left of the following is changed to the code
  14295. on the right:
  14296. \begin{center}
  14297. \begin{minipage}{0.3\textwidth}
  14298. \begin{lstlisting}
  14299. start:
  14300. |$\itm{instr}_1$|
  14301. |$\cdots$|
  14302. |$\itm{instr}_n$|
  14303. \end{lstlisting}
  14304. \end{minipage}
  14305. $\Rightarrow$
  14306. \begin{minipage}{0.3\textwidth}
  14307. \begin{lstlisting}
  14308. |$f$|start:
  14309. movq %rdi, |$x_1$|
  14310. movq %rsi, |$x_2$|
  14311. |$\cdots$|
  14312. |$\itm{instr}_1$|
  14313. |$\cdots$|
  14314. |$\itm{instr}_n$|
  14315. \end{lstlisting}
  14316. \end{minipage}
  14317. \end{center}
  14318. Recall that we use the label \code{start} for the initial block of a
  14319. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14320. the conclusion of the program with \code{conclusion}, so that
  14321. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14322. by a jump to \code{conclusion}. With the addition of function
  14323. definitions, there is a start block and conclusion for each function,
  14324. but their labels need to be unique. We recommend prepending the
  14325. function's name to \code{start} and \code{conclusion}, respectively,
  14326. to obtain unique labels.
  14327. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14328. number of parameters the function expects, but the parameters are no
  14329. longer in the syntax of function definitions. Instead, add an entry
  14330. to $\itm{info}$ that maps \code{num-params} to the number of
  14331. parameters to construct $\itm{info}'$.}
  14332. By changing the parameters to local variables, we are giving the
  14333. register allocator control over which registers or stack locations to
  14334. use for them. If you implement the move-biasing challenge
  14335. (section~\ref{sec:move-biasing}), the register allocator will try to
  14336. assign the parameter variables to the corresponding argument register,
  14337. in which case the \code{patch\_instructions} pass will remove the
  14338. \code{movq} instruction. This happens in the example translation given
  14339. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14340. the \code{add} function.
  14341. %
  14342. Also, note that the register allocator will perform liveness analysis
  14343. on this sequence of move instructions and build the interference
  14344. graph. So, for example, $x_1$ will be marked as interfering with
  14345. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14346. which is good because otherwise the first \code{movq} would overwrite
  14347. the argument in \code{rsi} that is needed for $x_2$.
  14348. Next, consider the compilation of function calls. In the mirror image
  14349. of the handling of parameters in function definitions, the arguments
  14350. are moved to the argument-passing registers. Note that the function
  14351. is not given as a label, but its address is produced by the argument
  14352. $\itm{arg}_0$. So, we translate the call into an indirect function
  14353. call. The return value from the function is stored in \code{rax}, so
  14354. it needs to be moved into the \itm{lhs}.
  14355. \begin{lstlisting}
  14356. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14357. |$\Rightarrow$|
  14358. movq |$\itm{arg}_1$|, %rdi
  14359. movq |$\itm{arg}_2$|, %rsi
  14360. |$\vdots$|
  14361. callq *|$\itm{arg}_0$|
  14362. movq %rax, |$\itm{lhs}$|
  14363. \end{lstlisting}
  14364. The \code{IndirectCallq} AST node includes an integer for the arity of
  14365. the function, that is, the number of parameters. That information is
  14366. useful in the \code{uncover\_live} pass for determining which
  14367. argument-passing registers are potentially read during the call.
  14368. For tail calls, the parameter passing is the same as non-tail calls:
  14369. generate instructions to move the arguments into the argument-passing
  14370. registers. After that we need to pop the frame from the procedure
  14371. call stack. However, we do not yet know how big the frame is; that
  14372. gets determined during register allocation. So, instead of generating
  14373. those instructions here, we invent a new instruction that means ``pop
  14374. the frame and then do an indirect jump,'' which we name
  14375. \code{TailJmp}. The abstract syntax for this instruction includes an
  14376. argument that specifies where to jump and an integer that represents
  14377. the arity of the function being called.
  14378. \section{Register Allocation}
  14379. \label{sec:register-allocation-r4}
  14380. The addition of functions requires some changes to all three aspects
  14381. of register allocation, which we discuss in the following subsections.
  14382. \subsection{Liveness Analysis}
  14383. \label{sec:liveness-analysis-r4}
  14384. \index{subject}{liveness analysis}
  14385. %% The rest of the passes need only minor modifications to handle the new
  14386. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14387. %% \code{leaq}.
  14388. The \code{IndirectCallq} instruction should be treated like
  14389. \code{Callq} regarding its written locations $W$, in that they should
  14390. include all the caller-saved registers. Recall that the reason for
  14391. that is to force variables that are live across a function call to be assigned to callee-saved
  14392. registers or to be spilled to the stack.
  14393. Regarding the set of read locations $R$, the arity field of
  14394. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14395. argument-passing registers should be considered as read by those
  14396. instructions. Also, the target field of \code{TailJmp} and
  14397. \code{IndirectCallq} should be included in the set of read locations
  14398. $R$.
  14399. \subsection{Build Interference Graph}
  14400. \label{sec:build-interference-r4}
  14401. With the addition of function definitions, we compute a separate interference
  14402. graph for each function (not just one for the whole program).
  14403. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14404. spill tuple-typed variables that are live during a call to
  14405. \code{collect}, the garbage collector. With the addition of functions
  14406. to our language, we need to revisit this issue. Functions that perform
  14407. allocation contain calls to the collector. Thus, we should not only
  14408. spill a tuple-typed variable when it is live during a call to
  14409. \code{collect}, but we should spill the variable if it is live during
  14410. call to any user-defined function. Thus, in the
  14411. \code{build\_interference} pass, we recommend adding interference
  14412. edges between call-live tuple-typed variables and the callee-saved
  14413. registers (in addition to the usual addition of edges between
  14414. call-live variables and the caller-saved registers).
  14415. \subsection{Allocate Registers}
  14416. The primary change to the \code{allocate\_registers} pass is adding an
  14417. auxiliary function for handling definitions (the \Def{} nonterminal
  14418. shown in figure~\ref{fig:x86-3}) with one case for function
  14419. definitions. The logic is the same as described in
  14420. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14421. allocation is performed many times, once for each function definition,
  14422. instead of just once for the whole program.
  14423. \section{Patch Instructions}
  14424. In \code{patch\_instructions}, you should deal with the x86
  14425. idiosyncrasy that the destination argument of \code{leaq} must be a
  14426. register. Additionally, you should ensure that the argument of
  14427. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14428. trample many other registers before the tail call, as explained in the
  14429. next section.
  14430. \section{Prelude and Conclusion}
  14431. Now that register allocation is complete, we can translate the
  14432. \code{TailJmp} into a sequence of instructions. A naive translation of
  14433. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14434. before the jump we need to pop the current frame to achieve efficient
  14435. tail calls. This sequence of instructions is the same as the code for
  14436. the conclusion of a function, except that the \code{retq} is replaced with
  14437. \code{jmp *$\itm{arg}$}.
  14438. Regarding function definitions, we generate a prelude and conclusion
  14439. for each one. This code is similar to the prelude and conclusion
  14440. generated for the \code{main} function presented in
  14441. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14442. carry out the following steps:
  14443. % TODO: .align the functions!
  14444. \begin{enumerate}
  14445. %% \item Start with \code{.global} and \code{.align} directives followed
  14446. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14447. %% example.)
  14448. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14449. pointer.
  14450. \item Push to the stack all the callee-saved registers that were
  14451. used for register allocation.
  14452. \item Move the stack pointer \code{rsp} down to make room for the
  14453. regular spills (aligned to 16 bytes).
  14454. \item Move the root stack pointer \code{r15} up by the size of the
  14455. root-stack frame for this function, which depends on the number of
  14456. spilled tuple-typed variables. \label{root-stack-init}
  14457. \item Initialize to zero all new entries in the root-stack frame.
  14458. \item Jump to the start block.
  14459. \end{enumerate}
  14460. The prelude of the \code{main} function has an additional task: call
  14461. the \code{initialize} function to set up the garbage collector, and
  14462. then move the value of the global \code{rootstack\_begin} in
  14463. \code{r15}. This initialization should happen before step
  14464. \ref{root-stack-init}, which depends on \code{r15}.
  14465. The conclusion of every function should do the following:
  14466. \begin{enumerate}
  14467. \item Move the stack pointer back up past the regular spills.
  14468. \item Restore the callee-saved registers by popping them from the
  14469. stack.
  14470. \item Move the root stack pointer back down by the size of the
  14471. root-stack frame for this function.
  14472. \item Restore \code{rbp} by popping it from the stack.
  14473. \item Return to the caller with the \code{retq} instruction.
  14474. \end{enumerate}
  14475. The output of this pass is \LangXIndCallFlat{}, which differs from
  14476. \LangXIndCall{} in that there is no longer an AST node for function
  14477. definitions. Instead, a program is just an association list of basic
  14478. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  14479. \[
  14480. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  14481. \]
  14482. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  14483. compiling \LangFun{} to x86.
  14484. \begin{exercise}\normalfont\normalsize
  14485. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  14486. Create eight new programs that use functions, including examples that
  14487. pass functions and return functions from other functions, recursive
  14488. functions, functions that create vectors, and functions that make tail
  14489. calls. Test your compiler on these new programs and all your
  14490. previously created test programs.
  14491. \end{exercise}
  14492. \begin{figure}[tbp]
  14493. \begin{tcolorbox}[colback=white]
  14494. {\if\edition\racketEd
  14495. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  14496. \node (Lfun) at (0,2) {\large \LangFun{}};
  14497. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  14498. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  14499. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  14500. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  14501. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  14502. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14503. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14504. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14505. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14506. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14507. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14508. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  14509. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  14510. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  14511. \path[->,bend left=15] (Lfun) edge [above] node
  14512. {\ttfamily\footnotesize shrink} (Lfun-1);
  14513. \path[->,bend left=15] (Lfun-1) edge [above] node
  14514. {\ttfamily\footnotesize uniquify} (Lfun-2);
  14515. \path[->,bend left=15] (Lfun-2) edge [above] node
  14516. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14517. \path[->,bend left=15] (F1-1) edge [left] node
  14518. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14519. \path[->,bend left=15] (F1-2) edge [below] node
  14520. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  14521. \path[->,bend left=15] (F1-3) edge [below] node
  14522. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  14523. \path[->,bend right=15] (F1-4) edge [above] node
  14524. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14525. \path[->,bend right=15] (F1-5) edge [right] node
  14526. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14527. \path[->,bend right=15] (C3-2) edge [right] node
  14528. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14529. \path[->,bend left=15] (x86-2) edge [right] node
  14530. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14531. \path[->,bend right=15] (x86-2-1) edge [below] node
  14532. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  14533. \path[->,bend right=15] (x86-2-2) edge [right] node
  14534. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  14535. \path[->,bend left=15] (x86-3) edge [above] node
  14536. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14537. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14538. \end{tikzpicture}
  14539. \fi}
  14540. {\if\edition\pythonEd
  14541. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14542. \node (Lfun) at (0,2) {\large \LangFun{}};
  14543. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  14544. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  14545. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  14546. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14547. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14548. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14549. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14550. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14551. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14552. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  14553. \path[->,bend left=15] (Lfun) edge [above] node
  14554. {\ttfamily\footnotesize shrink} (Lfun-2);
  14555. \path[->,bend left=15] (Lfun-2) edge [above] node
  14556. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14557. \path[->,bend left=15] (F1-1) edge [above] node
  14558. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14559. \path[->,bend left=15] (F1-2) edge [right] node
  14560. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  14561. \path[->,bend right=15] (F1-4) edge [above] node
  14562. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14563. \path[->,bend right=15] (F1-5) edge [right] node
  14564. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14565. \path[->,bend left=15] (C3-2) edge [right] node
  14566. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14567. \path[->,bend right=15] (x86-2) edge [below] node
  14568. {\ttfamily\footnotesize assign\_homes} (x86-3);
  14569. \path[->,bend left=15] (x86-3) edge [above] node
  14570. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14571. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14572. \end{tikzpicture}
  14573. \fi}
  14574. \end{tcolorbox}
  14575. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  14576. \label{fig:Lfun-passes}
  14577. \end{figure}
  14578. \section{An Example Translation}
  14579. \label{sec:functions-example}
  14580. Figure~\ref{fig:add-fun} shows an example translation of a simple
  14581. function in \LangFun{} to x86. The figure also includes the results of the
  14582. \code{explicate\_control} and \code{select\_instructions} passes.
  14583. \begin{figure}[htbp]
  14584. \begin{tcolorbox}[colback=white]
  14585. \begin{tabular}{ll}
  14586. \begin{minipage}{0.4\textwidth}
  14587. % s3_2.rkt
  14588. {\if\edition\racketEd
  14589. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14590. (define (add [x : Integer]
  14591. [y : Integer])
  14592. : Integer
  14593. (+ x y))
  14594. (add 40 2)
  14595. \end{lstlisting}
  14596. \fi}
  14597. {\if\edition\pythonEd
  14598. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14599. def add(x:int, y:int) -> int:
  14600. return x + y
  14601. print(add(40, 2))
  14602. \end{lstlisting}
  14603. \fi}
  14604. $\Downarrow$
  14605. {\if\edition\racketEd
  14606. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14607. (define (add86 [x87 : Integer]
  14608. [y88 : Integer])
  14609. : Integer
  14610. add86start:
  14611. return (+ x87 y88);
  14612. )
  14613. (define (main) : Integer ()
  14614. mainstart:
  14615. tmp89 = (fun-ref add86 2);
  14616. (tail-call tmp89 40 2)
  14617. )
  14618. \end{lstlisting}
  14619. \fi}
  14620. {\if\edition\pythonEd
  14621. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14622. def add(x:int, y:int) -> int:
  14623. addstart:
  14624. return x + y
  14625. def main() -> int:
  14626. mainstart:
  14627. fun.0 = add
  14628. tmp.1 = fun.0(40, 2)
  14629. print(tmp.1)
  14630. return 0
  14631. \end{lstlisting}
  14632. \fi}
  14633. \end{minipage}
  14634. &
  14635. $\Rightarrow$
  14636. \begin{minipage}{0.5\textwidth}
  14637. {\if\edition\racketEd
  14638. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14639. (define (add86) : Integer
  14640. add86start:
  14641. movq %rdi, x87
  14642. movq %rsi, y88
  14643. movq x87, %rax
  14644. addq y88, %rax
  14645. jmp inc1389conclusion
  14646. )
  14647. (define (main) : Integer
  14648. mainstart:
  14649. leaq (fun-ref add86 2), tmp89
  14650. movq $40, %rdi
  14651. movq $2, %rsi
  14652. tail-jmp tmp89
  14653. )
  14654. \end{lstlisting}
  14655. \fi}
  14656. {\if\edition\pythonEd
  14657. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14658. def add() -> int:
  14659. addstart:
  14660. movq %rdi, x
  14661. movq %rsi, y
  14662. movq x, %rax
  14663. addq y, %rax
  14664. jmp addconclusion
  14665. def main() -> int:
  14666. mainstart:
  14667. leaq add, fun.0
  14668. movq $40, %rdi
  14669. movq $2, %rsi
  14670. callq *fun.0
  14671. movq %rax, tmp.1
  14672. movq tmp.1, %rdi
  14673. callq print_int
  14674. movq $0, %rax
  14675. jmp mainconclusion
  14676. \end{lstlisting}
  14677. \fi}
  14678. $\Downarrow$
  14679. \end{minipage}
  14680. \end{tabular}
  14681. \begin{tabular}{ll}
  14682. \begin{minipage}{0.3\textwidth}
  14683. {\if\edition\racketEd
  14684. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14685. .globl add86
  14686. .align 8
  14687. add86:
  14688. pushq %rbp
  14689. movq %rsp, %rbp
  14690. jmp add86start
  14691. add86start:
  14692. movq %rdi, %rax
  14693. addq %rsi, %rax
  14694. jmp add86conclusion
  14695. add86conclusion:
  14696. popq %rbp
  14697. retq
  14698. \end{lstlisting}
  14699. \fi}
  14700. {\if\edition\pythonEd
  14701. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14702. .align 8
  14703. add:
  14704. pushq %rbp
  14705. movq %rsp, %rbp
  14706. subq $0, %rsp
  14707. jmp addstart
  14708. addstart:
  14709. movq %rdi, %rdx
  14710. movq %rsi, %rcx
  14711. movq %rdx, %rax
  14712. addq %rcx, %rax
  14713. jmp addconclusion
  14714. addconclusion:
  14715. subq $0, %r15
  14716. addq $0, %rsp
  14717. popq %rbp
  14718. retq
  14719. \end{lstlisting}
  14720. \fi}
  14721. \end{minipage}
  14722. &
  14723. \begin{minipage}{0.5\textwidth}
  14724. {\if\edition\racketEd
  14725. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14726. .globl main
  14727. .align 8
  14728. main:
  14729. pushq %rbp
  14730. movq %rsp, %rbp
  14731. movq $16384, %rdi
  14732. movq $16384, %rsi
  14733. callq initialize
  14734. movq rootstack_begin(%rip), %r15
  14735. jmp mainstart
  14736. mainstart:
  14737. leaq add86(%rip), %rcx
  14738. movq $40, %rdi
  14739. movq $2, %rsi
  14740. movq %rcx, %rax
  14741. popq %rbp
  14742. jmp *%rax
  14743. mainconclusion:
  14744. popq %rbp
  14745. retq
  14746. \end{lstlisting}
  14747. \fi}
  14748. {\if\edition\pythonEd
  14749. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14750. .globl main
  14751. .align 8
  14752. main:
  14753. pushq %rbp
  14754. movq %rsp, %rbp
  14755. subq $0, %rsp
  14756. movq $65536, %rdi
  14757. movq $65536, %rsi
  14758. callq initialize
  14759. movq rootstack_begin(%rip), %r15
  14760. jmp mainstart
  14761. mainstart:
  14762. leaq add(%rip), %rcx
  14763. movq $40, %rdi
  14764. movq $2, %rsi
  14765. callq *%rcx
  14766. movq %rax, %rcx
  14767. movq %rcx, %rdi
  14768. callq print_int
  14769. movq $0, %rax
  14770. jmp mainconclusion
  14771. mainconclusion:
  14772. subq $0, %r15
  14773. addq $0, %rsp
  14774. popq %rbp
  14775. retq
  14776. \end{lstlisting}
  14777. \fi}
  14778. \end{minipage}
  14779. \end{tabular}
  14780. \end{tcolorbox}
  14781. \caption{Example compilation of a simple function to x86.}
  14782. \label{fig:add-fun}
  14783. \end{figure}
  14784. % Challenge idea: inlining! (simple version)
  14785. % Further Reading
  14786. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14787. \chapter{Lexically Scoped Functions}
  14788. \label{ch:Llambda}
  14789. \index{subject}{lambda}
  14790. \index{subject}{lexical scoping}
  14791. \setcounter{footnote}{0}
  14792. This chapter studies lexically scoped functions. Lexical scoping means
  14793. that a function's body may refer to variables whose binding site is
  14794. outside of the function, in an enclosing scope.
  14795. %
  14796. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  14797. in \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  14798. creating lexically scoped functions. The body of the \key{lambda}
  14799. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  14800. binding sites for \code{x} and \code{y} are outside of the
  14801. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  14802. \key{let}}\python{a local variable of function \code{f}}, and
  14803. \code{x} is a parameter of function \code{f}. Note that function
  14804. \code{f} returns the \key{lambda} as its result value. The main
  14805. expression of the program includes two calls to \code{f} with
  14806. different arguments for \code{x}: first \code{5} and then \code{3}. The
  14807. functions returned from \code{f} are bound to variables \code{g} and
  14808. \code{h}. Even though these two functions were created by the same
  14809. \code{lambda}, they are really different functions because they use
  14810. different values for \code{x}. Applying \code{g} to \code{11} produces
  14811. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  14812. so the result of the program is \code{42}.
  14813. \begin{figure}[btp]
  14814. \begin{tcolorbox}[colback=white]
  14815. {\if\edition\racketEd
  14816. % lambda_test_21.rkt
  14817. \begin{lstlisting}
  14818. (define (f [x : Integer]) : (Integer -> Integer)
  14819. (let ([y 4])
  14820. (lambda: ([z : Integer]) : Integer
  14821. (+ x (+ y z)))))
  14822. (let ([g (f 5)])
  14823. (let ([h (f 3)])
  14824. (+ (g 11) (h 15))))
  14825. \end{lstlisting}
  14826. \fi}
  14827. {\if\edition\pythonEd
  14828. \begin{lstlisting}
  14829. def f(x : int) -> Callable[[int], int]:
  14830. y = 4
  14831. return lambda z: x + y + z
  14832. g = f(5)
  14833. h = f(3)
  14834. print( g(11) + h(15) )
  14835. \end{lstlisting}
  14836. \fi}
  14837. \end{tcolorbox}
  14838. \caption{Example of a lexically scoped function.}
  14839. \label{fig:lexical-scoping}
  14840. \end{figure}
  14841. The approach that we take for implementing lexically scoped functions
  14842. is to compile them into top-level function definitions, translating
  14843. from \LangLam{} into \LangFun{}. However, the compiler must give
  14844. special treatment to variable occurrences such as \code{x} and
  14845. \code{y} in the body of the \code{lambda} shown in
  14846. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  14847. may not refer to variables defined outside of it. To identify such
  14848. variable occurrences, we review the standard notion of free variable.
  14849. \begin{definition}\normalfont
  14850. A variable is \emph{free in expression} $e$ if the variable occurs
  14851. inside $e$ but does not have an enclosing definition that is also in
  14852. $e$.\index{subject}{free variable}
  14853. \end{definition}
  14854. For example, in the expression
  14855. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  14856. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  14857. only \code{x} and \code{y} are free in the following expression,
  14858. because \code{z} is defined by the \code{lambda}
  14859. {\if\edition\racketEd
  14860. \begin{lstlisting}
  14861. (lambda: ([z : Integer]) : Integer
  14862. (+ x (+ y z)))
  14863. \end{lstlisting}
  14864. \fi}
  14865. {\if\edition\pythonEd
  14866. \begin{lstlisting}
  14867. lambda z: x + y + z
  14868. \end{lstlisting}
  14869. \fi}
  14870. %
  14871. \noindent Thus the free variables of a \code{lambda} are the ones that
  14872. need special treatment. We need to transport at runtime the values
  14873. of those variables from the point where the \code{lambda} was created
  14874. to the point where the \code{lambda} is applied. An efficient solution
  14875. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  14876. values of the free variables together with a function pointer into a
  14877. tuple, an arrangement called a \emph{flat closure} (which we shorten
  14878. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  14879. closure}
  14880. %
  14881. By design, we have all the ingredients to make closures:
  14882. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  14883. function pointers. The function pointer resides at index $0$, and the
  14884. values for the free variables fill in the rest of the tuple.
  14885. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  14886. to see how closures work. It is a three-step dance. The program calls
  14887. function \code{f}, which creates a closure for the \code{lambda}. The
  14888. closure is a tuple whose first element is a pointer to the top-level
  14889. function that we will generate for the \code{lambda}; the second
  14890. element is the value of \code{x}, which is \code{5}; and the third
  14891. element is \code{4}, the value of \code{y}. The closure does not
  14892. contain an element for \code{z} because \code{z} is not a free
  14893. variable of the \code{lambda}. Creating the closure is step 1 of the
  14894. dance. The closure is returned from \code{f} and bound to \code{g}, as
  14895. shown in figure~\ref{fig:closures}.
  14896. %
  14897. The second call to \code{f} creates another closure, this time with
  14898. \code{3} in the second slot (for \code{x}). This closure is also
  14899. returned from \code{f} but bound to \code{h}, which is also shown in
  14900. figure~\ref{fig:closures}.
  14901. \begin{figure}[tbp]
  14902. \centering
  14903. \begin{minipage}{0.65\textwidth}
  14904. \begin{tcolorbox}[colback=white]
  14905. \includegraphics[width=\textwidth]{figs/closures}
  14906. \end{tcolorbox}
  14907. \end{minipage}
  14908. \caption{Flat closure representations for the two functions
  14909. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  14910. \label{fig:closures}
  14911. \end{figure}
  14912. Continuing with the example, consider the application of \code{g} to
  14913. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  14914. closure, we obtain the function pointer from the first element of the
  14915. closure and call it, passing in the closure itself and then the
  14916. regular arguments, in this case \code{11}. This technique for applying
  14917. a closure is step 2 of the dance.
  14918. %
  14919. But doesn't this \code{lambda} take only one argument, for parameter
  14920. \code{z}? The third and final step of the dance is generating a
  14921. top-level function for a \code{lambda}. We add an additional
  14922. parameter for the closure and insert an initialization at the beginning
  14923. of the function for each free variable, to bind those variables to the
  14924. appropriate elements from the closure parameter.
  14925. %
  14926. This three-step dance is known as \emph{closure conversion}. We
  14927. discuss the details of closure conversion in
  14928. section~\ref{sec:closure-conversion} and show the code generated from
  14929. the example in section~\ref{sec:example-lambda}. First, we define
  14930. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  14931. \section{The \LangLam{} Language}
  14932. \label{sec:r5}
  14933. The definitions of the concrete syntax and abstract syntax for
  14934. \LangLam{}, a language with anonymous functions and lexical scoping,
  14935. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  14936. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  14937. for \LangFun{}, which already has syntax for function application.
  14938. %
  14939. \python{The syntax also includes an assignment statement that includes
  14940. a type annotation for the variable on the left-hand side, which
  14941. facilitates the type checking of \code{lambda} expressions that we
  14942. discuss later in this section.}
  14943. %
  14944. \racket{The \code{procedure-arity} operation returns the number of parameters
  14945. of a given function, an operation that we need for the translation
  14946. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  14947. %
  14948. \python{The \code{arity} operation returns the number of parameters of
  14949. a given function, an operation that we need for the translation
  14950. of dynamic typing in chapter~\ref{ch:Ldyn}.
  14951. The \code{arity} operation is not in Python, but the same functionality
  14952. is available in a more complex form. We include \code{arity} in the
  14953. \LangLam{} source language to enable testing.}
  14954. \newcommand{\LlambdaGrammarRacket}{
  14955. \begin{array}{lcl}
  14956. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  14957. &\MID& \LP \key{procedure-arity}~\Exp\RP
  14958. \end{array}
  14959. }
  14960. \newcommand{\LlambdaASTRacket}{
  14961. \begin{array}{lcl}
  14962. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  14963. \itm{op} &::=& \code{procedure-arity}
  14964. \end{array}
  14965. }
  14966. \newcommand{\LlambdaGrammarPython}{
  14967. \begin{array}{lcl}
  14968. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  14969. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  14970. \end{array}
  14971. }
  14972. \newcommand{\LlambdaASTPython}{
  14973. \begin{array}{lcl}
  14974. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  14975. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  14976. \end{array}
  14977. }
  14978. % include AnnAssign in ASTPython
  14979. \begin{figure}[tp]
  14980. \centering
  14981. \begin{tcolorbox}[colback=white]
  14982. \small
  14983. {\if\edition\racketEd
  14984. \[
  14985. \begin{array}{l}
  14986. \gray{\LintGrammarRacket{}} \\ \hline
  14987. \gray{\LvarGrammarRacket{}} \\ \hline
  14988. \gray{\LifGrammarRacket{}} \\ \hline
  14989. \gray{\LwhileGrammarRacket} \\ \hline
  14990. \gray{\LtupGrammarRacket} \\ \hline
  14991. \gray{\LfunGrammarRacket} \\ \hline
  14992. \LlambdaGrammarRacket \\
  14993. \begin{array}{lcl}
  14994. \LangLamM{} &::=& \Def\ldots \; \Exp
  14995. \end{array}
  14996. \end{array}
  14997. \]
  14998. \fi}
  14999. {\if\edition\pythonEd
  15000. \[
  15001. \begin{array}{l}
  15002. \gray{\LintGrammarPython{}} \\ \hline
  15003. \gray{\LvarGrammarPython{}} \\ \hline
  15004. \gray{\LifGrammarPython{}} \\ \hline
  15005. \gray{\LwhileGrammarPython} \\ \hline
  15006. \gray{\LtupGrammarPython} \\ \hline
  15007. \gray{\LfunGrammarPython} \\ \hline
  15008. \LlambdaGrammarPython \\
  15009. \begin{array}{lcl}
  15010. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15011. \end{array}
  15012. \end{array}
  15013. \]
  15014. \fi}
  15015. \end{tcolorbox}
  15016. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15017. with \key{lambda}.}
  15018. \label{fig:Llam-concrete-syntax}
  15019. \end{figure}
  15020. \begin{figure}[tp]
  15021. \centering
  15022. \begin{tcolorbox}[colback=white]
  15023. \small
  15024. {\if\edition\racketEd
  15025. \[\arraycolsep=3pt
  15026. \begin{array}{l}
  15027. \gray{\LintOpAST} \\ \hline
  15028. \gray{\LvarASTRacket{}} \\ \hline
  15029. \gray{\LifASTRacket{}} \\ \hline
  15030. \gray{\LwhileASTRacket{}} \\ \hline
  15031. \gray{\LtupASTRacket{}} \\ \hline
  15032. \gray{\LfunASTRacket} \\ \hline
  15033. \LlambdaASTRacket \\
  15034. \begin{array}{lcl}
  15035. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15036. \end{array}
  15037. \end{array}
  15038. \]
  15039. \fi}
  15040. {\if\edition\pythonEd
  15041. \[
  15042. \begin{array}{l}
  15043. \gray{\LintASTPython} \\ \hline
  15044. \gray{\LvarASTPython{}} \\ \hline
  15045. \gray{\LifASTPython{}} \\ \hline
  15046. \gray{\LwhileASTPython{}} \\ \hline
  15047. \gray{\LtupASTPython{}} \\ \hline
  15048. \gray{\LfunASTPython} \\ \hline
  15049. \LlambdaASTPython \\
  15050. \begin{array}{lcl}
  15051. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15052. \end{array}
  15053. \end{array}
  15054. \]
  15055. \fi}
  15056. \end{tcolorbox}
  15057. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15058. \label{fig:Llam-syntax}
  15059. \end{figure}
  15060. \index{subject}{interpreter}
  15061. \label{sec:interp-Llambda}
  15062. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  15063. \LangLam{}. The case for \key{Lambda} saves the current environment
  15064. inside the returned function value. Recall that during function
  15065. application, the environment stored in the function value, extended
  15066. with the mapping of parameters to argument values, is used to
  15067. interpret the body of the function.
  15068. \begin{figure}[tbp]
  15069. \begin{tcolorbox}[colback=white]
  15070. {\if\edition\racketEd
  15071. \begin{lstlisting}
  15072. (define interp-Llambda-class
  15073. (class interp-Lfun-class
  15074. (super-new)
  15075. (define/override (interp-op op)
  15076. (match op
  15077. ['procedure-arity
  15078. (lambda (v)
  15079. (match v
  15080. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15081. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15082. [else (super interp-op op)]))
  15083. (define/override ((interp-exp env) e)
  15084. (define recur (interp-exp env))
  15085. (match e
  15086. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15087. `(function ,xs ,body ,env)]
  15088. [else ((super interp-exp env) e)]))
  15089. ))
  15090. (define (interp-Llambda p)
  15091. (send (new interp-Llambda-class) interp-program p))
  15092. \end{lstlisting}
  15093. \fi}
  15094. {\if\edition\pythonEd
  15095. \begin{lstlisting}
  15096. class InterpLlambda(InterpLfun):
  15097. def arity(self, v):
  15098. match v:
  15099. case Function(name, params, body, env):
  15100. return len(params)
  15101. case _:
  15102. raise Exception('Llambda arity unexpected ' + repr(v))
  15103. def interp_exp(self, e, env):
  15104. match e:
  15105. case Call(Name('arity'), [fun]):
  15106. f = self.interp_exp(fun, env)
  15107. return self.arity(f)
  15108. case Lambda(params, body):
  15109. return Function('lambda', params, [Return(body)], env)
  15110. case _:
  15111. return super().interp_exp(e, env)
  15112. def interp_stmts(self, ss, env):
  15113. if len(ss) == 0:
  15114. return
  15115. match ss[0]:
  15116. case AnnAssign(lhs, typ, value, simple):
  15117. env[lhs.id] = self.interp_exp(value, env)
  15118. return self.interp_stmts(ss[1:], env)
  15119. case _:
  15120. return super().interp_stmts(ss, env)
  15121. \end{lstlisting}
  15122. \fi}
  15123. \end{tcolorbox}
  15124. \caption{Interpreter for \LangLam{}.}
  15125. \label{fig:interp-Llambda}
  15126. \end{figure}
  15127. \label{sec:type-check-r5}
  15128. \index{subject}{type checking}
  15129. {\if\edition\racketEd
  15130. %
  15131. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15132. \key{lambda} form. The body of the \key{lambda} is checked in an
  15133. environment that includes the current environment (because it is
  15134. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15135. require the body's type to match the declared return type.
  15136. %
  15137. \fi}
  15138. {\if\edition\pythonEd
  15139. %
  15140. Figures~\ref{fig:type-check-Llambda} and
  15141. \ref{fig:type-check-Llambda-part2} define the type checker for
  15142. \LangLam{}, which is more complex than one might expect. The reason
  15143. for the added complexity is that the syntax of \key{lambda} does not
  15144. include type annotations for the parameters or return type. Instead
  15145. they must be inferred. There are many approaches of type inference to
  15146. choose from of varying degrees of complexity. We choose one of the
  15147. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  15148. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  15149. this book is compilation, not type inference.
  15150. The main idea of bidirectional type inference is to add an auxiliary
  15151. function, here named \code{check\_exp}, that takes an expected type
  15152. and checks whether the given expression is of that type. Thus, in
  15153. \code{check\_exp}, type information flows in a top-down manner with
  15154. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15155. function, where type information flows in a primarily bottom-up
  15156. manner.
  15157. %
  15158. The idea then is to use \code{check\_exp} in all the places where we
  15159. already know what the type of an expression should be, such as in the
  15160. \code{return} statement of a top-level function definition, or on the
  15161. right-hand side of an annotated assignment statement.
  15162. Getting back to \code{lambda}, it is straightforward to check a
  15163. \code{lambda} inside \code{check\_exp} because the expected type
  15164. provides the parameter types and the return type. On the other hand,
  15165. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15166. that we do not allow \code{lambda} in contexts where we don't already
  15167. know its type. This restriction does not incur a loss of
  15168. expressiveness for \LangLam{} because it is straightforward to modify
  15169. a program to sidestep the restriction, for example, by using an
  15170. annotated assignment statement to assign the \code{lambda} to a
  15171. temporary variable.
  15172. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15173. checker records their type in a \code{has\_type} field. This type
  15174. information is used later in this chapter.
  15175. %
  15176. \fi}
  15177. \begin{figure}[tbp]
  15178. \begin{tcolorbox}[colback=white]
  15179. {\if\edition\racketEd
  15180. \begin{lstlisting}
  15181. (define (type-check-Llambda env)
  15182. (lambda (e)
  15183. (match e
  15184. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15185. (define-values (new-body bodyT)
  15186. ((type-check-exp (append (map cons xs Ts) env)) body))
  15187. (define ty `(,@Ts -> ,rT))
  15188. (cond
  15189. [(equal? rT bodyT)
  15190. (values (HasType (Lambda params rT new-body) ty) ty)]
  15191. [else
  15192. (error "mismatch in return type" bodyT rT)])]
  15193. ...
  15194. )))
  15195. \end{lstlisting}
  15196. \fi}
  15197. {\if\edition\pythonEd
  15198. \begin{lstlisting}
  15199. class TypeCheckLlambda(TypeCheckLfun):
  15200. def type_check_exp(self, e, env):
  15201. match e:
  15202. case Name(id):
  15203. e.has_type = env[id]
  15204. return env[id]
  15205. case Lambda(params, body):
  15206. raise Exception('cannot synthesize a type for a lambda')
  15207. case Call(Name('arity'), [func]):
  15208. func_t = self.type_check_exp(func, env)
  15209. match func_t:
  15210. case FunctionType(params_t, return_t):
  15211. return IntType()
  15212. case _:
  15213. raise Exception('in arity, unexpected ' + repr(func_t))
  15214. case _:
  15215. return super().type_check_exp(e, env)
  15216. def check_exp(self, e, ty, env):
  15217. match e:
  15218. case Lambda(params, body):
  15219. e.has_type = ty
  15220. match ty:
  15221. case FunctionType(params_t, return_t):
  15222. new_env = env.copy().update(zip(params, params_t))
  15223. self.check_exp(body, return_t, new_env)
  15224. case _:
  15225. raise Exception('lambda does not have type ' + str(ty))
  15226. case Call(func, args):
  15227. func_t = self.type_check_exp(func, env)
  15228. match func_t:
  15229. case FunctionType(params_t, return_t):
  15230. for (arg, param_t) in zip(args, params_t):
  15231. self.check_exp(arg, param_t, env)
  15232. self.check_type_equal(return_t, ty, e)
  15233. case _:
  15234. raise Exception('type_check_exp: in call, unexpected ' + \
  15235. repr(func_t))
  15236. case _:
  15237. t = self.type_check_exp(e, env)
  15238. self.check_type_equal(t, ty, e)
  15239. \end{lstlisting}
  15240. \fi}
  15241. \end{tcolorbox}
  15242. \caption{Type checking \LangLam{}\python{, part 1}.}
  15243. \label{fig:type-check-Llambda}
  15244. \end{figure}
  15245. {\if\edition\pythonEd
  15246. \begin{figure}[tbp]
  15247. \begin{tcolorbox}[colback=white]
  15248. \begin{lstlisting}
  15249. def check_stmts(self, ss, return_ty, env):
  15250. if len(ss) == 0:
  15251. return
  15252. match ss[0]:
  15253. case FunctionDef(name, params, body, dl, returns, comment):
  15254. new_env = env.copy().update(params)
  15255. rt = self.check_stmts(body, returns, new_env)
  15256. self.check_stmts(ss[1:], return_ty, env)
  15257. case Return(value):
  15258. self.check_exp(value, return_ty, env)
  15259. case Assign([Name(id)], value):
  15260. if id in env:
  15261. self.check_exp(value, env[id], env)
  15262. else:
  15263. env[id] = self.type_check_exp(value, env)
  15264. self.check_stmts(ss[1:], return_ty, env)
  15265. case Assign([Subscript(tup, Constant(index), Store())], value):
  15266. tup_t = self.type_check_exp(tup, env)
  15267. match tup_t:
  15268. case TupleType(ts):
  15269. self.check_exp(value, ts[index], env)
  15270. case _:
  15271. raise Exception('expected a tuple, not ' + repr(tup_t))
  15272. self.check_stmts(ss[1:], return_ty, env)
  15273. case AnnAssign(Name(id), ty_annot, value, simple):
  15274. ss[0].annotation = ty_annot
  15275. if id in env:
  15276. self.check_type_equal(env[id], ty_annot)
  15277. else:
  15278. env[id] = ty_annot
  15279. self.check_exp(value, ty_annot, env)
  15280. self.check_stmts(ss[1:], return_ty, env)
  15281. case _:
  15282. self.type_check_stmts(ss, env)
  15283. def type_check(self, p):
  15284. match p:
  15285. case Module(body):
  15286. env = {}
  15287. for s in body:
  15288. match s:
  15289. case FunctionDef(name, params, bod, dl, returns, comment):
  15290. params_t = [t for (x,t) in params]
  15291. env[name] = FunctionType(params_t, returns)
  15292. self.check_stmts(body, int, env)
  15293. \end{lstlisting}
  15294. \end{tcolorbox}
  15295. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15296. \label{fig:type-check-Llambda-part2}
  15297. \end{figure}
  15298. \fi}
  15299. \clearpage
  15300. \section{Assignment and Lexically Scoped Functions}
  15301. \label{sec:assignment-scoping}
  15302. The combination of lexically scoped functions and assignment to
  15303. variables raises a challenge with the flat-closure approach to
  15304. implementing lexically scoped functions. Consider the following
  15305. example in which function \code{f} has a free variable \code{x} that
  15306. is changed after \code{f} is created but before the call to \code{f}.
  15307. % loop_test_11.rkt
  15308. {\if\edition\racketEd
  15309. \begin{lstlisting}
  15310. (let ([x 0])
  15311. (let ([y 0])
  15312. (let ([z 20])
  15313. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15314. (begin
  15315. (set! x 10)
  15316. (set! y 12)
  15317. (f y))))))
  15318. \end{lstlisting}
  15319. \fi}
  15320. {\if\edition\pythonEd
  15321. % box_free_assign.py
  15322. \begin{lstlisting}
  15323. def g(z : int) -> int:
  15324. x = 0
  15325. y = 0
  15326. f : Callable[[int],int] = lambda a: a + x + z
  15327. x = 10
  15328. y = 12
  15329. return f(y)
  15330. print( g(20) )
  15331. \end{lstlisting}
  15332. \fi} The correct output for this example is \code{42} because the call
  15333. to \code{f} is required to use the current value of \code{x} (which is
  15334. \code{10}). Unfortunately, the closure conversion pass
  15335. (section~\ref{sec:closure-conversion}) generates code for the
  15336. \code{lambda} that copies the old value of \code{x} into a
  15337. closure. Thus, if we naively applied closure conversion, the output of
  15338. this program would be \code{32}.
  15339. A first attempt at solving this problem would be to save a pointer to
  15340. \code{x} in the closure and change the occurrences of \code{x} inside
  15341. the lambda to dereference the pointer. Of course, this would require
  15342. assigning \code{x} to the stack and not to a register. However, the
  15343. problem goes a bit deeper.
  15344. Consider the following example that returns a function that refers to
  15345. a local variable of the enclosing function:
  15346. \begin{center}
  15347. \begin{minipage}{\textwidth}
  15348. {\if\edition\racketEd
  15349. \begin{lstlisting}
  15350. (define (f []) : Integer
  15351. (let ([x 0])
  15352. (let ([g (lambda: () : Integer x)])
  15353. (begin
  15354. (set! x 42)
  15355. g))))
  15356. ((f))
  15357. \end{lstlisting}
  15358. \fi}
  15359. {\if\edition\pythonEd
  15360. % counter.py
  15361. \begin{lstlisting}
  15362. def f():
  15363. x = 0
  15364. g = lambda: x
  15365. x = 42
  15366. return g
  15367. print( f()() )
  15368. \end{lstlisting}
  15369. \fi}
  15370. \end{minipage}
  15371. \end{center}
  15372. In this example, the lifetime of \code{x} extends beyond the lifetime
  15373. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15374. stack frame for the call to \code{f}, it would be gone by the time we
  15375. called \code{g}, leaving us with dangling pointers for
  15376. \code{x}. This example demonstrates that when a variable occurs free
  15377. inside a function, its lifetime becomes indefinite. Thus, the value of
  15378. the variable needs to live on the heap. The verb
  15379. \emph{box}\index{subject}{box} is often used for allocating a single
  15380. value on the heap, producing a pointer, and
  15381. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15382. %
  15383. We introduce a new pass named \code{convert\_assignments} to address
  15384. this challenge.
  15385. %
  15386. \python{But before diving into that, we have one more
  15387. problem to discuss.}
  15388. \if\edition\pythonEd
  15389. \section{Uniquify Variables}
  15390. \label{sec:uniquify-lambda}
  15391. With the addition of \code{lambda} we have a complication to deal
  15392. with: name shadowing. Consider the following program with a function
  15393. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15394. \code{lambda} expressions. The first \code{lambda} has a parameter
  15395. that is also named \code{x}.
  15396. \begin{lstlisting}
  15397. def f(x:int, y:int) -> Callable[[int], int]:
  15398. g : Callable[[int],int] = (lambda x: x + y)
  15399. h : Callable[[int],int] = (lambda y: x + y)
  15400. x = input_int()
  15401. return g
  15402. print(f(0, 10)(32))
  15403. \end{lstlisting}
  15404. Many of our compiler passes rely on being able to connect variable
  15405. uses with their definitions using just the name of the variable,
  15406. including new passes in this chapter. However, in the above example
  15407. the name of the variable does not uniquely determine its
  15408. definition. To solve this problem we recommend implementing a pass
  15409. named \code{uniquify} that renames every variable in the program to
  15410. make sure they are all unique.
  15411. The following shows the result of \code{uniquify} for the above
  15412. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  15413. and the \code{x} parameter of the \code{lambda} is renamed to
  15414. \code{x\_4}.
  15415. \begin{lstlisting}
  15416. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15417. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15418. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15419. x_0 = input_int()
  15420. return g_2
  15421. def main() -> int :
  15422. print(f(0, 10)(32))
  15423. return 0
  15424. \end{lstlisting}
  15425. \fi
  15426. %% \section{Reveal Functions}
  15427. %% \label{sec:reveal-functions-r5}
  15428. %% \racket{To support the \code{procedure-arity} operator we need to
  15429. %% communicate the arity of a function to the point of closure
  15430. %% creation.}
  15431. %% %
  15432. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15433. %% function at runtime. Thus, we need to communicate the arity of a
  15434. %% function to the point of closure creation.}
  15435. %% %
  15436. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15437. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15438. %% \[
  15439. %% \begin{array}{lcl}
  15440. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15441. %% \end{array}
  15442. %% \]
  15443. \section{Assignment Conversion}
  15444. \label{sec:convert-assignments}
  15445. The purpose of the \code{convert\_assignments} pass is to address the
  15446. challenge regarding the interaction between variable assignments and
  15447. closure conversion. First we identify which variables need to be
  15448. boxed, and then we transform the program to box those variables. In
  15449. general, boxing introduces runtime overhead that we would like to
  15450. avoid, so we should box as few variables as possible. We recommend
  15451. boxing the variables in the intersection of the following two sets of
  15452. variables:
  15453. \begin{enumerate}
  15454. \item The variables that are free in a \code{lambda}.
  15455. \item The variables that appear on the left-hand side of an
  15456. assignment.
  15457. \end{enumerate}
  15458. The first condition is a must but the second condition is
  15459. conservative. It is possible to develop a more liberal condition using
  15460. static program analysis.
  15461. Consider again the first example from
  15462. section~\ref{sec:assignment-scoping}:
  15463. %
  15464. {\if\edition\racketEd
  15465. \begin{lstlisting}
  15466. (let ([x 0])
  15467. (let ([y 0])
  15468. (let ([z 20])
  15469. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15470. (begin
  15471. (set! x 10)
  15472. (set! y 12)
  15473. (f y))))))
  15474. \end{lstlisting}
  15475. \fi}
  15476. {\if\edition\pythonEd
  15477. \begin{lstlisting}
  15478. def g(z : int) -> int:
  15479. x = 0
  15480. y = 0
  15481. f : Callable[[int],int] = lambda a: a + x + z
  15482. x = 10
  15483. y = 12
  15484. return f(y)
  15485. print( g(20) )
  15486. \end{lstlisting}
  15487. \fi}
  15488. %
  15489. \noindent The variables \code{x} and \code{y} are assigned to. The
  15490. variables \code{x} and \code{z} occur free inside the
  15491. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  15492. \code{y} or \code{z}. The boxing of \code{x} consists of three
  15493. transformations: initialize \code{x} with a tuple whose elements are
  15494. uninitialized, replace reads from \code{x} with tuple reads, and
  15495. replace each assignment to \code{x} with a tuple write. The output of
  15496. \code{convert\_assignments} for this example is as follows:
  15497. %
  15498. {\if\edition\racketEd
  15499. \begin{lstlisting}
  15500. (define (main) : Integer
  15501. (let ([x0 (vector 0)])
  15502. (let ([y1 0])
  15503. (let ([z2 20])
  15504. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  15505. (+ a3 (+ (vector-ref x0 0) z2)))])
  15506. (begin
  15507. (vector-set! x0 0 10)
  15508. (set! y1 12)
  15509. (f4 y1)))))))
  15510. \end{lstlisting}
  15511. \fi}
  15512. %
  15513. {\if\edition\pythonEd
  15514. \begin{lstlisting}
  15515. def g(z : int)-> int:
  15516. x = (uninitialized(int),)
  15517. x[0] = 0
  15518. y = 0
  15519. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  15520. x[0] = 10
  15521. y = 12
  15522. return f(y)
  15523. def main() -> int:
  15524. print(g(20))
  15525. return 0
  15526. \end{lstlisting}
  15527. \fi}
  15528. To compute the free variables of all the \code{lambda} expressions, we
  15529. recommend defining the following two auxiliary functions:
  15530. \begin{enumerate}
  15531. \item \code{free\_variables} computes the free variables of an expression, and
  15532. \item \code{free\_in\_lambda} collects all the variables that are
  15533. free in any of the \code{lambda} expressions, using
  15534. \code{free\_variables} in the case for each \code{lambda}.
  15535. \end{enumerate}
  15536. {\if\edition\racketEd
  15537. %
  15538. To compute the variables that are assigned to, we recommend updating
  15539. the \code{collect-set!} function that we introduced in
  15540. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  15541. as \code{Lambda}.
  15542. %
  15543. \fi}
  15544. {\if\edition\pythonEd
  15545. %
  15546. To compute the variables that are assigned to, we recommend defining
  15547. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  15548. the set of variables that occur in the left-hand side of an assignment
  15549. statement, and otherwise returns the empty set.
  15550. %
  15551. \fi}
  15552. Let $\mathit{AF}$ be the intersection of the set of variables that are
  15553. free in a \code{lambda} and that are assigned to in the enclosing
  15554. function definition.
  15555. Next we discuss the \code{convert\_assignments} pass. In the case for
  15556. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  15557. $\VAR{x}$ to a tuple read.
  15558. %
  15559. {\if\edition\racketEd
  15560. \begin{lstlisting}
  15561. (Var |$x$|)
  15562. |$\Rightarrow$|
  15563. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  15564. \end{lstlisting}
  15565. \fi}
  15566. %
  15567. {\if\edition\pythonEd
  15568. \begin{lstlisting}
  15569. Name(|$x$|)
  15570. |$\Rightarrow$|
  15571. Subscript(Name(|$x$|), Constant(0), Load())
  15572. \end{lstlisting}
  15573. \fi}
  15574. %
  15575. \noindent In the case for assignment, recursively process the
  15576. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  15577. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  15578. as follows:
  15579. %
  15580. {\if\edition\racketEd
  15581. \begin{lstlisting}
  15582. (SetBang |$x$| |$\itm{rhs}$|)
  15583. |$\Rightarrow$|
  15584. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  15585. \end{lstlisting}
  15586. \fi}
  15587. {\if\edition\pythonEd
  15588. \begin{lstlisting}
  15589. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15590. |$\Rightarrow$|
  15591. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15592. \end{lstlisting}
  15593. \fi}
  15594. %
  15595. {\if\edition\racketEd
  15596. The case for \code{Lambda} is nontrivial, but it is similar to the
  15597. case for function definitions, which we discuss next.
  15598. \fi}
  15599. %
  15600. To translate a function definition, we first compute $\mathit{AF}$,
  15601. the intersection of the variables that are free in a \code{lambda} and
  15602. that are assigned to. We then apply assignment conversion to the body
  15603. of the function definition. Finally, we box the parameters of this
  15604. function definition that are in $\mathit{AF}$. For example,
  15605. the parameter \code{x} of the following function \code{g}
  15606. needs to be boxed:
  15607. {\if\edition\racketEd
  15608. \begin{lstlisting}
  15609. (define (g [x : Integer]) : Integer
  15610. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15611. (begin
  15612. (set! x 10)
  15613. (f 32))))
  15614. \end{lstlisting}
  15615. \fi}
  15616. %
  15617. {\if\edition\pythonEd
  15618. \begin{lstlisting}
  15619. def g(x : int) -> int:
  15620. f : Callable[[int],int] = lambda a: a + x
  15621. x = 10
  15622. return f(32)
  15623. \end{lstlisting}
  15624. \fi}
  15625. %
  15626. \noindent We box parameter \code{x} by creating a local variable named
  15627. \code{x} that is initialized to a tuple whose contents is the value of
  15628. the parameter, which has been renamed to \code{x\_0}.
  15629. %
  15630. {\if\edition\racketEd
  15631. \begin{lstlisting}
  15632. (define (g [x_0 : Integer]) : Integer
  15633. (let ([x (vector x_0)])
  15634. (let ([f (lambda: ([a : Integer]) : Integer
  15635. (+ a (vector-ref x 0)))])
  15636. (begin
  15637. (vector-set! x 0 10)
  15638. (f 32)))))
  15639. \end{lstlisting}
  15640. \fi}
  15641. %
  15642. {\if\edition\pythonEd
  15643. \begin{lstlisting}
  15644. def g(x_0 : int)-> int:
  15645. x = (x_0,)
  15646. f : Callable[[int], int] = (lambda a: a + x[0])
  15647. x[0] = 10
  15648. return f(32)
  15649. \end{lstlisting}
  15650. \fi}
  15651. \section{Closure Conversion}
  15652. \label{sec:closure-conversion}
  15653. \index{subject}{closure conversion}
  15654. The compiling of lexically scoped functions into top-level function
  15655. definitions and flat closures is accomplished in the pass
  15656. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15657. and before \code{limit\_functions}.
  15658. As usual, we implement the pass as a recursive function over the
  15659. AST. The interesting cases are for \key{lambda} and function
  15660. application. We transform a \key{lambda} expression into an expression
  15661. that creates a closure, that is, a tuple for which the first element
  15662. is a function pointer and the rest of the elements are the values of
  15663. the free variables of the \key{lambda}.
  15664. %
  15665. However, we use the \code{Closure} AST node instead of using a tuple
  15666. so that we can record the arity.
  15667. %
  15668. In the generated code that follows, \itm{fvs} is the free variables of
  15669. the lambda and \itm{name} is a unique symbol generated to identify the
  15670. lambda.
  15671. %
  15672. \racket{The \itm{arity} is the number of parameters (the length of
  15673. \itm{ps}).}
  15674. %
  15675. {\if\edition\racketEd
  15676. \begin{lstlisting}
  15677. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15678. |$\Rightarrow$|
  15679. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15680. \end{lstlisting}
  15681. \fi}
  15682. %
  15683. {\if\edition\pythonEd
  15684. \begin{lstlisting}
  15685. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15686. |$\Rightarrow$|
  15687. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15688. \end{lstlisting}
  15689. \fi}
  15690. %
  15691. In addition to transforming each \key{Lambda} AST node into a
  15692. tuple, we create a top-level function definition for each
  15693. \key{Lambda}, as shown next.\\
  15694. \begin{minipage}{0.8\textwidth}
  15695. {\if\edition\racketEd
  15696. \begin{lstlisting}
  15697. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15698. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15699. ...
  15700. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15701. |\itm{body'}|)...))
  15702. \end{lstlisting}
  15703. \fi}
  15704. {\if\edition\pythonEd
  15705. \begin{lstlisting}
  15706. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15707. |$\itm{fvs}_1$| = clos[1]
  15708. |$\ldots$|
  15709. |$\itm{fvs}_n$| = clos[|$n$|]
  15710. |\itm{body'}|
  15711. \end{lstlisting}
  15712. \fi}
  15713. \end{minipage}\\
  15714. The \code{clos} parameter refers to the closure. Translate the type
  15715. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15716. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15717. \itm{closTy} is a tuple type for which the first element type is
  15718. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15719. the element types are the types of the free variables in the
  15720. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15721. is nontrivial to give a type to the function in the closure's type.%
  15722. %
  15723. \footnote{To give an accurate type to a closure, we would need to add
  15724. existential types to the type checker~\citep{Minamide:1996ys}.}
  15725. %
  15726. %% The dummy type is considered to be equal to any other type during type
  15727. %% checking.
  15728. The free variables become local variables that are initialized with
  15729. their values in the closure.
  15730. Closure conversion turns every function into a tuple, so the type
  15731. annotations in the program must also be translated. We recommend
  15732. defining an auxiliary recursive function for this purpose. Function
  15733. types should be translated as follows:
  15734. %
  15735. {\if\edition\racketEd
  15736. \begin{lstlisting}
  15737. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15738. |$\Rightarrow$|
  15739. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15740. \end{lstlisting}
  15741. \fi}
  15742. {\if\edition\pythonEd
  15743. \begin{lstlisting}
  15744. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15745. |$\Rightarrow$|
  15746. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15747. \end{lstlisting}
  15748. \fi}
  15749. %
  15750. This type indicates that the first thing in the tuple is a
  15751. function. The first parameter of the function is a tuple (a closure)
  15752. and the rest of the parameters are the ones from the original
  15753. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15754. omits the types of the free variables because (1) those types are not
  15755. available in this context, and (2) we do not need them in the code that
  15756. is generated for function application. So this type describes only the
  15757. first component of the closure tuple. At runtime the tuple may have
  15758. more components, but we ignore them at this point.
  15759. We transform function application into code that retrieves the
  15760. function from the closure and then calls the function, passing the
  15761. closure as the first argument. We place $e'$ in a temporary variable
  15762. to avoid code duplication.
  15763. \begin{center}
  15764. \begin{minipage}{\textwidth}
  15765. {\if\edition\racketEd
  15766. \begin{lstlisting}
  15767. (Apply |$e$| |$\itm{es}$|)
  15768. |$\Rightarrow$|
  15769. (Let |$\itm{tmp}$| |$e'$|
  15770. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15771. \end{lstlisting}
  15772. \fi}
  15773. %
  15774. {\if\edition\pythonEd
  15775. \begin{lstlisting}
  15776. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15777. |$\Rightarrow$|
  15778. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15779. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15780. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15781. \end{lstlisting}
  15782. \fi}
  15783. \end{minipage}
  15784. \end{center}
  15785. There is also the question of what to do with references to top-level
  15786. function definitions. To maintain a uniform translation of function
  15787. application, we turn function references into closures.
  15788. \begin{tabular}{lll}
  15789. \begin{minipage}{0.3\textwidth}
  15790. {\if\edition\racketEd
  15791. \begin{lstlisting}
  15792. (FunRef |$f$| |$n$|)
  15793. \end{lstlisting}
  15794. \fi}
  15795. {\if\edition\pythonEd
  15796. \begin{lstlisting}
  15797. FunRef(|$f$|, |$n$|)
  15798. \end{lstlisting}
  15799. \fi}
  15800. \end{minipage}
  15801. &
  15802. $\Rightarrow$
  15803. &
  15804. \begin{minipage}{0.5\textwidth}
  15805. {\if\edition\racketEd
  15806. \begin{lstlisting}
  15807. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  15808. \end{lstlisting}
  15809. \fi}
  15810. {\if\edition\pythonEd
  15811. \begin{lstlisting}
  15812. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  15813. \end{lstlisting}
  15814. \fi}
  15815. \end{minipage}
  15816. \end{tabular} \\
  15817. We no longer need the annotated assignment statement \code{AnnAssign}
  15818. to support the type checking of \code{lambda} expressions, so we
  15819. translate it to a regular \code{Assign} statement.
  15820. The top-level function definitions need to be updated to take an extra
  15821. closure parameter, but that parameter is ignored in the body of those
  15822. functions.
  15823. \section{An Example Translation}
  15824. \label{sec:example-lambda}
  15825. Figure~\ref{fig:lexical-functions-example} shows the result of
  15826. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  15827. program demonstrating lexical scoping that we discussed at the
  15828. beginning of this chapter.
  15829. \begin{figure}[tbp]
  15830. \begin{tcolorbox}[colback=white]
  15831. \begin{minipage}{0.8\textwidth}
  15832. {\if\edition\racketEd
  15833. % tests/lambda_test_6.rkt
  15834. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15835. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  15836. (let ([y8 4])
  15837. (lambda: ([z9 : Integer]) : Integer
  15838. (+ x7 (+ y8 z9)))))
  15839. (define (main) : Integer
  15840. (let ([g0 ((fun-ref f6 1) 5)])
  15841. (let ([h1 ((fun-ref f6 1) 3)])
  15842. (+ (g0 11) (h1 15)))))
  15843. \end{lstlisting}
  15844. $\Rightarrow$
  15845. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15846. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  15847. (let ([y8 4])
  15848. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  15849. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  15850. (let ([x7 (vector-ref fvs3 1)])
  15851. (let ([y8 (vector-ref fvs3 2)])
  15852. (+ x7 (+ y8 z9)))))
  15853. (define (main) : Integer
  15854. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  15855. ((vector-ref clos5 0) clos5 5))])
  15856. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  15857. ((vector-ref clos6 0) clos6 3))])
  15858. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  15859. \end{lstlisting}
  15860. \fi}
  15861. %
  15862. {\if\edition\pythonEd
  15863. % free_var.py
  15864. \begin{lstlisting}
  15865. def f(x : int) -> Callable[[int], int]:
  15866. y = 4
  15867. return lambda z: x + y + z
  15868. g = f(5)
  15869. h = f(3)
  15870. print( g(11) + h(15) )
  15871. \end{lstlisting}
  15872. $\Rightarrow$
  15873. \begin{lstlisting}
  15874. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  15875. x = fvs_1[1]
  15876. y = fvs_1[2]
  15877. return x + y[0] + z
  15878. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  15879. y = (777,)
  15880. y[0] = 4
  15881. return (lambda_0, x, y)
  15882. def main() -> int:
  15883. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  15884. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  15885. print((let clos_5 = g in clos_5[0](clos_5, 11))
  15886. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  15887. return 0
  15888. \end{lstlisting}
  15889. \fi}
  15890. \end{minipage}
  15891. \end{tcolorbox}
  15892. \caption{Example of closure conversion.}
  15893. \label{fig:lexical-functions-example}
  15894. \end{figure}
  15895. \begin{exercise}\normalfont\normalsize
  15896. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  15897. Create five new programs that use \key{lambda} functions and make use of
  15898. lexical scoping. Test your compiler on these new programs and all
  15899. your previously created test programs.
  15900. \end{exercise}
  15901. \section{Expose Allocation}
  15902. \label{sec:expose-allocation-r5}
  15903. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  15904. that allocates and initializes a tuple, similar to the translation of
  15905. the tuple creation in section~\ref{sec:expose-allocation}.
  15906. The only difference is replacing the use of
  15907. \ALLOC{\itm{len}}{\itm{type}} with
  15908. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  15909. \section{Explicate Control and \LangCLam{}}
  15910. \label{sec:explicate-r5}
  15911. The output language of \code{explicate\_control} is \LangCLam{}; the
  15912. definition of its abstract syntax is shown in
  15913. figure~\ref{fig:Clam-syntax}.
  15914. %
  15915. \racket{The only differences with respect to \LangCFun{} are the
  15916. addition of the \code{AllocateClosure} form to the grammar for
  15917. $\Exp$ and the \code{procedure-arity} operator. The handling of
  15918. \code{AllocateClosure} in the \code{explicate\_control} pass is
  15919. similar to the handling of other expressions such as primitive
  15920. operators.}
  15921. %
  15922. \python{The differences with respect to \LangCFun{} are the
  15923. additions of \code{Uninitialized}, \code{AllocateClosure},
  15924. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  15925. \code{explicate\_control} pass is similar to the handling of other
  15926. expressions such as primitive operators.}
  15927. \newcommand{\ClambdaASTRacket}{
  15928. \begin{array}{lcl}
  15929. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  15930. \itm{op} &::= & \code{procedure-arity}
  15931. \end{array}
  15932. }
  15933. \newcommand{\ClambdaASTPython}{
  15934. \begin{array}{lcl}
  15935. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  15936. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  15937. &\MID& \ARITY{\Atm}
  15938. \end{array}
  15939. }
  15940. \begin{figure}[tp]
  15941. \begin{tcolorbox}[colback=white]
  15942. \small
  15943. {\if\edition\racketEd
  15944. \[
  15945. \begin{array}{l}
  15946. \gray{\CvarASTRacket} \\ \hline
  15947. \gray{\CifASTRacket} \\ \hline
  15948. \gray{\CloopASTRacket} \\ \hline
  15949. \gray{\CtupASTRacket} \\ \hline
  15950. \gray{\CfunASTRacket} \\ \hline
  15951. \ClambdaASTRacket \\
  15952. \begin{array}{lcl}
  15953. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  15954. \end{array}
  15955. \end{array}
  15956. \]
  15957. \fi}
  15958. {\if\edition\pythonEd
  15959. \[
  15960. \begin{array}{l}
  15961. \gray{\CifASTPython} \\ \hline
  15962. \gray{\CtupASTPython} \\ \hline
  15963. \gray{\CfunASTPython} \\ \hline
  15964. \ClambdaASTPython \\
  15965. \begin{array}{lcl}
  15966. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  15967. \end{array}
  15968. \end{array}
  15969. \]
  15970. \fi}
  15971. \end{tcolorbox}
  15972. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  15973. \label{fig:Clam-syntax}
  15974. \end{figure}
  15975. \section{Select Instructions}
  15976. \label{sec:select-instructions-Llambda}
  15977. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  15978. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  15979. (section~\ref{sec:select-instructions-gc}). The only difference is
  15980. that you should place the \itm{arity} in the tag that is stored at
  15981. position $0$ of the vector. Recall that in
  15982. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  15983. was not used. We store the arity in the $5$ bits starting at position
  15984. $58$.
  15985. \racket{Compile the \code{procedure-arity} operator into a sequence of
  15986. instructions that access the tag from position $0$ of the vector and
  15987. extract the $5$ bits starting at position $58$ from the tag.}
  15988. %
  15989. \python{Compile a call to the \code{arity} operator to a sequence of
  15990. instructions that access the tag from position $0$ of the tuple
  15991. (representing a closure) and extract the $5$-bits starting at position
  15992. $58$ from the tag.}
  15993. \begin{figure}[p]
  15994. \begin{tcolorbox}[colback=white]
  15995. {\if\edition\racketEd
  15996. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15997. \node (Lfun) at (0,2) {\large \LangLam{}};
  15998. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  15999. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16000. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16001. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16002. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16003. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16004. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16005. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16006. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16007. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16008. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16009. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16010. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16011. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16012. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16013. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16014. \path[->,bend left=15] (Lfun) edge [above] node
  16015. {\ttfamily\footnotesize shrink} (Lfun-2);
  16016. \path[->,bend left=15] (Lfun-2) edge [above] node
  16017. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16018. \path[->,bend left=15] (Lfun-3) edge [above] node
  16019. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16020. \path[->,bend left=15] (F1-0) edge [left] node
  16021. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16022. \path[->,bend left=15] (F1-1) edge [below] node
  16023. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16024. \path[->,bend right=15] (F1-2) edge [above] node
  16025. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16026. \path[->,bend right=15] (F1-3) edge [above] node
  16027. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16028. \path[->,bend left=15] (F1-4) edge [right] node
  16029. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16030. \path[->,bend right=15] (F1-5) edge [below] node
  16031. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16032. \path[->,bend left=15] (F1-6) edge [above] node
  16033. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16034. \path[->] (C3-2) edge [right] node
  16035. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16036. \path[->,bend right=15] (x86-2) edge [right] node
  16037. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16038. \path[->,bend right=15] (x86-2-1) edge [below] node
  16039. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16040. \path[->,bend right=15] (x86-2-2) edge [right] node
  16041. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16042. \path[->,bend left=15] (x86-3) edge [above] node
  16043. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16044. \path[->,bend left=15] (x86-4) edge [right] node
  16045. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16046. \end{tikzpicture}
  16047. \fi}
  16048. {\if\edition\pythonEd
  16049. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16050. \node (Lfun) at (0,2) {\large \LangLam{}};
  16051. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16052. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16053. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16054. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16055. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16056. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16057. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16058. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16059. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16060. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16061. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16062. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16063. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16064. \path[->,bend left=15] (Lfun) edge [above] node
  16065. {\ttfamily\footnotesize shrink} (Lfun-2);
  16066. \path[->,bend left=15] (Lfun-2) edge [above] node
  16067. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16068. \path[->,bend left=15] (Lfun-3) edge [above] node
  16069. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16070. \path[->,bend left=15] (F1-0) edge [left] node
  16071. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16072. \path[->,bend left=15] (F1-1) edge [below] node
  16073. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16074. \path[->,bend left=15] (F1-2) edge [below] node
  16075. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16076. \path[->,bend right=15] (F1-3) edge [above] node
  16077. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16078. \path[->,bend right=15] (F1-5) edge [right] node
  16079. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16080. \path[->,bend left=15] (F1-6) edge [right] node
  16081. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16082. \path[->,bend right=15] (C3-2) edge [right] node
  16083. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16084. \path[->,bend right=15] (x86-2) edge [below] node
  16085. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16086. \path[->,bend right=15] (x86-3) edge [below] node
  16087. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16088. \path[->,bend left=15] (x86-4) edge [above] node
  16089. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16090. \end{tikzpicture}
  16091. \fi}
  16092. \end{tcolorbox}
  16093. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16094. functions.}
  16095. \label{fig:Llambda-passes}
  16096. \end{figure}
  16097. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16098. needed for the compilation of \LangLam{}.
  16099. \clearpage
  16100. \section{Challenge: Optimize Closures}
  16101. \label{sec:optimize-closures}
  16102. In this chapter we compile lexically scoped functions into a
  16103. relatively efficient representation: flat closures. However, even this
  16104. representation comes with some overhead. For example, consider the
  16105. following program with a function \code{tail\_sum} that does not have
  16106. any free variables and where all the uses of \code{tail\_sum} are in
  16107. applications in which we know that only \code{tail\_sum} is being applied
  16108. (and not any other functions):
  16109. \begin{center}
  16110. \begin{minipage}{0.95\textwidth}
  16111. {\if\edition\racketEd
  16112. \begin{lstlisting}
  16113. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16114. (if (eq? n 0)
  16115. s
  16116. (tail_sum (- n 1) (+ n s))))
  16117. (+ (tail_sum 3 0) 36)
  16118. \end{lstlisting}
  16119. \fi}
  16120. {\if\edition\pythonEd
  16121. \begin{lstlisting}
  16122. def tail_sum(n : int, s : int) -> int:
  16123. if n == 0:
  16124. return s
  16125. else:
  16126. return tail_sum(n - 1, n + s)
  16127. print( tail_sum(3, 0) + 36)
  16128. \end{lstlisting}
  16129. \fi}
  16130. \end{minipage}
  16131. \end{center}
  16132. As described in this chapter, we uniformly apply closure conversion to
  16133. all functions, obtaining the following output for this program:
  16134. \begin{center}
  16135. \begin{minipage}{0.95\textwidth}
  16136. {\if\edition\racketEd
  16137. \begin{lstlisting}
  16138. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16139. (if (eq? n2 0)
  16140. s3
  16141. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16142. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16143. (define (main) : Integer
  16144. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16145. ((vector-ref clos6 0) clos6 3 0)) 27))
  16146. \end{lstlisting}
  16147. \fi}
  16148. {\if\edition\pythonEd
  16149. \begin{lstlisting}
  16150. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16151. if n_0 == 0:
  16152. return s_1
  16153. else:
  16154. return (let clos_2 = (tail_sum,)
  16155. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16156. def main() -> int :
  16157. print((let clos_4 = (tail_sum,)
  16158. in clos_4[0](clos_4, 3, 0)) + 36)
  16159. return 0
  16160. \end{lstlisting}
  16161. \fi}
  16162. \end{minipage}
  16163. \end{center}
  16164. If this program were compiled according to the previous chapter, there
  16165. would be no allocation and the calls to \code{tail\_sum} would be
  16166. direct calls. In contrast, the program presented here allocates memory
  16167. for each closure and the calls to \code{tail\_sum} are indirect. These
  16168. two differences incur considerable overhead in a program such as this,
  16169. in which the allocations and indirect calls occur inside a tight loop.
  16170. One might think that this problem is trivial to solve: can't we just
  16171. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16172. and compile them to direct calls instead of treating it like a call to
  16173. a closure? We would also drop the new \code{fvs} parameter of
  16174. \code{tail\_sum}.
  16175. %
  16176. However, this problem is not so trivial, because a global function may
  16177. \emph{escape} and become involved in applications that also involve
  16178. closures. Consider the following example in which the application
  16179. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16180. application because the \code{lambda} may flow into \code{f}, but the
  16181. \code{inc} function might also flow into \code{f}:
  16182. \begin{center}
  16183. \begin{minipage}{\textwidth}
  16184. % lambda_test_30.rkt
  16185. {\if\edition\racketEd
  16186. \begin{lstlisting}
  16187. (define (inc [x : Integer]) : Integer
  16188. (+ x 1))
  16189. (let ([y (read)])
  16190. (let ([f (if (eq? (read) 0)
  16191. inc
  16192. (lambda: ([x : Integer]) : Integer (- x y)))])
  16193. (f 41)))
  16194. \end{lstlisting}
  16195. \fi}
  16196. {\if\edition\pythonEd
  16197. \begin{lstlisting}
  16198. def add1(x : int) -> int:
  16199. return x + 1
  16200. y = input_int()
  16201. g : Callable[[int], int] = lambda x: x - y
  16202. f = add1 if input_int() == 0 else g
  16203. print( f(41) )
  16204. \end{lstlisting}
  16205. \fi}
  16206. \end{minipage}
  16207. \end{center}
  16208. If a global function name is used in any way other than as the
  16209. operator in a direct call, then we say that the function
  16210. \emph{escapes}. If a global function does not escape, then we do not
  16211. need to perform closure conversion on the function.
  16212. \begin{exercise}\normalfont\normalsize
  16213. Implement an auxiliary function for detecting which global
  16214. functions escape. Using that function, implement an improved version
  16215. of closure conversion that does not apply closure conversion to
  16216. global functions that do not escape but instead compiles them as
  16217. regular functions. Create several new test cases that check whether
  16218. your compiler properly detect whether global functions escape or not.
  16219. \end{exercise}
  16220. So far we have reduced the overhead of calling global functions, but
  16221. it would also be nice to reduce the overhead of calling a
  16222. \code{lambda} when we can determine at compile time which
  16223. \code{lambda} will be called. We refer to such calls as \emph{known
  16224. calls}. Consider the following example in which a \code{lambda} is
  16225. bound to \code{f} and then applied.
  16226. {\if\edition\racketEd
  16227. % lambda_test_9.rkt
  16228. \begin{lstlisting}
  16229. (let ([y (read)])
  16230. (let ([f (lambda: ([x : Integer]) : Integer
  16231. (+ x y))])
  16232. (f 21)))
  16233. \end{lstlisting}
  16234. \fi}
  16235. {\if\edition\pythonEd
  16236. \begin{lstlisting}
  16237. y = input_int()
  16238. f : Callable[[int],int] = lambda x: x + y
  16239. print( f(21) )
  16240. \end{lstlisting}
  16241. \fi}
  16242. %
  16243. \noindent Closure conversion compiles the application
  16244. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16245. %
  16246. {\if\edition\racketEd
  16247. \begin{lstlisting}
  16248. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16249. (let ([y2 (vector-ref fvs6 1)])
  16250. (+ x3 y2)))
  16251. (define (main) : Integer
  16252. (let ([y2 (read)])
  16253. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16254. ((vector-ref f4 0) f4 21))))
  16255. \end{lstlisting}
  16256. \fi}
  16257. {\if\edition\pythonEd
  16258. \begin{lstlisting}
  16259. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16260. y_1 = fvs_4[1]
  16261. return x_2 + y_1[0]
  16262. def main() -> int:
  16263. y_1 = (777,)
  16264. y_1[0] = input_int()
  16265. f_0 = (lambda_3, y_1)
  16266. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16267. return 0
  16268. \end{lstlisting}
  16269. \fi}
  16270. %
  16271. \noindent However, we can instead compile the application
  16272. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16273. %
  16274. {\if\edition\racketEd
  16275. \begin{lstlisting}
  16276. (define (main) : Integer
  16277. (let ([y2 (read)])
  16278. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16279. ((fun-ref lambda5 1) f4 21))))
  16280. \end{lstlisting}
  16281. \fi}
  16282. {\if\edition\pythonEd
  16283. \begin{lstlisting}
  16284. def main() -> int:
  16285. y_1 = (777,)
  16286. y_1[0] = input_int()
  16287. f_0 = (lambda_3, y_1)
  16288. print(lambda_3(f_0, 21))
  16289. return 0
  16290. \end{lstlisting}
  16291. \fi}
  16292. The problem of determining which \code{lambda} will be called from a
  16293. particular application is quite challenging in general and the topic
  16294. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16295. following exercise we recommend that you compile an application to a
  16296. direct call when the operator is a variable and \racket{the variable
  16297. is \code{let}-bound to a closure}\python{the previous assignment to
  16298. the variable is a closure}. This can be accomplished by maintaining
  16299. an environment that maps variables to function names. Extend the
  16300. environment whenever you encounter a closure on the right-hand side of
  16301. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  16302. name of the global function for the closure. This pass should come
  16303. after closure conversion.
  16304. \begin{exercise}\normalfont\normalsize
  16305. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16306. compiles known calls into direct calls. Verify that your compiler is
  16307. successful in this regard on several example programs.
  16308. \end{exercise}
  16309. These exercises only scratch the surface of closure optimization. A
  16310. good next step for the interested reader is to look at the work of
  16311. \citet{Keep:2012ab}.
  16312. \section{Further Reading}
  16313. The notion of lexically scoped functions predates modern computers by
  16314. about a decade. They were invented by \citet{Church:1932aa}, who
  16315. proposed the lambda calculus as a foundation for logic. Anonymous
  16316. functions were included in the LISP~\citep{McCarthy:1960dz}
  16317. programming language but were initially dynamically scoped. The Scheme
  16318. dialect of LISP adopted lexical scoping, and
  16319. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16320. Scheme programs. However, environments were represented as linked
  16321. lists, so variable look-up was linear in the size of the
  16322. environment. \citet{Appel91} gives a detailed description of several
  16323. closure representations. In this chapter we represent environments
  16324. using flat closures, which were invented by
  16325. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  16326. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16327. closures, variable look-up is constant time but the time to create a
  16328. closure is proportional to the number of its free variables. Flat
  16329. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16330. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16331. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16332. % compilers)
  16333. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16334. \chapter{Dynamic Typing}
  16335. \label{ch:Ldyn}
  16336. \index{subject}{dynamic typing}
  16337. \setcounter{footnote}{0}
  16338. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16339. typed language that is a subset of \racket{Racket}\python{Python}. The
  16340. focus on dynamic typing is in contrast to the previous chapters, which
  16341. have studied the compilation of statically typed languages. In
  16342. dynamically typed languages such as \LangDyn{}, a particular
  16343. expression may produce a value of a different type each time it is
  16344. executed. Consider the following example with a conditional \code{if}
  16345. expression that may return a Boolean or an integer depending on the
  16346. input to the program:
  16347. % part of dynamic_test_25.rkt
  16348. {\if\edition\racketEd
  16349. \begin{lstlisting}
  16350. (not (if (eq? (read) 1) #f 0))
  16351. \end{lstlisting}
  16352. \fi}
  16353. {\if\edition\pythonEd
  16354. \begin{lstlisting}
  16355. not (False if input_int() == 1 else 0)
  16356. \end{lstlisting}
  16357. \fi}
  16358. Languages that allow expressions to produce different kinds of values
  16359. are called \emph{polymorphic}, a word composed of the Greek roots
  16360. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16361. There are several kinds of polymorphism in programming languages, such as
  16362. subtype polymorphism and parametric polymorphism
  16363. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16364. study in this chapter does not have a special name; it is the kind
  16365. that arises in dynamically typed languages.
  16366. Another characteristic of dynamically typed languages is that
  16367. their primitive operations, such as \code{not}, are often defined to operate
  16368. on many different types of values. In fact, in
  16369. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16370. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16371. given anything else it returns \FALSE{}.
  16372. Furthermore, even when primitive operations restrict their inputs to
  16373. values of a certain type, this restriction is enforced at runtime
  16374. instead of during compilation. For example, the tuple read
  16375. operation
  16376. \racket{\code{(vector-ref \#t 0)}}
  16377. \python{\code{True[0]}}
  16378. results in a runtime error because the first argument must
  16379. be a tuple, not a Boolean.
  16380. \section{The \LangDyn{} Language}
  16381. \newcommand{\LdynGrammarRacket}{
  16382. \begin{array}{rcl}
  16383. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16384. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16385. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16386. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16387. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16388. \end{array}
  16389. }
  16390. \newcommand{\LdynASTRacket}{
  16391. \begin{array}{lcl}
  16392. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16393. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16394. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16395. \end{array}
  16396. }
  16397. \begin{figure}[tp]
  16398. \centering
  16399. \begin{tcolorbox}[colback=white]
  16400. \small
  16401. {\if\edition\racketEd
  16402. \[
  16403. \begin{array}{l}
  16404. \gray{\LintGrammarRacket{}} \\ \hline
  16405. \gray{\LvarGrammarRacket{}} \\ \hline
  16406. \gray{\LifGrammarRacket{}} \\ \hline
  16407. \gray{\LwhileGrammarRacket} \\ \hline
  16408. \gray{\LtupGrammarRacket} \\ \hline
  16409. \LdynGrammarRacket \\
  16410. \begin{array}{rcl}
  16411. \LangDynM{} &::=& \Def\ldots\; \Exp
  16412. \end{array}
  16413. \end{array}
  16414. \]
  16415. \fi}
  16416. {\if\edition\pythonEd
  16417. \[
  16418. \begin{array}{rcl}
  16419. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16420. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16421. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16422. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16423. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16424. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16425. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16426. \MID \CLEN{\Exp} \\
  16427. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16428. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16429. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16430. \MID \Var\mathop{\key{=}}\Exp \\
  16431. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16432. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16433. &\MID& \CRETURN{\Exp} \\
  16434. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16435. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16436. \end{array}
  16437. \]
  16438. \fi}
  16439. \end{tcolorbox}
  16440. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16441. \label{fig:r7-concrete-syntax}
  16442. \end{figure}
  16443. \begin{figure}[tp]
  16444. \centering
  16445. \begin{tcolorbox}[colback=white]
  16446. \small
  16447. {\if\edition\racketEd
  16448. \[
  16449. \begin{array}{l}
  16450. \gray{\LintASTRacket{}} \\ \hline
  16451. \gray{\LvarASTRacket{}} \\ \hline
  16452. \gray{\LifASTRacket{}} \\ \hline
  16453. \gray{\LwhileASTRacket} \\ \hline
  16454. \gray{\LtupASTRacket} \\ \hline
  16455. \LdynASTRacket \\
  16456. \begin{array}{lcl}
  16457. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16458. \end{array}
  16459. \end{array}
  16460. \]
  16461. \fi}
  16462. {\if\edition\pythonEd
  16463. \[
  16464. \begin{array}{rcl}
  16465. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16466. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16467. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16468. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16469. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16470. &\MID & \code{Is()} \\
  16471. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16472. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16473. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16474. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16475. \MID \VAR{\Var{}} \\
  16476. &\MID& \BOOL{\itm{bool}}
  16477. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  16478. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  16479. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  16480. &\MID& \LEN{\Exp} \\
  16481. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  16482. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  16483. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  16484. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  16485. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  16486. &\MID& \RETURN{\Exp} \\
  16487. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  16488. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  16489. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16490. \end{array}
  16491. \]
  16492. \fi}
  16493. \end{tcolorbox}
  16494. \caption{The abstract syntax of \LangDyn{}.}
  16495. \label{fig:r7-syntax}
  16496. \end{figure}
  16497. The definitions of the concrete and abstract syntax of \LangDyn{} are
  16498. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  16499. %
  16500. There is no type checker for \LangDyn{} because it checks types only
  16501. at runtime.
  16502. The definitional interpreter for \LangDyn{} is presented in
  16503. \racket{figure~\ref{fig:interp-Ldyn}}
  16504. \python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}},
  16505. and definitions of its auxiliary functions are shown in
  16506. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  16507. \INT{n}. Instead of simply returning the integer \code{n} (as
  16508. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  16509. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  16510. value} that combines an underlying value with a tag that identifies
  16511. what kind of value it is. We define the following \racket{struct}\python{class}
  16512. to represent tagged values:
  16513. %
  16514. {\if\edition\racketEd
  16515. \begin{lstlisting}
  16516. (struct Tagged (value tag) #:transparent)
  16517. \end{lstlisting}
  16518. \fi}
  16519. {\if\edition\pythonEd
  16520. \begin{minipage}{\textwidth}
  16521. \begin{lstlisting}
  16522. @dataclass(eq=True)
  16523. class Tagged(Value):
  16524. value : Value
  16525. tag : str
  16526. def __str__(self):
  16527. return str(self.value)
  16528. \end{lstlisting}
  16529. \end{minipage}
  16530. \fi}
  16531. %
  16532. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  16533. \code{Vector}, and \code{Procedure}.}
  16534. %
  16535. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  16536. \code{'tuple'}, and \code{'function'}.}
  16537. %
  16538. Tags are closely related to types but do not always capture all the
  16539. information that a type does.
  16540. %
  16541. \racket{For example, a vector of type \code{(Vector Any Any)} is
  16542. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  16543. Any)} is tagged with \code{Procedure}.}
  16544. %
  16545. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  16546. is tagged with \code{'tuple'} and a function of type
  16547. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  16548. is tagged with \code{'function'}.}
  16549. Next consider the match case for accessing the element of a tuple.
  16550. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  16551. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  16552. argument is a tuple and the second is an integer.
  16553. \racket{
  16554. If they are not, a \code{trapped-error} is raised. Recall from
  16555. section~\ref{sec:interp_Lint} that when a definition interpreter
  16556. raises a \code{trapped-error} error, the compiled code must also
  16557. signal an error by exiting with return code \code{255}. A
  16558. \code{trapped-error} is also raised if the index is not less than the
  16559. length of the vector.
  16560. }
  16561. %
  16562. \python{If they are not, an exception is raised. The compiled code
  16563. must also signal an error by exiting with return code \code{255}. A
  16564. exception is also raised if the index is not less than the length of the
  16565. tuple or if it is negative.}
  16566. \begin{figure}[tbp]
  16567. \begin{tcolorbox}[colback=white]
  16568. {\if\edition\racketEd
  16569. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16570. (define ((interp-Ldyn-exp env) ast)
  16571. (define recur (interp-Ldyn-exp env))
  16572. (match ast
  16573. [(Var x) (dict-ref env x)]
  16574. [(Int n) (Tagged n 'Integer)]
  16575. [(Bool b) (Tagged b 'Boolean)]
  16576. [(Lambda xs rt body)
  16577. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  16578. [(Prim 'vector es)
  16579. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  16580. [(Prim 'vector-ref (list e1 e2))
  16581. (define vec (recur e1)) (define i (recur e2))
  16582. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16583. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16584. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16585. (vector-ref (Tagged-value vec) (Tagged-value i))]
  16586. [(Prim 'vector-set! (list e1 e2 e3))
  16587. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16588. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16589. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16590. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16591. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16592. (Tagged (void) 'Void)]
  16593. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16594. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16595. [(Prim 'or (list e1 e2))
  16596. (define v1 (recur e1))
  16597. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16598. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16599. [(Prim op (list e1))
  16600. #:when (set-member? type-predicates op)
  16601. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16602. [(Prim op es)
  16603. (define args (map recur es))
  16604. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16605. (unless (for/or ([expected-tags (op-tags op)])
  16606. (equal? expected-tags tags))
  16607. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16608. (tag-value
  16609. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16610. [(If q t f)
  16611. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16612. [(Apply f es)
  16613. (define new-f (recur f)) (define args (map recur es))
  16614. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16615. (match f-val
  16616. [`(function ,xs ,body ,lam-env)
  16617. (unless (eq? (length xs) (length args))
  16618. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16619. (define new-env (append (map cons xs args) lam-env))
  16620. ((interp-Ldyn-exp new-env) body)]
  16621. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16622. \end{lstlisting}
  16623. \fi}
  16624. {\if\edition\pythonEd
  16625. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16626. class InterpLdyn(InterpLlambda):
  16627. def interp_exp(self, e, env):
  16628. match e:
  16629. case Constant(n):
  16630. return self.tag(super().interp_exp(e, env))
  16631. case Tuple(es, Load()):
  16632. return self.tag(super().interp_exp(e, env))
  16633. case Lambda(params, body):
  16634. return self.tag(super().interp_exp(e, env))
  16635. case Call(Name('input_int'), []):
  16636. return self.tag(super().interp_exp(e, env))
  16637. case BinOp(left, Add(), right):
  16638. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16639. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16640. case BinOp(left, Sub(), right):
  16641. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16642. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16643. case UnaryOp(USub(), e1):
  16644. v = self.interp_exp(e1, env)
  16645. return self.tag(- self.untag(v, 'int', e))
  16646. case IfExp(test, body, orelse):
  16647. v = self.interp_exp(test, env)
  16648. if self.untag(v, 'bool', e):
  16649. return self.interp_exp(body, env)
  16650. else:
  16651. return self.interp_exp(orelse, env)
  16652. case UnaryOp(Not(), e1):
  16653. v = self.interp_exp(e1, env)
  16654. return self.tag(not self.untag(v, 'bool', e))
  16655. case BoolOp(And(), values):
  16656. left = values[0]; right = values[1]
  16657. l = self.interp_exp(left, env)
  16658. if self.untag(l, 'bool', e):
  16659. return self.interp_exp(right, env)
  16660. else:
  16661. return self.tag(False)
  16662. case BoolOp(Or(), values):
  16663. left = values[0]; right = values[1]
  16664. l = self.interp_exp(left, env)
  16665. if self.untag(l, 'bool', e):
  16666. return self.tag(True)
  16667. else:
  16668. return self.interp_exp(right, env)
  16669. case Compare(left, [cmp], [right]):
  16670. l = self.interp_exp(left, env)
  16671. r = self.interp_exp(right, env)
  16672. if l.tag == r.tag:
  16673. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16674. else:
  16675. raise Exception('interp Compare unexpected '
  16676. + repr(l) + ' ' + repr(r))
  16677. case Subscript(tup, index, Load()):
  16678. t = self.interp_exp(tup, env)
  16679. n = self.interp_exp(index, env)
  16680. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16681. case Call(Name('len'), [tup]):
  16682. t = self.interp_exp(tup, env)
  16683. return self.tag(len(self.untag(t, 'tuple', e)))
  16684. case _:
  16685. return self.tag(super().interp_exp(e, env))
  16686. \end{lstlisting}
  16687. \fi}
  16688. \end{tcolorbox}
  16689. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16690. \label{fig:interp-Ldyn}
  16691. \end{figure}
  16692. {\if\edition\pythonEd
  16693. \begin{figure}[tbp]
  16694. \begin{tcolorbox}[colback=white]
  16695. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16696. class InterpLdyn(InterpLlambda):
  16697. def interp_stmts(self, ss, env):
  16698. if len(ss) == 0:
  16699. return
  16700. match ss[0]:
  16701. case If(test, body, orelse):
  16702. v = self.interp_exp(test, env)
  16703. if self.untag(v, 'bool', ss[0]):
  16704. return self.interp_stmts(body + ss[1:], env)
  16705. else:
  16706. return self.interp_stmts(orelse + ss[1:], env)
  16707. case While(test, body, []):
  16708. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16709. self.interp_stmts(body, env)
  16710. return self.interp_stmts(ss[1:], env)
  16711. case Assign([Subscript(tup, index)], value):
  16712. tup = self.interp_exp(tup, env)
  16713. index = self.interp_exp(index, env)
  16714. tup_v = self.untag(tup, 'tuple', ss[0])
  16715. index_v = self.untag(index, 'int', ss[0])
  16716. tup_v[index_v] = self.interp_exp(value, env)
  16717. return self.interp_stmts(ss[1:], env)
  16718. case FunctionDef(name, params, bod, dl, returns, comment):
  16719. ps = [x for (x,t) in params]
  16720. env[name] = self.tag(Function(name, ps, bod, env))
  16721. return self.interp_stmts(ss[1:], env)
  16722. case _:
  16723. return super().interp_stmts(ss, env)
  16724. \end{lstlisting}
  16725. \end{tcolorbox}
  16726. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16727. \label{fig:interp-Ldyn-2}
  16728. \end{figure}
  16729. \fi}
  16730. \begin{figure}[tbp]
  16731. \begin{tcolorbox}[colback=white]
  16732. {\if\edition\racketEd
  16733. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16734. (define (interp-op op)
  16735. (match op
  16736. ['+ fx+]
  16737. ['- fx-]
  16738. ['read read-fixnum]
  16739. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16740. ['< (lambda (v1 v2)
  16741. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16742. ['<= (lambda (v1 v2)
  16743. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16744. ['> (lambda (v1 v2)
  16745. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16746. ['>= (lambda (v1 v2)
  16747. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16748. ['boolean? boolean?]
  16749. ['integer? fixnum?]
  16750. ['void? void?]
  16751. ['vector? vector?]
  16752. ['vector-length vector-length]
  16753. ['procedure? (match-lambda
  16754. [`(functions ,xs ,body ,env) #t] [else #f])]
  16755. [else (error 'interp-op "unknown operator" op)]))
  16756. (define (op-tags op)
  16757. (match op
  16758. ['+ '((Integer Integer))]
  16759. ['- '((Integer Integer) (Integer))]
  16760. ['read '(())]
  16761. ['not '((Boolean))]
  16762. ['< '((Integer Integer))]
  16763. ['<= '((Integer Integer))]
  16764. ['> '((Integer Integer))]
  16765. ['>= '((Integer Integer))]
  16766. ['vector-length '((Vector))]))
  16767. (define type-predicates
  16768. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16769. (define (tag-value v)
  16770. (cond [(boolean? v) (Tagged v 'Boolean)]
  16771. [(fixnum? v) (Tagged v 'Integer)]
  16772. [(procedure? v) (Tagged v 'Procedure)]
  16773. [(vector? v) (Tagged v 'Vector)]
  16774. [(void? v) (Tagged v 'Void)]
  16775. [else (error 'tag-value "unidentified value ~a" v)]))
  16776. (define (check-tag val expected ast)
  16777. (define tag (Tagged-tag val))
  16778. (unless (eq? tag expected)
  16779. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16780. \end{lstlisting}
  16781. \fi}
  16782. {\if\edition\pythonEd
  16783. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16784. class InterpLdyn(InterpLlambda):
  16785. def tag(self, v):
  16786. if v is True or v is False:
  16787. return Tagged(v, 'bool')
  16788. elif isinstance(v, int):
  16789. return Tagged(v, 'int')
  16790. elif isinstance(v, Function):
  16791. return Tagged(v, 'function')
  16792. elif isinstance(v, tuple):
  16793. return Tagged(v, 'tuple')
  16794. elif isinstance(v, type(None)):
  16795. return Tagged(v, 'none')
  16796. else:
  16797. raise Exception('tag: unexpected ' + repr(v))
  16798. def untag(self, v, expected_tag, ast):
  16799. match v:
  16800. case Tagged(val, tag) if tag == expected_tag:
  16801. return val
  16802. case _:
  16803. raise Exception('expected Tagged value with '
  16804. + expected_tag + ', not ' + ' ' + repr(v))
  16805. def apply_fun(self, fun, args, e):
  16806. f = self.untag(fun, 'function', e)
  16807. return super().apply_fun(f, args, e)
  16808. \end{lstlisting}
  16809. \fi}
  16810. \end{tcolorbox}
  16811. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  16812. \label{fig:interp-Ldyn-aux}
  16813. \end{figure}
  16814. \clearpage
  16815. \section{Representation of Tagged Values}
  16816. The interpreter for \LangDyn{} introduced a new kind of value: the
  16817. tagged value. To compile \LangDyn{} to x86 we must decide how to
  16818. represent tagged values at the bit level. Because almost every
  16819. operation in \LangDyn{} involves manipulating tagged values, the
  16820. representation must be efficient. Recall that all our values are 64
  16821. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  16822. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  16823. $011$ for procedures, and $101$ for the void value\python{,
  16824. \key{None}}. We define the following auxiliary function for mapping
  16825. types to tag codes:
  16826. %
  16827. {\if\edition\racketEd
  16828. \begin{align*}
  16829. \itm{tagof}(\key{Integer}) &= 001 \\
  16830. \itm{tagof}(\key{Boolean}) &= 100 \\
  16831. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  16832. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  16833. \itm{tagof}(\key{Void}) &= 101
  16834. \end{align*}
  16835. \fi}
  16836. {\if\edition\pythonEd
  16837. \begin{align*}
  16838. \itm{tagof}(\key{IntType()}) &= 001 \\
  16839. \itm{tagof}(\key{BoolType()}) &= 100 \\
  16840. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  16841. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  16842. \itm{tagof}(\key{type(None)}) &= 101
  16843. \end{align*}
  16844. \fi}
  16845. %
  16846. This stealing of 3 bits comes at some price: integers are now restricted
  16847. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  16848. affect tuples and procedures because those values are addresses, and
  16849. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  16850. they are always $000$. Thus, we do not lose information by overwriting
  16851. the rightmost 3 bits with the tag, and we can simply zero out the tag
  16852. to recover the original address.
  16853. To make tagged values into first-class entities, we can give them a
  16854. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  16855. operations such as \code{Inject} and \code{Project} for creating and
  16856. using them, yielding the statically typed \LangAny{} intermediate
  16857. language. We describe how to compile \LangDyn{} to \LangAny{} in
  16858. section~\ref{sec:compile-r7}; in th next section we describe the
  16859. \LangAny{} language in greater detail.
  16860. \section{The \LangAny{} Language}
  16861. \label{sec:Rany-lang}
  16862. \newcommand{\LanyASTRacket}{
  16863. \begin{array}{lcl}
  16864. \Type &::= & \ANYTY \\
  16865. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16866. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  16867. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  16868. \itm{op} &::= & \code{any-vector-length}
  16869. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  16870. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  16871. \MID \code{procedure?} \MID \code{void?} \\
  16872. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  16873. \end{array}
  16874. }
  16875. \newcommand{\LanyASTPython}{
  16876. \begin{array}{lcl}
  16877. \Type &::= & \key{AnyType()} \\
  16878. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  16879. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  16880. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  16881. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  16882. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  16883. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  16884. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  16885. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  16886. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  16887. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  16888. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  16889. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  16890. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  16891. \end{array}
  16892. }
  16893. \begin{figure}[tp]
  16894. \centering
  16895. \begin{tcolorbox}[colback=white]
  16896. \small
  16897. {\if\edition\racketEd
  16898. \[
  16899. \begin{array}{l}
  16900. \gray{\LintOpAST} \\ \hline
  16901. \gray{\LvarASTRacket{}} \\ \hline
  16902. \gray{\LifASTRacket{}} \\ \hline
  16903. \gray{\LwhileASTRacket{}} \\ \hline
  16904. \gray{\LtupASTRacket{}} \\ \hline
  16905. \gray{\LfunASTRacket} \\ \hline
  16906. \gray{\LlambdaASTRacket} \\ \hline
  16907. \LanyASTRacket \\
  16908. \begin{array}{lcl}
  16909. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16910. \end{array}
  16911. \end{array}
  16912. \]
  16913. \fi}
  16914. {\if\edition\pythonEd
  16915. \[
  16916. \begin{array}{l}
  16917. \gray{\LintASTPython} \\ \hline
  16918. \gray{\LvarASTPython{}} \\ \hline
  16919. \gray{\LifASTPython{}} \\ \hline
  16920. \gray{\LwhileASTPython{}} \\ \hline
  16921. \gray{\LtupASTPython{}} \\ \hline
  16922. \gray{\LfunASTPython} \\ \hline
  16923. \gray{\LlambdaASTPython} \\ \hline
  16924. \LanyASTPython \\
  16925. \begin{array}{lcl}
  16926. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16927. \end{array}
  16928. \end{array}
  16929. \]
  16930. \fi}
  16931. \end{tcolorbox}
  16932. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  16933. \label{fig:Lany-syntax}
  16934. \end{figure}
  16935. The definition of the abstract syntax of \LangAny{} is given in
  16936. figure~\ref{fig:Lany-syntax}.
  16937. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  16938. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  16939. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  16940. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  16941. converts the tagged value produced by expression $e$ into a value of
  16942. type $T$ or halts the program if the type tag does not match $T$.
  16943. %
  16944. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  16945. restricted to be a flat type (the nonterminal $\FType$) which
  16946. simplifies the implementation and complies with the needs for
  16947. compiling \LangDyn{}.
  16948. The \racket{\code{any-vector}} operators
  16949. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  16950. operations so that they can be applied to a value of type
  16951. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  16952. tuple operations in that the index is not restricted to a literal
  16953. integer in the grammar but is allowed to be any expression.
  16954. \racket{The type predicates such as
  16955. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  16956. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  16957. the predicate and return {\FALSE} otherwise.}
  16958. The type checker for \LangAny{} is shown in
  16959. figure~\ref{fig:type-check-Lany}
  16960. %
  16961. \racket{ and uses the auxiliary functions presented in
  16962. figure~\ref{fig:type-check-Lany-aux}}.
  16963. %
  16964. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  16965. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  16966. \begin{figure}[btp]
  16967. \begin{tcolorbox}[colback=white]
  16968. {\if\edition\racketEd
  16969. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16970. (define type-check-Lany-class
  16971. (class type-check-Llambda-class
  16972. (super-new)
  16973. (inherit check-type-equal?)
  16974. (define/override (type-check-exp env)
  16975. (lambda (e)
  16976. (define recur (type-check-exp env))
  16977. (match e
  16978. [(Inject e1 ty)
  16979. (unless (flat-ty? ty)
  16980. (error 'type-check "may only inject from flat type, not ~a" ty))
  16981. (define-values (new-e1 e-ty) (recur e1))
  16982. (check-type-equal? e-ty ty e)
  16983. (values (Inject new-e1 ty) 'Any)]
  16984. [(Project e1 ty)
  16985. (unless (flat-ty? ty)
  16986. (error 'type-check "may only project to flat type, not ~a" ty))
  16987. (define-values (new-e1 e-ty) (recur e1))
  16988. (check-type-equal? e-ty 'Any e)
  16989. (values (Project new-e1 ty) ty)]
  16990. [(Prim 'any-vector-length (list e1))
  16991. (define-values (e1^ t1) (recur e1))
  16992. (check-type-equal? t1 'Any e)
  16993. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  16994. [(Prim 'any-vector-ref (list e1 e2))
  16995. (define-values (e1^ t1) (recur e1))
  16996. (define-values (e2^ t2) (recur e2))
  16997. (check-type-equal? t1 'Any e)
  16998. (check-type-equal? t2 'Integer e)
  16999. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17000. [(Prim 'any-vector-set! (list e1 e2 e3))
  17001. (define-values (e1^ t1) (recur e1))
  17002. (define-values (e2^ t2) (recur e2))
  17003. (define-values (e3^ t3) (recur e3))
  17004. (check-type-equal? t1 'Any e)
  17005. (check-type-equal? t2 'Integer e)
  17006. (check-type-equal? t3 'Any e)
  17007. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17008. [(Prim pred (list e1))
  17009. #:when (set-member? (type-predicates) pred)
  17010. (define-values (new-e1 e-ty) (recur e1))
  17011. (check-type-equal? e-ty 'Any e)
  17012. (values (Prim pred (list new-e1)) 'Boolean)]
  17013. [(Prim 'eq? (list arg1 arg2))
  17014. (define-values (e1 t1) (recur arg1))
  17015. (define-values (e2 t2) (recur arg2))
  17016. (match* (t1 t2)
  17017. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17018. [(other wise) (check-type-equal? t1 t2 e)])
  17019. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17020. [else ((super type-check-exp env) e)])))
  17021. ))
  17022. \end{lstlisting}
  17023. \fi}
  17024. {\if\edition\pythonEd
  17025. \begin{lstlisting}
  17026. class TypeCheckLany(TypeCheckLlambda):
  17027. def type_check_exp(self, e, env):
  17028. match e:
  17029. case Inject(value, typ):
  17030. self.check_exp(value, typ, env)
  17031. return AnyType()
  17032. case Project(value, typ):
  17033. self.check_exp(value, AnyType(), env)
  17034. return typ
  17035. case Call(Name('any_tuple_load'), [tup, index]):
  17036. self.check_exp(tup, AnyType(), env)
  17037. self.check_exp(index, IntType(), env)
  17038. return AnyType()
  17039. case Call(Name('any_len'), [tup]):
  17040. self.check_exp(tup, AnyType(), env)
  17041. return IntType()
  17042. case Call(Name('arity'), [fun]):
  17043. ty = self.type_check_exp(fun, env)
  17044. match ty:
  17045. case FunctionType(ps, rt):
  17046. return IntType()
  17047. case TupleType([FunctionType(ps,rs)]):
  17048. return IntType()
  17049. case _:
  17050. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  17051. case Call(Name('make_any'), [value, tag]):
  17052. self.type_check_exp(value, env)
  17053. self.check_exp(tag, IntType(), env)
  17054. return AnyType()
  17055. case AnnLambda(params, returns, body):
  17056. new_env = {x:t for (x,t) in env.items()}
  17057. for (x,t) in params:
  17058. new_env[x] = t
  17059. return_t = self.type_check_exp(body, new_env)
  17060. self.check_type_equal(returns, return_t, e)
  17061. return FunctionType([t for (x,t) in params], return_t)
  17062. case _:
  17063. return super().type_check_exp(e, env)
  17064. \end{lstlisting}
  17065. \fi}
  17066. \end{tcolorbox}
  17067. \caption{Type checker for the \LangAny{} language.}
  17068. \label{fig:type-check-Lany}
  17069. \end{figure}
  17070. {\if\edition\racketEd
  17071. \begin{figure}[tbp]
  17072. \begin{tcolorbox}[colback=white]
  17073. \begin{lstlisting}
  17074. (define/override (operator-types)
  17075. (append
  17076. '((integer? . ((Any) . Boolean))
  17077. (vector? . ((Any) . Boolean))
  17078. (procedure? . ((Any) . Boolean))
  17079. (void? . ((Any) . Boolean)))
  17080. (super operator-types)))
  17081. (define/public (type-predicates)
  17082. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17083. (define/public (flat-ty? ty)
  17084. (match ty
  17085. [(or `Integer `Boolean `Void) #t]
  17086. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17087. [`(,ts ... -> ,rt)
  17088. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17089. [else #f]))
  17090. \end{lstlisting}
  17091. \end{tcolorbox}
  17092. \caption{Auxiliary methods for type checking \LangAny{}.}
  17093. \label{fig:type-check-Lany-aux}
  17094. \end{figure}
  17095. \fi}
  17096. \begin{figure}[btp]
  17097. \begin{tcolorbox}[colback=white]
  17098. {\if\edition\racketEd
  17099. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17100. (define interp-Lany-class
  17101. (class interp-Llambda-class
  17102. (super-new)
  17103. (define/override (interp-op op)
  17104. (match op
  17105. ['boolean? (match-lambda
  17106. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17107. [else #f])]
  17108. ['integer? (match-lambda
  17109. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17110. [else #f])]
  17111. ['vector? (match-lambda
  17112. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17113. [else #f])]
  17114. ['procedure? (match-lambda
  17115. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17116. [else #f])]
  17117. ['eq? (match-lambda*
  17118. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17119. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17120. [ls (apply (super interp-op op) ls)])]
  17121. ['any-vector-ref (lambda (v i)
  17122. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17123. ['any-vector-set! (lambda (v i a)
  17124. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17125. ['any-vector-length (lambda (v)
  17126. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17127. [else (super interp-op op)]))
  17128. (define/override ((interp-exp env) e)
  17129. (define recur (interp-exp env))
  17130. (match e
  17131. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17132. [(Project e ty2) (apply-project (recur e) ty2)]
  17133. [else ((super interp-exp env) e)]))
  17134. ))
  17135. (define (interp-Lany p)
  17136. (send (new interp-Lany-class) interp-program p))
  17137. \end{lstlisting}
  17138. \fi}
  17139. {\if\edition\pythonEd
  17140. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17141. class InterpLany(InterpLlambda):
  17142. def interp_exp(self, e, env):
  17143. match e:
  17144. case Inject(value, typ):
  17145. v = self.interp_exp(value, env)
  17146. return Tagged(v, self.type_to_tag(typ))
  17147. case Project(value, typ):
  17148. v = self.interp_exp(value, env)
  17149. match v:
  17150. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17151. return val
  17152. case _:
  17153. raise Exception('interp project to ' + repr(typ)
  17154. + ' unexpected ' + repr(v))
  17155. case Call(Name('any_tuple_load'), [tup, index]):
  17156. tv = self.interp_exp(tup, env)
  17157. n = self.interp_exp(index, env)
  17158. match tv:
  17159. case Tagged(v, tag):
  17160. return v[n]
  17161. case _:
  17162. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  17163. case Call(Name('any_len'), [value]):
  17164. v = self.interp_exp(value, env)
  17165. match v:
  17166. case Tagged(value, tag):
  17167. return len(value)
  17168. case _:
  17169. raise Exception('interp any_len unexpected ' + repr(v))
  17170. case Call(Name('arity'), [fun]):
  17171. f = self.interp_exp(fun, env)
  17172. return self.arity(f)
  17173. case _:
  17174. return super().interp_exp(e, env)
  17175. \end{lstlisting}
  17176. \fi}
  17177. \end{tcolorbox}
  17178. \caption{Interpreter for \LangAny{}.}
  17179. \label{fig:interp-Lany}
  17180. \end{figure}
  17181. \begin{figure}[tbp]
  17182. \begin{tcolorbox}[colback=white]
  17183. {\if\edition\racketEd
  17184. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17185. (define/public (apply-inject v tg) (Tagged v tg))
  17186. (define/public (apply-project v ty2)
  17187. (define tag2 (any-tag ty2))
  17188. (match v
  17189. [(Tagged v1 tag1)
  17190. (cond
  17191. [(eq? tag1 tag2)
  17192. (match ty2
  17193. [`(Vector ,ts ...)
  17194. (define l1 ((interp-op 'vector-length) v1))
  17195. (cond
  17196. [(eq? l1 (length ts)) v1]
  17197. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17198. l1 (length ts))])]
  17199. [`(,ts ... -> ,rt)
  17200. (match v1
  17201. [`(function ,xs ,body ,env)
  17202. (cond [(eq? (length xs) (length ts)) v1]
  17203. [else
  17204. (error 'apply-project "arity mismatch ~a != ~a"
  17205. (length xs) (length ts))])]
  17206. [else (error 'apply-project "expected function not ~a" v1)])]
  17207. [else v1])]
  17208. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17209. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17210. \end{lstlisting}
  17211. \fi}
  17212. {\if\edition\pythonEd
  17213. \begin{lstlisting}
  17214. class InterpLany(InterpLlambda):
  17215. def type_to_tag(self, typ):
  17216. match typ:
  17217. case FunctionType(params, rt):
  17218. return 'function'
  17219. case TupleType(fields):
  17220. return 'tuple'
  17221. case t if t == int:
  17222. return 'int'
  17223. case t if t == bool:
  17224. return 'bool'
  17225. case IntType():
  17226. return 'int'
  17227. case BoolType():
  17228. return 'int'
  17229. case _:
  17230. raise Exception('type_to_tag unexpected ' + repr(typ))
  17231. def arity(self, v):
  17232. match v:
  17233. case Function(name, params, body, env):
  17234. return len(params)
  17235. case ClosureTuple(args, arity):
  17236. return arity
  17237. case _:
  17238. raise Exception('Lany arity unexpected ' + repr(v))
  17239. \end{lstlisting}
  17240. \fi}
  17241. \end{tcolorbox}
  17242. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17243. \label{fig:interp-Lany-aux}
  17244. \end{figure}
  17245. \clearpage
  17246. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17247. \label{sec:compile-r7}
  17248. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17249. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17250. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17251. is that given any subexpression $e$ in the \LangDyn{} program, the
  17252. pass will produce an expression $e'$ in \LangAny{} that has type
  17253. \ANYTY{}. For example, the first row in
  17254. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17255. \TRUE{}, which must be injected to produce an expression of type
  17256. \ANYTY{}.
  17257. %
  17258. The compilation of addition is shown in the second row of
  17259. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17260. representative of many primitive operations: the arguments have type
  17261. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17262. be performed.
  17263. The compilation of \key{lambda} (third row of
  17264. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17265. produce type annotations: we simply use \ANYTY{}.
  17266. %
  17267. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17268. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17269. this pass has to account for some differences in behavior between
  17270. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17271. permissive than \LangAny{} regarding what kind of values can be used
  17272. in various places. For example, the condition of an \key{if} does
  17273. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17274. of the same type (in that case the result is \code{\#f}).}
  17275. \begin{figure}[btp]
  17276. \centering
  17277. \begin{tcolorbox}[colback=white]
  17278. {\if\edition\racketEd
  17279. \begin{tabular}{lll}
  17280. \begin{minipage}{0.27\textwidth}
  17281. \begin{lstlisting}
  17282. #t
  17283. \end{lstlisting}
  17284. \end{minipage}
  17285. &
  17286. $\Rightarrow$
  17287. &
  17288. \begin{minipage}{0.65\textwidth}
  17289. \begin{lstlisting}
  17290. (inject #t Boolean)
  17291. \end{lstlisting}
  17292. \end{minipage}
  17293. \\[2ex]\hline
  17294. \begin{minipage}{0.27\textwidth}
  17295. \begin{lstlisting}
  17296. (+ |$e_1$| |$e_2$|)
  17297. \end{lstlisting}
  17298. \end{minipage}
  17299. &
  17300. $\Rightarrow$
  17301. &
  17302. \begin{minipage}{0.65\textwidth}
  17303. \begin{lstlisting}
  17304. (inject
  17305. (+ (project |$e'_1$| Integer)
  17306. (project |$e'_2$| Integer))
  17307. Integer)
  17308. \end{lstlisting}
  17309. \end{minipage}
  17310. \\[2ex]\hline
  17311. \begin{minipage}{0.27\textwidth}
  17312. \begin{lstlisting}
  17313. (lambda (|$x_1 \ldots$|) |$e$|)
  17314. \end{lstlisting}
  17315. \end{minipage}
  17316. &
  17317. $\Rightarrow$
  17318. &
  17319. \begin{minipage}{0.65\textwidth}
  17320. \begin{lstlisting}
  17321. (inject
  17322. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17323. (Any|$\ldots$|Any -> Any))
  17324. \end{lstlisting}
  17325. \end{minipage}
  17326. \\[2ex]\hline
  17327. \begin{minipage}{0.27\textwidth}
  17328. \begin{lstlisting}
  17329. (|$e_0$| |$e_1 \ldots e_n$|)
  17330. \end{lstlisting}
  17331. \end{minipage}
  17332. &
  17333. $\Rightarrow$
  17334. &
  17335. \begin{minipage}{0.65\textwidth}
  17336. \begin{lstlisting}
  17337. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17338. \end{lstlisting}
  17339. \end{minipage}
  17340. \\[2ex]\hline
  17341. \begin{minipage}{0.27\textwidth}
  17342. \begin{lstlisting}
  17343. (vector-ref |$e_1$| |$e_2$|)
  17344. \end{lstlisting}
  17345. \end{minipage}
  17346. &
  17347. $\Rightarrow$
  17348. &
  17349. \begin{minipage}{0.65\textwidth}
  17350. \begin{lstlisting}
  17351. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17352. \end{lstlisting}
  17353. \end{minipage}
  17354. \\[2ex]\hline
  17355. \begin{minipage}{0.27\textwidth}
  17356. \begin{lstlisting}
  17357. (if |$e_1$| |$e_2$| |$e_3$|)
  17358. \end{lstlisting}
  17359. \end{minipage}
  17360. &
  17361. $\Rightarrow$
  17362. &
  17363. \begin{minipage}{0.65\textwidth}
  17364. \begin{lstlisting}
  17365. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17366. \end{lstlisting}
  17367. \end{minipage}
  17368. \\[2ex]\hline
  17369. \begin{minipage}{0.27\textwidth}
  17370. \begin{lstlisting}
  17371. (eq? |$e_1$| |$e_2$|)
  17372. \end{lstlisting}
  17373. \end{minipage}
  17374. &
  17375. $\Rightarrow$
  17376. &
  17377. \begin{minipage}{0.65\textwidth}
  17378. \begin{lstlisting}
  17379. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17380. \end{lstlisting}
  17381. \end{minipage}
  17382. \\[2ex]\hline
  17383. \begin{minipage}{0.27\textwidth}
  17384. \begin{lstlisting}
  17385. (not |$e_1$|)
  17386. \end{lstlisting}
  17387. \end{minipage}
  17388. &
  17389. $\Rightarrow$
  17390. &
  17391. \begin{minipage}{0.65\textwidth}
  17392. \begin{lstlisting}
  17393. (if (eq? |$e'_1$| (inject #f Boolean))
  17394. (inject #t Boolean) (inject #f Boolean))
  17395. \end{lstlisting}
  17396. \end{minipage}
  17397. \end{tabular}
  17398. \fi}
  17399. {\if\edition\pythonEd
  17400. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17401. \begin{minipage}{0.23\textwidth}
  17402. \begin{lstlisting}
  17403. True
  17404. \end{lstlisting}
  17405. \end{minipage}
  17406. &
  17407. $\Rightarrow$
  17408. &
  17409. \begin{minipage}{0.7\textwidth}
  17410. \begin{lstlisting}
  17411. Inject(True, BoolType())
  17412. \end{lstlisting}
  17413. \end{minipage}
  17414. \\[2ex]\hline
  17415. \begin{minipage}{0.23\textwidth}
  17416. \begin{lstlisting}
  17417. |$e_1$| + |$e_2$|
  17418. \end{lstlisting}
  17419. \end{minipage}
  17420. &
  17421. $\Rightarrow$
  17422. &
  17423. \begin{minipage}{0.7\textwidth}
  17424. \begin{lstlisting}
  17425. Inject(Project(|$e'_1$|, IntType())
  17426. + Project(|$e'_2$|, IntType()),
  17427. IntType())
  17428. \end{lstlisting}
  17429. \end{minipage}
  17430. \\[2ex]\hline
  17431. \begin{minipage}{0.23\textwidth}
  17432. \begin{lstlisting}
  17433. lambda |$x_1 \ldots$|: |$e$|
  17434. \end{lstlisting}
  17435. \end{minipage}
  17436. &
  17437. $\Rightarrow$
  17438. &
  17439. \begin{minipage}{0.7\textwidth}
  17440. \begin{lstlisting}
  17441. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17442. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17443. \end{lstlisting}
  17444. \end{minipage}
  17445. \\[2ex]\hline
  17446. \begin{minipage}{0.23\textwidth}
  17447. \begin{lstlisting}
  17448. |$e_0$|(|$e_1 \ldots e_n$|)
  17449. \end{lstlisting}
  17450. \end{minipage}
  17451. &
  17452. $\Rightarrow$
  17453. &
  17454. \begin{minipage}{0.7\textwidth}
  17455. \begin{lstlisting}
  17456. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17457. AnyType())), |$e'_1, \ldots, e'_n$|)
  17458. \end{lstlisting}
  17459. \end{minipage}
  17460. \\[2ex]\hline
  17461. \begin{minipage}{0.23\textwidth}
  17462. \begin{lstlisting}
  17463. |$e_1$|[|$e_2$|]
  17464. \end{lstlisting}
  17465. \end{minipage}
  17466. &
  17467. $\Rightarrow$
  17468. &
  17469. \begin{minipage}{0.7\textwidth}
  17470. \begin{lstlisting}
  17471. Call(Name('any_tuple_load'),
  17472. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17473. \end{lstlisting}
  17474. \end{minipage}
  17475. %% \begin{minipage}{0.23\textwidth}
  17476. %% \begin{lstlisting}
  17477. %% |$e_2$| if |$e_1$| else |$e_3$|
  17478. %% \end{lstlisting}
  17479. %% \end{minipage}
  17480. %% &
  17481. %% $\Rightarrow$
  17482. %% &
  17483. %% \begin{minipage}{0.7\textwidth}
  17484. %% \begin{lstlisting}
  17485. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17486. %% \end{lstlisting}
  17487. %% \end{minipage}
  17488. %% \\[2ex]\hline
  17489. %% \begin{minipage}{0.23\textwidth}
  17490. %% \begin{lstlisting}
  17491. %% (eq? |$e_1$| |$e_2$|)
  17492. %% \end{lstlisting}
  17493. %% \end{minipage}
  17494. %% &
  17495. %% $\Rightarrow$
  17496. %% &
  17497. %% \begin{minipage}{0.7\textwidth}
  17498. %% \begin{lstlisting}
  17499. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17500. %% \end{lstlisting}
  17501. %% \end{minipage}
  17502. %% \\[2ex]\hline
  17503. %% \begin{minipage}{0.23\textwidth}
  17504. %% \begin{lstlisting}
  17505. %% (not |$e_1$|)
  17506. %% \end{lstlisting}
  17507. %% \end{minipage}
  17508. %% &
  17509. %% $\Rightarrow$
  17510. %% &
  17511. %% \begin{minipage}{0.7\textwidth}
  17512. %% \begin{lstlisting}
  17513. %% (if (eq? |$e'_1$| (inject #f Boolean))
  17514. %% (inject #t Boolean) (inject #f Boolean))
  17515. %% \end{lstlisting}
  17516. %% \end{minipage}
  17517. %% \\[2ex]\hline
  17518. \\\hline
  17519. \end{tabular}
  17520. \fi}
  17521. \end{tcolorbox}
  17522. \caption{Cast insertion}
  17523. \label{fig:compile-r7-Lany}
  17524. \end{figure}
  17525. \section{Reveal Casts}
  17526. \label{sec:reveal-casts-Lany}
  17527. % TODO: define R'_6
  17528. In the \code{reveal\_casts} pass, we recommend compiling
  17529. \code{Project} into a conditional expression that checks whether the
  17530. value's tag matches the target type; if it does, the value is
  17531. converted to a value of the target type by removing the tag; if it
  17532. does not, the program exits.
  17533. %
  17534. {\if\edition\racketEd
  17535. %
  17536. To perform these actions we need a new primitive operation,
  17537. \code{tag-of-any}, and a new form, \code{ValueOf}.
  17538. The \code{tag-of-any} operation retrieves the type tag from a tagged
  17539. value of type \code{Any}. The \code{ValueOf} form retrieves the
  17540. underlying value from a tagged value. The \code{ValueOf} form
  17541. includes the type for the underlying value that is used by the type
  17542. checker.
  17543. %
  17544. \fi}
  17545. %
  17546. {\if\edition\pythonEd
  17547. %
  17548. To perform these actions we need two new AST classes: \code{TagOf} and
  17549. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  17550. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  17551. the underlying value from a tagged value. The \code{ValueOf}
  17552. operation includes the type for the underlying value which is used by
  17553. the type checker.
  17554. %
  17555. \fi}
  17556. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  17557. \code{Project} can be translated as follows.
  17558. \begin{center}
  17559. \begin{minipage}{1.0\textwidth}
  17560. {\if\edition\racketEd
  17561. \begin{lstlisting}
  17562. (Project |$e$| |$\FType$|)
  17563. |$\Rightarrow$|
  17564. (Let |$\itm{tmp}$| |$e'$|
  17565. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  17566. (Int |$\itm{tagof}(\FType)$|)))
  17567. (ValueOf |$\itm{tmp}$| |$\FType$|)
  17568. (Exit)))
  17569. \end{lstlisting}
  17570. \fi}
  17571. {\if\edition\pythonEd
  17572. \begin{lstlisting}
  17573. Project(|$e$|, |$\FType$|)
  17574. |$\Rightarrow$|
  17575. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  17576. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  17577. [Constant(|$\itm{tagof}(\FType)$|)]),
  17578. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  17579. Call(Name('exit'), [])))
  17580. \end{lstlisting}
  17581. \fi}
  17582. \end{minipage}
  17583. \end{center}
  17584. If the target type of the projection is a tuple or function type, then
  17585. there is a bit more work to do. For tuples, check that the length of
  17586. the tuple type matches the length of the tuple. For functions, check
  17587. that the number of parameters in the function type matches the
  17588. function's arity.
  17589. Regarding \code{Inject}, we recommend compiling it to a slightly
  17590. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17591. takes a tag instead of a type.
  17592. \begin{center}
  17593. \begin{minipage}{1.0\textwidth}
  17594. {\if\edition\racketEd
  17595. \begin{lstlisting}
  17596. (Inject |$e$| |$\FType$|)
  17597. |$\Rightarrow$|
  17598. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17599. \end{lstlisting}
  17600. \fi}
  17601. {\if\edition\pythonEd
  17602. \begin{lstlisting}
  17603. Inject(|$e$|, |$\FType$|)
  17604. |$\Rightarrow$|
  17605. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17606. \end{lstlisting}
  17607. \fi}
  17608. \end{minipage}
  17609. \end{center}
  17610. {\if\edition\pythonEd
  17611. %
  17612. The introduction of \code{make\_any} makes it difficult to use
  17613. bidirectional type checking because we no longer have an expected type
  17614. to use for type checking the expression $e'$. Thus, we run into
  17615. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17616. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17617. annotated lambda) whose parameters have type annotations and that
  17618. records the return type.
  17619. %
  17620. \fi}
  17621. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17622. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17623. translation of \code{Project}.}
  17624. {\if\edition\racketEd
  17625. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17626. combine the projection action with the vector operation. Also, the
  17627. read and write operations allow arbitrary expressions for the index, so
  17628. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17629. cannot guarantee that the index is within bounds. Thus, we insert code
  17630. to perform bounds checking at runtime. The translation for
  17631. \code{any-vector-ref} is as follows, and the other two operations are
  17632. translated in a similar way:
  17633. \begin{center}
  17634. \begin{minipage}{0.95\textwidth}
  17635. \begin{lstlisting}
  17636. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17637. |$\Rightarrow$|
  17638. (Let |$v$| |$e'_1$|
  17639. (Let |$i$| |$e'_2$|
  17640. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17641. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17642. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17643. (Exit))
  17644. (Exit))))
  17645. \end{lstlisting}
  17646. \end{minipage}
  17647. \end{center}
  17648. \fi}
  17649. %
  17650. {\if\edition\pythonEd
  17651. %
  17652. The \code{any\_tuple\_load} operation combines the projection action
  17653. with the load operation. Also, the load operation allows arbitrary
  17654. expressions for the index so the type checker for \LangAny{}
  17655. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17656. within bounds. Thus, we insert code to perform bounds checking at
  17657. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17658. \begin{lstlisting}
  17659. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17660. |$\Rightarrow$|
  17661. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17662. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17663. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17664. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17665. Call(Name('exit'), [])),
  17666. Call(Name('exit'), [])))
  17667. \end{lstlisting}
  17668. \fi}
  17669. {\if\edition\pythonEd
  17670. \section{Assignment Conversion}
  17671. \label{sec:convert-assignments-Lany}
  17672. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17673. \code{AnnLambda} AST classes.
  17674. \section{Closure Conversion}
  17675. \label{sec:closure-conversion-Lany}
  17676. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17677. \code{AnnLambda} AST classes.
  17678. \fi}
  17679. \section{Remove Complex Operands}
  17680. \label{sec:rco-Lany}
  17681. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17682. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17683. %
  17684. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17685. complex expressions. Their subexpressions must be atomic.}
  17686. \section{Explicate Control and \LangCAny{}}
  17687. \label{sec:explicate-Lany}
  17688. The output of \code{explicate\_control} is the \LangCAny{} language,
  17689. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17690. %
  17691. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17692. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17693. note that the index argument of \code{vector-ref} and
  17694. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17695. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17696. %
  17697. \python{
  17698. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17699. and \code{explicate\_pred} as appropriately to handle the new expressions
  17700. in \LangCAny{}.
  17701. }
  17702. \newcommand{\CanyASTPython}{
  17703. \begin{array}{lcl}
  17704. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17705. &\MID& \key{TagOf}\LP \Atm \RP
  17706. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17707. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17708. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17709. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17710. \end{array}
  17711. }
  17712. \newcommand{\CanyASTRacket}{
  17713. \begin{array}{lcl}
  17714. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17715. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17716. &\MID& \VALUEOF{\Atm}{\FType} \\
  17717. \Tail &::= & \LP\key{Exit}\RP
  17718. \end{array}
  17719. }
  17720. \begin{figure}[tp]
  17721. \begin{tcolorbox}[colback=white]
  17722. \small
  17723. {\if\edition\racketEd
  17724. \[
  17725. \begin{array}{l}
  17726. \gray{\CvarASTRacket} \\ \hline
  17727. \gray{\CifASTRacket} \\ \hline
  17728. \gray{\CloopASTRacket} \\ \hline
  17729. \gray{\CtupASTRacket} \\ \hline
  17730. \gray{\CfunASTRacket} \\ \hline
  17731. \gray{\ClambdaASTRacket} \\ \hline
  17732. \CanyASTRacket \\
  17733. \begin{array}{lcl}
  17734. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17735. \end{array}
  17736. \end{array}
  17737. \]
  17738. \fi}
  17739. {\if\edition\pythonEd
  17740. \[
  17741. \begin{array}{l}
  17742. \gray{\CifASTPython} \\ \hline
  17743. \gray{\CtupASTPython} \\ \hline
  17744. \gray{\CfunASTPython} \\ \hline
  17745. \gray{\ClambdaASTPython} \\ \hline
  17746. \CanyASTPython \\
  17747. \begin{array}{lcl}
  17748. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17749. \end{array}
  17750. \end{array}
  17751. \]
  17752. \fi}
  17753. \end{tcolorbox}
  17754. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17755. \label{fig:c5-syntax}
  17756. \end{figure}
  17757. \section{Select Instructions}
  17758. \label{sec:select-Lany}
  17759. In the \code{select\_instructions} pass, we translate the primitive
  17760. operations on the \ANYTY{} type to x86 instructions that manipulate
  17761. the three tag bits of the tagged value. In the following descriptions,
  17762. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17763. of translating $e$ into an x86 argument:
  17764. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17765. We recommend compiling the
  17766. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17767. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17768. shifts the destination to the left by the number of bits specified its
  17769. source argument (in this case three, the length of the tag), and it
  17770. preserves the sign of the integer. We use the \key{orq} instruction to
  17771. combine the tag and the value to form the tagged value. \\
  17772. %
  17773. {\if\edition\racketEd
  17774. \begin{lstlisting}
  17775. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17776. |$\Rightarrow$|
  17777. movq |$e'$|, |\itm{lhs'}|
  17778. salq $3, |\itm{lhs'}|
  17779. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17780. \end{lstlisting}
  17781. \fi}
  17782. %
  17783. {\if\edition\pythonEd
  17784. \begin{lstlisting}
  17785. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17786. |$\Rightarrow$|
  17787. movq |$e'$|, |\itm{lhs'}|
  17788. salq $3, |\itm{lhs'}|
  17789. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17790. \end{lstlisting}
  17791. \fi}
  17792. %
  17793. The instruction selection for tuples and procedures is different
  17794. because their is no need to shift them to the left. The rightmost 3
  17795. bits are already zeros, so we simply combine the value and the tag
  17796. using \key{orq}. \\
  17797. %
  17798. {\if\edition\racketEd
  17799. \begin{center}
  17800. \begin{minipage}{\textwidth}
  17801. \begin{lstlisting}
  17802. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17803. |$\Rightarrow$|
  17804. movq |$e'$|, |\itm{lhs'}|
  17805. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17806. \end{lstlisting}
  17807. \end{minipage}
  17808. \end{center}
  17809. \fi}
  17810. %
  17811. {\if\edition\pythonEd
  17812. \begin{lstlisting}
  17813. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17814. |$\Rightarrow$|
  17815. movq |$e'$|, |\itm{lhs'}|
  17816. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17817. \end{lstlisting}
  17818. \fi}
  17819. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  17820. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  17821. operation extracts the type tag from a value of type \ANYTY{}. The
  17822. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  17823. bitwise-and of the value with $111$ ($7$ decimal).
  17824. %
  17825. {\if\edition\racketEd
  17826. \begin{lstlisting}
  17827. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  17828. |$\Rightarrow$|
  17829. movq |$e'$|, |\itm{lhs'}|
  17830. andq $7, |\itm{lhs'}|
  17831. \end{lstlisting}
  17832. \fi}
  17833. %
  17834. {\if\edition\pythonEd
  17835. \begin{lstlisting}
  17836. Assign([|\itm{lhs}|], TagOf(|$e$|))
  17837. |$\Rightarrow$|
  17838. movq |$e'$|, |\itm{lhs'}|
  17839. andq $7, |\itm{lhs'}|
  17840. \end{lstlisting}
  17841. \fi}
  17842. \paragraph{\code{ValueOf}}
  17843. The instructions for \key{ValueOf} also differ, depending on whether
  17844. the type $T$ is a pointer (tuple or function) or not (integer or
  17845. Boolean). The following shows the instruction selection for integers
  17846. and Booleans, in which we produce an untagged value by shifting it to
  17847. the right by 3 bits:
  17848. %
  17849. {\if\edition\racketEd
  17850. \begin{lstlisting}
  17851. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17852. |$\Rightarrow$|
  17853. movq |$e'$|, |\itm{lhs'}|
  17854. sarq $3, |\itm{lhs'}|
  17855. \end{lstlisting}
  17856. \fi}
  17857. %
  17858. {\if\edition\pythonEd
  17859. \begin{lstlisting}
  17860. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17861. |$\Rightarrow$|
  17862. movq |$e'$|, |\itm{lhs'}|
  17863. sarq $3, |\itm{lhs'}|
  17864. \end{lstlisting}
  17865. \fi}
  17866. %
  17867. In the case for tuples and procedures, we zero out the rightmost 3
  17868. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  17869. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  17870. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  17871. Finally, we apply \code{andq} with the tagged value to get the desired
  17872. result.
  17873. %
  17874. {\if\edition\racketEd
  17875. \begin{lstlisting}
  17876. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17877. |$\Rightarrow$|
  17878. movq $|$-8$|, |\itm{lhs'}|
  17879. andq |$e'$|, |\itm{lhs'}|
  17880. \end{lstlisting}
  17881. \fi}
  17882. %
  17883. {\if\edition\pythonEd
  17884. \begin{lstlisting}
  17885. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17886. |$\Rightarrow$|
  17887. movq $|$-8$|, |\itm{lhs'}|
  17888. andq |$e'$|, |\itm{lhs'}|
  17889. \end{lstlisting}
  17890. \fi}
  17891. %% \paragraph{Type Predicates} We leave it to the reader to
  17892. %% devise a sequence of instructions to implement the type predicates
  17893. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  17894. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  17895. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  17896. operation combines the effect of \code{ValueOf} with accessing the
  17897. length of a tuple from the tag stored at the zero index of the tuple.
  17898. {\if\edition\racketEd
  17899. \begin{lstlisting}
  17900. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  17901. |$\Longrightarrow$|
  17902. movq $|$-8$|, %r11
  17903. andq |$e_1'$|, %r11
  17904. movq 0(%r11), %r11
  17905. andq $126, %r11
  17906. sarq $1, %r11
  17907. movq %r11, |$\itm{lhs'}$|
  17908. \end{lstlisting}
  17909. \fi}
  17910. {\if\edition\pythonEd
  17911. \begin{lstlisting}
  17912. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  17913. |$\Longrightarrow$|
  17914. movq $|$-8$|, %r11
  17915. andq |$e_1'$|, %r11
  17916. movq 0(%r11), %r11
  17917. andq $126, %r11
  17918. sarq $1, %r11
  17919. movq %r11, |$\itm{lhs'}$|
  17920. \end{lstlisting}
  17921. \fi}
  17922. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  17923. This operation combines the effect of \code{ValueOf} with reading an
  17924. element of the tuple (see
  17925. section~\ref{sec:select-instructions-gc}). However, the index may be
  17926. an arbitrary atom, so instead of computing the offset at compile time,
  17927. we must generate instructions to compute the offset at runtime as
  17928. follows. Note the use of the new instruction \code{imulq}.
  17929. \begin{center}
  17930. \begin{minipage}{0.96\textwidth}
  17931. {\if\edition\racketEd
  17932. \begin{lstlisting}
  17933. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17934. |$\Longrightarrow$|
  17935. movq |$\neg 111$|, %r11
  17936. andq |$e_1'$|, %r11
  17937. movq |$e_2'$|, %rax
  17938. addq $1, %rax
  17939. imulq $8, %rax
  17940. addq %rax, %r11
  17941. movq 0(%r11) |$\itm{lhs'}$|
  17942. \end{lstlisting}
  17943. \fi}
  17944. %
  17945. {\if\edition\pythonEd
  17946. \begin{lstlisting}
  17947. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  17948. |$\Longrightarrow$|
  17949. movq $|$-8$|, %r11
  17950. andq |$e_1'$|, %r11
  17951. movq |$e_2'$|, %rax
  17952. addq $1, %rax
  17953. imulq $8, %rax
  17954. addq %rax, %r11
  17955. movq 0(%r11) |$\itm{lhs'}$|
  17956. \end{lstlisting}
  17957. \fi}
  17958. \end{minipage}
  17959. \end{center}
  17960. % $ pacify font lock
  17961. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  17962. %% The code generation for
  17963. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  17964. %% analogous to the above translation for reading from a tuple.
  17965. \section{Register Allocation for \LangAny{}}
  17966. \label{sec:register-allocation-Lany}
  17967. \index{subject}{register allocation}
  17968. There is an interesting interaction between tagged values and garbage
  17969. collection that has an impact on register allocation. A variable of
  17970. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  17971. that needs to be inspected and copied during garbage collection. Thus,
  17972. we need to treat variables of type \ANYTY{} in a similar way to
  17973. variables of tuple type for purposes of register allocation,
  17974. with particular attention to the following:
  17975. \begin{itemize}
  17976. \item If a variable of type \ANYTY{} is live during a function call,
  17977. then it must be spilled. This can be accomplished by changing
  17978. \code{build\_interference} to mark all variables of type \ANYTY{}
  17979. that are live after a \code{callq} to be interfering with all the
  17980. registers.
  17981. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  17982. the root stack instead of the normal procedure call stack.
  17983. \end{itemize}
  17984. Another concern regarding the root stack is that the garbage collector
  17985. needs to differentiate among (1) plain old pointers to tuples, (2) a
  17986. tagged value that points to a tuple, and (3) a tagged value that is
  17987. not a tuple. We enable this differentiation by choosing not to use the
  17988. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  17989. reserved for identifying plain old pointers to tuples. That way, if
  17990. one of the first three bits is set, then we have a tagged value and
  17991. inspecting the tag can differentiate between tuples ($010$) and the
  17992. other kinds of values.
  17993. %% \begin{exercise}\normalfont
  17994. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  17995. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  17996. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  17997. %% compiler on these new programs and all of your previously created test
  17998. %% programs.
  17999. %% \end{exercise}
  18000. \begin{exercise}\normalfont\normalsize
  18001. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18002. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18003. by removing type annotations. Add five more test programs that
  18004. specifically rely on the language being dynamically typed. That is,
  18005. they should not be legal programs in a statically typed language, but
  18006. nevertheless they should be valid \LangDyn{} programs that run to
  18007. completion without error.
  18008. \end{exercise}
  18009. \begin{figure}[p]
  18010. \begin{tcolorbox}[colback=white]
  18011. {\if\edition\racketEd
  18012. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18013. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18014. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18015. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18016. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18017. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18018. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18019. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18020. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18021. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18022. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18023. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18024. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18025. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18026. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18027. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18028. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18029. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18030. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18031. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18032. \path[->,bend left=15] (Lfun) edge [above] node
  18033. {\ttfamily\footnotesize shrink} (Lfun-2);
  18034. \path[->,bend left=15] (Lfun-2) edge [above] node
  18035. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18036. \path[->,bend left=15] (Lfun-3) edge [above] node
  18037. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18038. \path[->,bend left=15] (Lfun-4) edge [left] node
  18039. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18040. \path[->,bend left=15] (Lfun-5) edge [below] node
  18041. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18042. \path[->,bend left=15] (Lfun-6) edge [below] node
  18043. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18044. \path[->,bend right=15] (Lfun-7) edge [above] node
  18045. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18046. \path[->,bend right=15] (F1-2) edge [right] node
  18047. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18048. \path[->,bend right=15] (F1-3) edge [below] node
  18049. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18050. \path[->,bend right=15] (F1-4) edge [below] node
  18051. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18052. \path[->,bend left=15] (F1-5) edge [above] node
  18053. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18054. \path[->,bend left=15] (F1-6) edge [below] node
  18055. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18056. \path[->,bend left=15] (C3-2) edge [right] node
  18057. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18058. \path[->,bend right=15] (x86-2) edge [right] node
  18059. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18060. \path[->,bend right=15] (x86-2-1) edge [below] node
  18061. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18062. \path[->,bend right=15] (x86-2-2) edge [right] node
  18063. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18064. \path[->,bend left=15] (x86-3) edge [above] node
  18065. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18066. \path[->,bend left=15] (x86-4) edge [right] node
  18067. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18068. \end{tikzpicture}
  18069. \fi}
  18070. {\if\edition\pythonEd
  18071. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18072. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18073. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18074. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18075. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18076. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18077. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18078. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18079. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18080. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18081. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18082. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18083. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18084. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18085. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18086. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18087. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18088. \path[->,bend left=15] (Lfun) edge [above] node
  18089. {\ttfamily\footnotesize shrink} (Lfun-2);
  18090. \path[->,bend left=15] (Lfun-2) edge [above] node
  18091. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18092. \path[->,bend left=15] (Lfun-3) edge [above] node
  18093. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18094. \path[->,bend left=15] (Lfun-4) edge [left] node
  18095. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18096. \path[->,bend left=15] (Lfun-5) edge [below] node
  18097. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18098. \path[->,bend right=15] (Lfun-6) edge [above] node
  18099. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18100. \path[->,bend right=15] (Lfun-7) edge [above] node
  18101. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18102. \path[->,bend right=15] (F1-2) edge [right] node
  18103. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18104. \path[->,bend right=15] (F1-3) edge [below] node
  18105. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18106. \path[->,bend left=15] (F1-5) edge [above] node
  18107. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18108. \path[->,bend left=15] (F1-6) edge [below] node
  18109. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18110. \path[->,bend right=15] (C3-2) edge [right] node
  18111. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18112. \path[->,bend right=15] (x86-2) edge [below] node
  18113. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18114. \path[->,bend right=15] (x86-3) edge [below] node
  18115. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18116. \path[->,bend left=15] (x86-4) edge [above] node
  18117. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18118. \end{tikzpicture}
  18119. \fi}
  18120. \end{tcolorbox}
  18121. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18122. \label{fig:Ldyn-passes}
  18123. \end{figure}
  18124. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18125. for the compilation of \LangDyn{}.
  18126. % Further Reading
  18127. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18128. %% {\if\edition\pythonEd
  18129. %% \chapter{Objects}
  18130. %% \label{ch:Lobject}
  18131. %% \index{subject}{objects}
  18132. %% \index{subject}{classes}
  18133. %% \setcounter{footnote}{0}
  18134. %% \fi}
  18135. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18136. \chapter{Gradual Typing}
  18137. \label{ch:Lgrad}
  18138. \index{subject}{gradual typing}
  18139. \setcounter{footnote}{0}
  18140. This chapter studies the language \LangGrad{}, in which the programmer
  18141. can choose between static and dynamic type checking in different parts
  18142. of a program, thereby mixing the statically typed \LangLam{} language
  18143. with the dynamically typed \LangDyn{}. There are several approaches to
  18144. mixing static and dynamic typing, including multilanguage
  18145. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18146. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18147. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18148. programmer controls the amount of static versus dynamic checking by
  18149. adding or removing type annotations on parameters and
  18150. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18151. The definition of the concrete syntax of \LangGrad{} is shown in
  18152. figure~\ref{fig:Lgrad-concrete-syntax} and the definition of its
  18153. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18154. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18155. annotations are optional, which is specified in the grammar using the
  18156. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18157. annotations are not optional, but we use the \CANYTY{} type when a type
  18158. annotation is absent.
  18159. %
  18160. Both the type checker and the interpreter for \LangGrad{} require some
  18161. interesting changes to enable gradual typing, which we discuss in the
  18162. next two sections.
  18163. \newcommand{\LgradGrammarRacket}{
  18164. \begin{array}{lcl}
  18165. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18166. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18167. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18168. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18169. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18170. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18171. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18172. \end{array}
  18173. }
  18174. \newcommand{\LgradASTRacket}{
  18175. \begin{array}{lcl}
  18176. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18177. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18178. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18179. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18180. \itm{op} &::=& \code{procedure-arity} \\
  18181. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18182. \end{array}
  18183. }
  18184. \newcommand{\LgradGrammarPython}{
  18185. \begin{array}{lcl}
  18186. \Type &::=& \key{Any}
  18187. \MID \key{int}
  18188. \MID \key{bool}
  18189. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18190. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18191. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18192. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18193. \MID \CARITY{\Exp} \\
  18194. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18195. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18196. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18197. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18198. \end{array}
  18199. }
  18200. \newcommand{\LgradASTPython}{
  18201. \begin{array}{lcl}
  18202. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18203. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18204. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18205. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18206. &\MID& \ARITY{\Exp} \\
  18207. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18208. \MID \RETURN{\Exp} \\
  18209. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18210. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18211. \end{array}
  18212. }
  18213. \begin{figure}[tp]
  18214. \centering
  18215. \begin{tcolorbox}[colback=white]
  18216. \small
  18217. {\if\edition\racketEd
  18218. \[
  18219. \begin{array}{l}
  18220. \gray{\LintGrammarRacket{}} \\ \hline
  18221. \gray{\LvarGrammarRacket{}} \\ \hline
  18222. \gray{\LifGrammarRacket{}} \\ \hline
  18223. \gray{\LwhileGrammarRacket} \\ \hline
  18224. \gray{\LtupGrammarRacket} \\ \hline
  18225. \LgradGrammarRacket \\
  18226. \begin{array}{lcl}
  18227. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18228. \end{array}
  18229. \end{array}
  18230. \]
  18231. \fi}
  18232. {\if\edition\pythonEd
  18233. \[
  18234. \begin{array}{l}
  18235. \gray{\LintGrammarPython{}} \\ \hline
  18236. \gray{\LvarGrammarPython{}} \\ \hline
  18237. \gray{\LifGrammarPython{}} \\ \hline
  18238. \gray{\LwhileGrammarPython} \\ \hline
  18239. \gray{\LtupGrammarPython} \\ \hline
  18240. \LgradGrammarPython \\
  18241. \begin{array}{lcl}
  18242. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18243. \end{array}
  18244. \end{array}
  18245. \]
  18246. \fi}
  18247. \end{tcolorbox}
  18248. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18249. \label{fig:Lgrad-concrete-syntax}
  18250. \end{figure}
  18251. \begin{figure}[tp]
  18252. \centering
  18253. \begin{tcolorbox}[colback=white]
  18254. \small
  18255. {\if\edition\racketEd
  18256. \[
  18257. \begin{array}{l}
  18258. \gray{\LintOpAST} \\ \hline
  18259. \gray{\LvarASTRacket{}} \\ \hline
  18260. \gray{\LifASTRacket{}} \\ \hline
  18261. \gray{\LwhileASTRacket{}} \\ \hline
  18262. \gray{\LtupASTRacket{}} \\ \hline
  18263. \LgradASTRacket \\
  18264. \begin{array}{lcl}
  18265. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18266. \end{array}
  18267. \end{array}
  18268. \]
  18269. \fi}
  18270. {\if\edition\pythonEd
  18271. \[
  18272. \begin{array}{l}
  18273. \gray{\LintASTPython{}} \\ \hline
  18274. \gray{\LvarASTPython{}} \\ \hline
  18275. \gray{\LifASTPython{}} \\ \hline
  18276. \gray{\LwhileASTPython} \\ \hline
  18277. \gray{\LtupASTPython} \\ \hline
  18278. \LgradASTPython \\
  18279. \begin{array}{lcl}
  18280. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18281. \end{array}
  18282. \end{array}
  18283. \]
  18284. \fi}
  18285. \end{tcolorbox}
  18286. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18287. \label{fig:Lgrad-syntax}
  18288. \end{figure}
  18289. % TODO: more road map -Jeremy
  18290. %\clearpage
  18291. \section{Type Checking \LangGrad{}}
  18292. \label{sec:gradual-type-check}
  18293. We begin by discussing the type checking of a partially typed variant
  18294. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18295. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18296. statically typed, so there is nothing special happening there with
  18297. respect to type checking. On the other hand, the \code{inc} function
  18298. does not have type annotations, so the type checker assigns the type
  18299. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18300. \code{+} operator inside \code{inc}. It expects both arguments to have
  18301. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18302. a gradually typed language, such differences are allowed so long as
  18303. the types are \emph{consistent}; that is, they are equal except in
  18304. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18305. is consistent with every other type. Figure~\ref{fig:consistent}
  18306. shows the definition of the
  18307. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18308. %
  18309. So the type checker allows the \code{+} operator to be applied
  18310. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18311. %
  18312. Next consider the call to the \code{map} function shown in
  18313. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18314. tuple. The \code{inc} function has type
  18315. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18316. but parameter \code{f} of \code{map} has type
  18317. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18318. The type checker for \LangGrad{} accepts this call because the two types are
  18319. consistent.
  18320. \begin{figure}[btp]
  18321. % gradual_test_9.rkt
  18322. \begin{tcolorbox}[colback=white]
  18323. {\if\edition\racketEd
  18324. \begin{lstlisting}
  18325. (define (map [f : (Integer -> Integer)]
  18326. [v : (Vector Integer Integer)])
  18327. : (Vector Integer Integer)
  18328. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18329. (define (inc x) (+ x 1))
  18330. (vector-ref (map inc (vector 0 41)) 1)
  18331. \end{lstlisting}
  18332. \fi}
  18333. {\if\edition\pythonEd
  18334. \begin{lstlisting}
  18335. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18336. return f(v[0]), f(v[1])
  18337. def inc(x):
  18338. return x + 1
  18339. t = map(inc, (0, 41))
  18340. print(t[1])
  18341. \end{lstlisting}
  18342. \fi}
  18343. \end{tcolorbox}
  18344. \caption{A partially typed version of the \code{map} example.}
  18345. \label{fig:gradual-map}
  18346. \end{figure}
  18347. \begin{figure}[tbp]
  18348. \begin{tcolorbox}[colback=white]
  18349. {\if\edition\racketEd
  18350. \begin{lstlisting}
  18351. (define/public (consistent? t1 t2)
  18352. (match* (t1 t2)
  18353. [('Integer 'Integer) #t]
  18354. [('Boolean 'Boolean) #t]
  18355. [('Void 'Void) #t]
  18356. [('Any t2) #t]
  18357. [(t1 'Any) #t]
  18358. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18359. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18360. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18361. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18362. (consistent? rt1 rt2))]
  18363. [(other wise) #f]))
  18364. \end{lstlisting}
  18365. \fi}
  18366. {\if\edition\pythonEd
  18367. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18368. def consistent(self, t1, t2):
  18369. match (t1, t2):
  18370. case (AnyType(), _):
  18371. return True
  18372. case (_, AnyType()):
  18373. return True
  18374. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18375. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18376. case (TupleType(ts1), TupleType(ts2)):
  18377. return all(map(self.consistent, ts1, ts2))
  18378. case (_, _):
  18379. return t1 == t2
  18380. \end{lstlisting}
  18381. \fi}
  18382. \end{tcolorbox}
  18383. \caption{The consistency method on types.}
  18384. \label{fig:consistent}
  18385. \end{figure}
  18386. It is also helpful to consider how gradual typing handles programs with an
  18387. error, such as applying \code{map} to a function that sometimes
  18388. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18389. type checker for \LangGrad{} accepts this program because the type of
  18390. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18391. \code{map}; that is,
  18392. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18393. is consistent with
  18394. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18395. One might say that a gradual type checker is optimistic in that it
  18396. accepts programs that might execute without a runtime type error.
  18397. %
  18398. The definition of the type checker for \LangGrad{} is shown in
  18399. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18400. and \ref{fig:type-check-Lgradual-3}.
  18401. %% \begin{figure}[tp]
  18402. %% \centering
  18403. %% \fbox{
  18404. %% \begin{minipage}{0.96\textwidth}
  18405. %% \small
  18406. %% \[
  18407. %% \begin{array}{lcl}
  18408. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18409. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18410. %% \end{array}
  18411. %% \]
  18412. %% \end{minipage}
  18413. %% }
  18414. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18415. %% \label{fig:Lgrad-prime-syntax}
  18416. %% \end{figure}
  18417. \begin{figure}[tbp]
  18418. \begin{tcolorbox}[colback=white]
  18419. {\if\edition\racketEd
  18420. \begin{lstlisting}
  18421. (define (map [f : (Integer -> Integer)]
  18422. [v : (Vector Integer Integer)])
  18423. : (Vector Integer Integer)
  18424. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18425. (define (inc x) (+ x 1))
  18426. (define (true) #t)
  18427. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18428. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18429. \end{lstlisting}
  18430. \fi}
  18431. {\if\edition\pythonEd
  18432. \begin{lstlisting}
  18433. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18434. return f(v[0]), f(v[1])
  18435. def inc(x):
  18436. return x + 1
  18437. def true():
  18438. return True
  18439. def maybe_inc(x):
  18440. return inc(x) if input_int() == 0 else true()
  18441. t = map(maybe_inc, (0, 41))
  18442. print( t[1] )
  18443. \end{lstlisting}
  18444. \fi}
  18445. \end{tcolorbox}
  18446. \caption{A variant of the \code{map} example with an error.}
  18447. \label{fig:map-maybe_inc}
  18448. \end{figure}
  18449. Running this program with input \code{1} triggers an
  18450. error when the \code{maybe\_inc} function returns
  18451. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18452. performs checking at runtime to ensure the integrity of the static
  18453. types, such as the
  18454. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18455. annotation on
  18456. parameter \code{f} of \code{map}.
  18457. Here we give a preview of how the runtime checking is accomplished;
  18458. the following sections provide the details.
  18459. The runtime checking is carried out by a new \code{Cast} AST node that
  18460. is generated in a new pass named \code{cast\_insert}. The output of
  18461. \code{cast\_insert} is a program in the \LangCast{} language, which
  18462. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18463. %
  18464. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18465. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18466. inserted every time the type checker encounters two types that are
  18467. consistent but not equal. In the \code{inc} function, \code{x} is
  18468. cast to \INTTY{} and the result of the \code{+} is cast to
  18469. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18470. is cast from
  18471. \racket{\code{(Any -> Any)}}
  18472. \python{\code{Callable[[Any], Any]}}
  18473. to
  18474. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18475. %
  18476. In the next section we see how to interpret the \code{Cast} node.
  18477. \begin{figure}[btp]
  18478. \begin{tcolorbox}[colback=white]
  18479. {\if\edition\racketEd
  18480. \begin{lstlisting}
  18481. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  18482. : (Vector Integer Integer)
  18483. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18484. (define (inc [x : Any]) : Any
  18485. (cast (+ (cast x Any Integer) 1) Integer Any))
  18486. (define (true) : Any (cast #t Boolean Any))
  18487. (define (maybe_inc [x : Any]) : Any
  18488. (if (eq? 0 (read)) (inc x) (true)))
  18489. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  18490. (vector 0 41)) 0)
  18491. \end{lstlisting}
  18492. \fi}
  18493. {\if\edition\pythonEd
  18494. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18495. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18496. return f(v[0]), f(v[1])
  18497. def inc(x : Any) -> Any:
  18498. return Cast(Cast(x, Any, int) + 1, int, Any)
  18499. def true() -> Any:
  18500. return Cast(True, bool, Any)
  18501. def maybe_inc(x : Any) -> Any:
  18502. return inc(x) if input_int() == 0 else true()
  18503. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  18504. (0, 41))
  18505. print(t[1])
  18506. \end{lstlisting}
  18507. \fi}
  18508. \end{tcolorbox}
  18509. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  18510. and \code{maybe\_inc} example.}
  18511. \label{fig:map-cast}
  18512. \end{figure}
  18513. {\if\edition\pythonEd
  18514. \begin{figure}[tbp]
  18515. \begin{tcolorbox}[colback=white]
  18516. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18517. class TypeCheckLgrad(TypeCheckLlambda):
  18518. def type_check_exp(self, e, env) -> Type:
  18519. match e:
  18520. case Name(id):
  18521. return env[id]
  18522. case Constant(value) if isinstance(value, bool):
  18523. return BoolType()
  18524. case Constant(value) if isinstance(value, int):
  18525. return IntType()
  18526. case Call(Name('input_int'), []):
  18527. return IntType()
  18528. case BinOp(left, op, right):
  18529. left_type = self.type_check_exp(left, env)
  18530. self.check_consistent(left_type, IntType(), left)
  18531. right_type = self.type_check_exp(right, env)
  18532. self.check_consistent(right_type, IntType(), right)
  18533. return IntType()
  18534. case IfExp(test, body, orelse):
  18535. test_t = self.type_check_exp(test, env)
  18536. self.check_consistent(test_t, BoolType(), test)
  18537. body_t = self.type_check_exp(body, env)
  18538. orelse_t = self.type_check_exp(orelse, env)
  18539. self.check_consistent(body_t, orelse_t, e)
  18540. return self.join_types(body_t, orelse_t)
  18541. case Call(func, args):
  18542. func_t = self.type_check_exp(func, env)
  18543. args_t = [self.type_check_exp(arg, env) for arg in args]
  18544. match func_t:
  18545. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  18546. for (arg_t, param_t) in zip(args_t, params_t):
  18547. self.check_consistent(param_t, arg_t, e)
  18548. return return_t
  18549. case AnyType():
  18550. return AnyType()
  18551. case _:
  18552. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  18553. ...
  18554. case _:
  18555. raise Exception('type_check_exp: unexpected ' + repr(e))
  18556. \end{lstlisting}
  18557. \end{tcolorbox}
  18558. \caption{Type checking expressions in the \LangGrad{} language.}
  18559. \label{fig:type-check-Lgradual-1}
  18560. \end{figure}
  18561. \begin{figure}[tbp]
  18562. \begin{tcolorbox}[colback=white]
  18563. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18564. def check_exp(self, e, expected_ty, env):
  18565. match e:
  18566. case Lambda(params, body):
  18567. match expected_ty:
  18568. case FunctionType(params_t, return_t):
  18569. new_env = env.copy().update(zip(params, params_t))
  18570. e.has_type = expected_ty
  18571. body_ty = self.type_check_exp(body, new_env)
  18572. self.check_consistent(body_ty, return_t)
  18573. case AnyType():
  18574. new_env = env.copy().update((p, AnyType()) for p in params)
  18575. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  18576. body_ty = self.type_check_exp(body, new_env)
  18577. case _:
  18578. raise Exception('lambda does not have type ' + str(expected_ty))
  18579. case _:
  18580. e_ty = self.type_check_exp(e, env)
  18581. self.check_consistent(e_ty, expected_ty, e)
  18582. \end{lstlisting}
  18583. \end{tcolorbox}
  18584. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  18585. \label{fig:type-check-Lgradual-2}
  18586. \end{figure}
  18587. \begin{figure}[tbp]
  18588. \begin{tcolorbox}[colback=white]
  18589. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18590. def type_check_stmt(self, s, env, return_type):
  18591. match s:
  18592. case Assign([Name(id)], value):
  18593. value_ty = self.type_check_exp(value, env)
  18594. if id in env:
  18595. self.check_consistent(env[id], value_ty, value)
  18596. else:
  18597. env[id] = value_ty
  18598. ...
  18599. case _:
  18600. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18601. def type_check_stmts(self, ss, env, return_type):
  18602. for s in ss:
  18603. self.type_check_stmt(s, env, return_type)
  18604. \end{lstlisting}
  18605. \end{tcolorbox}
  18606. \caption{Type checking statements in the \LangGrad{} language.}
  18607. \label{fig:type-check-Lgradual-3}
  18608. \end{figure}
  18609. \begin{figure}[tbp]
  18610. \begin{tcolorbox}[colback=white]
  18611. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18612. def join_types(self, t1, t2):
  18613. match (t1, t2):
  18614. case (AnyType(), _):
  18615. return t2
  18616. case (_, AnyType()):
  18617. return t1
  18618. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18619. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18620. self.join_types(rt1,rt2))
  18621. case (TupleType(ts1), TupleType(ts2)):
  18622. return TupleType(list(map(self.join_types, ts1, ts2)))
  18623. case (_, _):
  18624. return t1
  18625. def check_consistent(self, t1, t2, e):
  18626. if not self.consistent(t1, t2):
  18627. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18628. + ' in ' + repr(e))
  18629. \end{lstlisting}
  18630. \end{tcolorbox}
  18631. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18632. \label{fig:type-check-Lgradual-aux}
  18633. \end{figure}
  18634. \fi}
  18635. {\if\edition\racketEd
  18636. \begin{figure}[tbp]
  18637. \begin{tcolorbox}[colback=white]
  18638. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18639. (define/override (type-check-exp env)
  18640. (lambda (e)
  18641. (define recur (type-check-exp env))
  18642. (match e
  18643. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18644. (define-values (new-es ts)
  18645. (for/lists (exprs types) ([e es])
  18646. (recur e)))
  18647. (define t-ret (type-check-op op ts e))
  18648. (values (Prim op new-es) t-ret)]
  18649. [(Prim 'eq? (list e1 e2))
  18650. (define-values (e1^ t1) (recur e1))
  18651. (define-values (e2^ t2) (recur e2))
  18652. (check-consistent? t1 t2 e)
  18653. (define T (meet t1 t2))
  18654. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18655. [(Prim 'and (list e1 e2))
  18656. (recur (If e1 e2 (Bool #f)))]
  18657. [(Prim 'or (list e1 e2))
  18658. (define tmp (gensym 'tmp))
  18659. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18660. [(If e1 e2 e3)
  18661. (define-values (e1^ T1) (recur e1))
  18662. (define-values (e2^ T2) (recur e2))
  18663. (define-values (e3^ T3) (recur e3))
  18664. (check-consistent? T1 'Boolean e)
  18665. (check-consistent? T2 T3 e)
  18666. (define Tif (meet T2 T3))
  18667. (values (If e1^ e2^ e3^) Tif)]
  18668. [(SetBang x e1)
  18669. (define-values (e1^ T1) (recur e1))
  18670. (define varT (dict-ref env x))
  18671. (check-consistent? T1 varT e)
  18672. (values (SetBang x e1^) 'Void)]
  18673. [(WhileLoop e1 e2)
  18674. (define-values (e1^ T1) (recur e1))
  18675. (check-consistent? T1 'Boolean e)
  18676. (define-values (e2^ T2) ((type-check-exp env) e2))
  18677. (values (WhileLoop e1^ e2^) 'Void)]
  18678. [(Prim 'vector-length (list e1))
  18679. (define-values (e1^ t) (recur e1))
  18680. (match t
  18681. [`(Vector ,ts ...)
  18682. (values (Prim 'vector-length (list e1^)) 'Integer)]
  18683. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  18684. \end{lstlisting}
  18685. \end{tcolorbox}
  18686. \caption{Type checker for the \LangGrad{} language, part 1.}
  18687. \label{fig:type-check-Lgradual-1}
  18688. \end{figure}
  18689. \begin{figure}[tbp]
  18690. \begin{tcolorbox}[colback=white]
  18691. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18692. [(Prim 'vector-ref (list e1 e2))
  18693. (define-values (e1^ t1) (recur e1))
  18694. (define-values (e2^ t2) (recur e2))
  18695. (check-consistent? t2 'Integer e)
  18696. (match t1
  18697. [`(Vector ,ts ...)
  18698. (match e2^
  18699. [(Int i)
  18700. (unless (and (0 . <= . i) (i . < . (length ts)))
  18701. (error 'type-check "invalid index ~a in ~a" i e))
  18702. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  18703. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  18704. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  18705. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18706. [(Prim 'vector-set! (list e1 e2 e3) )
  18707. (define-values (e1^ t1) (recur e1))
  18708. (define-values (e2^ t2) (recur e2))
  18709. (define-values (e3^ t3) (recur e3))
  18710. (check-consistent? t2 'Integer e)
  18711. (match t1
  18712. [`(Vector ,ts ...)
  18713. (match e2^
  18714. [(Int i)
  18715. (unless (and (0 . <= . i) (i . < . (length ts)))
  18716. (error 'type-check "invalid index ~a in ~a" i e))
  18717. (check-consistent? (list-ref ts i) t3 e)
  18718. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  18719. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  18720. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  18721. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18722. [(Apply e1 e2s)
  18723. (define-values (e1^ T1) (recur e1))
  18724. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18725. (match T1
  18726. [`(,T1ps ... -> ,T1rt)
  18727. (for ([T2 T2s] [Tp T1ps])
  18728. (check-consistent? T2 Tp e))
  18729. (values (Apply e1^ e2s^) T1rt)]
  18730. [`Any (values (Apply e1^ e2s^) 'Any)]
  18731. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18732. [(Lambda params Tr e1)
  18733. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18734. (match p
  18735. [`[,x : ,T] (values x T)]
  18736. [(? symbol? x) (values x 'Any)])))
  18737. (define-values (e1^ T1)
  18738. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18739. (check-consistent? Tr T1 e)
  18740. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  18741. `(,@Ts -> ,Tr))]
  18742. [else ((super type-check-exp env) e)]
  18743. )))
  18744. \end{lstlisting}
  18745. \end{tcolorbox}
  18746. \caption{Type checker for the \LangGrad{} language, part 2.}
  18747. \label{fig:type-check-Lgradual-2}
  18748. \end{figure}
  18749. \begin{figure}[tbp]
  18750. \begin{tcolorbox}[colback=white]
  18751. \begin{lstlisting}
  18752. (define/override (type-check-def env)
  18753. (lambda (e)
  18754. (match e
  18755. [(Def f params rt info body)
  18756. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  18757. (match p
  18758. [`[,x : ,T] (values x T)]
  18759. [(? symbol? x) (values x 'Any)])))
  18760. (define new-env (append (map cons xs ps) env))
  18761. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18762. (check-consistent? ty^ rt e)
  18763. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  18764. [else (error 'type-check "ill-formed function definition ~a" e)]
  18765. )))
  18766. (define/override (type-check-program e)
  18767. (match e
  18768. [(Program info body)
  18769. (define-values (body^ ty) ((type-check-exp '()) body))
  18770. (check-consistent? ty 'Integer e)
  18771. (ProgramDefsExp info '() body^)]
  18772. [(ProgramDefsExp info ds body)
  18773. (define new-env (for/list ([d ds])
  18774. (cons (Def-name d) (fun-def-type d))))
  18775. (define ds^ (for/list ([d ds])
  18776. ((type-check-def new-env) d)))
  18777. (define-values (body^ ty) ((type-check-exp new-env) body))
  18778. (check-consistent? ty 'Integer e)
  18779. (ProgramDefsExp info ds^ body^)]
  18780. [else (super type-check-program e)]))
  18781. \end{lstlisting}
  18782. \end{tcolorbox}
  18783. \caption{Type checker for the \LangGrad{} language, part 3.}
  18784. \label{fig:type-check-Lgradual-3}
  18785. \end{figure}
  18786. \begin{figure}[tbp]
  18787. \begin{tcolorbox}[colback=white]
  18788. \begin{lstlisting}
  18789. (define/public (join t1 t2)
  18790. (match* (t1 t2)
  18791. [('Integer 'Integer) 'Integer]
  18792. [('Boolean 'Boolean) 'Boolean]
  18793. [('Void 'Void) 'Void]
  18794. [('Any t2) t2]
  18795. [(t1 'Any) t1]
  18796. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18797. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  18798. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18799. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  18800. -> ,(join rt1 rt2))]))
  18801. (define/public (meet t1 t2)
  18802. (match* (t1 t2)
  18803. [('Integer 'Integer) 'Integer]
  18804. [('Boolean 'Boolean) 'Boolean]
  18805. [('Void 'Void) 'Void]
  18806. [('Any t2) 'Any]
  18807. [(t1 'Any) 'Any]
  18808. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18809. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  18810. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18811. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  18812. -> ,(meet rt1 rt2))]))
  18813. (define/public (check-consistent? t1 t2 e)
  18814. (unless (consistent? t1 t2)
  18815. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  18816. (define explicit-prim-ops
  18817. (set-union
  18818. (type-predicates)
  18819. (set 'procedure-arity 'eq? 'not 'and 'or
  18820. 'vector 'vector-length 'vector-ref 'vector-set!
  18821. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  18822. (define/override (fun-def-type d)
  18823. (match d
  18824. [(Def f params rt info body)
  18825. (define ps
  18826. (for/list ([p params])
  18827. (match p
  18828. [`[,x : ,T] T]
  18829. [(? symbol?) 'Any]
  18830. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  18831. `(,@ps -> ,rt)]
  18832. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  18833. \end{lstlisting}
  18834. \end{tcolorbox}
  18835. \caption{Auxiliary functions for type checking \LangGrad{}.}
  18836. \label{fig:type-check-Lgradual-aux}
  18837. \end{figure}
  18838. \fi}
  18839. \clearpage
  18840. \section{Interpreting \LangCast{}}
  18841. \label{sec:interp-casts}
  18842. The runtime behavior of casts involving simple types such as
  18843. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  18844. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  18845. \code{Inject} operator of \LangAny{}, which puts the integer into a
  18846. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  18847. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  18848. operator, by checking the value's tag and either retrieving
  18849. the underlying integer or signaling an error if the tag is not the
  18850. one for integers (figure~\ref{fig:interp-Lany-aux}).
  18851. %
  18852. Things get more interesting with casts involving
  18853. \racket{function and tuple types}\python{function, tuple, and array types}.
  18854. Consider the cast of the function \code{maybe\_inc} from
  18855. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  18856. to
  18857. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  18858. shown in figure~\ref{fig:map-maybe_inc}.
  18859. When the \code{maybe\_inc} function flows through
  18860. this cast at runtime, we don't know whether it will return
  18861. an integer, because that depends on the input from the user.
  18862. The \LangCast{} interpreter therefore delays the checking
  18863. of the cast until the function is applied. To do so it
  18864. wraps \code{maybe\_inc} in a new function that casts its parameter
  18865. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  18866. casts the return value from \CANYTY{} to \INTTY{}.
  18867. {\if\edition\pythonEd
  18868. %
  18869. There are further complications regarding casts on mutable data
  18870. such as the \code{list} type introduced in
  18871. the challenge assignment of section~\ref{sec:arrays}.
  18872. %
  18873. \fi}
  18874. %
  18875. Consider the example presented in figure~\ref{fig:map-bang} that
  18876. defines a partially typed version of \code{map} whose parameter
  18877. \code{v} has type
  18878. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  18879. and that updates \code{v} in place
  18880. instead of returning a new tuple. So, we name this function
  18881. \code{map\_inplace}. We apply \code{map\_inplace} to an
  18882. \racket{tuple}\python{array} of integers, so the type checker inserts a
  18883. cast from
  18884. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  18885. to
  18886. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  18887. A naive way for the \LangCast{} interpreter to cast between
  18888. \racket{tuple}\python{array} types would be a build a new
  18889. \racket{tuple}\python{array}
  18890. whose elements are the result
  18891. of casting each of the original elements to the appropriate target
  18892. type.
  18893. However, this approach is not valid for mutable data structures.
  18894. In the example of figure~\ref{fig:map-bang},
  18895. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  18896. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  18897. the original one.
  18898. \begin{figure}[tbp]
  18899. \begin{tcolorbox}[colback=white]
  18900. % gradual_test_11.rkt
  18901. {\if\edition\racketEd
  18902. \begin{lstlisting}
  18903. (define (map_inplace [f : (Any -> Any)]
  18904. [v : (Vector Any Any)]) : Void
  18905. (begin
  18906. (vector-set! v 0 (f (vector-ref v 0)))
  18907. (vector-set! v 1 (f (vector-ref v 1)))))
  18908. (define (inc x) (+ x 1))
  18909. (let ([v (vector 0 41)])
  18910. (begin (map_inplace inc v) (vector-ref v 1)))
  18911. \end{lstlisting}
  18912. \fi}
  18913. {\if\edition\pythonEd
  18914. \begin{lstlisting}
  18915. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  18916. i = 0
  18917. while i != len(v):
  18918. v[i] = f(v[i])
  18919. i = i + 1
  18920. def inc(x : int) -> int:
  18921. return x + 1
  18922. v = [0, 41]
  18923. map_inplace(inc, v)
  18924. print( v[1] )
  18925. \end{lstlisting}
  18926. \fi}
  18927. \end{tcolorbox}
  18928. \caption{An example involving casts on arrays.}
  18929. \label{fig:map-bang}
  18930. \end{figure}
  18931. Instead the interpreter needs to create a new kind of value, a
  18932. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  18933. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  18934. and then applies a
  18935. cast to the resulting value. On a write, the proxy casts the argument
  18936. value and then performs the write to the underlying \racket{tuple}\python{array}.
  18937. \racket{
  18938. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  18939. \code{0} from \INTTY{} to \CANYTY{}.
  18940. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  18941. from \CANYTY{} to \INTTY{}.
  18942. }
  18943. \python{
  18944. For the subscript \code{v[i]} in \code{f([v[i])} of \code{map\_inplace},
  18945. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  18946. For the subscript on the left of the assignment,
  18947. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  18948. }
  18949. The final category of cast that we need to consider consist of casts between
  18950. the \CANYTY{} type and higher-order types such as functions and
  18951. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  18952. variant of \code{map\_inplace} in which parameter \code{v} does not
  18953. have a type annotation, so it is given type \CANYTY{}. In the call to
  18954. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  18955. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  18956. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  18957. \code{Inject}, but that doesn't work because
  18958. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  18959. a flat type. Instead, we must first cast to
  18960. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  18961. and then inject to \CANYTY{}.
  18962. \begin{figure}[tbp]
  18963. \begin{tcolorbox}[colback=white]
  18964. {\if\edition\racketEd
  18965. \begin{lstlisting}
  18966. (define (map_inplace [f : (Any -> Any)] v) : Void
  18967. (begin
  18968. (vector-set! v 0 (f (vector-ref v 0)))
  18969. (vector-set! v 1 (f (vector-ref v 1)))))
  18970. (define (inc x) (+ x 1))
  18971. (let ([v (vector 0 41)])
  18972. (begin (map_inplace inc v) (vector-ref v 1)))
  18973. \end{lstlisting}
  18974. \fi}
  18975. {\if\edition\pythonEd
  18976. \begin{lstlisting}
  18977. def map_inplace(f : Callable[[Any], Any], v) -> None:
  18978. i = 0
  18979. while i != len(v):
  18980. v[i] = f(v[i])
  18981. i = i + 1
  18982. def inc(x):
  18983. return x + 1
  18984. v = [0, 41]
  18985. map_inplace(inc, v)
  18986. print( v[1] )
  18987. \end{lstlisting}
  18988. \fi}
  18989. \end{tcolorbox}
  18990. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  18991. \label{fig:map-any}
  18992. \end{figure}
  18993. \begin{figure}[tbp]
  18994. \begin{tcolorbox}[colback=white]
  18995. {\if\edition\racketEd
  18996. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18997. (define/public (apply_cast v s t)
  18998. (match* (s t)
  18999. [(t1 t2) #:when (equal? t1 t2) v]
  19000. [('Any t2)
  19001. (match t2
  19002. [`(,ts ... -> ,rt)
  19003. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19004. (define v^ (apply-project v any->any))
  19005. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19006. [`(Vector ,ts ...)
  19007. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19008. (define v^ (apply-project v vec-any))
  19009. (apply_cast v^ vec-any `(Vector ,@ts))]
  19010. [else (apply-project v t2)])]
  19011. [(t1 'Any)
  19012. (match t1
  19013. [`(,ts ... -> ,rt)
  19014. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19015. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19016. (apply-inject v^ (any-tag any->any))]
  19017. [`(Vector ,ts ...)
  19018. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19019. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19020. (apply-inject v^ (any-tag vec-any))]
  19021. [else (apply-inject v (any-tag t1))])]
  19022. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19023. (define x (gensym 'x))
  19024. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19025. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19026. (define cast-writes
  19027. (for/list ([t1 ts1] [t2 ts2])
  19028. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19029. `(vector-proxy ,(vector v (apply vector cast-reads)
  19030. (apply vector cast-writes)))]
  19031. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19032. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19033. `(function ,xs ,(Cast
  19034. (Apply (Value v)
  19035. (for/list ([x xs][t1 ts1][t2 ts2])
  19036. (Cast (Var x) t2 t1)))
  19037. rt1 rt2) ())]
  19038. ))
  19039. \end{lstlisting}
  19040. \fi}
  19041. {\if\edition\pythonEd
  19042. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19043. def apply_cast(self, value, src, tgt):
  19044. match (src, tgt):
  19045. case (AnyType(), FunctionType(ps2, rt2)):
  19046. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19047. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19048. case (AnyType(), TupleType(ts2)):
  19049. anytup = TupleType([AnyType() for t1 in ts2])
  19050. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19051. case (AnyType(), ListType(t2)):
  19052. anylist = ListType([AnyType() for t1 in ts2])
  19053. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19054. case (AnyType(), AnyType()):
  19055. return value
  19056. case (AnyType(), _):
  19057. return self.apply_project(value, tgt)
  19058. case (FunctionType(ps1,rt1), AnyType()):
  19059. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19060. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19061. case (TupleType(ts1), AnyType()):
  19062. anytup = TupleType([AnyType() for t1 in ts1])
  19063. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19064. case (ListType(t1), AnyType()):
  19065. anylist = ListType(AnyType())
  19066. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19067. case (_, AnyType()):
  19068. return self.apply_inject(value, src)
  19069. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19070. params = [generate_name('x') for p in ps2]
  19071. args = [Cast(Name(x), t2, t1)
  19072. for (x,t1,t2) in zip(params, ps1, ps2)]
  19073. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19074. return Function('cast', params, [Return(body)], {})
  19075. case (TupleType(ts1), TupleType(ts2)):
  19076. x = generate_name('x')
  19077. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19078. for (t1,t2) in zip(ts1,ts2)]
  19079. return ProxiedTuple(value, reads)
  19080. case (ListType(t1), ListType(t2)):
  19081. x = generate_name('x')
  19082. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19083. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19084. return ProxiedList(value, read, write)
  19085. case (t1, t2) if t1 == t2:
  19086. return value
  19087. case (t1, t2):
  19088. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19089. def apply_inject(self, value, src):
  19090. return Tagged(value, self.type_to_tag(src))
  19091. def apply_project(self, value, tgt):
  19092. match value:
  19093. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19094. return val
  19095. case _:
  19096. raise Exception('apply_project, unexpected ' + repr(value))
  19097. \end{lstlisting}
  19098. \fi}
  19099. \end{tcolorbox}
  19100. \caption{The \code{apply\_cast} auxiliary method.}
  19101. \label{fig:apply_cast}
  19102. \end{figure}
  19103. The \LangCast{} interpreter uses an auxiliary function named
  19104. \code{apply\_cast} to cast a value from a source type to a target type,
  19105. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19106. the kinds of casts that we've discussed in this section.
  19107. %
  19108. The definition of the interpreter for \LangCast{} is shown in
  19109. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19110. dispatching to \code{apply\_cast}.
  19111. \racket{To handle the addition of tuple
  19112. proxies, we update the tuple primitives in \code{interp-op} using the
  19113. functions given in figure~\ref{fig:guarded-tuple}.}
  19114. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19115. \begin{figure}[tbp]
  19116. \begin{tcolorbox}[colback=white]
  19117. {\if\edition\racketEd
  19118. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19119. (define interp-Lcast-class
  19120. (class interp-Llambda-class
  19121. (super-new)
  19122. (inherit apply-fun apply-inject apply-project)
  19123. (define/override (interp-op op)
  19124. (match op
  19125. ['vector-length guarded-vector-length]
  19126. ['vector-ref guarded-vector-ref]
  19127. ['vector-set! guarded-vector-set!]
  19128. ['any-vector-ref (lambda (v i)
  19129. (match v [`(tagged ,v^ ,tg)
  19130. (guarded-vector-ref v^ i)]))]
  19131. ['any-vector-set! (lambda (v i a)
  19132. (match v [`(tagged ,v^ ,tg)
  19133. (guarded-vector-set! v^ i a)]))]
  19134. ['any-vector-length (lambda (v)
  19135. (match v [`(tagged ,v^ ,tg)
  19136. (guarded-vector-length v^)]))]
  19137. [else (super interp-op op)]
  19138. ))
  19139. (define/override ((interp-exp env) e)
  19140. (define (recur e) ((interp-exp env) e))
  19141. (match e
  19142. [(Value v) v]
  19143. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19144. [else ((super interp-exp env) e)]))
  19145. ))
  19146. (define (interp-Lcast p)
  19147. (send (new interp-Lcast-class) interp-program p))
  19148. \end{lstlisting}
  19149. \fi}
  19150. {\if\edition\pythonEd
  19151. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19152. class InterpLcast(InterpLany):
  19153. def interp_exp(self, e, env):
  19154. match e:
  19155. case Cast(value, src, tgt):
  19156. v = self.interp_exp(value, env)
  19157. return self.apply_cast(v, src, tgt)
  19158. case ValueExp(value):
  19159. return value
  19160. ...
  19161. case _:
  19162. return super().interp_exp(e, env)
  19163. \end{lstlisting}
  19164. \fi}
  19165. \end{tcolorbox}
  19166. \caption{The interpreter for \LangCast{}.}
  19167. \label{fig:interp-Lcast}
  19168. \end{figure}
  19169. {\if\edition\racketEd
  19170. \begin{figure}[tbp]
  19171. \begin{tcolorbox}[colback=white]
  19172. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19173. (define (guarded-vector-ref vec i)
  19174. (match vec
  19175. [`(vector-proxy ,proxy)
  19176. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19177. (define rd (vector-ref (vector-ref proxy 1) i))
  19178. (apply-fun rd (list val) 'guarded-vector-ref)]
  19179. [else (vector-ref vec i)]))
  19180. (define (guarded-vector-set! vec i arg)
  19181. (match vec
  19182. [`(vector-proxy ,proxy)
  19183. (define wr (vector-ref (vector-ref proxy 2) i))
  19184. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19185. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19186. [else (vector-set! vec i arg)]))
  19187. (define (guarded-vector-length vec)
  19188. (match vec
  19189. [`(vector-proxy ,proxy)
  19190. (guarded-vector-length (vector-ref proxy 0))]
  19191. [else (vector-length vec)]))
  19192. \end{lstlisting}
  19193. %% {\if\edition\pythonEd
  19194. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19195. %% UNDER CONSTRUCTION
  19196. %% \end{lstlisting}
  19197. %% \fi}
  19198. \end{tcolorbox}
  19199. \caption{The \code{guarded-vector} auxiliary functions.}
  19200. \label{fig:guarded-tuple}
  19201. \end{figure}
  19202. \fi}
  19203. {\if\edition\pythonEd
  19204. \section{Overload Resolution}
  19205. \label{sec:gradual-resolution}
  19206. Recall that when we added support for arrays in
  19207. section~\ref{sec:arrays}, the syntax for the array operations were the
  19208. same as for tuple operations (e.g., accessing an element, getting the
  19209. length). So we performed overload resolution, with a pass named
  19210. \code{resolve}, to separate the array and tuple operations. In
  19211. particular, we introduced the primitives \code{array\_load},
  19212. \code{array\_store}, and \code{array\_len}.
  19213. For gradual typing, we further overload these operators to work on
  19214. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19215. updated with new cases for the \CANYTY{} type, translating the element
  19216. access and length operations to the primitives \code{any\_load},
  19217. \code{any\_store}, and \code{any\_len}.
  19218. \fi}
  19219. \section{Cast Insertion}
  19220. \label{sec:gradual-insert-casts}
  19221. In our discussion of type checking of \LangGrad{}, we mentioned how
  19222. the runtime aspect of type checking is carried out by the \code{Cast}
  19223. AST node, which is added to the program by a new pass named
  19224. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19225. language. We now discuss the details of this pass.
  19226. The \code{cast\_insert} pass is closely related to the type checker
  19227. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19228. In particular, the type checker allows implicit casts between
  19229. consistent types. The job of the \code{cast\_insert} pass is to make
  19230. those casts explicit. It does so by inserting
  19231. \code{Cast} nodes into the AST.
  19232. %
  19233. For the most part, the implicit casts occur in places where the type
  19234. checker checks two types for consistency. Consider the case for
  19235. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19236. checker requires that the type of the left operand is consistent with
  19237. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19238. \code{Cast} around the left operand, converting from its type to
  19239. \INTTY{}. The story is similar for the right operand. It is not always
  19240. necessary to insert a cast, e.g., if the left operand already has type
  19241. \INTTY{} then there is no need for a \code{Cast}.
  19242. Some of the implicit casts are not as straightforward. One such case
  19243. arises with the
  19244. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19245. see that the type checker requires that the two branches have
  19246. consistent types and that type of the conditional expression is the
  19247. meet of the branches' types. In the target language \LangCast{}, both
  19248. branches will need to have the same type, and that type
  19249. will be the type of the conditional expression. Thus, each branch requires
  19250. a \code{Cast} to convert from its type to the meet of the branches' types.
  19251. The case for the function call exhibits another interesting situation. If
  19252. the function expression is of type \CANYTY{}, then it needs to be cast
  19253. to a function type so that it can be used in a function call in
  19254. \LangCast{}. Which function type should it be cast to? The parameter
  19255. and return types are unknown, so we can simply use \CANYTY{} for all
  19256. of them. Furthermore, in \LangCast{} the argument types will need to
  19257. exactly match the parameter types, so we must cast all the arguments
  19258. to type \CANYTY{} (if they are not already of that type).
  19259. {\if\edition\racketEd
  19260. %
  19261. Likewise, the cases for the tuple operators \code{vector-length},
  19262. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19263. where the tuple expression is of type \CANYTY{}. Instead of
  19264. handling these situations with casts, we recommend translating
  19265. the special-purpose variants of the tuple operators that handle
  19266. tuples of type \CANYTY{}: \code{any-vector-length},
  19267. \code{any-vector-ref}, and \code{any-vector-set!}.
  19268. %
  19269. \fi}
  19270. \section{Lower Casts}
  19271. \label{sec:lower_casts}
  19272. The next step in the journey toward x86 is the \code{lower\_casts}
  19273. pass that translates the casts in \LangCast{} to the lower-level
  19274. \code{Inject} and \code{Project} operators and new operators for
  19275. proxies, extending the \LangLam{} language to \LangProxy{}.
  19276. The \LangProxy{} language can also be described as an extension of
  19277. \LangAny{}, with the addition of proxies. We recommend creating an
  19278. auxiliary function named \code{lower\_cast} that takes an expression
  19279. (in \LangCast{}), a source type, and a target type and translates it
  19280. to an expression in \LangProxy{}.
  19281. The \code{lower\_cast} function can follow a code structure similar to
  19282. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19283. the interpreter for \LangCast{}, because it must handle the same cases
  19284. as \code{apply\_cast} and it needs to mimic the behavior of
  19285. \code{apply\_cast}. The most interesting cases concern
  19286. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19287. {\if\edition\racketEd
  19288. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19289. type to another tuple type is accomplished by creating a proxy that
  19290. intercepts the operations on the underlying tuple. Here we make the
  19291. creation of the proxy explicit with the \code{vector-proxy} AST
  19292. node. It takes three arguments: the first is an expression for the
  19293. tuple, the second is tuple of functions for casting an element that is
  19294. being read from the tuple, and the third is a tuple of functions for
  19295. casting an element that is being written to the array. You can create
  19296. the functions for reading and writing using lambda expressions. Also,
  19297. as we show in the next section, we need to differentiate these tuples
  19298. of functions from the user-created ones, so we recommend using a new
  19299. AST node named \code{raw-vector} instead of \code{vector}.
  19300. %
  19301. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19302. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19303. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19304. \fi}
  19305. {\if\edition\pythonEd
  19306. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19307. type to another array type is accomplished by creating a proxy that
  19308. intercepts the operations on the underlying array. Here we make the
  19309. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19310. takes fives arguments: the first is an expression for the array, the
  19311. second is a function for casting an element that is being read from
  19312. the array, the third is a function for casting an element that is
  19313. being written to the array, the fourth is the type of the underlying
  19314. array, and the fifth is the type of the proxied array. You can create
  19315. the functions for reading and writing using lambda expressions.
  19316. A cast between two tuple types can be handled in a similar manner. We
  19317. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19318. immutable, so there is no need for a function to cast the value during
  19319. a write. Because there is a separate element type for each slot in
  19320. the tuple, we need not just one function for casting during a read,
  19321. but instead a tuple of functions.
  19322. %
  19323. Also, as we show in the next section, we need to differentiate these
  19324. tuples from the user-created ones, so we recommend using a new AST
  19325. node named \code{RawTuple} instead of \code{Tuple} to create the
  19326. tuples of functions.
  19327. %
  19328. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19329. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19330. that involved casting an array of integers to an array of \CANYTY{}.
  19331. \fi}
  19332. \begin{figure}[tbp]
  19333. \begin{tcolorbox}[colback=white]
  19334. {\if\edition\racketEd
  19335. \begin{lstlisting}
  19336. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19337. (begin
  19338. (vector-set! v 0 (f (vector-ref v 0)))
  19339. (vector-set! v 1 (f (vector-ref v 1)))))
  19340. (define (inc [x : Any]) : Any
  19341. (inject (+ (project x Integer) 1) Integer))
  19342. (let ([v (vector 0 41)])
  19343. (begin
  19344. (map_inplace inc (vector-proxy v
  19345. (raw-vector (lambda: ([x9 : Integer]) : Any
  19346. (inject x9 Integer))
  19347. (lambda: ([x9 : Integer]) : Any
  19348. (inject x9 Integer)))
  19349. (raw-vector (lambda: ([x9 : Any]) : Integer
  19350. (project x9 Integer))
  19351. (lambda: ([x9 : Any]) : Integer
  19352. (project x9 Integer)))))
  19353. (vector-ref v 1)))
  19354. \end{lstlisting}
  19355. \fi}
  19356. {\if\edition\pythonEd
  19357. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19358. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19359. i = 0
  19360. while i != array_len(v):
  19361. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19362. i = (i + 1)
  19363. def inc(x : int) -> int:
  19364. return (x + 1)
  19365. def main() -> int:
  19366. v = [0, 41]
  19367. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19368. print(array_load(v, 1))
  19369. return 0
  19370. \end{lstlisting}
  19371. \fi}
  19372. \end{tcolorbox}
  19373. \caption{Output of \code{lower\_casts} on the example shown in
  19374. figure~\ref{fig:map-bang}.}
  19375. \label{fig:map-bang-lower-cast}
  19376. \end{figure}
  19377. A cast from one function type to another function type is accomplished
  19378. by generating a \code{lambda} whose parameter and return types match
  19379. the target function type. The body of the \code{lambda} should cast
  19380. the parameters from the target type to the source type. (Yes,
  19381. backward! Functions are contravariant\index{subject}{contravariant}
  19382. in the parameters.). Afterward, call the underlying function and then
  19383. cast the result from the source return type to the target return type.
  19384. Figure~\ref{fig:map-lower-cast} shows the output of the
  19385. \code{lower\_casts} pass on the \code{map} example give in
  19386. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19387. call to \code{map} is wrapped in a \code{lambda}.
  19388. \begin{figure}[tbp]
  19389. \begin{tcolorbox}[colback=white]
  19390. {\if\edition\racketEd
  19391. \begin{lstlisting}
  19392. (define (map [f : (Integer -> Integer)]
  19393. [v : (Vector Integer Integer)])
  19394. : (Vector Integer Integer)
  19395. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19396. (define (inc [x : Any]) : Any
  19397. (inject (+ (project x Integer) 1) Integer))
  19398. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19399. (project (inc (inject x9 Integer)) Integer))
  19400. (vector 0 41)) 1)
  19401. \end{lstlisting}
  19402. \fi}
  19403. {\if\edition\pythonEd
  19404. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19405. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19406. return (f(v[0]), f(v[1]),)
  19407. def inc(x : any) -> any:
  19408. return inject((project(x, int) + 1), int)
  19409. def main() -> int:
  19410. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19411. print(t[1])
  19412. return 0
  19413. \end{lstlisting}
  19414. \fi}
  19415. \end{tcolorbox}
  19416. \caption{Output of \code{lower\_casts} on the example shown in
  19417. figure~\ref{fig:gradual-map}.}
  19418. \label{fig:map-lower-cast}
  19419. \end{figure}
  19420. \section{Differentiate Proxies}
  19421. \label{sec:differentiate-proxies}
  19422. So far, the responsibility of differentiating tuples and tuple proxies
  19423. has been the job of the interpreter.
  19424. %
  19425. \racket{For example, the interpreter for \LangCast{} implements
  19426. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19427. figure~\ref{fig:guarded-tuple}.}
  19428. %
  19429. In the \code{differentiate\_proxies} pass we shift this responsibility
  19430. to the generated code.
  19431. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19432. we used the type \TUPLETYPENAME{} for both
  19433. real tuples and tuple proxies.
  19434. \python{Similarly, we use the type \code{list} for both arrays and
  19435. array proxies.}
  19436. In \LangPVec{} we return the
  19437. \TUPLETYPENAME{} type to its original
  19438. meaning, as the type of just tuples, and we introduce a new type,
  19439. \PTUPLETYNAME{}, whose values
  19440. can be either real tuples or tuple
  19441. proxies.
  19442. %
  19443. {\if\edition\pythonEd
  19444. Likewise, we return the
  19445. \ARRAYTYPENAME{} type to its original
  19446. meaning, as the type of arrays, and we introduce a new type,
  19447. \PARRAYTYNAME{}, whose values
  19448. can be either arrays or array proxies.
  19449. These new types come with a suite of new primitive operations.
  19450. \fi}
  19451. {\if\edition\racketEd
  19452. A tuple proxy is represented by a tuple containing three things: (1) the
  19453. underlying tuple, (2) a tuple of functions for casting elements that
  19454. are read from the tuple, and (3) a tuple of functions for casting
  19455. values to be written to the tuple. So, we define the following
  19456. abbreviation for the type of a tuple proxy:
  19457. \[
  19458. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19459. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19460. \]
  19461. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19462. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19463. %
  19464. Next we describe each of the new primitive operations.
  19465. \begin{description}
  19466. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19467. (\key{PVector} $T \ldots$)]\ \\
  19468. %
  19469. This operation brands a vector as a value of the \code{PVector} type.
  19470. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19471. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19472. %
  19473. This operation brands a vector proxy as value of the \code{PVector} type.
  19474. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19475. \BOOLTY{}] \ \\
  19476. %
  19477. This returns true if the value is a tuple proxy and false if it is a
  19478. real tuple.
  19479. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  19480. (\key{Vector} $T \ldots$)]\ \\
  19481. %
  19482. Assuming that the input is a tuple, this operation returns the
  19483. tuple.
  19484. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  19485. $\to$ \BOOLTY{}]\ \\
  19486. %
  19487. Given a tuple proxy, this operation returns the length of the tuple.
  19488. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  19489. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  19490. %
  19491. Given a tuple proxy, this operation returns the $i$th element of the
  19492. tuple.
  19493. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  19494. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  19495. Given a tuple proxy, this operation writes a value to the $i$th element
  19496. of the tuple.
  19497. \end{description}
  19498. \fi}
  19499. {\if\edition\pythonEd
  19500. %
  19501. A tuple proxy is represented by a tuple containing 1) the underlying
  19502. tuple and 2) a tuple of functions for casting elements that are read
  19503. from the tuple. The \LangPVec{} language includes the following AST
  19504. classes and primitive functions.
  19505. \begin{description}
  19506. \item[\code{InjectTuple}] \ \\
  19507. %
  19508. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  19509. \item[\code{InjectTupleProxy}]\ \\
  19510. %
  19511. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  19512. \item[\code{is\_tuple\_proxy}]\ \\
  19513. %
  19514. This primitive returns true if the value is a tuple proxy and false
  19515. if it is a tuple.
  19516. \item[\code{project\_tuple}]\ \\
  19517. %
  19518. Converts a tuple that is branded as \PTUPLETYNAME{}
  19519. back to a tuple.
  19520. \item[\code{proxy\_tuple\_len}]\ \\
  19521. %
  19522. Given a tuple proxy, returns the length of the underlying tuple.
  19523. \item[\code{proxy\_tuple\_load}]\ \\
  19524. %
  19525. Given a tuple proxy, returns the $i$th element of the underlying
  19526. tuple.
  19527. \end{description}
  19528. An array proxy is represented by a tuple containing 1) the underlying
  19529. array, 2) a function for casting elements that are read from the
  19530. array, and 3) a function for casting elements that are written to the
  19531. array. The \LangPVec{} language includes the following AST classes
  19532. and primitive functions.
  19533. \begin{description}
  19534. \item[\code{InjectList}]\ \\
  19535. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  19536. \item[\code{InjectListProxy}]\ \\
  19537. %
  19538. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  19539. \item[\code{is\_array\_proxy}]\ \\
  19540. %
  19541. Returns true if the value is a array proxy and false if it is an
  19542. array.
  19543. \item[\code{project\_array}]\ \\
  19544. %
  19545. Converts an array that is branded as \PARRAYTYNAME{} back to an
  19546. array.
  19547. \item[\code{proxy\_array\_len}]\ \\
  19548. %
  19549. Given a array proxy, returns the length of the underlying array.
  19550. \item[\code{proxy\_array\_load}]\ \\
  19551. %
  19552. Given a array proxy, returns the $i$th element of the underlying
  19553. array.
  19554. \item[\code{proxy\_array\_store}]\ \\
  19555. %
  19556. Given an array proxy, writes a value to the $i$th element of the
  19557. underlying array.
  19558. \end{description}
  19559. \fi}
  19560. Now we discuss the translation that differentiates tuples and arrays
  19561. from proxies. First, every type annotation in the program is
  19562. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  19563. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  19564. places. For example, we wrap every tuple creation with an
  19565. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  19566. %
  19567. {\if\edition\racketEd
  19568. \begin{minipage}{0.96\textwidth}
  19569. \begin{lstlisting}
  19570. (vector |$e_1 \ldots e_n$|)
  19571. |$\Rightarrow$|
  19572. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  19573. \end{lstlisting}
  19574. \end{minipage}
  19575. \fi}
  19576. {\if\edition\pythonEd
  19577. \begin{lstlisting}
  19578. Tuple(|$e_1, \ldots, e_n$|)
  19579. |$\Rightarrow$|
  19580. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  19581. \end{lstlisting}
  19582. \fi}
  19583. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  19584. AST node that we introduced in the previous
  19585. section does not get injected.
  19586. {\if\edition\racketEd
  19587. \begin{lstlisting}
  19588. (raw-vector |$e_1 \ldots e_n$|)
  19589. |$\Rightarrow$|
  19590. (vector |$e'_1 \ldots e'_n$|)
  19591. \end{lstlisting}
  19592. \fi}
  19593. {\if\edition\pythonEd
  19594. \begin{lstlisting}
  19595. RawTuple(|$e_1, \ldots, e_n$|)
  19596. |$\Rightarrow$|
  19597. Tuple(|$e'_1, \ldots, e'_n$|)
  19598. \end{lstlisting}
  19599. \fi}
  19600. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19601. translates as follows:
  19602. %
  19603. {\if\edition\racketEd
  19604. \begin{lstlisting}
  19605. (vector-proxy |$e_1~e_2~e_3$|)
  19606. |$\Rightarrow$|
  19607. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19608. \end{lstlisting}
  19609. \fi}
  19610. {\if\edition\pythonEd
  19611. \begin{lstlisting}
  19612. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19613. |$\Rightarrow$|
  19614. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19615. \end{lstlisting}
  19616. \fi}
  19617. We translate the element access operations into conditional
  19618. expressions that check whether the value is a proxy and then dispatch
  19619. to either the appropriate proxy tuple operation or the regular tuple
  19620. operation.
  19621. {\if\edition\racketEd
  19622. \begin{lstlisting}
  19623. (vector-ref |$e_1$| |$i$|)
  19624. |$\Rightarrow$|
  19625. (let ([|$v~e_1$|])
  19626. (if (proxy? |$v$|)
  19627. (proxy-vector-ref |$v$| |$i$|)
  19628. (vector-ref (project-vector |$v$|) |$i$|)
  19629. \end{lstlisting}
  19630. \fi}
  19631. %
  19632. Note that in the branch for a tuple, we must apply
  19633. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19634. from the tuple.
  19635. The translation of array operations is similar to the ones for tuples.
  19636. \section{Reveal Casts}
  19637. \label{sec:reveal-casts-gradual}
  19638. {\if\edition\racketEd
  19639. Recall that the \code{reveal\_casts} pass
  19640. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19641. \code{Inject} and \code{Project} into lower-level operations.
  19642. %
  19643. In particular, \code{Project} turns into a conditional expression that
  19644. inspects the tag and retrieves the underlying value. Here we need to
  19645. augment the translation of \code{Project} to handle the situation in which
  19646. the target type is \code{PVector}. Instead of using
  19647. \code{vector-length} we need to use \code{proxy-vector-length}.
  19648. \begin{lstlisting}
  19649. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19650. |$\Rightarrow$|
  19651. (let |$\itm{tmp}$| |$e'$|
  19652. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19653. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19654. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19655. (exit)))
  19656. \end{lstlisting}
  19657. \fi}
  19658. %
  19659. {\if\edition\pythonEd
  19660. Recall that the $\itm{tagof}$ function determines the bits used to
  19661. identify values of different types and it is used in the \code{reveal\_casts}
  19662. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19663. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19664. decimal), just like the tuple and array types.
  19665. \fi}
  19666. %
  19667. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19668. \section{Closure Conversion}
  19669. \label{sec:closure-conversion-gradual}
  19670. The auxiliary function that translates type annotations needs to be
  19671. updated to handle the \PTUPLETYNAME{}
  19672. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19673. %
  19674. Otherwise, the only other changes are adding cases that copy the new
  19675. AST nodes.
  19676. \section{Select Instructions}
  19677. \label{sec:select-instructions-gradual}
  19678. Recall that the \code{select\_instructions} pass is responsible for
  19679. lowering the primitive operations into x86 instructions. So, we need
  19680. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  19681. to x86. To do so, the first question we need to answer is how to
  19682. differentiate between tuple and tuples proxies\python{, and likewise for
  19683. arrays and array proxies}. We need just one bit to accomplish this;
  19684. we use the bit in position $63$ of the 64-bit tag at the front of
  19685. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  19686. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  19687. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19688. it that way.
  19689. {\if\edition\racketEd
  19690. \begin{lstlisting}
  19691. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19692. |$\Rightarrow$|
  19693. movq |$e'_1$|, |$\itm{lhs'}$|
  19694. \end{lstlisting}
  19695. \fi}
  19696. {\if\edition\pythonEd
  19697. \begin{lstlisting}
  19698. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19699. |$\Rightarrow$|
  19700. movq |$e'_1$|, |$\itm{lhs'}$|
  19701. \end{lstlisting}
  19702. \fi}
  19703. \python{The translation for \code{InjectList} is also a move instruction.}
  19704. \noindent On the other hand,
  19705. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19706. $63$ to $1$.
  19707. %
  19708. {\if\edition\racketEd
  19709. \begin{lstlisting}
  19710. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19711. |$\Rightarrow$|
  19712. movq |$e'_1$|, %r11
  19713. movq |$(1 << 63)$|, %rax
  19714. orq 0(%r11), %rax
  19715. movq %rax, 0(%r11)
  19716. movq %r11, |$\itm{lhs'}$|
  19717. \end{lstlisting}
  19718. \fi}
  19719. {\if\edition\pythonEd
  19720. \begin{lstlisting}
  19721. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19722. |$\Rightarrow$|
  19723. movq |$e'_1$|, %r11
  19724. movq |$(1 << 63)$|, %rax
  19725. orq 0(%r11), %rax
  19726. movq %rax, 0(%r11)
  19727. movq %r11, |$\itm{lhs'}$|
  19728. \end{lstlisting}
  19729. \fi}
  19730. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19731. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19732. The \racket{\code{proxy?} operation consumes}%
  19733. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  19734. consume}
  19735. the information so carefully stashed away by the injections. It
  19736. isolates bit $63$ to tell whether the value is a proxy.
  19737. %
  19738. {\if\edition\racketEd
  19739. \begin{lstlisting}
  19740. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19741. |$\Rightarrow$|
  19742. movq |$e_1'$|, %r11
  19743. movq 0(%r11), %rax
  19744. sarq $63, %rax
  19745. andq $1, %rax
  19746. movq %rax, |$\itm{lhs'}$|
  19747. \end{lstlisting}
  19748. \fi}%
  19749. %
  19750. {\if\edition\pythonEd
  19751. \begin{lstlisting}
  19752. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19753. |$\Rightarrow$|
  19754. movq |$e_1'$|, %r11
  19755. movq 0(%r11), %rax
  19756. sarq $63, %rax
  19757. andq $1, %rax
  19758. movq %rax, |$\itm{lhs'}$|
  19759. \end{lstlisting}
  19760. \fi}%
  19761. %
  19762. The \racket{\code{project-vector} operation is}
  19763. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19764. straightforward to translate, so we leave that to the reader.
  19765. Regarding the element access operations for tuples\python{ and arrays}, the
  19766. runtime provides procedures that implement them (they are recursive
  19767. functions!), so here we simply need to translate these tuple
  19768. operations into the appropriate function call. For example, here is
  19769. the translation for
  19770. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19771. {\if\edition\racketEd
  19772. \begin{minipage}{0.96\textwidth}
  19773. \begin{lstlisting}
  19774. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19775. |$\Rightarrow$|
  19776. movq |$e_1'$|, %rdi
  19777. movq |$e_2'$|, %rsi
  19778. callq proxy_vector_ref
  19779. movq %rax, |$\itm{lhs'}$|
  19780. \end{lstlisting}
  19781. \end{minipage}
  19782. \fi}
  19783. {\if\edition\pythonEd
  19784. \begin{lstlisting}
  19785. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19786. |$\Rightarrow$|
  19787. movq |$e_1'$|, %rdi
  19788. movq |$e_2'$|, %rsi
  19789. callq proxy_vector_ref
  19790. movq %rax, |$\itm{lhs'}$|
  19791. \end{lstlisting}
  19792. \fi}
  19793. {\if\edition\pythonEd
  19794. % TODO: revisit the names vecof for python -Jeremy
  19795. We translate
  19796. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  19797. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  19798. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  19799. \fi}
  19800. We have another batch of operations to deal with: those for the
  19801. \CANYTY{} type. Recall that we generate an
  19802. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  19803. there is a element access on something of type \CANYTY{}, and
  19804. similarly for
  19805. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  19806. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  19807. section~\ref{sec:select-Lany} we selected instructions for these
  19808. operations on the basis of the idea that the underlying value was a tuple or
  19809. array. But in the current setting, the underlying value is of type
  19810. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  19811. functions to deal with this:
  19812. \code{proxy\_vector\_ref},
  19813. \code{proxy\_vector\_set}, and
  19814. \code{proxy\_vector\_length}, that inspect bit $62$ of the tag
  19815. to determine whether the value is a proxy, and then
  19816. dispatches to the the appropriate code.
  19817. %
  19818. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  19819. can be translated as follows.
  19820. We begin by projecting the underlying value out of the tagged value and
  19821. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  19822. {\if\edition\racketEd
  19823. \begin{lstlisting}
  19824. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  19825. |$\Rightarrow$|
  19826. movq |$\neg 111$|, %rdi
  19827. andq |$e_1'$|, %rdi
  19828. movq |$e_2'$|, %rsi
  19829. callq proxy_vector_ref
  19830. movq %rax, |$\itm{lhs'}$|
  19831. \end{lstlisting}
  19832. \fi}
  19833. {\if\edition\pythonEd
  19834. \begin{lstlisting}
  19835. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  19836. |$\Rightarrow$|
  19837. movq |$\neg 111$|, %rdi
  19838. andq |$e_1'$|, %rdi
  19839. movq |$e_2'$|, %rsi
  19840. callq proxy_vector_ref
  19841. movq %rax, |$\itm{lhs'}$|
  19842. \end{lstlisting}
  19843. \fi}
  19844. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  19845. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  19846. are translated in a similar way. Alternatively, you could generate
  19847. instructions to open-code
  19848. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  19849. and \code{proxy\_vector\_length} functions.
  19850. \begin{exercise}\normalfont\normalsize
  19851. Implement a compiler for the gradually typed \LangGrad{} language by
  19852. extending and adapting your compiler for \LangLam{}. Create ten new
  19853. partially typed test programs. In addition to testing with these
  19854. new programs, test your compiler on all the tests for \LangLam{}
  19855. and for \LangDyn{}.
  19856. %
  19857. \racket{Sometimes you may get a type checking error on the
  19858. \LangDyn{} programs, but you can adapt them by inserting a cast to
  19859. the \CANYTY{} type around each subexpression that has caused a type
  19860. error. Although \LangDyn{} does not have explicit casts, you can
  19861. induce one by wrapping the subexpression \code{e} with a call to
  19862. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  19863. %
  19864. \python{Sometimes you may get a type checking error on the
  19865. \LangDyn{} programs but you can adapt them by inserting a
  19866. temporary variable of type \CANYTY{} that is initialized with the
  19867. troublesome expression.}
  19868. \end{exercise}
  19869. \begin{figure}[p]
  19870. \begin{tcolorbox}[colback=white]
  19871. {\if\edition\racketEd
  19872. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19873. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  19874. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  19875. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  19876. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  19877. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  19878. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  19879. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  19880. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  19881. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  19882. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  19883. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  19884. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  19885. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  19886. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  19887. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  19888. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  19889. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  19890. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  19891. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  19892. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  19893. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  19894. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  19895. \path[->,bend left=15] (Lgradual) edge [above] node
  19896. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  19897. \path[->,bend left=15] (Lgradual2) edge [above] node
  19898. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  19899. \path[->,bend left=15] (Lgradual3) edge [above] node
  19900. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  19901. \path[->,bend left=15] (Lgradual4) edge [left] node
  19902. {\ttfamily\footnotesize shrink} (Lgradualr);
  19903. \path[->,bend left=15] (Lgradualr) edge [above] node
  19904. {\ttfamily\footnotesize uniquify} (Lgradualp);
  19905. \path[->,bend right=15] (Lgradualp) edge [above] node
  19906. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  19907. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  19908. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  19909. \path[->,bend right=15] (Llambdapp) edge [above] node
  19910. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  19911. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  19912. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  19913. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  19914. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  19915. \path[->,bend left=15] (F1-2) edge [above] node
  19916. {\ttfamily\footnotesize limit\_functions} (F1-3);
  19917. \path[->,bend left=15] (F1-3) edge [left] node
  19918. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  19919. \path[->,bend left=15] (F1-4) edge [below] node
  19920. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19921. \path[->,bend right=15] (F1-5) edge [above] node
  19922. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  19923. \path[->,bend right=15] (F1-6) edge [above] node
  19924. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19925. \path[->,bend right=15] (C3-2) edge [right] node
  19926. {\ttfamily\footnotesize select\_instructions} (x86-2);
  19927. \path[->,bend right=15] (x86-2) edge [right] node
  19928. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19929. \path[->,bend right=15] (x86-2-1) edge [below] node
  19930. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  19931. \path[->,bend right=15] (x86-2-2) edge [right] node
  19932. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  19933. \path[->,bend left=15] (x86-3) edge [above] node
  19934. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  19935. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  19936. \end{tikzpicture}
  19937. \fi}
  19938. {\if\edition\pythonEd
  19939. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  19940. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  19941. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  19942. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  19943. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  19944. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  19945. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  19946. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  19947. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  19948. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  19949. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  19950. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  19951. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  19952. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  19953. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  19954. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  19955. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  19956. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  19957. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  19958. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  19959. \path[->,bend left=15] (Lgradual) edge [above] node
  19960. {\ttfamily\footnotesize shrink} (Lgradual2);
  19961. \path[->,bend left=15] (Lgradual2) edge [above] node
  19962. {\ttfamily\footnotesize uniquify} (Lgradual3);
  19963. \path[->,bend left=15] (Lgradual3) edge [above] node
  19964. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  19965. \path[->,bend left=15] (Lgradual4) edge [left] node
  19966. {\ttfamily\footnotesize resolve} (Lgradualr);
  19967. \path[->,bend left=15] (Lgradualr) edge [below] node
  19968. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  19969. \path[->,bend right=15] (Lgradualp) edge [above] node
  19970. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19971. \path[->,bend right=15] (Llambdapp) edge [above] node
  19972. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  19973. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  19974. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19975. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  19976. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19977. \path[->,bend left=15] (F1-1) edge [above] node
  19978. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  19979. \path[->,bend left=15] (F1-2) edge [above] node
  19980. {\ttfamily\footnotesize limit\_functions} (F1-3);
  19981. \path[->,bend left=15] (F1-3) edge [right] node
  19982. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  19983. \path[->,bend right=15] (F1-5) edge [above] node
  19984. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  19985. \path[->,bend right=15] (F1-6) edge [above] node
  19986. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19987. \path[->,bend right=15] (C3-2) edge [right] node
  19988. {\ttfamily\footnotesize select\_instructions} (x86-2);
  19989. \path[->,bend right=15] (x86-2) edge [below] node
  19990. {\ttfamily\footnotesize assign\_homes} (x86-3);
  19991. \path[->,bend right=15] (x86-3) edge [below] node
  19992. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  19993. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  19994. \end{tikzpicture}
  19995. \fi}
  19996. \end{tcolorbox}
  19997. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  19998. \label{fig:Lgradual-passes}
  19999. \end{figure}
  20000. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20001. needed for the compilation of \LangGrad{}.
  20002. \section{Further Reading}
  20003. This chapter just scratches the surface of gradual typing. The basic
  20004. approach described here is missing two key ingredients that one would
  20005. want in a implementation of gradual typing: blame
  20006. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20007. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20008. problem addressed by blame tracking is that when a cast on a
  20009. higher-order value fails, it often does so at a point in the program
  20010. that is far removed from the original cast. Blame tracking is a
  20011. technique for propagating extra information through casts and proxies
  20012. so that when a cast fails, the error message can point back to the
  20013. original location of the cast in the source program.
  20014. The problem addressed by space-efficient casts also relates to
  20015. higher-order casts. It turns out that in partially typed programs, a
  20016. function or tuple can flow through a great many casts at runtime. With
  20017. the approach described in this chapter, each cast adds another
  20018. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20019. considerable space, but it also makes the function calls and tuple
  20020. operations slow. For example, a partially typed version of quicksort
  20021. could, in the worst case, build a chain of proxies of length $O(n)$
  20022. around the tuple, changing the overall time complexity of the
  20023. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20024. solution to this problem by representing casts using the coercion
  20025. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20026. long chains of proxies by compressing them into a concise normal
  20027. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20028. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20029. the Grift compiler:
  20030. \begin{center}
  20031. \url{https://github.com/Gradual-Typing/Grift}
  20032. \end{center}
  20033. There are also interesting interactions between gradual typing and
  20034. other language features, such as generics, information-flow types, and
  20035. type inference, to name a few. We recommend to the reader the
  20036. online gradual typing bibliography for more material:
  20037. \begin{center}
  20038. \url{http://samth.github.io/gradual-typing-bib/}
  20039. \end{center}
  20040. % TODO: challenge problem:
  20041. % type analysis and type specialization?
  20042. % coercions?
  20043. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20044. \chapter{Generics}
  20045. \label{ch:Lpoly}
  20046. \index{subject}{parametric polymorphism}
  20047. \index{subject}{generics}
  20048. \setcounter{footnote}{0}
  20049. This chapter studies the compilation of
  20050. generics\index{subject}{generics} (aka parametric
  20051. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20052. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20053. enable programmers to make code more reusable by parameterizing
  20054. functions and data structures with respect to the types on which they
  20055. operate. For example, figure~\ref{fig:map-poly} revisits the
  20056. \code{map} example and this time gives it a more fitting type. This
  20057. \code{map} function is parameterized with respect to the element type
  20058. of the tuple. The type of \code{map} is the following generic type
  20059. specified by the \code{All} type with parameter \code{T}:
  20060. \if\edition\racketEd
  20061. \begin{lstlisting}
  20062. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20063. \end{lstlisting}
  20064. \fi
  20065. \if\edition\pythonEd
  20066. \begin{lstlisting}
  20067. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20068. \end{lstlisting}
  20069. \fi
  20070. %
  20071. The idea is that \code{map} can be used at \emph{all} choices of a
  20072. type for parameter \code{T}. In the example shown in
  20073. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20074. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20075. \code{T}, but we could have just as well applied \code{map} to a tuple
  20076. of Booleans.
  20077. %
  20078. A \emph{monomorphic} function is simply one that is not generic.
  20079. %
  20080. We use the term \emph{instantiation} for the process (within the
  20081. language implementation) of turning a generic function into a
  20082. monomorphic one, where the type parameters have been replaced by
  20083. types.
  20084. \if\edition\pythonEd
  20085. %
  20086. In Python, when writing a generic function such as \code{map}, one
  20087. does not explicitly write down its generic type (using \code{All}).
  20088. Instead, the fact that it is generic is implied by the use of type
  20089. variables (such as \code{T}) in the type annotations of its
  20090. parameters.
  20091. %
  20092. \fi
  20093. \begin{figure}[tbp]
  20094. % poly_test_2.rkt
  20095. \begin{tcolorbox}[colback=white]
  20096. \if\edition\racketEd
  20097. \begin{lstlisting}
  20098. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20099. (define (map f v)
  20100. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20101. (define (inc [x : Integer]) : Integer (+ x 1))
  20102. (vector-ref (map inc (vector 0 41)) 1)
  20103. \end{lstlisting}
  20104. \fi
  20105. \if\edition\pythonEd
  20106. \begin{lstlisting}
  20107. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20108. return (f(tup[0]), f(tup[1]))
  20109. def add1(x : int) -> int:
  20110. return x + 1
  20111. t = map(add1, (0, 41))
  20112. print(t[1])
  20113. \end{lstlisting}
  20114. \fi
  20115. \end{tcolorbox}
  20116. \caption{A generic version of the \code{map} function.}
  20117. \label{fig:map-poly}
  20118. \end{figure}
  20119. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20120. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20121. shows the definition of the abstract syntax.
  20122. %
  20123. \if\edition\racketEd
  20124. We add a second form for function definitions in which a type
  20125. declaration comes before the \code{define}. In the abstract syntax,
  20126. the return type in the \code{Def} is \CANYTY{}, but that should be
  20127. ignored in favor of the return type in the type declaration. (The
  20128. \CANYTY{} comes from using the same parser as discussed in
  20129. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20130. enables the use of an \code{All} type for a function, thereby making
  20131. it generic.
  20132. \fi
  20133. %
  20134. The grammar for types is extended to include the type of a generic
  20135. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  20136. abstract syntax)}.
  20137. \newcommand{\LpolyGrammarRacket}{
  20138. \begin{array}{lcl}
  20139. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20140. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20141. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20142. \end{array}
  20143. }
  20144. \newcommand{\LpolyASTRacket}{
  20145. \begin{array}{lcl}
  20146. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20147. \Def &::=& \DECL{\Var}{\Type} \\
  20148. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20149. \end{array}
  20150. }
  20151. \newcommand{\LpolyGrammarPython}{
  20152. \begin{array}{lcl}
  20153. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20154. \end{array}
  20155. }
  20156. \newcommand{\LpolyASTPython}{
  20157. \begin{array}{lcl}
  20158. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20159. \MID \key{GenericVar}\LP\Var\RP
  20160. \end{array}
  20161. }
  20162. \begin{figure}[tp]
  20163. \centering
  20164. \begin{tcolorbox}[colback=white]
  20165. \footnotesize
  20166. \if\edition\racketEd
  20167. \[
  20168. \begin{array}{l}
  20169. \gray{\LintGrammarRacket{}} \\ \hline
  20170. \gray{\LvarGrammarRacket{}} \\ \hline
  20171. \gray{\LifGrammarRacket{}} \\ \hline
  20172. \gray{\LwhileGrammarRacket} \\ \hline
  20173. \gray{\LtupGrammarRacket} \\ \hline
  20174. \gray{\LfunGrammarRacket} \\ \hline
  20175. \gray{\LlambdaGrammarRacket} \\ \hline
  20176. \LpolyGrammarRacket \\
  20177. \begin{array}{lcl}
  20178. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20179. \end{array}
  20180. \end{array}
  20181. \]
  20182. \fi
  20183. \if\edition\pythonEd
  20184. \[
  20185. \begin{array}{l}
  20186. \gray{\LintGrammarPython{}} \\ \hline
  20187. \gray{\LvarGrammarPython{}} \\ \hline
  20188. \gray{\LifGrammarPython{}} \\ \hline
  20189. \gray{\LwhileGrammarPython} \\ \hline
  20190. \gray{\LtupGrammarPython} \\ \hline
  20191. \gray{\LfunGrammarPython} \\ \hline
  20192. \gray{\LlambdaGrammarPython} \\\hline
  20193. \LpolyGrammarPython \\
  20194. \begin{array}{lcl}
  20195. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20196. \end{array}
  20197. \end{array}
  20198. \]
  20199. \fi
  20200. \end{tcolorbox}
  20201. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20202. (figure~\ref{fig:Llam-concrete-syntax}).}
  20203. \label{fig:Lpoly-concrete-syntax}
  20204. \end{figure}
  20205. \begin{figure}[tp]
  20206. \centering
  20207. \begin{tcolorbox}[colback=white]
  20208. \footnotesize
  20209. \if\edition\racketEd
  20210. \[
  20211. \begin{array}{l}
  20212. \gray{\LintOpAST} \\ \hline
  20213. \gray{\LvarASTRacket{}} \\ \hline
  20214. \gray{\LifASTRacket{}} \\ \hline
  20215. \gray{\LwhileASTRacket{}} \\ \hline
  20216. \gray{\LtupASTRacket{}} \\ \hline
  20217. \gray{\LfunASTRacket} \\ \hline
  20218. \gray{\LlambdaASTRacket} \\ \hline
  20219. \LpolyASTRacket \\
  20220. \begin{array}{lcl}
  20221. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20222. \end{array}
  20223. \end{array}
  20224. \]
  20225. \fi
  20226. \if\edition\pythonEd
  20227. \[
  20228. \begin{array}{l}
  20229. \gray{\LintASTPython} \\ \hline
  20230. \gray{\LvarASTPython{}} \\ \hline
  20231. \gray{\LifASTPython{}} \\ \hline
  20232. \gray{\LwhileASTPython{}} \\ \hline
  20233. \gray{\LtupASTPython{}} \\ \hline
  20234. \gray{\LfunASTPython} \\ \hline
  20235. \gray{\LlambdaASTPython} \\ \hline
  20236. \LpolyASTPython \\
  20237. \begin{array}{lcl}
  20238. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20239. \end{array}
  20240. \end{array}
  20241. \]
  20242. \fi
  20243. \end{tcolorbox}
  20244. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20245. (figure~\ref{fig:Llam-syntax}).}
  20246. \label{fig:Lpoly-syntax}
  20247. \end{figure}
  20248. By including the \code{All} type in the $\Type$ nonterminal of the
  20249. grammar we choose to make generics first class, which has interesting
  20250. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20251. not include syntax for the \code{All} type. It is inferred for functions whose
  20252. type annotations contain type variables.} Many languages with generics, such as
  20253. C++~\citep{stroustrup88:_param_types} and Standard
  20254. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20255. may be helpful to see an example of first-class generics in action. In
  20256. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20257. whose parameter is a generic function. Indeed, because the grammar for
  20258. $\Type$ includes the \code{All} type, a generic function may also be
  20259. returned from a function or stored inside a tuple. The body of
  20260. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20261. and also to an integer, which would not be possible if \code{f} were
  20262. not generic.
  20263. \begin{figure}[tbp]
  20264. \begin{tcolorbox}[colback=white]
  20265. \if\edition\racketEd
  20266. \begin{lstlisting}
  20267. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20268. (define (apply_twice f)
  20269. (if (f #t) (f 42) (f 777)))
  20270. (: id (All (T) (T -> T)))
  20271. (define (id x) x)
  20272. (apply_twice id)
  20273. \end{lstlisting}
  20274. \fi
  20275. \if\edition\pythonEd
  20276. \begin{lstlisting}
  20277. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20278. if f(True):
  20279. return f(42)
  20280. else:
  20281. return f(777)
  20282. def id(x: T) -> T:
  20283. return x
  20284. print(apply_twice(id))
  20285. \end{lstlisting}
  20286. \fi
  20287. \end{tcolorbox}
  20288. \caption{An example illustrating first-class generics.}
  20289. \label{fig:apply-twice}
  20290. \end{figure}
  20291. The type checker for \LangPoly{} shown in
  20292. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20293. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20294. \if\edition\pythonEd
  20295. %
  20296. Regarding function definitions, if the type annotations on its
  20297. parameters contain generic variables, then the function is generic and
  20298. therefore its type is an \code{All} type wrapped around a function
  20299. type. Otherwise the function is monomorphic and its type is simply
  20300. a function type.
  20301. %
  20302. \fi
  20303. The type checking of a function application is extended to handle the
  20304. case in which the operator expression is a generic function. In that case
  20305. the type arguments are deduced by matching the type of the parameters
  20306. with the types of the arguments.
  20307. %
  20308. The \code{match\_types} auxiliary function
  20309. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20310. recursively descending through a parameter type \code{param\_ty} and
  20311. the corresponding argument type \code{arg\_ty}, making sure that they
  20312. are equal except when there is a type parameter in the parameter
  20313. type. Upon encountering a type parameter for the first time, the
  20314. algorithm deduces an association of the type parameter to the
  20315. corresponding part of the argument type. If it is not the first time
  20316. that the type parameter has been encountered, the algorithm looks up
  20317. its deduced type and makes sure that it is equal to the corresponding
  20318. part of the argument type. The return type of the application is the
  20319. return type of the generic function with the type parameters
  20320. replaced by the deduced type arguments, using the
  20321. \code{substitute\_type} auxiliary function, which is also listed in
  20322. figure~\ref{fig:type-check-Lpoly-aux}.
  20323. The type checker extends type equality to handle the \code{All} type.
  20324. This is not quite as simple as for other types, such as function and
  20325. tuple types, because two \code{All} types can be syntactically
  20326. different even though they are equivalent. For example,
  20327. %
  20328. \racket{\code{(All (T) (T -> T))}}
  20329. \python{\code{All[[T], Callable[[T], T]]}}
  20330. is equivalent to
  20331. \racket{\code{(All (U) (U -> U))}}
  20332. \python{\code{All[[U], Callable[[U], U]]}}.
  20333. %
  20334. Two generic types should be considered equal if they differ only in
  20335. the choice of the names of the type parameters. The definition of type
  20336. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20337. parameters in one type to match the type parameters of the other type.
  20338. \if\edition\racketEd
  20339. %
  20340. The type checker also ensures that only defined type variables appear
  20341. in type annotations. The \code{check\_well\_formed} function for which
  20342. the definition is shown in figure~\ref{fig:well-formed-types}
  20343. recursively inspects a type, making sure that each type variable has
  20344. been defined.
  20345. %
  20346. \fi
  20347. \begin{figure}[tbp]
  20348. \begin{tcolorbox}[colback=white]
  20349. \if\edition\racketEd
  20350. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20351. (define type-check-poly-class
  20352. (class type-check-Llambda-class
  20353. (super-new)
  20354. (inherit check-type-equal?)
  20355. (define/override (type-check-apply env e1 es)
  20356. (define-values (e^ ty) ((type-check-exp env) e1))
  20357. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20358. ((type-check-exp env) e)))
  20359. (match ty
  20360. [`(,ty^* ... -> ,rt)
  20361. (for ([arg-ty ty*] [param-ty ty^*])
  20362. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20363. (values e^ es^ rt)]
  20364. [`(All ,xs (,tys ... -> ,rt))
  20365. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20366. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20367. (match_types env^^ param-ty arg-ty)))
  20368. (define targs
  20369. (for/list ([x xs])
  20370. (match (dict-ref env^^ x (lambda () #f))
  20371. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20372. x (Apply e1 es))]
  20373. [ty ty])))
  20374. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20375. [else (error 'type-check "expected a function, not ~a" ty)]))
  20376. (define/override ((type-check-exp env) e)
  20377. (match e
  20378. [(Lambda `([,xs : ,Ts] ...) rT body)
  20379. (for ([T Ts]) ((check_well_formed env) T))
  20380. ((check_well_formed env) rT)
  20381. ((super type-check-exp env) e)]
  20382. [(HasType e1 ty)
  20383. ((check_well_formed env) ty)
  20384. ((super type-check-exp env) e)]
  20385. [else ((super type-check-exp env) e)]))
  20386. (define/override ((type-check-def env) d)
  20387. (verbose 'type-check "poly/def" d)
  20388. (match d
  20389. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20390. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20391. (for ([p ps]) ((check_well_formed ts-env) p))
  20392. ((check_well_formed ts-env) rt)
  20393. (define new-env (append ts-env (map cons xs ps) env))
  20394. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20395. (check-type-equal? ty^ rt body)
  20396. (Generic ts (Def f p:t* rt info body^))]
  20397. [else ((super type-check-def env) d)]))
  20398. (define/override (type-check-program p)
  20399. (match p
  20400. [(Program info body)
  20401. (type-check-program (ProgramDefsExp info '() body))]
  20402. [(ProgramDefsExp info ds body)
  20403. (define ds^ (combine-decls-defs ds))
  20404. (define new-env (for/list ([d ds^])
  20405. (cons (def-name d) (fun-def-type d))))
  20406. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20407. (define-values (body^ ty) ((type-check-exp new-env) body))
  20408. (check-type-equal? ty 'Integer body)
  20409. (ProgramDefsExp info ds^^ body^)]))
  20410. ))
  20411. \end{lstlisting}
  20412. \fi
  20413. \if\edition\pythonEd
  20414. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20415. def type_check_exp(self, e, env):
  20416. match e:
  20417. case Call(Name(f), args) if f in builtin_functions:
  20418. return super().type_check_exp(e, env)
  20419. case Call(func, args):
  20420. func_t = self.type_check_exp(func, env)
  20421. func.has_type = func_t
  20422. match func_t:
  20423. case AllType(ps, FunctionType(p_tys, rt)):
  20424. for arg in args:
  20425. arg.has_type = self.type_check_exp(arg, env)
  20426. arg_tys = [arg.has_type for arg in args]
  20427. deduced = {}
  20428. for (p, a) in zip(p_tys, arg_tys):
  20429. self.match_types(p, a, deduced, e)
  20430. return self.substitute_type(rt, deduced)
  20431. case _:
  20432. return super().type_check_exp(e, env)
  20433. case _:
  20434. return super().type_check_exp(e, env)
  20435. def type_check(self, p):
  20436. match p:
  20437. case Module(body):
  20438. env = {}
  20439. for s in body:
  20440. match s:
  20441. case FunctionDef(name, params, bod, dl, returns, comment):
  20442. params_t = [t for (x,t) in params]
  20443. ty_params = set()
  20444. for t in params_t:
  20445. ty_params |$\mid$|= self.generic_variables(t)
  20446. ty = FunctionType(params_t, returns)
  20447. if len(ty_params) > 0:
  20448. ty = AllType(list(ty_params), ty)
  20449. env[name] = ty
  20450. self.check_stmts(body, IntType(), env)
  20451. case _:
  20452. raise Exception('type_check: unexpected ' + repr(p))
  20453. \end{lstlisting}
  20454. \fi
  20455. \end{tcolorbox}
  20456. \caption{Type checker for the \LangPoly{} language.}
  20457. \label{fig:type-check-Lpoly}
  20458. \end{figure}
  20459. \begin{figure}[tbp]
  20460. \begin{tcolorbox}[colback=white]
  20461. \if\edition\racketEd
  20462. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20463. (define/override (type-equal? t1 t2)
  20464. (match* (t1 t2)
  20465. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20466. (define env (map cons xs ys))
  20467. (type-equal? (substitute_type env T1) T2)]
  20468. [(other wise)
  20469. (super type-equal? t1 t2)]))
  20470. (define/public (match_types env pt at)
  20471. (match* (pt at)
  20472. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20473. [('Void 'Void) env] [('Any 'Any) env]
  20474. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20475. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20476. (match_types env^ pt1 at1))]
  20477. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20478. (define env^ (match_types env prt art))
  20479. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  20480. (match_types env^^ pt1 at1))]
  20481. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  20482. (define env^ (append (map cons pxs axs) env))
  20483. (match_types env^ pt1 at1)]
  20484. [((? symbol? x) at)
  20485. (match (dict-ref env x (lambda () #f))
  20486. [#f (error 'type-check "undefined type variable ~a" x)]
  20487. ['Type (cons (cons x at) env)]
  20488. [t^ (check-type-equal? at t^ 'matching) env])]
  20489. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  20490. (define/public (substitute_type env pt)
  20491. (match pt
  20492. ['Integer 'Integer] ['Boolean 'Boolean]
  20493. ['Void 'Void] ['Any 'Any]
  20494. [`(Vector ,ts ...)
  20495. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  20496. [`(,ts ... -> ,rt)
  20497. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  20498. [`(All ,xs ,t)
  20499. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  20500. [(? symbol? x) (dict-ref env x)]
  20501. [else (error 'type-check "expected a type not ~a" pt)]))
  20502. (define/public (combine-decls-defs ds)
  20503. (match ds
  20504. ['() '()]
  20505. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  20506. (unless (equal? name f)
  20507. (error 'type-check "name mismatch, ~a != ~a" name f))
  20508. (match type
  20509. [`(All ,xs (,ps ... -> ,rt))
  20510. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20511. (cons (Generic xs (Def name params^ rt info body))
  20512. (combine-decls-defs ds^))]
  20513. [`(,ps ... -> ,rt)
  20514. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20515. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  20516. [else (error 'type-check "expected a function type, not ~a" type) ])]
  20517. [`(,(Def f params rt info body) . ,ds^)
  20518. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  20519. \end{lstlisting}
  20520. \fi
  20521. \if\edition\pythonEd
  20522. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20523. def match_types(self, param_ty, arg_ty, deduced, e):
  20524. match (param_ty, arg_ty):
  20525. case (GenericVar(id), _):
  20526. if id in deduced:
  20527. self.check_type_equal(arg_ty, deduced[id], e)
  20528. else:
  20529. deduced[id] = arg_ty
  20530. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  20531. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  20532. new_arg_ty = self.substitute_type(arg_ty, rename)
  20533. self.match_types(ty, new_arg_ty, deduced, e)
  20534. case (TupleType(ps), TupleType(ts)):
  20535. for (p, a) in zip(ps, ts):
  20536. self.match_types(p, a, deduced, e)
  20537. case (ListType(p), ListType(a)):
  20538. self.match_types(p, a, deduced, e)
  20539. case (FunctionType(pps, prt), FunctionType(aps, art)):
  20540. for (pp, ap) in zip(pps, aps):
  20541. self.match_types(pp, ap, deduced, e)
  20542. self.match_types(prt, art, deduced, e)
  20543. case (IntType(), IntType()):
  20544. pass
  20545. case (BoolType(), BoolType()):
  20546. pass
  20547. case _:
  20548. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  20549. def substitute_type(self, ty, var_map):
  20550. match ty:
  20551. case GenericVar(id):
  20552. return var_map[id]
  20553. case AllType(ps, ty):
  20554. new_map = copy.deepcopy(var_map)
  20555. for p in ps:
  20556. new_map[p] = GenericVar(p)
  20557. return AllType(ps, self.substitute_type(ty, new_map))
  20558. case TupleType(ts):
  20559. return TupleType([self.substitute_type(t, var_map) for t in ts])
  20560. case ListType(ty):
  20561. return ListType(self.substitute_type(ty, var_map))
  20562. case FunctionType(pts, rt):
  20563. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  20564. self.substitute_type(rt, var_map))
  20565. case IntType():
  20566. return IntType()
  20567. case BoolType():
  20568. return BoolType()
  20569. case _:
  20570. raise Exception('substitute_type: unexpected ' + repr(ty))
  20571. def check_type_equal(self, t1, t2, e):
  20572. match (t1, t2):
  20573. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  20574. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  20575. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  20576. case (_, _):
  20577. return super().check_type_equal(t1, t2, e)
  20578. \end{lstlisting}
  20579. \fi
  20580. \end{tcolorbox}
  20581. \caption{Auxiliary functions for type checking \LangPoly{}.}
  20582. \label{fig:type-check-Lpoly-aux}
  20583. \end{figure}
  20584. \if\edition\racketEd
  20585. \begin{figure}[tbp]
  20586. \begin{tcolorbox}[colback=white]
  20587. \begin{lstlisting}
  20588. (define/public ((check_well_formed env) ty)
  20589. (match ty
  20590. ['Integer (void)]
  20591. ['Boolean (void)]
  20592. ['Void (void)]
  20593. [(? symbol? a)
  20594. (match (dict-ref env a (lambda () #f))
  20595. ['Type (void)]
  20596. [else (error 'type-check "undefined type variable ~a" a)])]
  20597. [`(Vector ,ts ...)
  20598. (for ([t ts]) ((check_well_formed env) t))]
  20599. [`(,ts ... -> ,t)
  20600. (for ([t ts]) ((check_well_formed env) t))
  20601. ((check_well_formed env) t)]
  20602. [`(All ,xs ,t)
  20603. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20604. ((check_well_formed env^) t)]
  20605. [else (error 'type-check "unrecognized type ~a" ty)]))
  20606. \end{lstlisting}
  20607. \end{tcolorbox}
  20608. \caption{Well-formed types.}
  20609. \label{fig:well-formed-types}
  20610. \end{figure}
  20611. \fi
  20612. % TODO: interpreter for R'_10
  20613. \clearpage
  20614. \section{Compiling Generics}
  20615. \label{sec:compiling-poly}
  20616. Broadly speaking, there are four approaches to compiling generics, as
  20617. follows:
  20618. \begin{description}
  20619. \item[Monomorphization] generates a different version of a generic
  20620. function for each set of type arguments with which it is used,
  20621. producing type-specialized code. This approach results in the most
  20622. efficient code but requires whole-program compilation (no separate
  20623. compilation) and may increase code size. Unfortunately,
  20624. monomorphization is incompatible with first-class generics, because
  20625. it is not always possible to determine which generic functions are
  20626. used with which type arguments during compilation. (It can be done
  20627. at runtime, with just-in-time compilation.) Monomorphization is
  20628. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20629. generic functions in NESL~\citep{Blelloch:1993aa} and
  20630. ML~\citep{Weeks:2006aa}.
  20631. \item[Uniform representation] generates one version of each generic
  20632. function and requires all values to have a common \emph{boxed} format,
  20633. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20634. generic and monomorphic code is compiled similarly to code in a
  20635. dynamically typed language (like \LangDyn{}), in which primitive
  20636. operators require their arguments to be projected from \CANYTY{} and
  20637. their results to be injected into \CANYTY{}. (In object-oriented
  20638. languages, the projection is accomplished via virtual method
  20639. dispatch.) The uniform representation approach is compatible with
  20640. separate compilation and with first-class generics. However, it
  20641. produces the least efficient code because it introduces overhead in
  20642. the entire program. This approach is used in
  20643. Java~\citep{Bracha:1998fk},
  20644. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20645. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20646. \item[Mixed representation] generates one version of each generic
  20647. function, using a boxed representation for type variables. However,
  20648. monomorphic code is compiled as usual (as in \LangLam{}), and
  20649. conversions are performed at the boundaries between monomorphic code
  20650. and polymorphic code (e.g., when a generic function is instantiated
  20651. and called). This approach is compatible with separate compilation
  20652. and first-class generics and maintains efficiency in monomorphic
  20653. code. The trade-off is increased overhead at the boundary between
  20654. monomorphic and generic code. This approach is used in
  20655. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20656. Java 5 with the addition of autoboxing.
  20657. \item[Type passing] uses the unboxed representation in both
  20658. monomorphic and generic code. Each generic function is compiled to a
  20659. single function with extra parameters that describe the type
  20660. arguments. The type information is used by the generated code to
  20661. determine how to access the unboxed values at runtime. This approach is
  20662. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20663. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20664. compilation and first-class generics and maintains the
  20665. efficiency for monomorphic code. There is runtime overhead in
  20666. polymorphic code from dispatching on type information.
  20667. \end{description}
  20668. In this chapter we use the mixed representation approach, partly
  20669. because of its favorable attributes and partly because it is
  20670. straightforward to implement using the tools that we have already
  20671. built to support gradual typing. The work of compiling generic
  20672. functions is performed in two passes, \code{resolve} and
  20673. \code{erase\_types}, that we discuss next. The output of
  20674. \code{erase\_types} is \LangCast{}
  20675. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20676. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20677. \section{Resolve Instantiation}
  20678. \label{sec:generic-resolve}
  20679. Recall that the type checker for \LangPoly{} deduces the type
  20680. arguments at call sites to a generic function. The purpose of the
  20681. \code{resolve} pass is to turn this implicit instantiation into an
  20682. explicit one, by adding \code{inst} nodes to the syntax of the
  20683. intermediate language. An \code{inst} node records the mapping of
  20684. type parameters to type arguments. The semantics of the \code{inst}
  20685. node is to instantiate the result of its first argument, a generic
  20686. function, to produce a monomorphic function. However, because the
  20687. interpreter never analyzes type annotations, instantiation can be a
  20688. no-op and simply return the generic function.
  20689. %
  20690. The output language of the \code{resolve} pass is \LangInst{},
  20691. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  20692. \if\edition\racketEd
  20693. The \code{resolve} pass combines the type declaration and polymorphic
  20694. function into a single definition, using the \code{Poly} form, to make
  20695. polymorphic functions more convenient to process in the next pass of the
  20696. compiler.
  20697. \fi
  20698. \newcommand{\LinstASTRacket}{
  20699. \begin{array}{lcl}
  20700. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20701. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  20702. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  20703. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  20704. \end{array}
  20705. }
  20706. \newcommand{\LinstASTPython}{
  20707. \begin{array}{lcl}
  20708. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  20709. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  20710. \end{array}
  20711. }
  20712. \begin{figure}[tp]
  20713. \centering
  20714. \begin{tcolorbox}[colback=white]
  20715. \small
  20716. \if\edition\racketEd
  20717. \[
  20718. \begin{array}{l}
  20719. \gray{\LintOpAST} \\ \hline
  20720. \gray{\LvarASTRacket{}} \\ \hline
  20721. \gray{\LifASTRacket{}} \\ \hline
  20722. \gray{\LwhileASTRacket{}} \\ \hline
  20723. \gray{\LtupASTRacket{}} \\ \hline
  20724. \gray{\LfunASTRacket} \\ \hline
  20725. \gray{\LlambdaASTRacket} \\ \hline
  20726. \LinstASTRacket \\
  20727. \begin{array}{lcl}
  20728. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20729. \end{array}
  20730. \end{array}
  20731. \]
  20732. \fi
  20733. \if\edition\pythonEd
  20734. \[
  20735. \begin{array}{l}
  20736. \gray{\LintASTPython} \\ \hline
  20737. \gray{\LvarASTPython{}} \\ \hline
  20738. \gray{\LifASTPython{}} \\ \hline
  20739. \gray{\LwhileASTPython{}} \\ \hline
  20740. \gray{\LtupASTPython{}} \\ \hline
  20741. \gray{\LfunASTPython} \\ \hline
  20742. \gray{\LlambdaASTPython} \\ \hline
  20743. \LinstASTPython \\
  20744. \begin{array}{lcl}
  20745. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20746. \end{array}
  20747. \end{array}
  20748. \]
  20749. \fi
  20750. \end{tcolorbox}
  20751. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  20752. (figure~\ref{fig:Llam-syntax}).}
  20753. \label{fig:Lpoly-prime-syntax}
  20754. \end{figure}
  20755. The output of the \code{resolve} pass on the generic \code{map}
  20756. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  20757. of \code{map} is wrapped in an \code{inst} node, with the parameter
  20758. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  20759. \begin{figure}[tbp]
  20760. % poly_test_2.rkt
  20761. \begin{tcolorbox}[colback=white]
  20762. \if\edition\racketEd
  20763. \begin{lstlisting}
  20764. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  20765. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20766. (define (inc [x : Integer]) : Integer (+ x 1))
  20767. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20768. (Integer))
  20769. inc (vector 0 41)) 1)
  20770. \end{lstlisting}
  20771. \fi
  20772. \if\edition\pythonEd
  20773. \begin{lstlisting}
  20774. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20775. return (f(tup[0]), f(tup[1]))
  20776. def add1(x : int) -> int:
  20777. return x + 1
  20778. t = inst(map, {T: int})(add1, (0, 41))
  20779. print(t[1])
  20780. \end{lstlisting}
  20781. \fi
  20782. \end{tcolorbox}
  20783. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20784. \label{fig:map-resolve}
  20785. \end{figure}
  20786. \section{Erase Types}
  20787. \label{sec:erase_types}
  20788. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  20789. represent type variables. For example, figure~\ref{fig:map-erase}
  20790. shows the output of the \code{erase\_types} pass on the generic
  20791. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  20792. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  20793. \code{All} types are removed from the type of \code{map}.
  20794. \begin{figure}[tbp]
  20795. \begin{tcolorbox}[colback=white]
  20796. \if\edition\racketEd
  20797. \begin{lstlisting}
  20798. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  20799. : (Vector Any Any)
  20800. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20801. (define (inc [x : Integer]) : Integer (+ x 1))
  20802. (vector-ref ((cast map
  20803. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20804. ((Integer -> Integer) (Vector Integer Integer)
  20805. -> (Vector Integer Integer)))
  20806. inc (vector 0 41)) 1)
  20807. \end{lstlisting}
  20808. \fi
  20809. \if\edition\pythonEd
  20810. \begin{lstlisting}
  20811. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  20812. return (f(tup[0]), f(tup[1]))
  20813. def add1(x : int) -> int:
  20814. return (x + 1)
  20815. def main() -> int:
  20816. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  20817. print(t[1])
  20818. return 0
  20819. \end{lstlisting}
  20820. {\small
  20821. where\\
  20822. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  20823. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  20824. }
  20825. \fi
  20826. \end{tcolorbox}
  20827. \caption{The generic \code{map} example after type erasure.}
  20828. \label{fig:map-erase}
  20829. \end{figure}
  20830. This process of type erasure creates a challenge at points of
  20831. instantiation. For example, consider the instantiation of
  20832. \code{map} shown in figure~\ref{fig:map-resolve}.
  20833. The type of \code{map} is
  20834. %
  20835. \if\edition\racketEd
  20836. \begin{lstlisting}
  20837. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20838. \end{lstlisting}
  20839. \fi
  20840. \if\edition\pythonEd
  20841. \begin{lstlisting}
  20842. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  20843. \end{lstlisting}
  20844. \fi
  20845. %
  20846. and it is instantiated to
  20847. %
  20848. \if\edition\racketEd
  20849. \begin{lstlisting}
  20850. ((Integer -> Integer) (Vector Integer Integer)
  20851. -> (Vector Integer Integer))
  20852. \end{lstlisting}
  20853. \fi
  20854. \if\edition\pythonEd
  20855. \begin{lstlisting}
  20856. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  20857. \end{lstlisting}
  20858. \fi
  20859. %
  20860. After erasure, the type of \code{map} is
  20861. %
  20862. \if\edition\racketEd
  20863. \begin{lstlisting}
  20864. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20865. \end{lstlisting}
  20866. \fi
  20867. \if\edition\pythonEd
  20868. \begin{lstlisting}
  20869. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  20870. \end{lstlisting}
  20871. \fi
  20872. %
  20873. but we need to convert it to the instantiated type. This is easy to
  20874. do in the language \LangCast{} with a single \code{cast}. In the
  20875. example shown in figure~\ref{fig:map-erase}, the instantiation of
  20876. \code{map} has been compiled to a \code{cast} from the type of
  20877. \code{map} to the instantiated type. The source and the target type of a
  20878. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  20879. the case because both the source and target are obtained from the same
  20880. generic type of \code{map}, replacing the type parameters with
  20881. \CANYTY{} in the former and with the deduced type arguments in the
  20882. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  20883. To implement the \code{erase\_types} pass, we first recommend defining
  20884. a recursive function that translates types, named
  20885. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  20886. follows.
  20887. %
  20888. \if\edition\racketEd
  20889. \begin{lstlisting}
  20890. |$T$|
  20891. |$\Rightarrow$|
  20892. Any
  20893. \end{lstlisting}
  20894. \fi
  20895. \if\edition\pythonEd
  20896. \begin{lstlisting}
  20897. GenericVar(|$T$|)
  20898. |$\Rightarrow$|
  20899. Any
  20900. \end{lstlisting}
  20901. \fi
  20902. %
  20903. \noindent The \code{erase\_type} function also removes the generic
  20904. \code{All} types.
  20905. %
  20906. \if\edition\racketEd
  20907. \begin{lstlisting}
  20908. (All |$xs$| |$T_1$|)
  20909. |$\Rightarrow$|
  20910. |$T'_1$|
  20911. \end{lstlisting}
  20912. \fi
  20913. \if\edition\pythonEd
  20914. \begin{lstlisting}
  20915. AllType(|$xs$|, |$T_1$|)
  20916. |$\Rightarrow$|
  20917. |$T'_1$|
  20918. \end{lstlisting}
  20919. \fi
  20920. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  20921. %
  20922. In this compiler pass, apply the \code{erase\_type} function to all
  20923. the type annotations in the program.
  20924. Regarding the translation of expressions, the case for \code{Inst} is
  20925. the interesting one. We translate it into a \code{Cast}, as shown
  20926. next.
  20927. The type of the subexpression $e$ is a generic type of the form
  20928. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  20929. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  20930. cast is the erasure of $T$, the type $T_s$.
  20931. %
  20932. \if\edition\racketEd
  20933. %
  20934. The target type $T_t$ is the result of substituting the argument types
  20935. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  20936. erasure.
  20937. %
  20938. \begin{lstlisting}
  20939. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  20940. |$\Rightarrow$|
  20941. (Cast |$e'$| |$T_s$| |$T_t$|)
  20942. \end{lstlisting}
  20943. %
  20944. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  20945. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  20946. \fi
  20947. \if\edition\pythonEd
  20948. %
  20949. The target type $T_t$ is the result of substituting the deduced
  20950. argument types $d$ in $T$ followed by doing type erasure.
  20951. %
  20952. \begin{lstlisting}
  20953. Inst(|$e$|, |$d$|)
  20954. |$\Rightarrow$|
  20955. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  20956. \end{lstlisting}
  20957. %
  20958. where
  20959. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  20960. \fi
  20961. Finally, each generic function is translated to a regular
  20962. function in which type erasure has been applied to all the type
  20963. annotations and the body.
  20964. %% \begin{lstlisting}
  20965. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  20966. %% |$\Rightarrow$|
  20967. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  20968. %% \end{lstlisting}
  20969. \begin{exercise}\normalfont\normalsize
  20970. Implement a compiler for the polymorphic language \LangPoly{} by
  20971. extending and adapting your compiler for \LangGrad{}. Create six new
  20972. test programs that use polymorphic functions. Some of them should
  20973. make use of first-class generics.
  20974. \end{exercise}
  20975. \begin{figure}[tbp]
  20976. \begin{tcolorbox}[colback=white]
  20977. \if\edition\racketEd
  20978. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20979. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  20980. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  20981. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  20982. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  20983. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  20984. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  20985. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  20986. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20987. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20988. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20989. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20990. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20991. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20992. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20993. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20994. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20995. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20996. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20997. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20998. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20999. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21000. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21001. \path[->,bend left=15] (Lpoly) edge [above] node
  21002. {\ttfamily\footnotesize resolve} (Lpolyp);
  21003. \path[->,bend left=15] (Lpolyp) edge [above] node
  21004. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21005. \path[->,bend left=15] (Lgradualp) edge [above] node
  21006. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21007. \path[->,bend left=15] (Llambdapp) edge [left] node
  21008. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21009. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21010. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21011. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21012. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21013. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21014. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21015. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21016. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21017. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21018. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21019. \path[->,bend left=15] (F1-1) edge [above] node
  21020. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21021. \path[->,bend left=15] (F1-2) edge [above] node
  21022. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21023. \path[->,bend left=15] (F1-3) edge [left] node
  21024. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21025. \path[->,bend left=15] (F1-4) edge [below] node
  21026. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21027. \path[->,bend right=15] (F1-5) edge [above] node
  21028. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21029. \path[->,bend right=15] (F1-6) edge [above] node
  21030. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21031. \path[->,bend right=15] (C3-2) edge [right] node
  21032. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21033. \path[->,bend right=15] (x86-2) edge [right] node
  21034. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21035. \path[->,bend right=15] (x86-2-1) edge [below] node
  21036. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21037. \path[->,bend right=15] (x86-2-2) edge [right] node
  21038. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21039. \path[->,bend left=15] (x86-3) edge [above] node
  21040. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21041. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21042. \end{tikzpicture}
  21043. \fi
  21044. \if\edition\pythonEd
  21045. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21046. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21047. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21048. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21049. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21050. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21051. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21052. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21053. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21054. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21055. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21056. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21057. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21058. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21059. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21060. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21061. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21062. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21063. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21064. \path[->,bend left=15] (Lgradual) edge [above] node
  21065. {\ttfamily\footnotesize shrink} (Lgradual2);
  21066. \path[->,bend left=15] (Lgradual2) edge [above] node
  21067. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21068. \path[->,bend left=15] (Lgradual3) edge [above] node
  21069. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21070. \path[->,bend left=15] (Lgradual4) edge [left] node
  21071. {\ttfamily\footnotesize resolve} (Lgradualr);
  21072. \path[->,bend left=15] (Lgradualr) edge [below] node
  21073. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21074. \path[->,bend right=15] (Llambdapp) edge [above] node
  21075. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21076. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21077. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21078. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21079. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21080. \path[->,bend right=15] (F1-1) edge [below] node
  21081. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21082. \path[->,bend right=15] (F1-2) edge [below] node
  21083. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21084. \path[->,bend left=15] (F1-3) edge [above] node
  21085. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21086. \path[->,bend left=15] (F1-5) edge [left] node
  21087. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21088. \path[->,bend left=5] (F1-6) edge [below] node
  21089. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21090. \path[->,bend right=15] (C3-2) edge [right] node
  21091. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21092. \path[->,bend right=15] (x86-2) edge [below] node
  21093. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21094. \path[->,bend right=15] (x86-3) edge [below] node
  21095. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21096. \path[->,bend left=15] (x86-4) edge [above] node
  21097. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21098. \end{tikzpicture}
  21099. \fi
  21100. \end{tcolorbox}
  21101. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21102. \label{fig:Lpoly-passes}
  21103. \end{figure}
  21104. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21105. needed to compile \LangPoly{}.
  21106. % TODO: challenge problem: specialization of instantiations
  21107. % Further Reading
  21108. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21109. \clearpage
  21110. \appendix
  21111. \chapter{Appendix}
  21112. \setcounter{footnote}{0}
  21113. \if\edition\racketEd
  21114. \section{Interpreters}
  21115. \label{appendix:interp}
  21116. \index{subject}{interpreter}
  21117. We provide interpreters for each of the source languages \LangInt{},
  21118. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21119. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21120. intermediate languages \LangCVar{} and \LangCIf{} are in
  21121. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21122. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21123. \key{interp.rkt} file.
  21124. \section{Utility Functions}
  21125. \label{appendix:utilities}
  21126. The utility functions described in this section are in the
  21127. \key{utilities.rkt} file of the support code.
  21128. \paragraph{\code{interp-tests}}
  21129. This function runs the compiler passes and the interpreters on each of
  21130. the specified tests to check whether each pass is correct. The
  21131. \key{interp-tests} function has the following parameters:
  21132. \begin{description}
  21133. \item[name (a string)] A name to identify the compiler,
  21134. \item[typechecker] A function of exactly one argument that either
  21135. raises an error using the \code{error} function when it encounters a
  21136. type error or returns \code{\#f} when it encounters a type
  21137. error. If there is no type error, the type checker returns the
  21138. program.
  21139. \item[passes] A list with one entry per pass. An entry is a list
  21140. consisting of four things:
  21141. \begin{enumerate}
  21142. \item a string giving the name of the pass;
  21143. \item the function that implements the pass (a translator from AST
  21144. to AST);
  21145. \item a function that implements the interpreter (a function from
  21146. AST to result value) for the output language; and,
  21147. \item a type checker for the output language. Type checkers for
  21148. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21149. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21150. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21151. type checker entry is optional. The support code does not provide
  21152. type checkers for the x86 languages.
  21153. \end{enumerate}
  21154. \item[source-interp] An interpreter for the source language. The
  21155. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21156. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21157. \item[tests] A list of test numbers that specifies which tests to
  21158. run (explained next).
  21159. \end{description}
  21160. %
  21161. The \key{interp-tests} function assumes that the subdirectory
  21162. \key{tests} has a collection of Racket programs whose names all start
  21163. with the family name, followed by an underscore and then the test
  21164. number, and ending with the file extension \key{.rkt}. Also, for each test
  21165. program that calls \code{read} one or more times, there is a file with
  21166. the same name except that the file extension is \key{.in}, which
  21167. provides the input for the Racket program. If the test program is
  21168. expected to fail type checking, then there should be an empty file of
  21169. the same name with extension \key{.tyerr}.
  21170. \paragraph{\code{compiler-tests}}
  21171. This function runs the compiler passes to generate x86 (a \key{.s}
  21172. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21173. It runs the machine code and checks that the output is $42$. The
  21174. parameters to the \code{compiler-tests} function are similar to those
  21175. of the \code{interp-tests} function, and they consist of
  21176. \begin{itemize}
  21177. \item a compiler name (a string),
  21178. \item a type checker,
  21179. \item description of the passes,
  21180. \item name of a test-family, and
  21181. \item a list of test numbers.
  21182. \end{itemize}
  21183. \paragraph{\code{compile-file}}
  21184. This function takes a description of the compiler passes (see the
  21185. comment for \key{interp-tests}) and returns a function that, given a
  21186. program file name (a string ending in \key{.rkt}), applies all the
  21187. passes and writes the output to a file whose name is the same as the
  21188. program file name with extension \key{.rkt} replaced by \key{.s}.
  21189. \paragraph{\code{read-program}}
  21190. This function takes a file path and parses that file (it must be a
  21191. Racket program) into an abstract syntax tree.
  21192. \paragraph{\code{parse-program}}
  21193. This function takes an S-expression representation of an abstract
  21194. syntax tree and converts it into the struct-based representation.
  21195. \paragraph{\code{assert}}
  21196. This function takes two parameters, a string (\code{msg}) and Boolean
  21197. (\code{bool}), and displays the message \key{msg} if the Boolean
  21198. \key{bool} is false.
  21199. \paragraph{\code{lookup}}
  21200. % remove discussion of lookup? -Jeremy
  21201. This function takes a key and an alist and returns the first value that is
  21202. associated with the given key, if there is one. If not, an error is
  21203. triggered. The alist may contain both immutable pairs (built with
  21204. \key{cons}) and mutable pairs (built with \key{mcons}).
  21205. %The \key{map2} function ...
  21206. \fi %\racketEd
  21207. \section{x86 Instruction Set Quick Reference}
  21208. \label{sec:x86-quick-reference}
  21209. \index{subject}{x86}
  21210. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21211. do. We write $A \to B$ to mean that the value of $A$ is written into
  21212. location $B$. Address offsets are given in bytes. The instruction
  21213. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21214. registers (such as \code{\%rax}), or memory references (such as
  21215. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21216. reference per instruction. Other operands must be immediates or
  21217. registers.
  21218. \begin{table}[tbp]
  21219. \centering
  21220. \begin{tabular}{l|l}
  21221. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21222. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21223. \texttt{negq} $A$ & $- A \to A$ \\
  21224. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21225. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  21226. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  21227. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21228. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  21229. \texttt{retq} & Pops the return address and jumps to it \\
  21230. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  21231. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  21232. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  21233. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21234. be an immediate) \\
  21235. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21236. matches the condition code of the instruction; otherwise go to the
  21237. next instructions. The condition codes are \key{e} for \emph{equal},
  21238. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21239. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21240. \texttt{jl} $L$ & \\
  21241. \texttt{jle} $L$ & \\
  21242. \texttt{jg} $L$ & \\
  21243. \texttt{jge} $L$ & \\
  21244. \texttt{jmp} $L$ & Jump to label $L$ \\
  21245. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21246. \texttt{movzbq} $A$, $B$ &
  21247. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21248. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21249. and the extra bytes of $B$ are set to zero.} \\
  21250. & \\
  21251. & \\
  21252. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  21253. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  21254. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  21255. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21256. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21257. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21258. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21259. description of the condition codes. $A$ must be a single byte register
  21260. (e.g., \texttt{al} or \texttt{cl}).} \\
  21261. \texttt{setl} $A$ & \\
  21262. \texttt{setle} $A$ & \\
  21263. \texttt{setg} $A$ & \\
  21264. \texttt{setge} $A$ &
  21265. \end{tabular}
  21266. \vspace{5pt}
  21267. \caption{Quick reference for the x86 instructions used in this book.}
  21268. \label{tab:x86-instr}
  21269. \end{table}
  21270. %% \if\edition\racketEd
  21271. %% \cleardoublepage
  21272. %% \section{Concrete Syntax for Intermediate Languages}
  21273. %% The concrete syntax of \LangAny{} is defined in
  21274. %% figure~\ref{fig:Lany-concrete-syntax}.
  21275. %% \begin{figure}[tp]
  21276. %% \centering
  21277. %% \fbox{
  21278. %% \begin{minipage}{0.97\textwidth}\small
  21279. %% \[
  21280. %% \begin{array}{lcl}
  21281. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  21282. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  21283. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  21284. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  21285. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  21286. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  21287. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  21288. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  21289. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  21290. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  21291. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  21292. %% \MID \LP\key{void?}\;\Exp\RP \\
  21293. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  21294. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  21295. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  21296. %% \end{array}
  21297. %% \]
  21298. %% \end{minipage}
  21299. %% }
  21300. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  21301. %% (figure~\ref{fig:Llam-syntax}).}
  21302. %% \label{fig:Lany-concrete-syntax}
  21303. %% \end{figure}
  21304. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  21305. %% \LangCFun{} is defined in figures~\ref{fig:c0-concrete-syntax},
  21306. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  21307. %% \ref{fig:c3-concrete-syntax}, respectively.
  21308. %% \begin{figure}[tbp]
  21309. %% \fbox{
  21310. %% \begin{minipage}{0.96\textwidth}
  21311. %% \small
  21312. %% \[
  21313. %% \begin{array}{lcl}
  21314. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  21315. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21316. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  21317. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  21318. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  21319. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  21320. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  21321. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  21322. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  21323. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  21324. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  21325. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  21326. %% \end{array}
  21327. %% \]
  21328. %% \end{minipage}
  21329. %% }
  21330. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  21331. %% \label{fig:c2-concrete-syntax}
  21332. %% \end{figure}
  21333. %% \begin{figure}[tp]
  21334. %% \fbox{
  21335. %% \begin{minipage}{0.96\textwidth}
  21336. %% \small
  21337. %% \[
  21338. %% \begin{array}{lcl}
  21339. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  21340. %% \\
  21341. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21342. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  21343. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  21344. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  21345. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  21346. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  21347. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  21348. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  21349. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  21350. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  21351. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  21352. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  21353. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  21354. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  21355. %% \LangCFunM{} & ::= & \Def\ldots
  21356. %% \end{array}
  21357. %% \]
  21358. %% \end{minipage}
  21359. %% }
  21360. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  21361. %% \label{fig:c3-concrete-syntax}
  21362. %% \end{figure}
  21363. %% \fi % racketEd
  21364. \backmatter
  21365. \addtocontents{toc}{\vspace{11pt}}
  21366. %% \addtocontents{toc}{\vspace{11pt}}
  21367. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  21368. \nocite{*}\let\bibname\refname
  21369. \addcontentsline{toc}{fmbm}{\refname}
  21370. \printbibliography
  21371. %\printindex{authors}{Author Index}
  21372. \printindex{subject}{Index}
  21373. \end{document}
  21374. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21375. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21376. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21377. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21378. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21379. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21380. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21381. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21382. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21383. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21384. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21385. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21386. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21387. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21388. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21389. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21390. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21391. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21392. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21393. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21394. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21395. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21396. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21397. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21398. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21399. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21400. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21401. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21402. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21403. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21404. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21405. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21406. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21407. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21408. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21409. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21410. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21411. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21412. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21413. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21414. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21415. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21416. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21417. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21418. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21419. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21420. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21421. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21422. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21423. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21424. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21425. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21426. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21427. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21428. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21429. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21430. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21431. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21432. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21433. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21434. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21435. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21436. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21437. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21438. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21439. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21440. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21441. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21442. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21443. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21444. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21445. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21446. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21447. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21448. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21449. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21450. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21451. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21452. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21453. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith
  21454. % LocalWords: racketEd subparts subpart nonterminal nonterminals
  21455. % LocalWords: pseudocode underapproximation underapproximations
  21456. % LocalWords: semilattices overapproximate incrementing
  21457. % LocalWords: multilanguage