book.tex 836 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. \usepackage[utf8]{inputenc}
  3. %% \usepackage{setspace}
  4. %% \doublespacing
  5. \usepackage{listings}
  6. \usepackage{verbatim}
  7. \usepackage{amssymb}
  8. \usepackage{lmodern} % better typewriter font for code
  9. %\usepackage{wrapfig}
  10. \usepackage{multirow}
  11. \usepackage{tcolorbox}
  12. \usepackage{color}
  13. %\usepackage{ifthen}
  14. \usepackage{upquote}
  15. \usepackage[all]{xy}
  16. \usepackage{url}
  17. \definecolor{lightgray}{gray}{1}
  18. \newcommand{\black}[1]{{\color{black} #1}}
  19. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  20. \newcommand{\gray}[1]{{\color{gray} #1}}
  21. \def\racketEd{0}
  22. \def\pythonEd{1}
  23. \def\edition{1}
  24. % material that is specific to the Racket edition of the book
  25. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  26. % would like a command for: \if\edition\racketEd\color{olive}
  27. % and : \fi\color{black}
  28. %\newcommand{\pythonColor}[0]{\color{purple}}
  29. \newcommand{\pythonColor}[0]{}
  30. % material that is specific to the Python edition of the book
  31. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  32. \makeatletter
  33. \newcommand{\captionabove}[2][]{%
  34. \vskip-\abovecaptionskip
  35. \vskip+\belowcaptionskip
  36. \ifx\@nnil#1\@nnil
  37. \caption{#2}%
  38. \else
  39. \caption[#1]{#2}%
  40. \fi
  41. \vskip+\abovecaptionskip
  42. \vskip-\belowcaptionskip
  43. }
  44. %% For multiple indices:
  45. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  46. \makeindex{subject}
  47. %\makeindex{authors}
  48. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  49. \if\edition\racketEd
  50. \lstset{%
  51. language=Lisp,
  52. basicstyle=\ttfamily\small,
  53. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  54. deletekeywords={read,mapping,vector},
  55. escapechar=|,
  56. columns=flexible,
  57. %moredelim=[is][\color{red}]{~}{~},
  58. showstringspaces=false
  59. }
  60. \fi
  61. \if\edition\pythonEd
  62. \lstset{%
  63. language=Python,
  64. basicstyle=\ttfamily\small,
  65. morekeywords={match,case,bool,int,let,begin,if,else,closure},
  66. deletekeywords={},
  67. escapechar=|,
  68. columns=flexible,
  69. %moredelim=[is][\color{red}]{~}{~},
  70. showstringspaces=false
  71. }
  72. \fi
  73. %%% Any shortcut own defined macros place here
  74. %% sample of author macro:
  75. \input{defs}
  76. \newtheorem{exercise}[theorem]{Exercise}
  77. \numberwithin{theorem}{chapter}
  78. \numberwithin{definition}{chapter}
  79. \numberwithin{equation}{chapter}
  80. % Adjusted settings
  81. \setlength{\columnsep}{4pt}
  82. %% \begingroup
  83. %% \setlength{\intextsep}{0pt}%
  84. %% \setlength{\columnsep}{0pt}%
  85. %% \begin{wrapfigure}{r}{0.5\textwidth}
  86. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  87. %% \caption{Basic layout}
  88. %% \end{wrapfigure}
  89. %% \lipsum[1]
  90. %% \endgroup
  91. \def\ShowFrameLinethickness{0.125pt}
  92. \addbibresource{book.bib}
  93. \if\edition\pythonEd
  94. \addbibresource{python.bib}
  95. \fi
  96. \begin{document}
  97. \frontmatter
  98. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  99. \HalfTitle{Essentials of Compilation}
  100. \halftitlepage
  101. \clearemptydoublepage
  102. \Title{Essentials of Compilation}
  103. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  104. %\edition{First Edition}
  105. \BookAuthor{Jeremy G. Siek}
  106. \imprint{The MIT Press\\
  107. Cambridge, Massachusetts\\
  108. London, England}
  109. \begin{copyrightpage}
  110. \textcopyright\ 2023 Jeremy G. Siek \\[2ex]
  111. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  112. Subject to such license, all rights are reserved. \\[2ex]
  113. \includegraphics{CCBY-logo}
  114. The MIT Press would like to thank the anonymous peer reviewers who
  115. provided comments on drafts of this book. The generous work of
  116. academic experts is essential for establishing the authority and
  117. quality of our publications. We acknowledge with gratitude the
  118. contributions of these otherwise uncredited readers.
  119. This book was set in Times LT Std Roman by the author. Printed and
  120. bound in the United States of America.
  121. {\if\edition\racketEd
  122. Library of Congress Cataloging-in-Publication Data\\
  123. \ \\
  124. Names: Siek, Jeremy, author. \\
  125. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  126. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  127. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  128. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  129. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  130. LC record available at https://lccn.loc.gov/2022015399\\
  131. LC ebook record available at https://lccn.loc.gov/2022015400\\
  132. \ \\
  133. \fi}
  134. %
  135. {\if\edition\pythonEd
  136. Library of Congress Cataloging-in-Publication Data\\
  137. \ \\
  138. Names: Siek, Jeremy, author. \\
  139. Title: Essentials of compilation : an incremental approach in Python / Jeremy G. Siek. \\
  140. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes
  141. bibliographical references and index. \\
  142. Identifiers: LCCN 2022043053 (print) | LCCN 2022043054 (ebook) | ISBN
  143. 9780262048248 | ISBN 9780262375542 (epub) | ISBN 9780262375559 (pdf) \\
  144. Subjects: LCSH: Compilers (Computer programs) | Python (Computer program
  145. language) | Programming languages (Electronic computers) | Computer
  146. programming. \\
  147. Classification: LCC QA76.76.C65 S54 2023 (print) | LCC QA76.76.C65
  148. (ebook) | DDC 005.4/53--dc23/eng/20221117 \\
  149. LC record available at https://lccn.loc.gov/2022043053\\
  150. LC ebook record available at https://lccn.loc.gov/2022043054 \\
  151. \ \\
  152. \fi}
  153. 10 9 8 7 6 5 4 3 2 1
  154. %% Jeremy G. Siek. Available for free viewing
  155. %% or personal downloading under the
  156. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  157. %% license.
  158. %% Copyright in this monograph has been licensed exclusively to The MIT
  159. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  160. %% version to the public in 2022. All inquiries regarding rights should
  161. %% be addressed to The MIT Press, Rights and Permissions Department.
  162. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  163. %% All rights reserved. No part of this book may be reproduced in any
  164. %% form by any electronic or mechanical means (including photocopying,
  165. %% recording, or information storage and retrieval) without permission in
  166. %% writing from the publisher.
  167. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  168. %% United States of America.
  169. %% Library of Congress Cataloging-in-Publication Data is available.
  170. %% ISBN:
  171. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  172. \end{copyrightpage}
  173. \dedication{This book is dedicated to Katie, my partner in everything,
  174. my children, who grew up during the writing of this book, and the
  175. programming language students at Indiana University, whose
  176. thoughtful questions made this a better book.}
  177. %% \begin{epigraphpage}
  178. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  179. %% \textit{Book Name if any}}
  180. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  181. %% \end{epigraphpage}
  182. \tableofcontents
  183. %\listoffigures
  184. %\listoftables
  185. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  186. \chapter*{Preface}
  187. \addcontentsline{toc}{fmbm}{Preface}
  188. There is a magical moment when a programmer presses the \emph{run}
  189. button and the software begins to execute. Somehow a program written
  190. in a high-level language is running on a computer that is capable only
  191. of shuffling bits. Here we reveal the wizardry that makes that moment
  192. possible. Beginning with the groundbreaking work of Backus and
  193. colleagues in the 1950s, computer scientists developed techniques for
  194. constructing programs called \emph{compilers} that automatically
  195. translate high-level programs into machine code.
  196. We take you on a journey through constructing your own compiler for a
  197. small but powerful language. Along the way we explain the essential
  198. concepts, algorithms, and data structures that underlie compilers. We
  199. develop your understanding of how programs are mapped onto computer
  200. hardware, which is helpful in reasoning about properties at the
  201. junction of hardware and software, such as execution time, software
  202. errors, and security vulnerabilities. For those interested in
  203. pursuing compiler construction as a career, our goal is to provide a
  204. stepping-stone to advanced topics such as just-in-time compilation,
  205. program analysis, and program optimization. For those interested in
  206. designing and implementing programming languages, we connect language
  207. design choices to their impact on the compiler and the generated code.
  208. A compiler is typically organized as a sequence of stages that
  209. progressively translate a program to the code that runs on
  210. hardware. We take this approach to the extreme by partitioning our
  211. compiler into a large number of \emph{nanopasses}, each of which
  212. performs a single task. This enables the testing of each pass in
  213. isolation and focuses our attention, making the compiler far easier to
  214. understand.
  215. The most familiar approach to describing compilers is to dedicate each
  216. chapter to one pass. The problem with that approach is that it
  217. obfuscates how language features motivate design choices in a
  218. compiler. We instead take an \emph{incremental} approach in which we
  219. build a complete compiler in each chapter, starting with a small input
  220. language that includes only arithmetic and variables. We add new
  221. language features in subsequent chapters, extending the compiler as
  222. necessary.
  223. Our choice of language features is designed to elicit fundamental
  224. concepts and algorithms used in compilers.
  225. \begin{itemize}
  226. \item We begin with integer arithmetic and local variables in
  227. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  228. the fundamental tools of compiler construction: \emph{abstract
  229. syntax trees} and \emph{recursive functions}.
  230. {\if\edition\pythonEd\pythonColor
  231. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  232. parser framework to create a parser for the language of integer
  233. arithmetic and local variables. We learn about the parsing
  234. algorithms inside Lark, including Earley and LALR(1).
  235. %
  236. \fi}
  237. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  238. \emph{graph coloring} to assign variables to machine registers.
  239. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  240. motivates an elegant recursive algorithm for translating them into
  241. conditional \code{goto} statements.
  242. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  243. variables}. This elicits the need for \emph{dataflow
  244. analysis} in the register allocator.
  245. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  246. \emph{garbage collection}.
  247. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  248. without lexical scoping, similar to functions in the C programming
  249. language~\citep{Kernighan:1988nx}. The reader learns about the
  250. procedure call stack and \emph{calling conventions} and how they interact
  251. with register allocation and garbage collection. The chapter also
  252. describes how to generate efficient tail calls.
  253. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  254. scoping, that is, \emph{lambda} expressions. The reader learns about
  255. \emph{closure conversion}, in which lambdas are translated into a
  256. combination of functions and tuples.
  257. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  258. point the input languages are statically typed. The reader extends
  259. the statically typed language with an \code{Any} type that serves
  260. as a target for compiling the dynamically typed language.
  261. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  262. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  263. in which different regions of a program may be static or dynamically
  264. typed. The reader implements runtime support for \emph{proxies} that
  265. allow values to safely move between regions.
  266. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  267. leveraging the \code{Any} type and type casts developed in chapters
  268. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  269. \end{itemize}
  270. There are many language features that we do not include. Our choices
  271. balance the incidental complexity of a feature versus the fundamental
  272. concepts that it exposes. For example, we include tuples and not
  273. records because although they both elicit the study of heap allocation and
  274. garbage collection, records come with more incidental complexity.
  275. Since 2009, drafts of this book have served as the textbook for
  276. sixteen-week compiler courses for upper-level undergraduates and
  277. first-year graduate students at the University of Colorado and Indiana
  278. University.
  279. %
  280. Students come into the course having learned the basics of
  281. programming, data structures and algorithms, and discrete
  282. mathematics.
  283. %
  284. At the beginning of the course, students form groups of two to four
  285. people. The groups complete approximately one chapter every two
  286. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  287. according to the students interests while respecting the dependencies
  288. between chapters shown in
  289. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  290. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  291. implementation of efficient tail calls.
  292. %
  293. The last two weeks of the course involve a final project in which
  294. students design and implement a compiler extension of their choosing.
  295. The last few chapters can be used in support of these projects. Many
  296. chapters include a challenge problem that we assign to the graduate
  297. students.
  298. For compiler courses at universities on the quarter system
  299. (about ten weeks in length), we recommend completing the course
  300. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  301. some scaffolding code to the students for each compiler pass.
  302. %
  303. The course can be adapted to emphasize functional languages by
  304. skipping chapter~\ref{ch:Lwhile} (loops) and including
  305. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  306. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  307. This book has been used in compiler courses at California Polytechnic
  308. State University, Portland State University, Rose–Hulman Institute of
  309. Technology, University of Freiburg, University of Massachusetts
  310. Lowell, and the University of Vermont.
  311. \begin{figure}[tp]
  312. \begin{tcolorbox}[colback=white]
  313. {\if\edition\racketEd
  314. \begin{tikzpicture}[baseline=(current bounding box.center)]
  315. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  316. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  317. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  318. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  319. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  320. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  321. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  322. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  323. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  324. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  325. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  326. \path[->] (C1) edge [above] node {} (C2);
  327. \path[->] (C2) edge [above] node {} (C3);
  328. \path[->] (C3) edge [above] node {} (C4);
  329. \path[->] (C4) edge [above] node {} (C5);
  330. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  331. \path[->] (C5) edge [above] node {} (C7);
  332. \path[->] (C6) edge [above] node {} (C7);
  333. \path[->] (C4) edge [above] node {} (C8);
  334. \path[->] (C4) edge [above] node {} (C9);
  335. \path[->] (C7) edge [above] node {} (C10);
  336. \path[->] (C8) edge [above] node {} (C10);
  337. \path[->] (C10) edge [above] node {} (C11);
  338. \end{tikzpicture}
  339. \fi}
  340. {\if\edition\pythonEd\pythonColor
  341. \begin{tikzpicture}[baseline=(current bounding box.center)]
  342. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  343. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  344. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  345. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  346. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  347. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  348. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  349. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  350. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  351. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  352. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  353. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  354. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  355. \path[->] (Prelim) edge [above] node {} (Var);
  356. \path[->] (Var) edge [above] node {} (Reg);
  357. \path[->] (Var) edge [above] node {} (Parse);
  358. \path[->] (Reg) edge [above] node {} (Cond);
  359. \path[->] (Cond) edge [above] node {} (Tuple);
  360. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  361. \path[->] (Cond) edge [above] node {} (Fun);
  362. \path[->] (Tuple) edge [above] node {} (Lam);
  363. \path[->] (Fun) edge [above] node {} (Lam);
  364. \path[->] (Cond) edge [above] node {} (Dyn);
  365. \path[->] (Cond) edge [above] node {} (Loop);
  366. \path[->] (Lam) edge [above] node {} (Gradual);
  367. \path[->] (Dyn) edge [above] node {} (Gradual);
  368. % \path[->] (Dyn) edge [above] node {} (CO);
  369. \path[->] (Gradual) edge [above] node {} (Generic);
  370. \end{tikzpicture}
  371. \fi}
  372. \end{tcolorbox}
  373. \caption{Diagram of chapter dependencies.}
  374. \label{fig:chapter-dependences}
  375. \end{figure}
  376. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  377. the implementation of the compiler and for the input language, so the
  378. reader should be proficient with Racket or Scheme. There are many
  379. excellent resources for learning Scheme and
  380. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  381. %
  382. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  383. both for the implementation of the compiler and for the input language, so the
  384. reader should be proficient with Python. There are many
  385. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  386. %
  387. The support code for this book is in the GitHub repository at
  388. the following location:
  389. \begin{center}\small\texttt
  390. https://github.com/IUCompilerCourse/
  391. \end{center}
  392. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  393. is helpful but not necessary for the reader to have taken a computer
  394. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  395. assembly language that are needed in the compiler.
  396. %
  397. We follow the System V calling
  398. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  399. that we generate works with the runtime system (written in C) when it
  400. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  401. operating systems on Intel hardware.
  402. %
  403. On the Windows operating system, \code{gcc} uses the Microsoft x64
  404. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  405. assembly code that we generate does \emph{not} work with the runtime
  406. system on Windows. One workaround is to use a virtual machine with
  407. Linux as the guest operating system.
  408. \section*{Acknowledgments}
  409. The tradition of compiler construction at Indiana University goes back
  410. to research and courses on programming languages by Daniel Friedman in
  411. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  412. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  413. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  414. the compiler course and continued the development of Chez Scheme.
  415. %
  416. The compiler course evolved to incorporate novel pedagogical ideas
  417. while also including elements of real-world compilers. One of
  418. Friedman's ideas was to split the compiler into many small
  419. passes. Another idea, called ``the game,'' was to test the code
  420. generated by each pass using interpreters.
  421. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  422. developed infrastructure to support this approach and evolved the
  423. course to use even smaller
  424. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  425. design decisions in this book are inspired by the assignment
  426. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  427. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  428. organization of the course made it difficult for students to
  429. understand the rationale for the compiler design. Ghuloum proposed the
  430. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  431. based.
  432. I thank the many students who served as teaching assistants for the
  433. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  434. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  435. garbage collector and x86 interpreter, Michael Vollmer for work on
  436. efficient tail calls, and Michael Vitousek for help with the first
  437. offering of the incremental compiler course at IU.
  438. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  439. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  440. Michael Wollowski for teaching courses based on drafts of this book
  441. and for their feedback. I thank the National Science Foundation for
  442. the grants that helped to support this work: Grant Numbers 1518844,
  443. 1763922, and 1814460.
  444. I thank Ronald Garcia for helping me survive Dybvig's compiler
  445. course in the early 2000s and especially for finding the bug that
  446. sent our garbage collector on a wild goose chase!
  447. \mbox{}\\
  448. \noindent Jeremy G. Siek \\
  449. Bloomington, Indiana
  450. \mainmatter
  451. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  452. \chapter{Preliminaries}
  453. \label{ch:trees-recur}
  454. \setcounter{footnote}{0}
  455. In this chapter we introduce the basic tools needed to implement a
  456. compiler. Programs are typically input by a programmer as text, that
  457. is, a sequence of characters. The program-as-text representation is
  458. called \emph{concrete syntax}. We use concrete syntax to concisely
  459. write down and talk about programs. Inside the compiler, we use
  460. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  461. that efficiently supports the operations that the compiler needs to
  462. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  463. syntax}\index{subject}{abstract syntax
  464. tree}\index{subject}{AST}\index{subject}{program}
  465. The process of translating concrete syntax to abstract syntax is
  466. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  467. chapter~\ref{ch:parsing}}.
  468. \racket{This book does not cover the theory and implementation of parsing.
  469. We refer the readers interested in parsing to the thorough treatment
  470. of parsing by \citet{Aho:2006wb}. }%
  471. %
  472. \racket{A parser is provided in the support code for translating from
  473. concrete to abstract syntax.}%
  474. %
  475. \python{For now we use the \code{parse} function in Python's
  476. \code{ast} module to translate from concrete to abstract syntax.}
  477. ASTs can be represented inside the compiler in many different ways,
  478. depending on the programming language used to write the compiler.
  479. %
  480. \racket{We use Racket's
  481. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  482. feature to represent ASTs (section~\ref{sec:ast}).}
  483. %
  484. \python{We use Python classes and objects to represent ASTs, especially the
  485. classes defined in the standard \code{ast} module for the Python
  486. source language.}
  487. %
  488. We use grammars to define the abstract syntax of programming languages
  489. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  490. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  491. recursive functions to construct and deconstruct ASTs
  492. (section~\ref{sec:recursion}). This chapter provides a brief
  493. introduction to these components.
  494. \racket{\index{subject}{struct}}
  495. \python{\index{subject}{class}\index{subject}{object}}
  496. \section{Abstract Syntax Trees}
  497. \label{sec:ast}
  498. Compilers use abstract syntax trees to represent programs because they
  499. often need to ask questions such as, for a given part of a program,
  500. what kind of language feature is it? What are its subparts? Consider
  501. the program on the left and the diagram of its AST on the
  502. right~\eqref{eq:arith-prog}. This program is an addition operation
  503. that has two subparts, a \racket{read}\python{input} operation and a
  504. negation. The negation has another subpart, the integer constant
  505. \code{8}. By using a tree to represent the program, we can easily
  506. follow the links to go from one part of a program to its subparts.
  507. \begin{center}
  508. \begin{minipage}{0.4\textwidth}
  509. {\if\edition\racketEd
  510. \begin{lstlisting}
  511. (+ (read) (- 8))
  512. \end{lstlisting}
  513. \fi}
  514. {\if\edition\pythonEd\pythonColor
  515. \begin{lstlisting}
  516. input_int() + -8
  517. \end{lstlisting}
  518. \fi}
  519. \end{minipage}
  520. \begin{minipage}{0.4\textwidth}
  521. \begin{equation}
  522. \begin{tikzpicture}
  523. \node[draw] (plus) at (0 , 0) {\key{+}};
  524. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  525. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  526. \node[draw] (8) at (1 , -2) {\key{8}};
  527. \draw[->] (plus) to (read);
  528. \draw[->] (plus) to (minus);
  529. \draw[->] (minus) to (8);
  530. \end{tikzpicture}
  531. \label{eq:arith-prog}
  532. \end{equation}
  533. \end{minipage}
  534. \end{center}
  535. We use the standard terminology for trees to describe ASTs: each
  536. rectangle above is called a \emph{node}. The arrows connect a node to its
  537. \emph{children}, which are also nodes. The top-most node is the
  538. \emph{root}. Every node except for the root has a \emph{parent} (the
  539. node of which it is the child). If a node has no children, it is a
  540. \emph{leaf} node; otherwise it is an \emph{internal} node.
  541. \index{subject}{node}
  542. \index{subject}{children}
  543. \index{subject}{root}
  544. \index{subject}{parent}
  545. \index{subject}{leaf}
  546. \index{subject}{internal node}
  547. %% Recall that an \emph{symbolic expression} (S-expression) is either
  548. %% \begin{enumerate}
  549. %% \item an atom, or
  550. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  551. %% where $e_1$ and $e_2$ are each an S-expression.
  552. %% \end{enumerate}
  553. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  554. %% null value \code{'()}, etc. We can create an S-expression in Racket
  555. %% simply by writing a backquote (called a quasi-quote in Racket)
  556. %% followed by the textual representation of the S-expression. It is
  557. %% quite common to use S-expressions to represent a list, such as $a, b
  558. %% ,c$ in the following way:
  559. %% \begin{lstlisting}
  560. %% `(a . (b . (c . ())))
  561. %% \end{lstlisting}
  562. %% Each element of the list is in the first slot of a pair, and the
  563. %% second slot is either the rest of the list or the null value, to mark
  564. %% the end of the list. Such lists are so common that Racket provides
  565. %% special notation for them that removes the need for the periods
  566. %% and so many parenthesis:
  567. %% \begin{lstlisting}
  568. %% `(a b c)
  569. %% \end{lstlisting}
  570. %% The following expression creates an S-expression that represents AST
  571. %% \eqref{eq:arith-prog}.
  572. %% \begin{lstlisting}
  573. %% `(+ (read) (- 8))
  574. %% \end{lstlisting}
  575. %% When using S-expressions to represent ASTs, the convention is to
  576. %% represent each AST node as a list and to put the operation symbol at
  577. %% the front of the list. The rest of the list contains the children. So
  578. %% in the above case, the root AST node has operation \code{`+} and its
  579. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  580. %% diagram \eqref{eq:arith-prog}.
  581. %% To build larger S-expressions one often needs to splice together
  582. %% several smaller S-expressions. Racket provides the comma operator to
  583. %% splice an S-expression into a larger one. For example, instead of
  584. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  585. %% we could have first created an S-expression for AST
  586. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  587. %% S-expression.
  588. %% \begin{lstlisting}
  589. %% (define ast1.4 `(- 8))
  590. %% (define ast1_1 `(+ (read) ,ast1.4))
  591. %% \end{lstlisting}
  592. %% In general, the Racket expression that follows the comma (splice)
  593. %% can be any expression that produces an S-expression.
  594. {\if\edition\racketEd
  595. We define a Racket \code{struct} for each kind of node. For this
  596. chapter we require just two kinds of nodes: one for integer constants
  597. (aka literals\index{subject}{literals})
  598. and one for primitive operations. The following is the \code{struct}
  599. definition for integer constants.\footnote{All the AST structures are
  600. defined in the file \code{utilities.rkt} in the support code.}
  601. \begin{lstlisting}
  602. (struct Int (value))
  603. \end{lstlisting}
  604. An integer node contains just one thing: the integer value.
  605. We establish the convention that \code{struct} names, such
  606. as \code{Int}, are capitalized.
  607. To create an AST node for the integer $8$, we write \INT{8}.
  608. \begin{lstlisting}
  609. (define eight (Int 8))
  610. \end{lstlisting}
  611. We say that the value created by \INT{8} is an
  612. \emph{instance} of the
  613. \code{Int} structure.
  614. The following is the \code{struct} definition for primitive operations.
  615. \begin{lstlisting}
  616. (struct Prim (op args))
  617. \end{lstlisting}
  618. A primitive operation node includes an operator symbol \code{op} and a
  619. list of child arguments called \code{args}. For example, to create an
  620. AST that negates the number $8$, we write the following.
  621. \begin{lstlisting}
  622. (define neg-eight (Prim '- (list eight)))
  623. \end{lstlisting}
  624. Primitive operations may have zero or more children. The \code{read}
  625. operator has zero:
  626. \begin{lstlisting}
  627. (define rd (Prim 'read '()))
  628. \end{lstlisting}
  629. The addition operator has two children:
  630. \begin{lstlisting}
  631. (define ast1_1 (Prim '+ (list rd neg-eight)))
  632. \end{lstlisting}
  633. We have made a design choice regarding the \code{Prim} structure.
  634. Instead of using one structure for many different operations
  635. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  636. structure for each operation, as follows:
  637. \begin{lstlisting}
  638. (struct Read ())
  639. (struct Add (left right))
  640. (struct Neg (value))
  641. \end{lstlisting}
  642. The reason that we choose to use just one structure is that many parts
  643. of the compiler can use the same code for the different primitive
  644. operators, so we might as well just write that code once by using a
  645. single structure.
  646. %
  647. \fi}
  648. {\if\edition\pythonEd\pythonColor
  649. We use a Python \code{class} for each kind of node.
  650. The following is the class definition for
  651. constants (aka literals\index{subject}{literals})
  652. from the Python \code{ast} module.
  653. \begin{lstlisting}
  654. class Constant:
  655. def __init__(self, value):
  656. self.value = value
  657. \end{lstlisting}
  658. An integer constant node includes just one thing: the integer value.
  659. To create an AST node for the integer $8$, we write \INT{8}.
  660. \begin{lstlisting}
  661. eight = Constant(8)
  662. \end{lstlisting}
  663. We say that the value created by \INT{8} is an
  664. \emph{instance} of the \code{Constant} class.
  665. The following is the class definition for unary operators.
  666. \begin{lstlisting}
  667. class UnaryOp:
  668. def __init__(self, op, operand):
  669. self.op = op
  670. self.operand = operand
  671. \end{lstlisting}
  672. The specific operation is specified by the \code{op} parameter. For
  673. example, the class \code{USub} is for unary subtraction.
  674. (More unary operators are introduced in later chapters.) To create an AST that
  675. negates the number $8$, we write the following.
  676. \begin{lstlisting}
  677. neg_eight = UnaryOp(USub(), eight)
  678. \end{lstlisting}
  679. The call to the \code{input\_int} function is represented by the
  680. \code{Call} and \code{Name} classes.
  681. \begin{lstlisting}
  682. class Call:
  683. def __init__(self, func, args):
  684. self.func = func
  685. self.args = args
  686. class Name:
  687. def __init__(self, id):
  688. self.id = id
  689. \end{lstlisting}
  690. To create an AST node that calls \code{input\_int}, we write
  691. \begin{lstlisting}
  692. read = Call(Name('input_int'), [])
  693. \end{lstlisting}
  694. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  695. the \code{BinOp} class for binary operators.
  696. \begin{lstlisting}
  697. class BinOp:
  698. def __init__(self, left, op, right):
  699. self.op = op
  700. self.left = left
  701. self.right = right
  702. \end{lstlisting}
  703. Similar to \code{UnaryOp}, the specific operation is specified by the
  704. \code{op} parameter, which for now is just an instance of the
  705. \code{Add} class. So to create the AST
  706. node that adds negative eight to some user input, we write the following.
  707. \begin{lstlisting}
  708. ast1_1 = BinOp(read, Add(), neg_eight)
  709. \end{lstlisting}
  710. \fi}
  711. To compile a program such as \eqref{eq:arith-prog}, we need to know
  712. that the operation associated with the root node is addition and we
  713. need to be able to access its two
  714. children. \racket{Racket}\python{Python} provides pattern matching to
  715. support these kinds of queries, as we see in
  716. section~\ref{sec:pattern-matching}.
  717. We often write down the concrete syntax of a program even when we
  718. actually have in mind the AST, because the concrete syntax is more
  719. concise. We recommend that you always think of programs as abstract
  720. syntax trees.
  721. \section{Grammars}
  722. \label{sec:grammar}
  723. \index{subject}{integer}
  724. %\index{subject}{constant}
  725. A programming language can be thought of as a \emph{set} of programs.
  726. The set is infinite (that is, one can always create larger programs),
  727. so one cannot simply describe a language by listing all the
  728. programs in the language. Instead we write down a set of rules, a
  729. \emph{context-free grammar}, for building programs. Grammars are often used to
  730. define the concrete syntax of a language, but they can also be used to
  731. describe the abstract syntax. We write our rules in a variant of
  732. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  733. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  734. we describe a small language, named \LangInt{}, that consists of
  735. integers and arithmetic operations.\index{subject}{grammar}
  736. \index{subject}{context-free grammar}
  737. The first grammar rule for the abstract syntax of \LangInt{} says that an
  738. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  739. \begin{equation}
  740. \Exp ::= \INT{\Int} \label{eq:arith-int}
  741. \end{equation}
  742. %
  743. Each rule has a left-hand side and a right-hand side.
  744. If you have an AST node that matches the
  745. right-hand side, then you can categorize it according to the
  746. left-hand side.
  747. %
  748. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  749. are \emph{terminal} symbols and must literally appear in the program for the
  750. rule to be applicable.\index{subject}{terminal}
  751. %
  752. Our grammars do not mention \emph{white space}, that is, delimiter
  753. characters like spaces, tabs, and new lines. White space may be
  754. inserted between symbols for disambiguation and to improve
  755. readability. \index{subject}{white space}
  756. %
  757. A name such as $\Exp$ that is defined by the grammar rules is a
  758. \emph{nonterminal}. \index{subject}{nonterminal}
  759. %
  760. The name $\Int$ is also a nonterminal, but instead of defining it with
  761. a grammar rule, we define it with the following explanation. An
  762. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  763. $-$ (for negative integers), such that the sequence of decimals
  764. %
  765. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  766. enables the representation of integers using 63 bits, which simplifies
  767. several aspects of compilation.
  768. %
  769. Thus, these integers correspond to the Racket \texttt{fixnum}
  770. datatype on a 64-bit machine.}
  771. %
  772. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  773. enables the representation of integers using 64 bits, which simplifies
  774. several aspects of compilation. In contrast, integers in Python have
  775. unlimited precision, but the techniques needed to handle unlimited
  776. precision fall outside the scope of this book.}
  777. The second grammar rule is the \READOP{} operation, which receives an
  778. input integer from the user of the program.
  779. \begin{equation}
  780. \Exp ::= \READ{} \label{eq:arith-read}
  781. \end{equation}
  782. The third rule categorizes the negation of an $\Exp$ node as an
  783. $\Exp$.
  784. \begin{equation}
  785. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  786. \end{equation}
  787. We can apply these rules to categorize the ASTs that are in the
  788. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  789. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  790. following AST is an $\Exp$.
  791. \begin{center}
  792. \begin{minipage}{0.5\textwidth}
  793. \NEG{\INT{\code{8}}}
  794. \end{minipage}
  795. \begin{minipage}{0.25\textwidth}
  796. \begin{equation}
  797. \begin{tikzpicture}
  798. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  799. \node[draw, circle] (8) at (0, -1.2) {$8$};
  800. \draw[->] (minus) to (8);
  801. \end{tikzpicture}
  802. \label{eq:arith-neg8}
  803. \end{equation}
  804. \end{minipage}
  805. \end{center}
  806. The next two grammar rules are for addition and subtraction expressions:
  807. \begin{align}
  808. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  809. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  810. \end{align}
  811. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  812. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  813. \eqref{eq:arith-read}, and we have already categorized
  814. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  815. to show that
  816. \[
  817. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  818. \]
  819. is an $\Exp$ in the \LangInt{} language.
  820. If you have an AST for which these rules do not apply, then the
  821. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  822. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  823. because there is no rule for the \key{*} operator. Whenever we
  824. define a language with a grammar, the language includes only those
  825. programs that are justified by the grammar rules.
  826. {\if\edition\pythonEd\pythonColor
  827. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  828. There is a statement for printing the value of an expression
  829. \[
  830. \Stmt{} ::= \PRINT{\Exp}
  831. \]
  832. and a statement that evaluates an expression but ignores the result.
  833. \[
  834. \Stmt{} ::= \EXPR{\Exp}
  835. \]
  836. \fi}
  837. {\if\edition\racketEd
  838. The last grammar rule for \LangInt{} states that there is a
  839. \code{Program} node to mark the top of the whole program:
  840. \[
  841. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  842. \]
  843. The \code{Program} structure is defined as follows:
  844. \begin{lstlisting}
  845. (struct Program (info body))
  846. \end{lstlisting}
  847. where \code{body} is an expression. In further chapters, the \code{info}
  848. part is used to store auxiliary information, but for now it is
  849. just the empty list.
  850. \fi}
  851. {\if\edition\pythonEd\pythonColor
  852. The last grammar rule for \LangInt{} states that there is a
  853. \code{Module} node to mark the top of the whole program:
  854. \[
  855. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  856. \]
  857. The asterisk $*$ indicates a list of the preceding grammar item, in
  858. this case a list of statements.
  859. %
  860. The \code{Module} class is defined as follows:
  861. \begin{lstlisting}
  862. class Module:
  863. def __init__(self, body):
  864. self.body = body
  865. \end{lstlisting}
  866. where \code{body} is a list of statements.
  867. \fi}
  868. It is common to have many grammar rules with the same left-hand side
  869. but different right-hand sides, such as the rules for $\Exp$ in the
  870. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  871. combine several right-hand sides into a single rule.
  872. The concrete syntax for \LangInt{} is shown in
  873. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  874. \LangInt{} is shown in figure~\ref{fig:r0-syntax}. %
  875. %
  876. \racket{The \code{read-program} function provided in
  877. \code{utilities.rkt} of the support code reads a program from a file
  878. (the sequence of characters in the concrete syntax of Racket) and
  879. parses it into an abstract syntax tree. Refer to the description of
  880. \code{read-program} in appendix~\ref{appendix:utilities} for more
  881. details.}
  882. %
  883. \python{We recommend using the \code{parse} function in Python's
  884. \code{ast} module to convert the concrete syntax into an abstract
  885. syntax tree.}
  886. \newcommand{\LintGrammarRacket}{
  887. \begin{array}{rcl}
  888. \Type &::=& \key{Integer} \\
  889. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  890. \MID \CSUB{\Exp}{\Exp}
  891. \end{array}
  892. }
  893. \newcommand{\LintASTRacket}{
  894. \begin{array}{rcl}
  895. \Type &::=& \key{Integer} \\
  896. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  897. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  898. \end{array}
  899. }
  900. \newcommand{\LintGrammarPython}{
  901. \begin{array}{rcl}
  902. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  903. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  904. \end{array}
  905. }
  906. \newcommand{\LintASTPython}{
  907. \begin{array}{rcl}
  908. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  909. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  910. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  911. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  912. \end{array}
  913. }
  914. \begin{figure}[tp]
  915. \begin{tcolorbox}[colback=white]
  916. {\if\edition\racketEd
  917. \[
  918. \begin{array}{l}
  919. \LintGrammarRacket \\
  920. \begin{array}{rcl}
  921. \LangInt{} &::=& \Exp
  922. \end{array}
  923. \end{array}
  924. \]
  925. \fi}
  926. {\if\edition\pythonEd\pythonColor
  927. \[
  928. \begin{array}{l}
  929. \LintGrammarPython \\
  930. \begin{array}{rcl}
  931. \LangInt{} &::=& \Stmt^{*}
  932. \end{array}
  933. \end{array}
  934. \]
  935. \fi}
  936. \end{tcolorbox}
  937. \caption{The concrete syntax of \LangInt{}.}
  938. \label{fig:r0-concrete-syntax}
  939. \index{subject}{Lint@\LangInt{} concrete syntax}
  940. \end{figure}
  941. \begin{figure}[tp]
  942. \begin{tcolorbox}[colback=white]
  943. {\if\edition\racketEd
  944. \[
  945. \begin{array}{l}
  946. \LintASTRacket{} \\
  947. \begin{array}{rcl}
  948. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  949. \end{array}
  950. \end{array}
  951. \]
  952. \fi}
  953. {\if\edition\pythonEd\pythonColor
  954. \[
  955. \begin{array}{l}
  956. \LintASTPython\\
  957. \begin{array}{rcl}
  958. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  959. \end{array}
  960. \end{array}
  961. \]
  962. \fi}
  963. \end{tcolorbox}
  964. \python{
  965. \index{subject}{Constant@\texttt{Constant}}
  966. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  967. \index{subject}{USub@\texttt{USub}}
  968. \index{subject}{inputint@\texttt{input\_int}}
  969. \index{subject}{Call@\texttt{Call}}
  970. \index{subject}{Name@\texttt{Name}}
  971. \index{subject}{BinOp@\texttt{BinOp}}
  972. \index{subject}{Add@\texttt{Add}}
  973. \index{subject}{Sub@\texttt{Sub}}
  974. \index{subject}{print@\texttt{print}}
  975. \index{subject}{Expr@\texttt{Expr}}
  976. \index{subject}{Module@\texttt{Module}}
  977. }
  978. \caption{The abstract syntax of \LangInt{}.}
  979. \label{fig:r0-syntax}
  980. \index{subject}{Lint@\LangInt{} abstract syntax}
  981. \end{figure}
  982. \section{Pattern Matching}
  983. \label{sec:pattern-matching}
  984. As mentioned in section~\ref{sec:ast}, compilers often need to access
  985. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  986. provides the \texttt{match} feature to access the parts of a value.
  987. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  988. \begin{center}
  989. \begin{minipage}{1.0\textwidth}
  990. {\if\edition\racketEd
  991. \begin{lstlisting}
  992. (match ast1_1
  993. [(Prim op (list child1 child2))
  994. (print op)])
  995. \end{lstlisting}
  996. \fi}
  997. {\if\edition\pythonEd\pythonColor
  998. \begin{lstlisting}
  999. match ast1_1:
  1000. case BinOp(child1, op, child2):
  1001. print(op)
  1002. \end{lstlisting}
  1003. \fi}
  1004. \end{minipage}
  1005. \end{center}
  1006. {\if\edition\racketEd
  1007. %
  1008. In this example, the \texttt{match} form checks whether the AST
  1009. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1010. three pattern variables \texttt{op}, \texttt{child1}, and
  1011. \texttt{child2}. In general, a match clause consists of a
  1012. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1013. recursively defined to be a pattern variable, a structure name
  1014. followed by a pattern for each of the structure's arguments, or an
  1015. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1016. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1017. and chapter 9 of The Racket
  1018. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1019. for complete descriptions of \code{match}.)
  1020. %
  1021. The body of a match clause may contain arbitrary Racket code. The
  1022. pattern variables can be used in the scope of the body, such as
  1023. \code{op} in \code{(print op)}.
  1024. %
  1025. \fi}
  1026. %
  1027. %
  1028. {\if\edition\pythonEd\pythonColor
  1029. %
  1030. In the example above, the \texttt{match} form checks whether the AST
  1031. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1032. three pattern variables (\texttt{child1}, \texttt{op}, and
  1033. \texttt{child2}). In general, each \code{case} consists of a
  1034. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1035. recursively defined to be one of the following: a pattern variable, a
  1036. class name followed by a pattern for each of its constructor's
  1037. arguments, or other literals\index{subject}{literals} such as strings
  1038. or lists.
  1039. %
  1040. The body of each \code{case} may contain arbitrary Python code. The
  1041. pattern variables can be used in the body, such as \code{op} in
  1042. \code{print(op)}.
  1043. %
  1044. \fi}
  1045. A \code{match} form may contain several clauses, as in the following
  1046. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1047. the AST. The \code{match} proceeds through the clauses in order,
  1048. checking whether the pattern can match the input AST. The body of the
  1049. first clause that matches is executed. The output of \code{leaf} for
  1050. several ASTs is shown on the right side of the following:
  1051. \begin{center}
  1052. \begin{minipage}{0.6\textwidth}
  1053. {\if\edition\racketEd
  1054. \begin{lstlisting}
  1055. (define (leaf arith)
  1056. (match arith
  1057. [(Int n) #t]
  1058. [(Prim 'read '()) #t]
  1059. [(Prim '- (list e1)) #f]
  1060. [(Prim '+ (list e1 e2)) #f]
  1061. [(Prim '- (list e1 e2)) #f]))
  1062. (leaf (Prim 'read '()))
  1063. (leaf (Prim '- (list (Int 8))))
  1064. (leaf (Int 8))
  1065. \end{lstlisting}
  1066. \fi}
  1067. {\if\edition\pythonEd\pythonColor
  1068. \begin{lstlisting}
  1069. def leaf(arith):
  1070. match arith:
  1071. case Constant(n):
  1072. return True
  1073. case Call(Name('input_int'), []):
  1074. return True
  1075. case UnaryOp(USub(), e1):
  1076. return False
  1077. case BinOp(e1, Add(), e2):
  1078. return False
  1079. case BinOp(e1, Sub(), e2):
  1080. return False
  1081. print(leaf(Call(Name('input_int'), [])))
  1082. print(leaf(UnaryOp(USub(), eight)))
  1083. print(leaf(Constant(8)))
  1084. \end{lstlisting}
  1085. \fi}
  1086. \end{minipage}
  1087. \vrule
  1088. \begin{minipage}{0.25\textwidth}
  1089. {\if\edition\racketEd
  1090. \begin{lstlisting}
  1091. #t
  1092. #f
  1093. #t
  1094. \end{lstlisting}
  1095. \fi}
  1096. {\if\edition\pythonEd\pythonColor
  1097. \begin{lstlisting}
  1098. True
  1099. False
  1100. True
  1101. \end{lstlisting}
  1102. \fi}
  1103. \end{minipage}
  1104. \index{subject}{True@\TRUE{}}
  1105. \index{subject}{False@\FALSE{}}
  1106. \end{center}
  1107. When constructing a \code{match} expression, we refer to the grammar
  1108. definition to identify which nonterminal we are expecting to match
  1109. against, and then we make sure that (1) we have one
  1110. \racket{clause}\python{case} for each alternative of that nonterminal
  1111. and (2) the pattern in each \racket{clause}\python{case}
  1112. corresponds to the corresponding right-hand side of a grammar
  1113. rule. For the \code{match} in the \code{leaf} function, we refer to
  1114. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1115. nonterminal has five alternatives, so the \code{match} has five
  1116. \racket{clauses}\python{cases}. The pattern in each
  1117. \racket{clause}\python{case} corresponds to the right-hand side of a
  1118. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1119. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1120. translating from grammars to patterns, replace nonterminals such as
  1121. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1122. \code{e2}).
  1123. \section{Recursive Functions}
  1124. \label{sec:recursion}
  1125. \index{subject}{recursive function}
  1126. Programs are inherently recursive. For example, an expression is often
  1127. made of smaller expressions. Thus, the natural way to process an
  1128. entire program is to use a recursive function. As a first example of
  1129. such a recursive function, we define the function \code{is\_exp} as
  1130. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1131. value and determine whether or not it is an expression in \LangInt{}.
  1132. %
  1133. We say that a function is defined by \emph{structural recursion} if
  1134. it is defined using a sequence of match \racket{clauses}\python{cases}
  1135. that correspond to a grammar and the body of each
  1136. \racket{clause}\python{case} makes a recursive call on each child
  1137. node.\footnote{This principle of structuring code according to the
  1138. data definition is advocated in the book \emph{How to Design
  1139. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1140. second function, named \code{is\_stmt}, that recognizes whether a value
  1141. is a \LangInt{} statement.} \python{Finally, }
  1142. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1143. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1144. In general, we can write one recursive function to handle each
  1145. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1146. two examples at the bottom of the figure, the first is in
  1147. \LangInt{} and the second is not.
  1148. \begin{figure}[tp]
  1149. \begin{tcolorbox}[colback=white]
  1150. {\if\edition\racketEd
  1151. \begin{lstlisting}
  1152. (define (is_exp ast)
  1153. (match ast
  1154. [(Int n) #t]
  1155. [(Prim 'read '()) #t]
  1156. [(Prim '- (list e)) (is_exp e)]
  1157. [(Prim '+ (list e1 e2))
  1158. (and (is_exp e1) (is_exp e2))]
  1159. [(Prim '- (list e1 e2))
  1160. (and (is_exp e1) (is_exp e2))]
  1161. [else #f]))
  1162. (define (is_Lint ast)
  1163. (match ast
  1164. [(Program '() e) (is_exp e)]
  1165. [else #f]))
  1166. (is_Lint (Program '() ast1_1))
  1167. (is_Lint (Program '()
  1168. (Prim '* (list (Prim 'read '())
  1169. (Prim '+ (list (Int 8)))))))
  1170. \end{lstlisting}
  1171. \fi}
  1172. {\if\edition\pythonEd\pythonColor
  1173. \begin{lstlisting}
  1174. def is_exp(e):
  1175. match e:
  1176. case Constant(n):
  1177. return True
  1178. case Call(Name('input_int'), []):
  1179. return True
  1180. case UnaryOp(USub(), e1):
  1181. return is_exp(e1)
  1182. case BinOp(e1, Add(), e2):
  1183. return is_exp(e1) and is_exp(e2)
  1184. case BinOp(e1, Sub(), e2):
  1185. return is_exp(e1) and is_exp(e2)
  1186. case _:
  1187. return False
  1188. def is_stmt(s):
  1189. match s:
  1190. case Expr(Call(Name('print'), [e])):
  1191. return is_exp(e)
  1192. case Expr(e):
  1193. return is_exp(e)
  1194. case _:
  1195. return False
  1196. def is_Lint(p):
  1197. match p:
  1198. case Module(body):
  1199. return all([is_stmt(s) for s in body])
  1200. case _:
  1201. return False
  1202. print(is_Lint(Module([Expr(ast1_1)])))
  1203. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1204. UnaryOp(Add(), Constant(8))))])))
  1205. \end{lstlisting}
  1206. \fi}
  1207. \end{tcolorbox}
  1208. \caption{Example of recursive functions for \LangInt{}. These functions
  1209. recognize whether an AST is in \LangInt{}.}
  1210. \label{fig:exp-predicate}
  1211. \end{figure}
  1212. %% You may be tempted to merge the two functions into one, like this:
  1213. %% \begin{center}
  1214. %% \begin{minipage}{0.5\textwidth}
  1215. %% \begin{lstlisting}
  1216. %% (define (Lint ast)
  1217. %% (match ast
  1218. %% [(Int n) #t]
  1219. %% [(Prim 'read '()) #t]
  1220. %% [(Prim '- (list e)) (Lint e)]
  1221. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1222. %% [(Program '() e) (Lint e)]
  1223. %% [else #f]))
  1224. %% \end{lstlisting}
  1225. %% \end{minipage}
  1226. %% \end{center}
  1227. %% %
  1228. %% Sometimes such a trick will save a few lines of code, especially when
  1229. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1230. %% \emph{not} recommended because it can get you into trouble.
  1231. %% %
  1232. %% For example, the above function is subtly wrong:
  1233. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1234. %% returns true when it should return false.
  1235. \section{Interpreters}
  1236. \label{sec:interp_Lint}
  1237. \index{subject}{interpreter}
  1238. The behavior of a program is defined by the specification of the
  1239. programming language.
  1240. %
  1241. \racket{For example, the Scheme language is defined in the report by
  1242. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1243. reference manual~\citep{plt-tr}.}
  1244. %
  1245. \python{For example, the Python language is defined in the Python
  1246. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1247. %
  1248. In this book we use interpreters to specify each language that we
  1249. consider. An interpreter that is designated as the definition of a
  1250. language is called a \emph{definitional
  1251. interpreter}~\citep{reynolds72:_def_interp}.
  1252. \index{subject}{definitional interpreter} We warm up by creating a
  1253. definitional interpreter for the \LangInt{} language. This interpreter
  1254. serves as a second example of structural recursion. The definition of the
  1255. \code{interp\_Lint} function is shown in
  1256. figure~\ref{fig:interp_Lint}.
  1257. %
  1258. \racket{The body of the function is a match on the input program
  1259. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1260. which in turn has one match clause per grammar rule for \LangInt{}
  1261. expressions.}
  1262. %
  1263. \python{The body of the function matches on the \code{Module} AST node
  1264. and then invokes \code{interp\_stmt} on each statement in the
  1265. module. The \code{interp\_stmt} function includes a case for each
  1266. grammar rule of the \Stmt{} nonterminal, and it calls
  1267. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1268. function includes a case for each grammar rule of the \Exp{}
  1269. nonterminal. We use several auxiliary functions such as \code{add64}
  1270. and \code{input\_int} that are defined in the support code for this book.}
  1271. \begin{figure}[tp]
  1272. \begin{tcolorbox}[colback=white]
  1273. {\if\edition\racketEd
  1274. \begin{lstlisting}
  1275. (define (interp_exp e)
  1276. (match e
  1277. [(Int n) n]
  1278. [(Prim 'read '())
  1279. (define r (read))
  1280. (cond [(fixnum? r) r]
  1281. [else (error 'interp_exp "read expected an integer: ~v" r)])]
  1282. [(Prim '- (list e))
  1283. (define v (interp_exp e))
  1284. (fx- 0 v)]
  1285. [(Prim '+ (list e1 e2))
  1286. (define v1 (interp_exp e1))
  1287. (define v2 (interp_exp e2))
  1288. (fx+ v1 v2)]
  1289. [(Prim '- (list e1 e2))
  1290. (define v1 (interp_exp e1))
  1291. (define v2 (interp_exp e2))
  1292. (fx- v1 v2)]))
  1293. (define (interp_Lint p)
  1294. (match p
  1295. [(Program '() e) (interp_exp e)]))
  1296. \end{lstlisting}
  1297. \fi}
  1298. {\if\edition\pythonEd\pythonColor
  1299. \begin{lstlisting}
  1300. def interp_exp(e):
  1301. match e:
  1302. case BinOp(left, Add(), right):
  1303. l = interp_exp(left); r = interp_exp(right)
  1304. return add64(l, r)
  1305. case BinOp(left, Sub(), right):
  1306. l = interp_exp(left); r = interp_exp(right)
  1307. return sub64(l, r)
  1308. case UnaryOp(USub(), v):
  1309. return neg64(interp_exp(v))
  1310. case Constant(value):
  1311. return value
  1312. case Call(Name('input_int'), []):
  1313. return input_int()
  1314. def interp_stmt(s):
  1315. match s:
  1316. case Expr(Call(Name('print'), [arg])):
  1317. print(interp_exp(arg))
  1318. case Expr(value):
  1319. interp_exp(value)
  1320. def interp_Lint(p):
  1321. match p:
  1322. case Module(body):
  1323. for s in body:
  1324. interp_stmt(s)
  1325. \end{lstlisting}
  1326. \fi}
  1327. \end{tcolorbox}
  1328. \caption{Interpreter for the \LangInt{} language.}
  1329. \label{fig:interp_Lint}
  1330. \end{figure}
  1331. Let us consider the result of interpreting a few \LangInt{} programs. The
  1332. following program adds two integers:
  1333. {\if\edition\racketEd
  1334. \begin{lstlisting}
  1335. (+ 10 32)
  1336. \end{lstlisting}
  1337. \fi}
  1338. {\if\edition\pythonEd\pythonColor
  1339. \begin{lstlisting}
  1340. print(10 + 32)
  1341. \end{lstlisting}
  1342. \fi}
  1343. %
  1344. \noindent The result is \key{42}, the answer to life, the universe,
  1345. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1346. the Galaxy} by Douglas Adams.}
  1347. %
  1348. We wrote this program in concrete syntax, whereas the parsed
  1349. abstract syntax is
  1350. {\if\edition\racketEd
  1351. \begin{lstlisting}
  1352. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1353. \end{lstlisting}
  1354. \fi}
  1355. {\if\edition\pythonEd\pythonColor
  1356. \begin{lstlisting}
  1357. Module([Expr(Call(Name('print'),
  1358. [BinOp(Constant(10), Add(), Constant(32))]))])
  1359. \end{lstlisting}
  1360. \fi}
  1361. The following program demonstrates that expressions may be nested within
  1362. each other, in this case nesting several additions and negations.
  1363. {\if\edition\racketEd
  1364. \begin{lstlisting}
  1365. (+ 10 (- (+ 12 20)))
  1366. \end{lstlisting}
  1367. \fi}
  1368. {\if\edition\pythonEd\pythonColor
  1369. \begin{lstlisting}
  1370. print(10 + -(12 + 20))
  1371. \end{lstlisting}
  1372. \fi}
  1373. %
  1374. \noindent What is the result of this program?
  1375. {\if\edition\racketEd
  1376. As mentioned previously, the \LangInt{} language does not support
  1377. arbitrarily large integers but only $63$-bit integers, so we
  1378. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1379. in Racket.
  1380. Suppose that
  1381. \[
  1382. n = 999999999999999999
  1383. \]
  1384. which indeed fits in $63$ bits. What happens when we run the
  1385. following program in our interpreter?
  1386. \begin{lstlisting}
  1387. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1388. \end{lstlisting}
  1389. It produces the following error:
  1390. \begin{lstlisting}
  1391. fx+: result is not a fixnum
  1392. \end{lstlisting}
  1393. We establish the convention that if running the definitional
  1394. interpreter on a program produces an error, then the meaning of that
  1395. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1396. error is a \code{trapped-error}. A compiler for the language is under
  1397. no obligation regarding programs with unspecified behavior; it does
  1398. not have to produce an executable, and if it does, that executable can
  1399. do anything. On the other hand, if the error is a
  1400. \code{trapped-error}, then the compiler must produce an executable and
  1401. it is required to report that an error occurred. To signal an error,
  1402. exit with a return code of \code{255}. The interpreters in chapters
  1403. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1404. \code{trapped-error}.
  1405. \fi}
  1406. % TODO: how to deal with too-large integers in the Python interpreter?
  1407. %% This convention applies to the languages defined in this
  1408. %% book, as a way to simplify the student's task of implementing them,
  1409. %% but this convention is not applicable to all programming languages.
  1410. %%
  1411. The last feature of the \LangInt{} language, the \READOP{} operation,
  1412. prompts the user of the program for an integer. Recall that program
  1413. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1414. \code{8}. So, if we run {\if\edition\racketEd
  1415. \begin{lstlisting}
  1416. (interp_Lint (Program '() ast1_1))
  1417. \end{lstlisting}
  1418. \fi}
  1419. {\if\edition\pythonEd\pythonColor
  1420. \begin{lstlisting}
  1421. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1422. \end{lstlisting}
  1423. \fi}
  1424. \noindent and if the input is \code{50}, the result is \code{42}.
  1425. We include the \READOP{} operation in \LangInt{} so that a clever
  1426. student cannot implement a compiler for \LangInt{} that simply runs
  1427. the interpreter during compilation to obtain the output and then
  1428. generates the trivial code to produce the output.\footnote{Yes, a
  1429. clever student did this in the first instance of this course!}
  1430. The job of a compiler is to translate a program in one language into a
  1431. program in another language so that the output program behaves the
  1432. same way as the input program. This idea is depicted in the
  1433. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1434. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1435. Given a compiler that translates from language $\mathcal{L}_1$ to
  1436. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1437. compiler must translate it into some program $P_2$ such that
  1438. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1439. same input $i$ yields the same output $o$.
  1440. \begin{equation} \label{eq:compile-correct}
  1441. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1442. \node (p1) at (0, 0) {$P_1$};
  1443. \node (p2) at (3, 0) {$P_2$};
  1444. \node (o) at (3, -2.5) {$o$};
  1445. \path[->] (p1) edge [above] node {compile} (p2);
  1446. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1447. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1448. \end{tikzpicture}
  1449. \end{equation}
  1450. \python{We establish the convention that if running the definitional
  1451. interpreter on a program produces an error, then the meaning of that
  1452. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1453. unless the exception raised is a \code{TrappedError}. A compiler for
  1454. the language is under no obligation regarding programs with
  1455. unspecified behavior; it does not have to produce an executable, and
  1456. if it does, that executable can do anything. On the other hand, if
  1457. the error is a \code{TrappedError}, then the compiler must produce
  1458. an executable and it is required to report that an error
  1459. occurred. To signal an error, exit with a return code of \code{255}.
  1460. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1461. section \ref{sec:arrays} use \code{TrappedError}.}
  1462. In the next section we see our first example of a compiler.
  1463. \section{Example Compiler: A Partial Evaluator}
  1464. \label{sec:partial-evaluation}
  1465. In this section we consider a compiler that translates \LangInt{}
  1466. programs into \LangInt{} programs that may be more efficient. The
  1467. compiler eagerly computes the parts of the program that do not depend
  1468. on any inputs, a process known as \emph{partial
  1469. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1470. For example, given the following program
  1471. {\if\edition\racketEd
  1472. \begin{lstlisting}
  1473. (+ (read) (- (+ 5 3)))
  1474. \end{lstlisting}
  1475. \fi}
  1476. {\if\edition\pythonEd\pythonColor
  1477. \begin{lstlisting}
  1478. print(input_int() + -(5 + 3) )
  1479. \end{lstlisting}
  1480. \fi}
  1481. \noindent our compiler translates it into the program
  1482. {\if\edition\racketEd
  1483. \begin{lstlisting}
  1484. (+ (read) -8)
  1485. \end{lstlisting}
  1486. \fi}
  1487. {\if\edition\pythonEd\pythonColor
  1488. \begin{lstlisting}
  1489. print(input_int() + -8)
  1490. \end{lstlisting}
  1491. \fi}
  1492. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1493. evaluator for the \LangInt{} language. The output of the partial evaluator
  1494. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1495. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1496. whereas the code for partially evaluating the negation and addition
  1497. operations is factored into three auxiliary functions:
  1498. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1499. functions is the output of partially evaluating the children.
  1500. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1501. arguments are integers and if they are, perform the appropriate
  1502. arithmetic. Otherwise, they create an AST node for the arithmetic
  1503. operation.
  1504. \begin{figure}[tp]
  1505. \begin{tcolorbox}[colback=white]
  1506. {\if\edition\racketEd
  1507. \begin{lstlisting}
  1508. (define (pe_neg r)
  1509. (match r
  1510. [(Int n) (Int (fx- 0 n))]
  1511. [else (Prim '- (list r))]))
  1512. (define (pe_add r1 r2)
  1513. (match* (r1 r2)
  1514. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1515. [(_ _) (Prim '+ (list r1 r2))]))
  1516. (define (pe_sub r1 r2)
  1517. (match* (r1 r2)
  1518. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1519. [(_ _) (Prim '- (list r1 r2))]))
  1520. (define (pe_exp e)
  1521. (match e
  1522. [(Int n) (Int n)]
  1523. [(Prim 'read '()) (Prim 'read '())]
  1524. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1525. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1526. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1527. (define (pe_Lint p)
  1528. (match p
  1529. [(Program '() e) (Program '() (pe_exp e))]))
  1530. \end{lstlisting}
  1531. \fi}
  1532. {\if\edition\pythonEd\pythonColor
  1533. \begin{lstlisting}
  1534. def pe_neg(r):
  1535. match r:
  1536. case Constant(n):
  1537. return Constant(neg64(n))
  1538. case _:
  1539. return UnaryOp(USub(), r)
  1540. def pe_add(r1, r2):
  1541. match (r1, r2):
  1542. case (Constant(n1), Constant(n2)):
  1543. return Constant(add64(n1, n2))
  1544. case _:
  1545. return BinOp(r1, Add(), r2)
  1546. def pe_sub(r1, r2):
  1547. match (r1, r2):
  1548. case (Constant(n1), Constant(n2)):
  1549. return Constant(sub64(n1, n2))
  1550. case _:
  1551. return BinOp(r1, Sub(), r2)
  1552. def pe_exp(e):
  1553. match e:
  1554. case BinOp(left, Add(), right):
  1555. return pe_add(pe_exp(left), pe_exp(right))
  1556. case BinOp(left, Sub(), right):
  1557. return pe_sub(pe_exp(left), pe_exp(right))
  1558. case UnaryOp(USub(), v):
  1559. return pe_neg(pe_exp(v))
  1560. case Constant(value):
  1561. return e
  1562. case Call(Name('input_int'), []):
  1563. return e
  1564. def pe_stmt(s):
  1565. match s:
  1566. case Expr(Call(Name('print'), [arg])):
  1567. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1568. case Expr(value):
  1569. return Expr(pe_exp(value))
  1570. def pe_Lint(p):
  1571. match p:
  1572. case Module(body):
  1573. new_body = [pe_stmt(s) for s in body]
  1574. return Module(new_body)
  1575. \end{lstlisting}
  1576. \fi}
  1577. \end{tcolorbox}
  1578. \caption{A partial evaluator for \LangInt{}.}
  1579. \label{fig:pe-arith}
  1580. \end{figure}
  1581. To gain some confidence that the partial evaluator is correct, we can
  1582. test whether it produces programs that produce the same result as the
  1583. input programs. That is, we can test whether it satisfies the diagram
  1584. of \eqref{eq:compile-correct}.
  1585. %
  1586. {\if\edition\racketEd
  1587. The following code runs the partial evaluator on several examples and
  1588. tests the output program. The \texttt{parse-program} and
  1589. \texttt{assert} functions are defined in
  1590. appendix~\ref{appendix:utilities}.\\
  1591. \begin{minipage}{1.0\textwidth}
  1592. \begin{lstlisting}
  1593. (define (test_pe p)
  1594. (assert "testing pe_Lint"
  1595. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1596. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1597. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1598. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1599. \end{lstlisting}
  1600. \end{minipage}
  1601. \fi}
  1602. % TODO: python version of testing the PE
  1603. \begin{exercise}\normalfont\normalsize
  1604. Create three programs in the \LangInt{} language and test whether
  1605. partially evaluating them with \code{pe\_Lint} and then
  1606. interpreting them with \code{interp\_Lint} gives the same result
  1607. as directly interpreting them with \code{interp\_Lint}.
  1608. \end{exercise}
  1609. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1610. \chapter{Integers and Variables}
  1611. \label{ch:Lvar}
  1612. \setcounter{footnote}{0}
  1613. This chapter covers compiling a subset of
  1614. \racket{Racket}\python{Python} to x86-64 assembly
  1615. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1616. integer arithmetic and local variables. We often refer to x86-64
  1617. simply as x86. The chapter first describes the \LangVar{} language
  1618. (section~\ref{sec:s0}) and then introduces x86 assembly
  1619. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1620. discuss only the instructions needed for compiling \LangVar{}. We
  1621. introduce more x86 instructions in subsequent chapters. After
  1622. introducing \LangVar{} and x86, we reflect on their differences and
  1623. create a plan to break down the translation from \LangVar{} to x86
  1624. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1625. the chapter gives detailed hints regarding each step. We aim to give
  1626. enough hints that the well-prepared reader, together with a few
  1627. friends, can implement a compiler from \LangVar{} to x86 in a short
  1628. time. To suggest the scale of this first compiler, we note that the
  1629. instructor solution for the \LangVar{} compiler is approximately
  1630. \racket{500}\python{300} lines of code.
  1631. \section{The \LangVar{} Language}
  1632. \label{sec:s0}
  1633. \index{subject}{variable}
  1634. The \LangVar{} language extends the \LangInt{} language with
  1635. variables. The concrete syntax of the \LangVar{} language is defined
  1636. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1637. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1638. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1639. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1640. \key{-} is a unary operator, and \key{+} is a binary operator.
  1641. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1642. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1643. the top of the program.
  1644. %% The $\itm{info}$
  1645. %% field of the \key{Program} structure contains an \emph{association
  1646. %% list} (a list of key-value pairs) that is used to communicate
  1647. %% auxiliary data from one compiler pass the next.
  1648. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1649. exhibit several compilation techniques.
  1650. \newcommand{\LvarGrammarRacket}{
  1651. \begin{array}{rcl}
  1652. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1653. \end{array}
  1654. }
  1655. \newcommand{\LvarASTRacket}{
  1656. \begin{array}{rcl}
  1657. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1658. \end{array}
  1659. }
  1660. \newcommand{\LvarGrammarPython}{
  1661. \begin{array}{rcl}
  1662. \Exp &::=& \Var{} \\
  1663. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1664. \end{array}
  1665. }
  1666. \newcommand{\LvarASTPython}{
  1667. \begin{array}{rcl}
  1668. \Exp{} &::=& \VAR{\Var{}} \\
  1669. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1670. \end{array}
  1671. }
  1672. \begin{figure}[tp]
  1673. \centering
  1674. \begin{tcolorbox}[colback=white]
  1675. {\if\edition\racketEd
  1676. \[
  1677. \begin{array}{l}
  1678. \gray{\LintGrammarRacket{}} \\ \hline
  1679. \LvarGrammarRacket{} \\
  1680. \begin{array}{rcl}
  1681. \LangVarM{} &::=& \Exp
  1682. \end{array}
  1683. \end{array}
  1684. \]
  1685. \fi}
  1686. {\if\edition\pythonEd\pythonColor
  1687. \[
  1688. \begin{array}{l}
  1689. \gray{\LintGrammarPython} \\ \hline
  1690. \LvarGrammarPython \\
  1691. \begin{array}{rcl}
  1692. \LangVarM{} &::=& \Stmt^{*}
  1693. \end{array}
  1694. \end{array}
  1695. \]
  1696. \fi}
  1697. \end{tcolorbox}
  1698. \caption{The concrete syntax of \LangVar{}.}
  1699. \label{fig:Lvar-concrete-syntax}
  1700. \index{subject}{Lvar@\LangVar{} concrete syntax}
  1701. \end{figure}
  1702. \begin{figure}[tp]
  1703. \centering
  1704. \begin{tcolorbox}[colback=white]
  1705. {\if\edition\racketEd
  1706. \[
  1707. \begin{array}{l}
  1708. \gray{\LintASTRacket{}} \\ \hline
  1709. \LvarASTRacket \\
  1710. \begin{array}{rcl}
  1711. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1712. \end{array}
  1713. \end{array}
  1714. \]
  1715. \fi}
  1716. {\if\edition\pythonEd\pythonColor
  1717. \[
  1718. \begin{array}{l}
  1719. \gray{\LintASTPython}\\ \hline
  1720. \LvarASTPython \\
  1721. \begin{array}{rcl}
  1722. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1723. \end{array}
  1724. \end{array}
  1725. \]
  1726. \fi}
  1727. \end{tcolorbox}
  1728. \caption{The abstract syntax of \LangVar{}.}
  1729. \label{fig:Lvar-syntax}
  1730. \index{subject}{Lvar@\LangVar{} abstract syntax}
  1731. \end{figure}
  1732. {\if\edition\racketEd
  1733. Let us dive further into the syntax and semantics of the \LangVar{}
  1734. language. The \key{let} feature defines a variable for use within its
  1735. body and initializes the variable with the value of an expression.
  1736. The abstract syntax for \key{let} is shown in
  1737. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1738. \begin{lstlisting}
  1739. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1740. \end{lstlisting}
  1741. For example, the following program initializes \code{x} to $32$ and then
  1742. evaluates the body \code{(+ 10 x)}, producing $42$.
  1743. \begin{lstlisting}
  1744. (let ([x (+ 12 20)]) (+ 10 x))
  1745. \end{lstlisting}
  1746. \fi}
  1747. %
  1748. {\if\edition\pythonEd\pythonColor
  1749. %
  1750. The \LangVar{} language includes an assignment statement, which defines a
  1751. variable for use in later statements and initializes the variable with
  1752. the value of an expression. The abstract syntax for assignment is
  1753. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1754. assignment is \index{subject}{Assign@\texttt{Assign}}
  1755. \begin{lstlisting}
  1756. |$\itm{var}$| = |$\itm{exp}$|
  1757. \end{lstlisting}
  1758. For example, the following program initializes the variable \code{x}
  1759. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1760. \begin{lstlisting}
  1761. x = 12 + 20
  1762. print(10 + x)
  1763. \end{lstlisting}
  1764. \fi}
  1765. {\if\edition\racketEd
  1766. %
  1767. When there are multiple \key{let}s for the same variable, the closest
  1768. enclosing \key{let} is used. That is, variable definitions overshadow
  1769. prior definitions. Consider the following program with two \key{let}s
  1770. that define two variables named \code{x}. Can you figure out the
  1771. result?
  1772. \begin{lstlisting}
  1773. (let ([x 32]) (+ (let ([x 10]) x) x))
  1774. \end{lstlisting}
  1775. For the purposes of depicting which variable occurrences correspond to
  1776. which definitions, the following shows the \code{x}'s annotated with
  1777. subscripts to distinguish them. Double-check that your answer for the
  1778. previous program is the same as your answer for this annotated version
  1779. of the program.
  1780. \begin{lstlisting}
  1781. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1782. \end{lstlisting}
  1783. The initializing expression is always evaluated before the body of the
  1784. \key{let}, so in the following, the \key{read} for \code{x} is
  1785. performed before the \key{read} for \code{y}. Given the input
  1786. $52$ then $10$, the following produces $42$ (not $-42$).
  1787. \begin{lstlisting}
  1788. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1789. \end{lstlisting}
  1790. \fi}
  1791. \subsection{Extensible Interpreters via Method Overriding}
  1792. \label{sec:extensible-interp}
  1793. \index{subject}{method overriding}
  1794. To prepare for discussing the interpreter of \LangVar{}, we explain
  1795. why we implement it in an object-oriented style. Throughout this book
  1796. we define many interpreters, one for each language that we
  1797. study. Because each language builds on the prior one, there is a lot
  1798. of commonality between these interpreters. We want to write down the
  1799. common parts just once instead of many times. A naive interpreter for
  1800. \LangVar{} would handle the \racket{cases for variables and
  1801. \code{let}}\python{case for variables} but dispatch to an
  1802. interpreter for \LangInt{} in the rest of the cases. The following
  1803. code sketches this idea. (We explain the \code{env} parameter in
  1804. section~\ref{sec:interp-Lvar}.)
  1805. \begin{center}
  1806. {\if\edition\racketEd
  1807. \begin{minipage}{0.45\textwidth}
  1808. \begin{lstlisting}
  1809. (define ((interp_Lint env) e)
  1810. (match e
  1811. [(Prim '- (list e1))
  1812. (fx- 0 ((interp_Lint env) e1))]
  1813. ...))
  1814. \end{lstlisting}
  1815. \end{minipage}
  1816. \begin{minipage}{0.45\textwidth}
  1817. \begin{lstlisting}
  1818. (define ((interp_Lvar env) e)
  1819. (match e
  1820. [(Var x)
  1821. (dict-ref env x)]
  1822. [(Let x e body)
  1823. (define v ((interp_Lvar env) e))
  1824. (define env^ (dict-set env x v))
  1825. ((interp_Lvar env^) body)]
  1826. [else ((interp_Lint env) e)]))
  1827. \end{lstlisting}
  1828. \end{minipage}
  1829. \fi}
  1830. {\if\edition\pythonEd\pythonColor
  1831. \begin{minipage}{0.45\textwidth}
  1832. \begin{lstlisting}
  1833. def interp_Lint(e, env):
  1834. match e:
  1835. case UnaryOp(USub(), e1):
  1836. return - interp_Lint(e1, env)
  1837. ...
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. \begin{minipage}{0.45\textwidth}
  1841. \begin{lstlisting}
  1842. def interp_Lvar(e, env):
  1843. match e:
  1844. case Name(id):
  1845. return env[id]
  1846. case _:
  1847. return interp_Lint(e, env)
  1848. \end{lstlisting}
  1849. \end{minipage}
  1850. \fi}
  1851. \end{center}
  1852. The problem with this naive approach is that it does not handle
  1853. situations in which an \LangVar{} feature, such as a variable, is
  1854. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1855. in the following program.
  1856. {\if\edition\racketEd
  1857. \begin{lstlisting}
  1858. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1859. \end{lstlisting}
  1860. \fi}
  1861. {\if\edition\pythonEd\pythonColor
  1862. \begin{minipage}{1.0\textwidth}
  1863. \begin{lstlisting}
  1864. y = 10
  1865. print(-y)
  1866. \end{lstlisting}
  1867. \end{minipage}
  1868. \fi}
  1869. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1870. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1871. then it recursively calls \code{interp\_Lint} again on its argument.
  1872. Because there is no case for \racket{\code{Var}}\python{\code{Name}} in
  1873. \code{interp\_Lint}, we get an error!
  1874. To make our interpreters extensible we need something called
  1875. \emph{open recursion}\index{subject}{open recursion}, in which the
  1876. tying of the recursive knot is delayed until the functions are
  1877. composed. Object-oriented languages provide open recursion via method
  1878. overriding. The following code uses
  1879. method overriding to interpret \LangInt{} and \LangVar{} using
  1880. %
  1881. \racket{the
  1882. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1883. \index{subject}{class} feature of Racket.}%
  1884. %
  1885. \python{Python \code{class} definitions.}
  1886. %
  1887. We define one class for each language and define a method for
  1888. interpreting expressions inside each class. The class for \LangVar{}
  1889. inherits from the class for \LangInt{}, and the method
  1890. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1891. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1892. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1893. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1894. \code{interp\_exp} in \LangInt{}.
  1895. \begin{center}
  1896. \hspace{-20pt}
  1897. {\if\edition\racketEd
  1898. \begin{minipage}{0.45\textwidth}
  1899. \begin{lstlisting}
  1900. (define interp-Lint-class
  1901. (class object%
  1902. (define/public ((interp_exp env) e)
  1903. (match e
  1904. [(Prim '- (list e))
  1905. (fx- 0 ((interp_exp env) e))]
  1906. ...))
  1907. ...))
  1908. \end{lstlisting}
  1909. \end{minipage}
  1910. \begin{minipage}{0.45\textwidth}
  1911. \begin{lstlisting}
  1912. (define interp-Lvar-class
  1913. (class interp-Lint-class
  1914. (define/override ((interp_exp env) e)
  1915. (match e
  1916. [(Var x)
  1917. (dict-ref env x)]
  1918. [(Let x e body)
  1919. (define v ((interp_exp env) e))
  1920. (define env^ (dict-set env x v))
  1921. ((interp_exp env^) body)]
  1922. [else
  1923. ((super interp_exp env) e)]))
  1924. ...
  1925. ))
  1926. \end{lstlisting}
  1927. \end{minipage}
  1928. \fi}
  1929. {\if\edition\pythonEd\pythonColor
  1930. \begin{minipage}{0.45\textwidth}
  1931. \begin{lstlisting}
  1932. class InterpLint:
  1933. def interp_exp(e):
  1934. match e:
  1935. case UnaryOp(USub(), e1):
  1936. return neg64(self.interp_exp(e1))
  1937. ...
  1938. ...
  1939. \end{lstlisting}
  1940. \end{minipage}
  1941. \begin{minipage}{0.45\textwidth}
  1942. \begin{lstlisting}
  1943. class InterpLvar(InterpLint):
  1944. def interp_exp(e):
  1945. match e:
  1946. case Name(id):
  1947. return env[id]
  1948. case _:
  1949. return super().interp_exp(e)
  1950. ...
  1951. \end{lstlisting}
  1952. \end{minipage}
  1953. \fi}
  1954. \end{center}
  1955. We return to the troublesome example, repeated here:
  1956. {\if\edition\racketEd
  1957. \begin{lstlisting}
  1958. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1959. \end{lstlisting}
  1960. \fi}
  1961. {\if\edition\pythonEd\pythonColor
  1962. \begin{lstlisting}
  1963. y = 10
  1964. print(-y)
  1965. \end{lstlisting}
  1966. \fi}
  1967. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1968. \racket{on this expression,}%
  1969. \python{on the \code{-y} expression,}
  1970. %
  1971. which we call \code{e0}, by creating an object of the \LangVar{} class
  1972. and calling the \code{interp\_exp} method
  1973. {\if\edition\racketEd
  1974. \begin{lstlisting}
  1975. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1976. \end{lstlisting}
  1977. \fi}
  1978. {\if\edition\pythonEd\pythonColor
  1979. \begin{lstlisting}
  1980. InterpLvar().interp_exp(e0)
  1981. \end{lstlisting}
  1982. \fi}
  1983. \noindent To process the \code{-} operator, the default case of
  1984. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1985. method in \LangInt{}. But then for the recursive method call, it
  1986. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1987. \racket{\code{Var}}\python{\code{Name}} node is handled correctly.
  1988. Thus, method overriding gives us the open recursion that we need to
  1989. implement our interpreters in an extensible way.
  1990. \subsection{Definitional Interpreter for \LangVar{}}
  1991. \label{sec:interp-Lvar}
  1992. Having justified the use of classes and methods to implement
  1993. interpreters, we revisit the definitional interpreter for \LangInt{}
  1994. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1995. create an interpreter for \LangVar{}, shown in
  1996. figure~\ref{fig:interp-Lvar}.
  1997. %
  1998. \python{We change the \code{interp\_stmt} method in the interpreter
  1999. for \LangInt{} to take two extra parameters named \code{env}, which
  2000. we discuss in the next paragraph, and \code{cont} for
  2001. \emph{continuation}, which is the technical name for what comes
  2002. after a particular point in a program. The \code{cont} parameter is
  2003. the list of statements that follow the current statement. Note
  2004. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  2005. statement and passes the rest of the statements as the argument for
  2006. \code{cont}. This organization enables each statement to decide what
  2007. if anything should be evaluated after it, for example, allowing a
  2008. \code{return} statement to exit early from a function (see
  2009. Chapter~\ref{ch:Lfun}).}
  2010. The interpreter for \LangVar{} adds two new cases for
  2011. variables and \racket{\key{let}}\python{assignment}. For
  2012. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  2013. value bound to a variable to all the uses of the variable. To
  2014. accomplish this, we maintain a mapping from variables to values called
  2015. an \emph{environment}\index{subject}{environment}.
  2016. %
  2017. We use
  2018. %
  2019. \racket{an association list (alist) }%
  2020. %
  2021. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2022. %
  2023. to represent the environment.
  2024. %
  2025. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2026. and the \code{racket/dict} package.}
  2027. %
  2028. The \code{interp\_exp} function takes the current environment,
  2029. \code{env}, as an extra parameter. When the interpreter encounters a
  2030. variable, it looks up the corresponding value in the environment. If
  2031. the variable is not in the environment (because the variable was not
  2032. defined) then the lookup will fail and the interpreter will
  2033. halt with an error. Recall that the compiler is not obligated to
  2034. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2035. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2036. prohibit access to undefined variables.}
  2037. %
  2038. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2039. initializing expression, extends the environment with the result
  2040. value bound to the variable, using \code{dict-set}, then evaluates
  2041. the body of the \key{Let}.}
  2042. %
  2043. \python{When the interpreter encounters an assignment, it evaluates
  2044. the initializing expression and then associates the resulting value
  2045. with the variable in the environment.}
  2046. \begin{figure}[tp]
  2047. \begin{tcolorbox}[colback=white]
  2048. {\if\edition\racketEd
  2049. \begin{lstlisting}
  2050. (define interp-Lint-class
  2051. (class object%
  2052. (super-new)
  2053. (define/public ((interp_exp env) e)
  2054. (match e
  2055. [(Int n) n]
  2056. [(Prim 'read '())
  2057. (define r (read))
  2058. (cond [(fixnum? r) r]
  2059. [else (error 'interp_exp "expected an integer" r)])]
  2060. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2061. [(Prim '+ (list e1 e2))
  2062. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2063. [(Prim '- (list e1 e2))
  2064. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2065. (define/public (interp_program p)
  2066. (match p
  2067. [(Program '() e) ((interp_exp '()) e)]))
  2068. ))
  2069. \end{lstlisting}
  2070. \fi}
  2071. {\if\edition\pythonEd\pythonColor
  2072. \begin{lstlisting}
  2073. class InterpLint:
  2074. def interp_exp(self, e, env):
  2075. match e:
  2076. case BinOp(left, Add(), right):
  2077. l = self.interp_exp(left, env)
  2078. r = self.interp_exp(right, env)
  2079. return add64(l, r)
  2080. case BinOp(left, Sub(), right):
  2081. l = self.interp_exp(left, env)
  2082. r = self.interp_exp(right, env)
  2083. return sub64(l, r)
  2084. case UnaryOp(USub(), v):
  2085. return neg64(self.interp_exp(v, env))
  2086. case Constant(value):
  2087. return value
  2088. case Call(Name('input_int'), []):
  2089. return int(input())
  2090. def interp_stmt(self, s, env, cont):
  2091. match s:
  2092. case Expr(Call(Name('print'), [arg])):
  2093. val = self.interp_exp(arg, env)
  2094. print(val, end='')
  2095. return self.interp_stmts(cont, env)
  2096. case Expr(value):
  2097. self.interp_exp(value, env)
  2098. return self.interp_stmts(cont, env)
  2099. case _:
  2100. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2101. def interp_stmts(self, ss, env):
  2102. match ss:
  2103. case []:
  2104. return 0
  2105. case [s, *ss]:
  2106. return self.interp_stmt(s, env, ss)
  2107. def interp(self, p):
  2108. match p:
  2109. case Module(body):
  2110. self.interp_stmts(body, {})
  2111. def interp_Lint(p):
  2112. return InterpLint().interp(p)
  2113. \end{lstlisting}
  2114. \fi}
  2115. \end{tcolorbox}
  2116. \caption{Interpreter for \LangInt{} as a class.}
  2117. \label{fig:interp-Lint-class}
  2118. \end{figure}
  2119. \begin{figure}[tp]
  2120. \begin{tcolorbox}[colback=white]
  2121. {\if\edition\racketEd
  2122. \begin{lstlisting}
  2123. (define interp-Lvar-class
  2124. (class interp-Lint-class
  2125. (super-new)
  2126. (define/override ((interp_exp env) e)
  2127. (match e
  2128. [(Var x) (dict-ref env x)]
  2129. [(Let x e body)
  2130. (define new-env (dict-set env x ((interp_exp env) e)))
  2131. ((interp_exp new-env) body)]
  2132. [else ((super interp_exp env) e)]))
  2133. ))
  2134. (define (interp_Lvar p)
  2135. (send (new interp-Lvar-class) interp_program p))
  2136. \end{lstlisting}
  2137. \fi}
  2138. {\if\edition\pythonEd\pythonColor
  2139. \begin{lstlisting}
  2140. class InterpLvar(InterpLint):
  2141. def interp_exp(self, e, env):
  2142. match e:
  2143. case Name(id):
  2144. return env[id]
  2145. case _:
  2146. return super().interp_exp(e, env)
  2147. def interp_stmt(self, s, env, cont):
  2148. match s:
  2149. case Assign([Name(id)], value):
  2150. env[id] = self.interp_exp(value, env)
  2151. return self.interp_stmts(cont, env)
  2152. case _:
  2153. return super().interp_stmt(s, env, cont)
  2154. def interp_Lvar(p):
  2155. return InterpLvar().interp(p)
  2156. \end{lstlisting}
  2157. \fi}
  2158. \end{tcolorbox}
  2159. \caption{Interpreter for the \LangVar{} language.}
  2160. \label{fig:interp-Lvar}
  2161. \end{figure}
  2162. {\if\edition\racketEd
  2163. \begin{figure}[tp]
  2164. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2165. \small
  2166. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2167. An \emph{association list} (called an alist) is a list of key-value pairs.
  2168. For example, we can map people to their ages with an alist
  2169. \index{subject}{alist}\index{subject}{association list}
  2170. \begin{lstlisting}[basicstyle=\ttfamily]
  2171. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2172. \end{lstlisting}
  2173. The \emph{dictionary} interface is for mapping keys to values.
  2174. Every alist implements this interface. \index{subject}{dictionary}
  2175. The package
  2176. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2177. provides many functions for working with dictionaries, such as
  2178. \begin{description}
  2179. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2180. returns the value associated with the given $\itm{key}$.
  2181. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2182. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2183. and otherwise is the same as $\itm{dict}$.
  2184. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2185. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2186. of keys and values in $\itm{dict}$. For example, the following
  2187. creates a new alist in which the ages are incremented:
  2188. \end{description}
  2189. \vspace{-10pt}
  2190. \begin{lstlisting}[basicstyle=\ttfamily]
  2191. (for/list ([(k v) (in-dict ages)])
  2192. (cons k (add1 v)))
  2193. \end{lstlisting}
  2194. \end{tcolorbox}
  2195. %\end{wrapfigure}
  2196. \caption{Association lists implement the dictionary interface.}
  2197. \label{fig:alist}
  2198. \end{figure}
  2199. \fi}
  2200. The goal for this chapter is to implement a compiler that translates
  2201. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2202. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2203. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2204. That is, they output the same integer $n$. We depict this correctness
  2205. criteria in the following diagram:
  2206. \[
  2207. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2208. \node (p1) at (0, 0) {$P_1$};
  2209. \node (p2) at (4, 0) {$P_2$};
  2210. \node (o) at (4, -2) {$n$};
  2211. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2212. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2213. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2214. \end{tikzpicture}
  2215. \]
  2216. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2217. compiling \LangVar{}.
  2218. \section{The \LangXInt{} Assembly Language}
  2219. \label{sec:x86}
  2220. \index{subject}{x86}
  2221. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2222. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2223. assembler.
  2224. %
  2225. A program begins with a \code{main} label followed by a sequence of
  2226. instructions. The \key{globl} directive makes the \key{main} procedure
  2227. externally visible so that the operating system can call it.
  2228. %
  2229. An x86 program is stored in the computer's memory. For our purposes,
  2230. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2231. values. The computer has a \emph{program counter}
  2232. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2233. \code{rip} register that points to the address of the next instruction
  2234. to be executed. For most instructions, the program counter is
  2235. incremented after the instruction is executed so that it points to the
  2236. next instruction in memory. Most x86 instructions take two operands,
  2237. each of which is an integer constant (called an \emph{immediate
  2238. value}\index{subject}{immediate value}), a
  2239. \emph{register}\index{subject}{register}, or a memory location.
  2240. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2241. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2242. && \key{r8} \MID \key{r9} \MID \key{r10}
  2243. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2244. \MID \key{r14} \MID \key{r15}}
  2245. \newcommand{\GrammarXIntRacket}{
  2246. \begin{array}{rcl}
  2247. \Reg &::=& \allregisters{} \\
  2248. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2249. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2250. \key{subq} \; \Arg\key{,} \Arg \MID
  2251. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2252. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2253. \key{callq} \; \mathit{label} \MID
  2254. \key{retq} \MID
  2255. \key{jmp}\,\itm{label} \MID \\
  2256. && \itm{label}\key{:}\; \Instr
  2257. \end{array}
  2258. }
  2259. \newcommand{\GrammarXIntPython}{
  2260. % no jmp and label in the python version
  2261. \begin{array}{rcl}
  2262. \Reg &::=& \allregisters{} \\
  2263. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2264. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2265. \key{subq} \; \Arg\key{,} \Arg \MID
  2266. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2267. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2268. \key{callq} \; \mathit{label} \MID \key{retq}
  2269. \end{array}
  2270. }
  2271. \begin{figure}[tp]
  2272. \begin{tcolorbox}[colback=white]
  2273. {\if\edition\racketEd
  2274. \[
  2275. \begin{array}{l}
  2276. \GrammarXIntRacket \\
  2277. \begin{array}{lcl}
  2278. \LangXIntM{} &::= & \key{.globl main}\\
  2279. & & \key{main:} \; \Instr\ldots
  2280. \end{array}
  2281. \end{array}
  2282. \]
  2283. \fi}
  2284. {\if\edition\pythonEd\pythonColor
  2285. \[
  2286. \begin{array}{lcl}
  2287. \Reg &::=& \allregisters{} \\
  2288. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2289. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2290. \key{subq} \; \Arg\key{,} \Arg \MID
  2291. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2292. && \key{callq} \; \mathit{label} \MID
  2293. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2294. \LangXIntM{} &::= & \key{.globl main}\\
  2295. & & \key{main:} \; \Instr^{*}
  2296. \end{array}
  2297. \]
  2298. \fi}
  2299. \end{tcolorbox}
  2300. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2301. \label{fig:x86-int-concrete}
  2302. \index{subject}{x86int@\LangXInt{} concrete syntax}
  2303. \end{figure}
  2304. A register is a special kind of variable that holds a 64-bit
  2305. value. There are 16 general-purpose registers in the computer; their
  2306. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2307. written with a percent sign, \key{\%}, followed by its name,
  2308. for example, \key{\%rax}.
  2309. An immediate value is written using the notation \key{\$}$n$ where $n$
  2310. is an integer.
  2311. %
  2312. %
  2313. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2314. which obtains the address stored in register $r$ and then adds $n$
  2315. bytes to the address. The resulting address is used to load or to store
  2316. to memory depending on whether it occurs as a source or destination
  2317. argument of an instruction.
  2318. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2319. the source $s$ and destination $d$, applies the arithmetic operation,
  2320. and then writes the result to the destination $d$. \index{subject}{instruction}
  2321. %
  2322. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2323. stores the result in $d$.
  2324. %
  2325. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2326. specified by the label, and $\key{retq}$ returns from a procedure to
  2327. its caller.
  2328. %
  2329. We discuss procedure calls in more detail further in this chapter and
  2330. in chapter~\ref{ch:Lfun}.
  2331. %
  2332. The last letter \key{q} indicates that these instructions operate on
  2333. quadwords, which are 64-bit values.
  2334. %
  2335. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2336. counter to the address of the instruction immediately after the
  2337. specified label.}
  2338. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2339. all the x86 instructions used in this book.
  2340. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2341. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2342. \lstinline{movq $10, %rax}
  2343. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2344. adds $32$ to the $10$ in \key{rax} and
  2345. puts the result, $42$, into \key{rax}.
  2346. %
  2347. The last instruction \key{retq} finishes the \key{main} function by
  2348. returning the integer in \key{rax} to the operating system. The
  2349. operating system interprets this integer as the program's exit
  2350. code. By convention, an exit code of 0 indicates that a program has
  2351. completed successfully, and all other exit codes indicate various
  2352. errors.
  2353. %
  2354. \racket{However, in this book we return the result of the program
  2355. as the exit code.}
  2356. \begin{figure}[tbp]
  2357. \begin{minipage}{0.45\textwidth}
  2358. \begin{tcolorbox}[colback=white]
  2359. \begin{lstlisting}
  2360. .globl main
  2361. main:
  2362. movq $10, %rax
  2363. addq $32, %rax
  2364. retq
  2365. \end{lstlisting}
  2366. \end{tcolorbox}
  2367. \end{minipage}
  2368. \caption{An x86 program that computes
  2369. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2370. \label{fig:p0-x86}
  2371. \end{figure}
  2372. We exhibit the use of memory for storing intermediate results in the
  2373. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2374. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2375. uses a region of memory called the \emph{procedure call stack}
  2376. (\emph{stack} for
  2377. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2378. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2379. for each procedure call. The memory layout for an individual frame is
  2380. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2381. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2382. address of the item at the top of the stack. In general, we use the
  2383. term \emph{pointer}\index{subject}{pointer} for something that
  2384. contains an address. The stack grows downward in memory, so we
  2385. increase the size of the stack by subtracting from the stack pointer.
  2386. In the context of a procedure call, the \emph{return
  2387. address}\index{subject}{return address} is the location of the
  2388. instruction that immediately follows the call instruction on the
  2389. caller side. The function call instruction, \code{callq}, pushes the
  2390. return address onto the stack prior to jumping to the procedure. The
  2391. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2392. pointer} and is used to access variables that are stored in the
  2393. frame of the current procedure call. The base pointer of the caller
  2394. is stored immediately after the return address.
  2395. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2396. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2397. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2398. $-16\key{(\%rbp)}$, and so on.
  2399. \begin{figure}[tbp]
  2400. \begin{minipage}{0.66\textwidth}
  2401. \begin{tcolorbox}[colback=white]
  2402. {\if\edition\racketEd
  2403. \begin{lstlisting}
  2404. start:
  2405. movq $10, -8(%rbp)
  2406. negq -8(%rbp)
  2407. movq -8(%rbp), %rax
  2408. addq $52, %rax
  2409. jmp conclusion
  2410. .globl main
  2411. main:
  2412. pushq %rbp
  2413. movq %rsp, %rbp
  2414. subq $16, %rsp
  2415. jmp start
  2416. conclusion:
  2417. addq $16, %rsp
  2418. popq %rbp
  2419. retq
  2420. \end{lstlisting}
  2421. \fi}
  2422. {\if\edition\pythonEd\pythonColor
  2423. \begin{lstlisting}
  2424. .globl main
  2425. main:
  2426. pushq %rbp
  2427. movq %rsp, %rbp
  2428. subq $16, %rsp
  2429. movq $10, -8(%rbp)
  2430. negq -8(%rbp)
  2431. movq -8(%rbp), %rax
  2432. addq $52, %rax
  2433. addq $16, %rsp
  2434. popq %rbp
  2435. retq
  2436. \end{lstlisting}
  2437. \fi}
  2438. \end{tcolorbox}
  2439. \end{minipage}
  2440. \caption{An x86 program that computes
  2441. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2442. \label{fig:p1-x86}
  2443. \end{figure}
  2444. \begin{figure}[tbp]
  2445. \begin{minipage}{0.66\textwidth}
  2446. \begin{tcolorbox}[colback=white]
  2447. \centering
  2448. \begin{tabular}{|r|l|} \hline
  2449. Position & Contents \\ \hline
  2450. $8$(\key{\%rbp}) & return address \\
  2451. $0$(\key{\%rbp}) & old \key{rbp} \\
  2452. $-8$(\key{\%rbp}) & variable $1$ \\
  2453. $-16$(\key{\%rbp}) & variable $2$ \\
  2454. \ldots & \ldots \\
  2455. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2456. \end{tabular}
  2457. \end{tcolorbox}
  2458. \end{minipage}
  2459. \caption{Memory layout of a frame.}
  2460. \label{fig:frame}
  2461. \end{figure}
  2462. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2463. is transferred from the operating system to the \code{main} function.
  2464. The operating system issues a \code{callq main} instruction that
  2465. pushes its return address on the stack and then jumps to
  2466. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2467. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2468. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2469. out of alignment (because the \code{callq} pushed the return address).
  2470. The first three instructions are the typical
  2471. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2472. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2473. pointer \code{rsp} and then saves the base pointer of the caller at
  2474. address \code{rsp} on the stack. The next instruction \code{movq
  2475. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2476. which is pointing to the location of the old base pointer. The
  2477. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2478. make enough room for storing variables. This program needs one
  2479. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2480. 16-byte-aligned, and then we are ready to make calls to other functions.
  2481. \racket{The last instruction of the prelude is \code{jmp start}, which
  2482. transfers control to the instructions that were generated from the
  2483. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2484. \racket{The first instruction under the \code{start} label is}
  2485. %
  2486. \python{The first instruction after the prelude is}
  2487. %
  2488. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2489. %
  2490. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2491. $1$ to $-10$.
  2492. %
  2493. The next instruction moves the $-10$ from variable $1$ into the
  2494. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2495. the value in \code{rax}, updating its contents to $42$.
  2496. \racket{The three instructions under the label \code{conclusion} are the
  2497. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2498. %
  2499. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2500. \code{main} function consists of the last three instructions.}
  2501. %
  2502. The first two restore the \code{rsp} and \code{rbp} registers to their
  2503. states at the beginning of the procedure. In particular,
  2504. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2505. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2506. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2507. \key{retq}, jumps back to the procedure that called this one and adds
  2508. $8$ to the stack pointer.
  2509. Our compiler needs a convenient representation for manipulating x86
  2510. programs, so we define an abstract syntax for x86, shown in
  2511. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2512. \LangXInt{}.
  2513. %
  2514. {\if\edition\pythonEd\pythonColor%
  2515. The main difference between this and the concrete syntax of \LangXInt{}
  2516. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2517. names, and register names are explicitly represented by strings.
  2518. \fi} %
  2519. {\if\edition\racketEd
  2520. The main difference between this and the concrete syntax of \LangXInt{}
  2521. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2522. front of every instruction. Instead instructions are grouped into
  2523. \emph{basic blocks}\index{subject}{basic block} with a
  2524. label associated with every basic block; this is why the \key{X86Program}
  2525. struct includes an alist mapping labels to basic blocks. The reason for this
  2526. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2527. introduce conditional branching. The \code{Block} structure includes
  2528. an $\itm{info}$ field that is not needed in this chapter but becomes
  2529. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2530. $\itm{info}$ field should contain an empty list.
  2531. \fi}
  2532. %
  2533. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2534. node includes an integer for representing the arity of the function,
  2535. that is, the number of arguments, which is helpful to know during
  2536. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2537. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2538. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2539. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2540. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2541. \MID \skey{r14} \MID \skey{r15}}
  2542. \newcommand{\ASTXIntRacket}{
  2543. \begin{array}{lcl}
  2544. \Reg &::=& \allregisters{} \\
  2545. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2546. \MID \DEREF{\Reg}{\Int} \\
  2547. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2548. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2549. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2550. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2551. &\MID& \PUSHQ{\Arg}
  2552. \MID \POPQ{\Arg} \\
  2553. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2554. \MID \RETQ{}
  2555. \MID \JMP{\itm{label}} \\
  2556. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2557. \end{array}
  2558. }
  2559. \newcommand{\ASTXIntPython}{
  2560. \begin{array}{lcl}
  2561. \Reg &::=& \allregisters{} \\
  2562. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2563. \MID \DEREF{\Reg}{\Int} \\
  2564. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2565. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2566. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2567. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2568. &\MID& \PUSHQ{\Arg}
  2569. \MID \POPQ{\Arg} \\
  2570. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2571. \MID \RETQ{} \\
  2572. \Block &::= & \Instr^{+}
  2573. \end{array}
  2574. }
  2575. \begin{figure}[tp]
  2576. \begin{tcolorbox}[colback=white]
  2577. \small
  2578. {\if\edition\racketEd
  2579. \[\arraycolsep=3pt
  2580. \begin{array}{l}
  2581. \ASTXIntRacket \\
  2582. \begin{array}{lcl}
  2583. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2584. \end{array}
  2585. \end{array}
  2586. \]
  2587. \fi}
  2588. {\if\edition\pythonEd\pythonColor
  2589. \[
  2590. \begin{array}{l}
  2591. \ASTXIntPython \\
  2592. \begin{array}{lcl}
  2593. \LangXIntM{} &::= & \XPROGRAM{}{\Block}{}
  2594. \end{array}
  2595. \end{array}
  2596. \]
  2597. \fi}
  2598. \end{tcolorbox}
  2599. \caption{The abstract syntax of \LangXInt{} assembly.}
  2600. \label{fig:x86-int-ast}
  2601. \index{subject}{x86int@\LangXInt{} abstract syntax}
  2602. \end{figure}
  2603. \section{Planning the Trip to x86}
  2604. \label{sec:plan-s0-x86}
  2605. To compile one language to another, it helps to focus on the
  2606. differences between the two languages because the compiler will need
  2607. to bridge those differences. What are the differences between \LangVar{}
  2608. and x86 assembly? Here are some of the most important ones:
  2609. \begin{enumerate}
  2610. \item x86 arithmetic instructions typically have two arguments and
  2611. update the second argument in place. In contrast, \LangVar{}
  2612. arithmetic operations take two arguments and produce a new value.
  2613. An x86 instruction may have at most one memory-accessing argument.
  2614. Furthermore, some x86 instructions place special restrictions on
  2615. their arguments.
  2616. \item An argument of an \LangVar{} operator can be a deeply nested
  2617. expression, whereas x86 instructions restrict their arguments to be
  2618. integer constants, registers, and memory locations.
  2619. {\if\edition\racketEd
  2620. \item The order of execution in x86 is explicit in the syntax, which
  2621. is a sequence of instructions and jumps to labeled positions,
  2622. whereas in \LangVar{} the order of evaluation is a left-to-right
  2623. depth-first traversal of the abstract syntax tree. \fi}
  2624. \item A program in \LangVar{} can have any number of variables,
  2625. whereas x86 has 16 registers and the procedure call stack.
  2626. {\if\edition\racketEd
  2627. \item Variables in \LangVar{} can shadow other variables with the
  2628. same name. In x86, registers have unique names, and memory locations
  2629. have unique addresses.
  2630. \fi}
  2631. \end{enumerate}
  2632. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2633. down the problem into several steps, which deal with these differences
  2634. one at a time. Each of these steps is called a \emph{pass} of the
  2635. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2636. %
  2637. This term indicates that each step passes over, or traverses, the AST
  2638. of the program.
  2639. %
  2640. Furthermore, we follow the nanopass approach, which means that we
  2641. strive for each pass to accomplish one clear objective rather than two
  2642. or three at the same time.
  2643. %
  2644. We begin by sketching how we might implement each pass and give each
  2645. pass a name. We then figure out an ordering of the passes and the
  2646. input/output language for each pass. The very first pass has
  2647. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2648. its output language. In between these two passes, we can choose
  2649. whichever language is most convenient for expressing the output of
  2650. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2651. \emph{intermediate language} of our own design. Finally, to
  2652. implement each pass we write one recursive function per nonterminal in
  2653. the grammar of the input language of the pass.
  2654. \index{subject}{intermediate language}
  2655. Our compiler for \LangVar{} consists of the following passes:
  2656. %
  2657. \begin{description}
  2658. {\if\edition\racketEd
  2659. \item[\key{uniquify}] deals with the shadowing of variables by
  2660. renaming every variable to a unique name.
  2661. \fi}
  2662. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2663. of a primitive operation or function call is a variable or integer,
  2664. that is, an \emph{atomic} expression. We refer to nonatomic
  2665. expressions as \emph{complex}. This pass introduces temporary
  2666. variables to hold the results of complex
  2667. subexpressions.\index{subject}{atomic
  2668. expression}\index{subject}{complex expression}%
  2669. {\if\edition\racketEd
  2670. \item[\key{explicate\_control}] makes the execution order of the
  2671. program explicit. It converts the abstract syntax tree
  2672. representation into a graph in which each node is a labeled sequence
  2673. of statements and the edges are \code{goto} statements.
  2674. \fi}
  2675. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2676. handles the difference between
  2677. \LangVar{} operations and x86 instructions. This pass converts each
  2678. \LangVar{} operation to a short sequence of instructions that
  2679. accomplishes the same task.
  2680. \item[\key{assign\_homes}] replaces variables with registers or stack
  2681. locations.
  2682. \end{description}
  2683. %
  2684. {\if\edition\racketEd
  2685. %
  2686. Our treatment of \code{remove\_complex\_operands} and
  2687. \code{explicate\_control} as separate passes is an example of the
  2688. nanopass approach.\footnote{For analogous decompositions of the
  2689. translation into continuation passing style, see the work of
  2690. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2691. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2692. %
  2693. \fi}
  2694. The next question is, in what order should we apply these passes? This
  2695. question can be challenging because it is difficult to know ahead of
  2696. time which orderings will be better (that is, will be easier to
  2697. implement, produce more efficient code, and so on), and therefore
  2698. ordering often involves trial and error. Nevertheless, we can plan
  2699. ahead and make educated choices regarding the ordering.
  2700. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2701. \key{uniquify}? The \key{uniquify} pass should come first because
  2702. \key{explicate\_control} changes all the \key{let}-bound variables to
  2703. become local variables whose scope is the entire program, which would
  2704. confuse variables with the same name.}
  2705. %
  2706. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2707. because the latter removes the \key{let} form, but it is convenient to
  2708. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2709. %
  2710. \racket{The ordering of \key{uniquify} with respect to
  2711. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2712. \key{uniquify} to come first.}
  2713. The \key{select\_instructions} and \key{assign\_homes} passes are
  2714. intertwined.
  2715. %
  2716. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2717. passing arguments to functions and that it is preferable to assign
  2718. parameters to their corresponding registers. This suggests that it
  2719. would be better to start with the \key{select\_instructions} pass,
  2720. which generates the instructions for argument passing, before
  2721. performing register allocation.
  2722. %
  2723. On the other hand, by selecting instructions first we may run into a
  2724. dead end in \key{assign\_homes}. Recall that only one argument of an
  2725. x86 instruction may be a memory access, but \key{assign\_homes} might
  2726. be forced to assign both arguments to memory locations.
  2727. %
  2728. A sophisticated approach is to repeat the two passes until a solution
  2729. is found. However, to reduce implementation complexity we recommend
  2730. placing \key{select\_instructions} first, followed by the
  2731. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2732. that uses a reserved register to fix outstanding problems.
  2733. \begin{figure}[tbp]
  2734. \begin{tcolorbox}[colback=white]
  2735. {\if\edition\racketEd
  2736. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2737. \node (Lvar) at (0,2) {\large \LangVar{}};
  2738. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2739. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2740. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2741. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2742. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2743. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2744. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2745. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2746. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2747. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2748. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2749. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2750. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2751. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2752. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2753. \end{tikzpicture}
  2754. \fi}
  2755. {\if\edition\pythonEd\pythonColor
  2756. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2757. \node (Lvar) at (0,2) {\large \LangVar{}};
  2758. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2759. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2760. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2761. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2762. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2763. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2764. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2765. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2766. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2767. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2768. \end{tikzpicture}
  2769. \fi}
  2770. \end{tcolorbox}
  2771. \caption{Diagram of the passes for compiling \LangVar{}. }
  2772. \label{fig:Lvar-passes}
  2773. \end{figure}
  2774. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2775. passes and identifies the input and output language of each pass.
  2776. %
  2777. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2778. language, which extends \LangXInt{} with an unbounded number of
  2779. program-scope variables and removes the restrictions regarding
  2780. instruction arguments.
  2781. %
  2782. The last pass, \key{prelude\_and\_conclusion}, places the program
  2783. instructions inside a \code{main} function with instructions for the
  2784. prelude and conclusion.
  2785. %
  2786. \racket{In the next section we discuss the \LangCVar{} intermediate
  2787. language that serves as the output of \code{explicate\_control}.}
  2788. %
  2789. The remainder of this chapter provides guidance on the implementation
  2790. of each of the compiler passes represented in
  2791. figure~\ref{fig:Lvar-passes}.
  2792. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2793. %% are programs that are still in the \LangVar{} language, though the
  2794. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2795. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2796. %% %
  2797. %% The output of \code{explicate\_control} is in an intermediate language
  2798. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2799. %% syntax, which we introduce in the next section. The
  2800. %% \key{select-instruction} pass translates from \LangCVar{} to
  2801. %% \LangXVar{}. The \key{assign-homes} and
  2802. %% \key{patch-instructions}
  2803. %% passes input and output variants of x86 assembly.
  2804. \newcommand{\CvarGrammarRacket}{
  2805. \begin{array}{lcl}
  2806. \Atm &::=& \Int \MID \Var \\
  2807. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2808. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2809. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2810. \end{array}
  2811. }
  2812. \newcommand{\CvarASTRacket}{
  2813. \begin{array}{lcl}
  2814. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2815. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2816. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2817. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2818. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2819. \end{array}
  2820. }
  2821. {\if\edition\racketEd
  2822. \subsection{The \LangCVar{} Intermediate Language}
  2823. The output of \code{explicate\_control} is similar to the C
  2824. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2825. categories for expressions and statements, so we name it \LangCVar{}.
  2826. This style of intermediate language is also known as
  2827. \emph{three-address code}, to emphasize that the typical form of a
  2828. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2829. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2830. The concrete syntax for \LangCVar{} is shown in
  2831. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2832. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2833. %
  2834. The \LangCVar{} language supports the same operators as \LangVar{} but
  2835. the arguments of operators are restricted to atomic
  2836. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2837. assignment statements that can be executed in sequence using the
  2838. \key{Seq} form. A sequence of statements always ends with
  2839. \key{Return}, a guarantee that is baked into the grammar rules for
  2840. \itm{tail}. The naming of this nonterminal comes from the term
  2841. \emph{tail position}\index{subject}{tail position}, which refers to an
  2842. expression that is the last one to execute within a function or
  2843. program.
  2844. A \LangCVar{} program consists of an alist mapping labels to
  2845. tails. This is more general than necessary for the present chapter, as
  2846. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2847. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2848. there is just one label, \key{start}, and the whole program is
  2849. its tail.
  2850. %
  2851. The $\itm{info}$ field of the \key{CProgram} form, after the
  2852. \code{explicate\_control} pass, contains an alist that associates the
  2853. symbol \key{locals} with a list of all the variables used in the
  2854. program. At the start of the program, these variables are
  2855. uninitialized; they become initialized on their first assignment.
  2856. \begin{figure}[tbp]
  2857. \begin{tcolorbox}[colback=white]
  2858. \[
  2859. \begin{array}{l}
  2860. \CvarGrammarRacket \\
  2861. \begin{array}{lcl}
  2862. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2863. \end{array}
  2864. \end{array}
  2865. \]
  2866. \end{tcolorbox}
  2867. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2868. \label{fig:c0-concrete-syntax}
  2869. \index{subject}{Cvar@\LangCVar{} concrete syntax}
  2870. \end{figure}
  2871. \begin{figure}[tbp]
  2872. \begin{tcolorbox}[colback=white]
  2873. \[
  2874. \begin{array}{l}
  2875. \CvarASTRacket \\
  2876. \begin{array}{lcl}
  2877. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2878. \end{array}
  2879. \end{array}
  2880. \]
  2881. \end{tcolorbox}
  2882. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2883. \label{fig:c0-syntax}
  2884. \index{subject}{Cvar@\LangCVar{} abstract syntax}
  2885. \end{figure}
  2886. The definitional interpreter for \LangCVar{} is in the support code,
  2887. in the file \code{interp-Cvar.rkt}.
  2888. \fi}
  2889. {\if\edition\racketEd
  2890. \section{Uniquify Variables}
  2891. \label{sec:uniquify-Lvar}
  2892. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2893. with a unique name. Both the input and output of the \code{uniquify}
  2894. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2895. should translate the program on the left into the program on the
  2896. right.
  2897. \begin{transformation}
  2898. \begin{lstlisting}
  2899. (let ([x 32])
  2900. (+ (let ([x 10]) x) x))
  2901. \end{lstlisting}
  2902. \compilesto
  2903. \begin{lstlisting}
  2904. (let ([x.1 32])
  2905. (+ (let ([x.2 10]) x.2) x.1))
  2906. \end{lstlisting}
  2907. \end{transformation}
  2908. The following is another example translation, this time of a program
  2909. with a \key{let} nested inside the initializing expression of another
  2910. \key{let}.
  2911. \begin{transformation}
  2912. \begin{lstlisting}
  2913. (let ([x (let ([x 4])
  2914. (+ x 1))])
  2915. (+ x 2))
  2916. \end{lstlisting}
  2917. \compilesto
  2918. \begin{lstlisting}
  2919. (let ([x.2 (let ([x.1 4])
  2920. (+ x.1 1))])
  2921. (+ x.2 2))
  2922. \end{lstlisting}
  2923. \end{transformation}
  2924. We recommend implementing \code{uniquify} by creating a structurally
  2925. recursive function named \code{uniquify\_exp} that does little other
  2926. than copy an expression. However, when encountering a \key{let}, it
  2927. should generate a unique name for the variable and associate the old
  2928. name with the new name in an alist.\footnote{The Racket function
  2929. \code{gensym} is handy for generating unique variable names.} The
  2930. \code{uniquify\_exp} function needs to access this alist when it gets
  2931. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2932. for the alist.
  2933. The skeleton of the \code{uniquify\_exp} function is shown in
  2934. figure~\ref{fig:uniquify-Lvar}.
  2935. %% The function is curried so that it is
  2936. %% convenient to partially apply it to an alist and then apply it to
  2937. %% different expressions, as in the last case for primitive operations in
  2938. %% figure~\ref{fig:uniquify-Lvar}.
  2939. The
  2940. %
  2941. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2942. %
  2943. form of Racket is useful for transforming the element of a list to
  2944. produce a new list.\index{subject}{for/list}
  2945. \begin{figure}[tbp]
  2946. \begin{tcolorbox}[colback=white]
  2947. \begin{lstlisting}
  2948. (define (uniquify_exp env)
  2949. (lambda (e)
  2950. (match e
  2951. [(Var x) ___]
  2952. [(Int n) (Int n)]
  2953. [(Let x e body) ___]
  2954. [(Prim op es)
  2955. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2956. (define (uniquify p)
  2957. (match p
  2958. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2959. \end{lstlisting}
  2960. \end{tcolorbox}
  2961. \caption{Skeleton for the \key{uniquify} pass.}
  2962. \label{fig:uniquify-Lvar}
  2963. \end{figure}
  2964. \begin{exercise}
  2965. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2966. Complete the \code{uniquify} pass by filling in the blanks in
  2967. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2968. variables and for the \key{let} form in the file \code{compiler.rkt}
  2969. in the support code.
  2970. \end{exercise}
  2971. \begin{exercise}
  2972. \normalfont\normalsize
  2973. \label{ex:Lvar}
  2974. Create five \LangVar{} programs that exercise the most interesting
  2975. parts of the \key{uniquify} pass; that is, the programs should include
  2976. \key{let} forms, variables, and variables that shadow each other.
  2977. The five programs should be placed in the subdirectory named
  2978. \key{tests}, and the file names should start with \code{var\_test\_}
  2979. followed by a unique integer and end with the file extension
  2980. \key{.rkt}.
  2981. %
  2982. The \key{run-tests.rkt} script in the support code checks whether the
  2983. output programs produce the same result as the input programs. The
  2984. script uses the \key{interp-tests} function
  2985. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2986. your \key{uniquify} pass on the example programs. The \code{passes}
  2987. parameter of \key{interp-tests} is a list that should have one entry
  2988. for each pass in your compiler. For now, define \code{passes} to
  2989. contain just one entry for \code{uniquify} as follows:
  2990. \begin{lstlisting}
  2991. (define passes
  2992. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2993. \end{lstlisting}
  2994. Run the \key{run-tests.rkt} script in the support code to check
  2995. whether the output programs produce the same result as the input
  2996. programs.
  2997. \end{exercise}
  2998. \fi}
  2999. \section{Remove Complex Operands}
  3000. \label{sec:remove-complex-opera-Lvar}
  3001. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  3002. into a restricted form in which the arguments of operations are atomic
  3003. expressions. Put another way, this pass removes complex
  3004. operands\index{subject}{complex operand}, such as the expression
  3005. \racket{\code{(- 10)}}\python{\code{-10}}
  3006. in the following program. This is accomplished by introducing a new
  3007. temporary variable, assigning the complex operand to the new
  3008. variable, and then using the new variable in place of the complex
  3009. operand, as shown in the output of \code{remove\_complex\_operands} on the
  3010. right.
  3011. {\if\edition\racketEd
  3012. \begin{transformation}
  3013. % var_test_19.rkt
  3014. \begin{lstlisting}
  3015. (let ([x (+ 42 (- 10))])
  3016. (+ x 10))
  3017. \end{lstlisting}
  3018. \compilesto
  3019. \begin{lstlisting}
  3020. (let ([x (let ([tmp.1 (- 10)])
  3021. (+ 42 tmp.1))])
  3022. (+ x 10))
  3023. \end{lstlisting}
  3024. \end{transformation}
  3025. \fi}
  3026. {\if\edition\pythonEd\pythonColor
  3027. \begin{transformation}
  3028. \begin{lstlisting}
  3029. x = 42 + -10
  3030. print(x + 10)
  3031. \end{lstlisting}
  3032. \compilesto
  3033. \begin{lstlisting}
  3034. tmp_0 = -10
  3035. x = 42 + tmp_0
  3036. tmp_1 = x + 10
  3037. print(tmp_1)
  3038. \end{lstlisting}
  3039. \end{transformation}
  3040. \fi}
  3041. \newcommand{\LvarMonadASTRacket}{
  3042. \begin{array}{rcl}
  3043. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3044. \Exp &::=& \Atm \MID \READ{} \\
  3045. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3046. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3047. \end{array}
  3048. }
  3049. \newcommand{\LvarMonadASTPython}{
  3050. \begin{array}{rcl}
  3051. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3052. \Exp{} &::=& \Atm \MID \READ{} \\
  3053. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3054. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3055. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3056. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3057. \end{array}
  3058. }
  3059. \begin{figure}[tp]
  3060. \centering
  3061. \begin{tcolorbox}[colback=white]
  3062. {\if\edition\racketEd
  3063. \[
  3064. \begin{array}{l}
  3065. \LvarMonadASTRacket \\
  3066. \begin{array}{rcl}
  3067. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3068. \end{array}
  3069. \end{array}
  3070. \]
  3071. \fi}
  3072. {\if\edition\pythonEd\pythonColor
  3073. \[
  3074. \begin{array}{l}
  3075. \LvarMonadASTPython \\
  3076. \begin{array}{rcl}
  3077. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3078. \end{array}
  3079. \end{array}
  3080. \]
  3081. \fi}
  3082. \end{tcolorbox}
  3083. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3084. atomic expressions.}
  3085. \label{fig:Lvar-anf-syntax}
  3086. \index{subject}{Lvarmon@\LangVarANF{} abstract syntax}
  3087. \end{figure}
  3088. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3089. of this pass, the language \LangVarANF{}. The only difference is that
  3090. operator arguments are restricted to be atomic expressions that are
  3091. defined by the \Atm{} nonterminal. In particular, integer constants
  3092. and variables are atomic.
  3093. The atomic expressions are pure (they do not cause or depend on side
  3094. effects) whereas complex expressions may have side effects, such as
  3095. \READ{}. A language with this separation between pure expressions
  3096. versus expressions with side effects is said to be in monadic normal
  3097. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3098. in the name \LangVarANF{}. An important invariant of the
  3099. \code{remove\_complex\_operands} pass is that the relative ordering
  3100. among complex expressions is not changed, but the relative ordering
  3101. between atomic expressions and complex expressions can change and
  3102. often does. These changes are behavior preserving because
  3103. atomic expressions are pure.
  3104. {\if\edition\racketEd
  3105. Another well-known form for intermediate languages is the
  3106. \emph{administrative normal form}
  3107. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3108. \index{subject}{administrative normal form} \index{subject}{ANF}
  3109. %
  3110. The \LangVarANF{} language is not quite in ANF because it allows the
  3111. right-hand side of a \code{let} to be a complex expression, such as
  3112. another \code{let}. The flattening of nested \code{let} expressions is
  3113. instead one of the responsibilities of the \code{explicate\_control}
  3114. pass.
  3115. \fi}
  3116. {\if\edition\racketEd
  3117. We recommend implementing this pass with two mutually recursive
  3118. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3119. \code{rco\_atom} to subexpressions that need to become atomic and to
  3120. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3121. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3122. returns an expression. The \code{rco\_atom} function returns two
  3123. things: an atomic expression and an alist mapping temporary variables to
  3124. complex subexpressions. You can return multiple things from a function
  3125. using Racket's \key{values} form, and you can receive multiple things
  3126. from a function call using the \key{define-values} form.
  3127. \fi}
  3128. %
  3129. {\if\edition\pythonEd\pythonColor
  3130. %
  3131. We recommend implementing this pass with an auxiliary method named
  3132. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3133. Boolean that specifies whether the expression needs to become atomic
  3134. or not. The \code{rco\_exp} method should return a pair consisting of
  3135. the new expression and a list of pairs, associating new temporary
  3136. variables with their initializing expressions.
  3137. %
  3138. \fi}
  3139. {\if\edition\racketEd
  3140. %
  3141. In the example program with the expression \code{(+ 42 (-
  3142. 10))}, the subexpression \code{(- 10)} should be processed using the
  3143. \code{rco\_atom} function because it is an argument of the \code{+}
  3144. operator and therefore needs to become atomic. The output of
  3145. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3146. \begin{transformation}
  3147. \begin{lstlisting}
  3148. (- 10)
  3149. \end{lstlisting}
  3150. \compilesto
  3151. \begin{lstlisting}
  3152. tmp.1
  3153. ((tmp.1 . (- 10)))
  3154. \end{lstlisting}
  3155. \end{transformation}
  3156. \fi}
  3157. %
  3158. {\if\edition\pythonEd\pythonColor
  3159. %
  3160. Returning to the example program with the expression \code{42 + -10},
  3161. the subexpression \code{-10} should be processed using the
  3162. \code{rco\_exp} function with \code{True} as the second argument,
  3163. because \code{-10} is an argument of the \code{+} operator and
  3164. therefore needs to become atomic. The output of \code{rco\_exp}
  3165. applied to \code{-10} is as follows.
  3166. \begin{transformation}
  3167. \begin{lstlisting}
  3168. -10
  3169. \end{lstlisting}
  3170. \compilesto
  3171. \begin{lstlisting}
  3172. tmp_1
  3173. [(tmp_1, -10)]
  3174. \end{lstlisting}
  3175. \end{transformation}
  3176. %
  3177. \fi}
  3178. Take special care of programs, such as the following, that
  3179. %
  3180. \racket{bind a variable to an atomic expression.}
  3181. %
  3182. \python{assign an atomic expression to a variable.}
  3183. %
  3184. You should leave such \racket{variable bindings}\python{assignments}
  3185. unchanged, as shown in the program on the right:\\
  3186. %
  3187. {\if\edition\racketEd
  3188. \begin{transformation}
  3189. % var_test_20.rkt
  3190. \begin{lstlisting}
  3191. (let ([a 42])
  3192. (let ([b a])
  3193. b))
  3194. \end{lstlisting}
  3195. \compilesto
  3196. \begin{lstlisting}
  3197. (let ([a 42])
  3198. (let ([b a])
  3199. b))
  3200. \end{lstlisting}
  3201. \end{transformation}
  3202. \fi}
  3203. {\if\edition\pythonEd\pythonColor
  3204. \begin{transformation}
  3205. \begin{lstlisting}
  3206. a = 42
  3207. b = a
  3208. print(b)
  3209. \end{lstlisting}
  3210. \compilesto
  3211. \begin{lstlisting}
  3212. a = 42
  3213. b = a
  3214. print(b)
  3215. \end{lstlisting}
  3216. \end{transformation}
  3217. \fi}
  3218. %
  3219. \noindent A careless implementation might produce the following output with
  3220. unnecessary temporary variables.
  3221. \begin{center}
  3222. \begin{minipage}{0.4\textwidth}
  3223. {\if\edition\racketEd
  3224. \begin{lstlisting}
  3225. (let ([tmp.1 42])
  3226. (let ([a tmp.1])
  3227. (let ([tmp.2 a])
  3228. (let ([b tmp.2])
  3229. b))))
  3230. \end{lstlisting}
  3231. \fi}
  3232. {\if\edition\pythonEd\pythonColor
  3233. \begin{lstlisting}
  3234. tmp_1 = 42
  3235. a = tmp_1
  3236. tmp_2 = a
  3237. b = tmp_2
  3238. print(b)
  3239. \end{lstlisting}
  3240. \fi}
  3241. \end{minipage}
  3242. \end{center}
  3243. \begin{exercise}
  3244. \normalfont\normalsize
  3245. {\if\edition\racketEd
  3246. Implement the \code{remove\_complex\_operands} function in
  3247. \code{compiler.rkt}.
  3248. %
  3249. Create three new \LangVar{} programs that exercise the interesting
  3250. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3251. regarding file names described in exercise~\ref{ex:Lvar}.
  3252. %
  3253. In the \code{run-tests.rkt} script, add the following entry to the
  3254. list of \code{passes}, and then run the script to test your compiler.
  3255. \begin{lstlisting}
  3256. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3257. \end{lstlisting}
  3258. In debugging your compiler, it is often useful to see the intermediate
  3259. programs that are output from each pass. To print the intermediate
  3260. programs, place \lstinline{(debug-level 1)} before the call to
  3261. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3262. %
  3263. {\if\edition\pythonEd\pythonColor
  3264. Implement the \code{remove\_complex\_operands} pass in
  3265. \code{compiler.py}, creating auxiliary functions for each
  3266. nonterminal in the grammar, that is, \code{rco\_exp}
  3267. and \code{rco\_stmt}. We recommend that you use the function
  3268. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3269. \fi}
  3270. \end{exercise}
  3271. {\if\edition\pythonEd\pythonColor
  3272. \begin{exercise}
  3273. \normalfont\normalsize
  3274. \label{ex:Lvar}
  3275. Create five \LangVar{} programs that exercise the most interesting
  3276. parts of the \code{remove\_complex\_operands} pass. The five programs
  3277. should be placed in the subdirectory \key{tests/var}, and the file
  3278. names should end with the file extension \key{.py}. Run the
  3279. \key{run-tests.py} script in the support code to check whether the
  3280. output programs produce the same result as the input programs.
  3281. \end{exercise}
  3282. \fi}
  3283. {\if\edition\racketEd
  3284. \section{Explicate Control}
  3285. \label{sec:explicate-control-Lvar}
  3286. The \code{explicate\_control} pass compiles \LangVarANF{} programs into \LangCVar{}
  3287. programs that make the order of execution explicit in their
  3288. syntax. For now this amounts to flattening \key{let} constructs into a
  3289. sequence of assignment statements. For example, consider the following
  3290. \LangVar{} program:\\
  3291. % var_test_11.rkt
  3292. \begin{minipage}{0.96\textwidth}
  3293. \begin{lstlisting}
  3294. (let ([y (let ([x 20])
  3295. (+ x (let ([x 22]) x)))])
  3296. y)
  3297. \end{lstlisting}
  3298. \end{minipage}\\
  3299. %
  3300. The output of the previous pass is shown next, on the left, and the
  3301. output of \code{explicate\_control} is on the right. Recall that the
  3302. right-hand side of a \key{let} executes before its body, so that the order
  3303. of evaluation for this program is to assign \code{20} to \code{x.1},
  3304. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3305. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3306. this ordering explicit.
  3307. \begin{transformation}
  3308. \begin{lstlisting}
  3309. (let ([y (let ([x.1 20])
  3310. (let ([x.2 22])
  3311. (+ x.1 x.2)))])
  3312. y)
  3313. \end{lstlisting}
  3314. \compilesto
  3315. \begin{lstlisting}[language=C]
  3316. start:
  3317. x.1 = 20;
  3318. x.2 = 22;
  3319. y = (+ x.1 x.2);
  3320. return y;
  3321. \end{lstlisting}
  3322. \end{transformation}
  3323. \begin{figure}[tbp]
  3324. \begin{tcolorbox}[colback=white]
  3325. \begin{lstlisting}
  3326. (define (explicate_tail e)
  3327. (match e
  3328. [(Var x) ___]
  3329. [(Int n) (Return (Int n))]
  3330. [(Let x rhs body) ___]
  3331. [(Prim op es) ___]
  3332. [else (error "explicate_tail unhandled case" e)]))
  3333. (define (explicate_assign e x cont)
  3334. (match e
  3335. [(Var x) ___]
  3336. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3337. [(Let y rhs body) ___]
  3338. [(Prim op es) ___]
  3339. [else (error "explicate_assign unhandled case" e)]))
  3340. (define (explicate_control p)
  3341. (match p
  3342. [(Program info body) ___]))
  3343. \end{lstlisting}
  3344. \end{tcolorbox}
  3345. \caption{Skeleton for the \code{explicate\_control} pass.}
  3346. \label{fig:explicate-control-Lvar}
  3347. \end{figure}
  3348. The organization of this pass depends on the notion of tail position
  3349. to which we have alluded. Here is the definition.
  3350. \begin{definition}\normalfont
  3351. The following rules define when an expression is in \emph{tail
  3352. position}\index{subject}{tail position} for the language \LangVar{}.
  3353. \begin{enumerate}
  3354. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3355. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3356. \end{enumerate}
  3357. \end{definition}
  3358. We recommend implementing \code{explicate\_control} using two
  3359. recursive functions, \code{explicate\_tail} and
  3360. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3361. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3362. function should be applied to expressions in tail position, whereas the
  3363. \code{explicate\_assign} should be applied to expressions that occur on
  3364. the right-hand side of a \key{let}.
  3365. %
  3366. The \code{explicate\_tail} function takes an \Exp{} in \LangVarANF{} as
  3367. input and produces a \Tail{} in \LangCVar{} (see
  3368. figure~\ref{fig:c0-syntax}).
  3369. %
  3370. The \code{explicate\_assign} function takes an \Exp{} in \LangVarANF{},
  3371. the variable to which it is to be assigned, and a \Tail{} in
  3372. \LangCVar{} for the code that comes after the assignment. The
  3373. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3374. The \code{explicate\_assign} function is in accumulator-passing style:
  3375. the \code{cont} parameter is used for accumulating the output. This
  3376. accumulator-passing style plays an important role in the way that we
  3377. generate high-quality code for conditional expressions in
  3378. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3379. continuation because it contains the generated code that should come
  3380. after the current assignment. This code organization is also related
  3381. to continuation-passing style, except that \code{cont} is not what
  3382. happens next during compilation but is what happens next in the
  3383. generated code.
  3384. \begin{exercise}\normalfont\normalsize
  3385. %
  3386. Implement the \code{explicate\_control} function in
  3387. \code{compiler.rkt}. Create three new \LangVar{} programs that
  3388. exercise the code in \code{explicate\_control}.
  3389. %
  3390. In the \code{run-tests.rkt} script, add the following entry to the
  3391. list of \code{passes} and then run the script to test your compiler.
  3392. \begin{lstlisting}
  3393. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3394. \end{lstlisting}
  3395. \end{exercise}
  3396. \fi}
  3397. \section{Select Instructions}
  3398. \label{sec:select-Lvar}
  3399. \index{subject}{select instructions}
  3400. In the \code{select\_instructions} pass we begin the work of
  3401. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3402. language of this pass, \LangXVar{}, is a variant of x86 that still
  3403. uses variables, so we add an AST node of the form $\XVAR{\itm{var}}$
  3404. to the \Arg{} nonterminal of the \LangXInt{} abstract syntax
  3405. (figure~\ref{fig:x86-int-ast})\index{subject}{x86var@\LangXVar{}}.
  3406. \racket{We recommend implementing the \code{select\_instructions} with
  3407. three auxiliary functions, one for each of the nonterminals of
  3408. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.} \python{We recommend
  3409. implementing an auxiliary function named \code{select\_stmt} for the
  3410. $\Stmt$ nonterminal.}
  3411. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3412. same and integer constants change to immediates; that is, $\INT{n}$
  3413. changes to $\IMM{n}$.}
  3414. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3415. arithmetic operations. For example, consider the following addition
  3416. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3417. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3418. \key{addq} instruction in x86, but it performs an in-place update.
  3419. %
  3420. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3421. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into \itm{var}.
  3422. \begin{transformation}
  3423. {\if\edition\racketEd
  3424. \begin{lstlisting}
  3425. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3426. \end{lstlisting}
  3427. \fi}
  3428. {\if\edition\pythonEd\pythonColor
  3429. \begin{lstlisting}
  3430. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3431. \end{lstlisting}
  3432. \fi}
  3433. \compilesto
  3434. \begin{lstlisting}
  3435. movq |$\Arg_1$|, %rax
  3436. addq |$\Arg_2$|, %rax
  3437. movq %rax, |$\itm{var}$|
  3438. \end{lstlisting}
  3439. \end{transformation}
  3440. %
  3441. However, with some care we can generate shorter sequences of
  3442. instructions. Suppose that one or more of the arguments of the
  3443. addition is the same variable as the left-hand side of the assignment.
  3444. Then the assignment statement can be translated into a single
  3445. \key{addq} instruction, as follows.
  3446. \begin{transformation}
  3447. {\if\edition\racketEd
  3448. \begin{lstlisting}
  3449. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3450. \end{lstlisting}
  3451. \fi}
  3452. {\if\edition\pythonEd\pythonColor
  3453. \begin{lstlisting}
  3454. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3455. \end{lstlisting}
  3456. \fi}
  3457. \compilesto
  3458. \begin{lstlisting}
  3459. addq |$\Arg_1$|, |$\itm{var}$|
  3460. \end{lstlisting}
  3461. \end{transformation}
  3462. %
  3463. On the other hand, if $\Atm_2$ is not the same variable as the
  3464. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3465. and then add $\Arg_2$ to \itm{var}.
  3466. %
  3467. \begin{transformation}
  3468. {\if\edition\racketEd
  3469. \begin{lstlisting}
  3470. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3471. \end{lstlisting}
  3472. \fi}
  3473. {\if\edition\pythonEd\pythonColor
  3474. \begin{lstlisting}
  3475. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3476. \end{lstlisting}
  3477. \fi}
  3478. \compilesto
  3479. \begin{lstlisting}
  3480. movq |$\Arg_1$|, |$\itm{var}$|
  3481. addq |$\Arg_2$|, |$\itm{var}$|
  3482. \end{lstlisting}
  3483. \end{transformation}
  3484. The \READOP{} operation does not have a direct counterpart in x86
  3485. assembly, so we provide this functionality with the function
  3486. \code{read\_int} in the file \code{runtime.c}, written in
  3487. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3488. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3489. system}, or simply the \emph{runtime} for short. When compiling your
  3490. generated x86 assembly code, you need to compile \code{runtime.c} to
  3491. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3492. \code{-c}) and link it into the executable. For our purposes of code
  3493. generation, all you need to do is translate an assignment of
  3494. \READOP{} into a call to the \code{read\_int} function followed by a
  3495. move from \code{rax} to the left-hand side variable. (The
  3496. return value of a function is placed in \code{rax}.)
  3497. \begin{transformation}
  3498. {\if\edition\racketEd
  3499. \begin{lstlisting}
  3500. |$\itm{var}$| = (read);
  3501. \end{lstlisting}
  3502. \fi}
  3503. {\if\edition\pythonEd\pythonColor
  3504. \begin{lstlisting}
  3505. |$\itm{var}$| = input_int();
  3506. \end{lstlisting}
  3507. \fi}
  3508. \compilesto
  3509. \begin{lstlisting}
  3510. callq read_int
  3511. movq %rax, |$\itm{var}$|
  3512. \end{lstlisting}
  3513. \end{transformation}
  3514. {\if\edition\pythonEd\pythonColor
  3515. %
  3516. Similarly, we translate the \code{print} operation, shown below, into
  3517. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3518. In x86, the first six arguments to functions are passed in registers,
  3519. with the first argument passed in register \code{rdi}. So we move the
  3520. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3521. \code{callq} instruction.
  3522. \begin{transformation}
  3523. \begin{lstlisting}
  3524. print(|$\Atm$|)
  3525. \end{lstlisting}
  3526. \compilesto
  3527. \begin{lstlisting}
  3528. movq |$\Arg$|, %rdi
  3529. callq print_int
  3530. \end{lstlisting}
  3531. \end{transformation}
  3532. %
  3533. \fi}
  3534. {\if\edition\racketEd
  3535. %
  3536. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3537. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3538. assignment to the \key{rax} register followed by a jump to
  3539. the label \key{conclusion}. Later, in Section~\ref{sec:print-x86},
  3540. we discuss the generation of the \key{conclusion} block.
  3541. In the meantime, the interpreter for \LangXVar{} recognizes a jump
  3542. to \key{conclusion} as the end of the program.
  3543. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3544. recursively and then append the resulting instructions.
  3545. %
  3546. \fi}
  3547. {\if\edition\pythonEd\pythonColor
  3548. We recommend that you use the function \code{utils.label\_name} to
  3549. transform strings into labels, for example, in
  3550. the target of the \code{callq} instruction. This practice makes your
  3551. compiler portable across Linux and Mac OS X, which requires an underscore
  3552. prefixed to all labels.
  3553. \fi}
  3554. \begin{exercise}
  3555. \normalfont\normalsize
  3556. {\if\edition\racketEd
  3557. Implement the \code{select\_instructions} pass in
  3558. \code{compiler.rkt}. Create three new example programs that are
  3559. designed to exercise all the interesting cases in this pass.
  3560. %
  3561. In the \code{run-tests.rkt} script, add the following entry to the
  3562. list of \code{passes} and then run the script to test your compiler.
  3563. \begin{lstlisting}
  3564. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3565. \end{lstlisting}
  3566. \fi}
  3567. {\if\edition\pythonEd\pythonColor
  3568. Implement the \key{select\_instructions} pass in
  3569. \code{compiler.py}. Create three new example programs that are
  3570. designed to exercise all the interesting cases in this pass.
  3571. Run the \code{run-tests.py} script to check
  3572. whether the output programs produce the same result as the input
  3573. programs.
  3574. \fi}
  3575. \end{exercise}
  3576. \section{Assign Homes}
  3577. \label{sec:assign-Lvar}
  3578. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3579. \LangXVar{} programs that no longer use program variables. Thus, the
  3580. \code{assign\_homes} pass is responsible for placing all the program
  3581. variables in registers or on the stack. For runtime efficiency, it is
  3582. better to place variables in registers, but because there are only
  3583. sixteen registers, some programs must necessarily resort to placing
  3584. some variables on the stack. In this chapter we focus on the mechanics
  3585. of placing variables on the stack. We study an algorithm for placing
  3586. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3587. Consider again the following \LangVar{} program from
  3588. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3589. % var_test_20.rkt
  3590. \begin{minipage}{0.96\textwidth}
  3591. {\if\edition\racketEd
  3592. \begin{lstlisting}
  3593. (let ([a 42])
  3594. (let ([b a])
  3595. b))
  3596. \end{lstlisting}
  3597. \fi}
  3598. {\if\edition\pythonEd\pythonColor
  3599. \begin{lstlisting}
  3600. a = 42
  3601. b = a
  3602. print(b)
  3603. \end{lstlisting}
  3604. \fi}
  3605. \end{minipage}\\
  3606. %
  3607. The output of \code{select\_instructions} is shown next, on the left,
  3608. and the output of \code{assign\_homes} is on the right.
  3609. In this example, we assign variable \code{a} to stack location
  3610. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3611. {\if\edition\racketEd
  3612. \begin{transformation}
  3613. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3614. movq $42, a
  3615. movq a, b
  3616. movq b, %rax
  3617. \end{lstlisting}
  3618. \compilesto
  3619. %stack-space: 16
  3620. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3621. movq $42, -8(%rbp)
  3622. movq -8(%rbp), -16(%rbp)
  3623. movq -16(%rbp), %rax
  3624. \end{lstlisting}
  3625. \end{transformation}
  3626. \fi}
  3627. {\if\edition\pythonEd
  3628. \begin{transformation}
  3629. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3630. movq $42, a
  3631. movq a, b
  3632. movq b, %rdi
  3633. callq print_int
  3634. \end{lstlisting}
  3635. \compilesto
  3636. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3637. movq $42, -8(%rbp)
  3638. movq -8(%rbp), -16(%rbp)
  3639. movq -16(%rbp), %rdi
  3640. callq print_int
  3641. \end{lstlisting}
  3642. \end{transformation}
  3643. \fi}
  3644. \racket{
  3645. The \code{assign\_homes} pass should replace all variables
  3646. with stack locations.
  3647. The list of variables can be obtained from
  3648. the \code{locals-types} entry in the $\itm{info}$ of the
  3649. \code{X86Program} node. The \code{locals-types} entry is an alist
  3650. mapping all the variables in the program to their types
  3651. (for now, just \code{Integer}).
  3652. As an aside, the \code{locals-types} entry is
  3653. computed by \code{type-check-Cvar} in the support code, which
  3654. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3655. which you should propagate to the \code{X86Program} node.}
  3656. %
  3657. \python{The \code{assign\_homes} pass should replace all uses of
  3658. variables with stack locations.}
  3659. %
  3660. In the process of assigning variables to stack locations, it is
  3661. convenient for you to compute and store the size of the frame (in
  3662. bytes) in
  3663. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3664. %
  3665. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3666. %
  3667. which is needed later to generate the conclusion of the \code{main}
  3668. procedure. The x86-64 standard requires the frame size to be a
  3669. multiple of 16 bytes.\index{subject}{frame}
  3670. % TODO: store the number of variables instead? -Jeremy
  3671. \begin{exercise}\normalfont\normalsize
  3672. Implement the \code{assign\_homes} pass in
  3673. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3674. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3675. grammar. We recommend that the auxiliary functions take an extra
  3676. parameter that maps variable names to homes (stack locations for now).
  3677. %
  3678. {\if\edition\racketEd
  3679. In the \code{run-tests.rkt} script, add the following entry to the
  3680. list of \code{passes} and then run the script to test your compiler.
  3681. \begin{lstlisting}
  3682. (list "assign homes" assign-homes interp_x86-0)
  3683. \end{lstlisting}
  3684. \fi}
  3685. {\if\edition\pythonEd\pythonColor
  3686. Run the \code{run-tests.py} script to check
  3687. whether the output programs produce the same result as the input
  3688. programs.
  3689. \fi}
  3690. \end{exercise}
  3691. \section{Patch Instructions}
  3692. \label{sec:patch-s0}
  3693. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3694. \LangXInt{} by making sure that each instruction adheres to the
  3695. restriction that at most one argument of an instruction may be a
  3696. memory reference.
  3697. We return to the following example.\\
  3698. \begin{minipage}{0.5\textwidth}
  3699. % var_test_20.rkt
  3700. {\if\edition\racketEd
  3701. \begin{lstlisting}
  3702. (let ([a 42])
  3703. (let ([b a])
  3704. b))
  3705. \end{lstlisting}
  3706. \fi}
  3707. {\if\edition\pythonEd\pythonColor
  3708. \begin{lstlisting}
  3709. a = 42
  3710. b = a
  3711. print(b)
  3712. \end{lstlisting}
  3713. \fi}
  3714. \end{minipage}\\
  3715. The \code{assign\_homes} pass produces the following translation. \\
  3716. \begin{minipage}{0.5\textwidth}
  3717. {\if\edition\racketEd
  3718. \begin{lstlisting}
  3719. movq $42, -8(%rbp)
  3720. movq -8(%rbp), -16(%rbp)
  3721. movq -16(%rbp), %rax
  3722. \end{lstlisting}
  3723. \fi}
  3724. {\if\edition\pythonEd\pythonColor
  3725. \begin{lstlisting}
  3726. movq $42, -8(%rbp)
  3727. movq -8(%rbp), -16(%rbp)
  3728. movq -16(%rbp), %rdi
  3729. callq print_int
  3730. \end{lstlisting}
  3731. \fi}
  3732. \end{minipage}\\
  3733. The second \key{movq} instruction is problematic because both
  3734. arguments are stack locations. We suggest fixing this problem by
  3735. moving from the source location to the register \key{rax} and then
  3736. from \key{rax} to the destination location, as follows.
  3737. \begin{lstlisting}
  3738. movq -8(%rbp), %rax
  3739. movq %rax, -16(%rbp)
  3740. \end{lstlisting}
  3741. There is a similar corner case that also needs to be dealt with. If
  3742. one argument is an immediate integer larger than $2^{16}$ and the
  3743. other is a memory reference, then the instruction is invalid. One can
  3744. fix this, for example, by first moving the immediate integer into
  3745. \key{rax} and then using \key{rax} in place of the integer.
  3746. \begin{exercise}
  3747. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3748. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3749. Create three new example programs that are
  3750. designed to exercise all the interesting cases in this pass.
  3751. %
  3752. {\if\edition\racketEd
  3753. In the \code{run-tests.rkt} script, add the following entry to the
  3754. list of \code{passes} and then run the script to test your compiler.
  3755. \begin{lstlisting}
  3756. (list "patch instructions" patch_instructions interp_x86-0)
  3757. \end{lstlisting}
  3758. \fi}
  3759. {\if\edition\pythonEd\pythonColor
  3760. Run the \code{run-tests.py} script to check
  3761. whether the output programs produce the same result as the input
  3762. programs.
  3763. \fi}
  3764. \end{exercise}
  3765. \section{Generate Prelude and Conclusion}
  3766. \label{sec:print-x86}
  3767. \index{subject}{prelude}\index{subject}{conclusion}
  3768. The last step of the compiler from \LangVar{} to x86 is to generate
  3769. the \code{main} function with a prelude and conclusion wrapped around
  3770. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3771. discussed in section~\ref{sec:x86}.
  3772. When running on Mac OS X, your compiler should prefix an underscore to
  3773. all labels (for example, changing \key{main} to \key{\_main}).
  3774. %
  3775. \racket{The Racket call \code{(system-type 'os)} is useful for
  3776. determining which operating system the compiler is running on. It
  3777. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3778. %
  3779. \python{The Python \code{platform.system}
  3780. function returns \code{\textquotesingle Linux\textquotesingle},
  3781. \code{\textquotesingle Windows\textquotesingle}, or
  3782. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3783. \begin{exercise}\normalfont\normalsize
  3784. %
  3785. Implement the \key{prelude\_and\_conclusion} pass in
  3786. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3787. %
  3788. {\if\edition\racketEd
  3789. In the \code{run-tests.rkt} script, add the following entry to the
  3790. list of \code{passes} and then run the script to test your compiler.
  3791. \begin{lstlisting}
  3792. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3793. \end{lstlisting}
  3794. %
  3795. Uncomment the call to the \key{compiler-tests} function
  3796. (appendix~\ref{appendix:utilities}), which tests your complete
  3797. compiler by executing the generated x86 code. It translates the x86
  3798. AST that you produce into a string by invoking the \code{print-x86}
  3799. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3800. the provided \key{runtime.c} file to \key{runtime.o} using
  3801. \key{gcc}. Run the script to test your compiler.
  3802. %
  3803. \fi}
  3804. {\if\edition\pythonEd\pythonColor
  3805. %
  3806. Run the \code{run-tests.py} script to check whether the output
  3807. programs produce the same result as the input programs. That script
  3808. translates the x86 AST that you produce into a string by invoking the
  3809. \code{repr} method that is implemented by the x86 AST classes in
  3810. \code{x86\_ast.py}.
  3811. %
  3812. \fi}
  3813. \end{exercise}
  3814. \section{Challenge: Partial Evaluator for \LangVar{}}
  3815. \label{sec:pe-Lvar}
  3816. \index{subject}{partialevaluation@partial evaluation}
  3817. This section describes two optional challenge exercises that involve
  3818. adapting and improving the partial evaluator for \LangInt{} that was
  3819. introduced in section~\ref{sec:partial-evaluation}.
  3820. \begin{exercise}\label{ex:pe-Lvar}
  3821. \normalfont\normalsize
  3822. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3823. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3824. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3825. %
  3826. \racket{\key{let} binding}\python{assignment}
  3827. %
  3828. to the \LangInt{} language, so you will need to add cases for them in
  3829. the \code{pe\_exp}
  3830. %
  3831. \racket{function.}
  3832. %
  3833. \python{and \code{pe\_stmt} functions.}
  3834. %
  3835. Once complete, add the partial evaluation pass to the front of your
  3836. compiler.
  3837. \python{In particular, add a method named \code{partial\_eval} to
  3838. the \code{Compiler} class in \code{compiler.py}.}
  3839. Check that your compiler still passes all the
  3840. tests.
  3841. \end{exercise}
  3842. \begin{exercise}
  3843. \normalfont\normalsize
  3844. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3845. \code{pe\_add} auxiliary functions with functions that know more about
  3846. arithmetic. For example, your partial evaluator should translate
  3847. {\if\edition\racketEd
  3848. \[
  3849. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3850. \code{(+ 2 (read))}
  3851. \]
  3852. \fi}
  3853. {\if\edition\pythonEd\pythonColor
  3854. \[
  3855. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3856. \code{2 + input\_int()}
  3857. \]
  3858. \fi}
  3859. %
  3860. To accomplish this, the \code{pe\_exp} function should produce output
  3861. in the form of the $\itm{residual}$ nonterminal of the following
  3862. grammar. The idea is that when processing an addition expression, we
  3863. can always produce one of the following: (1) an integer constant, (2)
  3864. an addition expression with an integer constant on the left-hand side
  3865. but not the right-hand side, or (3) an addition expression in which
  3866. neither subexpression is a constant.
  3867. %
  3868. {\if\edition\racketEd
  3869. \[
  3870. \begin{array}{lcl}
  3871. \itm{inert} &::=& \Var
  3872. \MID \LP\key{read}\RP
  3873. \MID \LP\key{-} ~\Var\RP
  3874. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3875. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3876. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3877. \itm{residual} &::=& \Int
  3878. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3879. \MID \itm{inert}
  3880. \end{array}
  3881. \]
  3882. \fi}
  3883. {\if\edition\pythonEd\pythonColor
  3884. \[
  3885. \begin{array}{lcl}
  3886. \itm{inert} &::=& \Var
  3887. \MID \key{input\_int}\LP\RP
  3888. \MID \key{-} \Var
  3889. \MID \key{-} \key{input\_int}\LP\RP
  3890. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3891. \itm{residual} &::=& \Int
  3892. \MID \Int ~ \key{+} ~ \itm{inert}
  3893. \MID \itm{inert}
  3894. \end{array}
  3895. \]
  3896. \fi}
  3897. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3898. inputs are $\itm{residual}$ expressions and they should return
  3899. $\itm{residual}$ expressions. Once the improvements are complete,
  3900. make sure that your compiler still passes all the tests. After
  3901. all, fast code is useless if it produces incorrect results!
  3902. \end{exercise}
  3903. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3904. {\if\edition\pythonEd\pythonColor
  3905. \chapter{Parsing}
  3906. \label{ch:parsing}
  3907. \setcounter{footnote}{0}
  3908. \index{subject}{parsing}
  3909. In this chapter we learn how to use the Lark parser
  3910. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3911. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3912. You are then asked to create a parser for \LangVar{} using Lark.
  3913. We also describe the parsing algorithms used inside Lark, studying the
  3914. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3915. A parser framework such as Lark takes in a specification of the
  3916. concrete syntax and an input program and produces a parse tree. Even
  3917. though a parser framework does most of the work for us, using one
  3918. properly requires some knowledge. In particular, we must learn about
  3919. its specification languages and we must learn how to deal with
  3920. ambiguity in our language specifications. Also, some algorithms, such
  3921. as LALR(1), place restrictions on the grammars they can handle, in
  3922. which case knowing the algorithm helps with trying to decipher the
  3923. error messages.
  3924. The process of parsing is traditionally subdivided into two phases:
  3925. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3926. analysis} (also called parsing). The lexical analysis phase
  3927. translates the sequence of characters into a sequence of
  3928. \emph{tokens}, that is, words consisting of several characters. The
  3929. parsing phase organizes the tokens into a \emph{parse tree} that
  3930. captures how the tokens were matched by rules in the grammar of the
  3931. language. The reason for the subdivision into two phases is to enable
  3932. the use of a faster but less powerful algorithm for lexical analysis
  3933. and the use of a slower but more powerful algorithm for parsing.
  3934. %
  3935. %% Likewise, parser generators typical come in pairs, with separate
  3936. %% generators for the lexical analyzer (or lexer for short) and for the
  3937. %% parser. A particularly influential pair of generators were
  3938. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3939. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3940. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3941. %% Compiler Compiler.
  3942. %
  3943. The Lark parser framework that we use in this chapter includes both
  3944. lexical analyzers and parsers. The next section discusses lexical
  3945. analysis, and the remainder of the chapter discusses parsing.
  3946. \section{Lexical Analysis and Regular Expressions}
  3947. \label{sec:lex}
  3948. The lexical analyzers produced by Lark turn a sequence of characters
  3949. (a string) into a sequence of token objects. For example, a Lark
  3950. generated lexer for \LangInt{} converts the string
  3951. \begin{lstlisting}
  3952. 'print(1 + 3)'
  3953. \end{lstlisting}
  3954. \noindent into the following sequence of token objects:
  3955. \begin{center}
  3956. \begin{minipage}{0.95\textwidth}
  3957. \begin{lstlisting}
  3958. Token('PRINT', 'print')
  3959. Token('LPAR', '(')
  3960. Token('INT', '1')
  3961. Token('PLUS', '+')
  3962. Token('INT', '3')
  3963. Token('RPAR', ')')
  3964. Token('NEWLINE', '\n')
  3965. \end{lstlisting}
  3966. \end{minipage}
  3967. \end{center}
  3968. Each token includes a field for its \code{type}, such as \skey{INT},
  3969. and a field for its \code{value}, such as \skey{1}.
  3970. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3971. specification language for Lark's lexer is one regular expression for
  3972. each type of token. The term \emph{regular} comes from the term
  3973. \emph{regular languages}, which are the languages that can be
  3974. recognized by a finite state machine. A \emph{regular expression} is a
  3975. pattern formed of the following core elements:\index{subject}{regular
  3976. expression}\footnote{Regular expressions traditionally include the
  3977. empty regular expression that matches any zero-length part of a
  3978. string, but Lark does not support the empty regular expression.}
  3979. \begin{itemize}
  3980. \item A single character $c$ is a regular expression, and it matches
  3981. only itself. For example, the regular expression \code{a} matches
  3982. only the string \skey{a}.
  3983. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3984. R_2$ form a regular expression that matches any string that matches
  3985. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3986. matches the string \skey{a} and the string \skey{c}.
  3987. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3988. expression that matches any string that can be formed by
  3989. concatenating two strings, where the first string matches $R_1$ and
  3990. the second string matches $R_2$. For example, the regular expression
  3991. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3992. (Parentheses can be used to control the grouping of operators within
  3993. a regular expression.)
  3994. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3995. Kleene closure) is a regular expression that matches any string that
  3996. can be formed by concatenating zero or more strings that each match
  3997. the regular expression $R$. For example, the regular expression
  3998. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3999. \skey{abc}.
  4000. \end{itemize}
  4001. For our convenience, Lark also accepts the following extended set of
  4002. regular expressions that are automatically translated into the core
  4003. regular expressions.
  4004. \begin{itemize}
  4005. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  4006. c_n]$ is a regular expression that matches any one of the
  4007. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  4008. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  4009. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  4010. a regular expression that matches any character between $c_1$ and
  4011. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  4012. letter in the alphabet.
  4013. \item A regular expression followed by the plus symbol $R\ttm{+}$
  4014. is a regular expression that matches any string that can
  4015. be formed by concatenating one or more strings that each match $R$.
  4016. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  4017. matches \skey{b} and \skey{bzca}.
  4018. \item A regular expression followed by a question mark $R\ttm{?}$
  4019. is a regular expression that matches any string that either
  4020. matches $R$ or is the empty string.
  4021. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  4022. \end{itemize}
  4023. In a Lark grammar file, each kind of token is specified by a
  4024. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  4025. that consists of the name of the terminal followed by a colon followed
  4026. by a sequence of literals. The literals include strings such as
  4027. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  4028. terminal names, and literals composed using the regular expression
  4029. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  4030. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  4031. \begin{center}
  4032. \begin{minipage}{0.95\textwidth}
  4033. \begin{lstlisting}
  4034. DIGIT: /[0-9]/
  4035. INT: "-"? DIGIT+
  4036. NEWLINE: (/\r/? /\n/)+
  4037. \end{lstlisting}
  4038. \end{minipage}
  4039. \end{center}
  4040. \section{Grammars and Parse Trees}
  4041. \label{sec:CFG}
  4042. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4043. specify the abstract syntax of a language. We now take a closer look
  4044. at using grammar rules to specify the concrete syntax. Recall that
  4045. each rule has a left-hand side and a right-hand side, where the
  4046. left-hand side is a nonterminal and the right-hand side is a pattern
  4047. that defines what can be parsed as that nonterminal. For concrete
  4048. syntax, each right-hand side expresses a pattern for a string instead
  4049. of a pattern for an abstract syntax tree. In particular, each
  4050. right-hand side is a sequence of
  4051. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4052. terminal or a nonterminal. The nonterminals play the same role as in
  4053. the abstract syntax, defining categories of syntax. The nonterminals
  4054. of a grammar include the tokens defined in the lexer and all the
  4055. nonterminals defined by the grammar rules.
  4056. As an example, let us take a closer look at the concrete syntax of the
  4057. \LangInt{} language, repeated here.
  4058. \[
  4059. \begin{array}{l}
  4060. \LintGrammarPython \\
  4061. \begin{array}{rcl}
  4062. \LangInt{} &::=& \Stmt^{*}
  4063. \end{array}
  4064. \end{array}
  4065. \]
  4066. The Lark syntax for grammar rules differs slightly from the variant of
  4067. BNF that we use in this book. In particular, the notation $::=$ is
  4068. replaced by a single colon, and the use of typewriter font for string
  4069. literals is replaced by quotation marks. The following grammar serves
  4070. as a first draft of a Lark grammar for \LangInt{}.
  4071. \begin{center}
  4072. \begin{minipage}{0.95\textwidth}
  4073. \begin{lstlisting}[escapechar=$]
  4074. exp: INT
  4075. | "input_int" "(" ")"
  4076. | "-" exp
  4077. | exp "+" exp
  4078. | exp "-" exp
  4079. | "(" exp ")"
  4080. stmt_list:
  4081. | stmt NEWLINE stmt_list
  4082. lang_int: stmt_list
  4083. \end{lstlisting}
  4084. \end{minipage}
  4085. \end{center}
  4086. Let us begin by discussing the rule \code{exp: INT}, which says that
  4087. if the lexer matches a string to \code{INT}, then the parser also
  4088. categorizes the string as an \code{exp}. Recall that in
  4089. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4090. nonterminal with a sentence in English. Here we specify \code{INT}
  4091. more formally using a type of token \code{INT} and its regular
  4092. expression \code{"-"? DIGIT+}.
  4093. The rule \code{exp: exp "+" exp} says that any string that matches
  4094. \code{exp}, followed by the \code{+} character, followed by another
  4095. string that matches \code{exp}, is itself an \code{exp}. For example,
  4096. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4097. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4098. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4099. \code{exp}. We can visualize the application of grammar rules to parse
  4100. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4101. internal node in the tree is an application of a grammar rule and is
  4102. labeled with its left-hand side nonterminal. Each leaf node is a
  4103. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4104. shown in figure~\ref{fig:simple-parse-tree}.
  4105. \begin{figure}[tbp]
  4106. \begin{tcolorbox}[colback=white]
  4107. \centering
  4108. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4109. \end{tcolorbox}
  4110. \caption{The parse tree for \lstinline{'1+3'}.}
  4111. \label{fig:simple-parse-tree}
  4112. \end{figure}
  4113. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4114. following parse tree as represented by \code{Tree} and \code{Token}
  4115. objects.
  4116. \begin{lstlisting}
  4117. Tree('lang_int',
  4118. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4119. Tree('exp', [Token('INT', '3')])])]),
  4120. Token('NEWLINE', '\n')])
  4121. \end{lstlisting}
  4122. The nodes that come from the lexer are \code{Token} objects, whereas
  4123. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4124. object has a \code{data} field containing the name of the nonterminal
  4125. for the grammar rule that was applied. Each \code{Tree} object also
  4126. has a \code{children} field that is a list containing trees and/or
  4127. tokens. Note that Lark does not produce nodes for string literals in
  4128. the grammar. For example, the \code{Tree} node for the addition
  4129. expression has only two children for the two integers but is missing
  4130. its middle child for the \code{"+"} terminal. This would be
  4131. problematic except that Lark provides a mechanism for customizing the
  4132. \code{data} field of each \code{Tree} node on the basis of which rule was
  4133. applied. Next to each alternative in a grammar rule, write \code{->}
  4134. followed by a string that you want to appear in the \code{data}
  4135. field. The following is a second draft of a Lark grammar for
  4136. \LangInt{}, this time with more specific labels on the \code{Tree}
  4137. nodes.
  4138. \begin{center}
  4139. \begin{minipage}{0.95\textwidth}
  4140. \begin{lstlisting}[escapechar=$]
  4141. exp: INT -> int
  4142. | "input_int" "(" ")" -> input_int
  4143. | "-" exp -> usub
  4144. | exp "+" exp -> add
  4145. | exp "-" exp -> sub
  4146. | "(" exp ")" -> paren
  4147. stmt: "print" "(" exp ")" -> print
  4148. | exp -> expr
  4149. stmt_list: -> empty_stmt
  4150. | stmt NEWLINE stmt_list -> add_stmt
  4151. lang_int: stmt_list -> module
  4152. \end{lstlisting}
  4153. \end{minipage}
  4154. \end{center}
  4155. Here is the resulting parse tree.
  4156. \begin{lstlisting}
  4157. Tree('module',
  4158. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4159. Tree('int', [Token('INT', '3')])])]),
  4160. Token('NEWLINE', '\n')])
  4161. \end{lstlisting}
  4162. \section{Ambiguous Grammars}
  4163. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4164. can be parsed in more than one way. For example, consider the string
  4165. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4166. our draft grammar, resulting in the two parse trees shown in
  4167. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4168. interpreting the second parse tree would yield \code{-4} even through
  4169. the correct answer is \code{2}.
  4170. \begin{figure}[tbp]
  4171. \begin{tcolorbox}[colback=white]
  4172. \centering
  4173. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4174. \end{tcolorbox}
  4175. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4176. \label{fig:ambig-parse-tree}
  4177. \end{figure}
  4178. To deal with this problem we can change the grammar by categorizing
  4179. the syntax in a more fine-grained fashion. In this case we want to
  4180. disallow the application of the rule \code{exp: exp "-" exp} when the
  4181. child on the right is an addition. To do this we can replace the
  4182. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4183. the expressions except for addition, as in the following.
  4184. \begin{center}
  4185. \begin{minipage}{0.95\textwidth}
  4186. \begin{lstlisting}[escapechar=$]
  4187. exp: exp "-" exp_no_add -> sub
  4188. | exp "+" exp -> add
  4189. | exp_no_add
  4190. exp_no_add: INT -> int
  4191. | "input_int" "(" ")" -> input_int
  4192. | "-" exp -> usub
  4193. | exp "-" exp_no_add -> sub
  4194. | "(" exp ")" -> paren
  4195. \end{lstlisting}
  4196. \end{minipage}
  4197. \end{center}
  4198. However, there remains some ambiguity in the grammar. For example, the
  4199. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4200. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4201. (incorrect). That is, subtraction is left associative. Likewise,
  4202. addition in Python is left associative. We also need to consider the
  4203. interaction of unary subtraction with both addition and
  4204. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4205. has higher \emph{precedence}\index{subject}{precedence} than addition
  4206. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4207. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4208. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4209. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4210. all the other expressions, and it uses \code{exp\_hi} for the second
  4211. child in the rules for addition and subtraction. Furthermore, unary
  4212. subtraction uses \code{exp\_hi} for its child.
  4213. For languages with more operators and more precedence levels, one must
  4214. refine the \code{exp} nonterminal into several nonterminals, one for
  4215. each precedence level.
  4216. \begin{figure}[tbp]
  4217. \begin{tcolorbox}[colback=white]
  4218. \centering
  4219. \begin{lstlisting}[escapechar=$]
  4220. exp: exp "+" exp_hi -> add
  4221. | exp "-" exp_hi -> sub
  4222. | exp_hi
  4223. exp_hi: INT -> int
  4224. | "input_int" "(" ")" -> input_int
  4225. | "-" exp_hi -> usub
  4226. | "(" exp ")" -> paren
  4227. stmt: "print" "(" exp ")" -> print
  4228. | exp -> expr
  4229. stmt_list: -> empty_stmt
  4230. | stmt NEWLINE stmt_list -> add_stmt
  4231. lang_int: stmt_list -> module
  4232. \end{lstlisting}
  4233. \end{tcolorbox}
  4234. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4235. \label{fig:Lint-lark-grammar}
  4236. \end{figure}
  4237. \section{From Parse Trees to Abstract Syntax Trees}
  4238. As we have seen, the output of a Lark parser is a parse tree, that is,
  4239. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4240. step is to convert the parse tree to an abstract syntax tree. This can
  4241. be accomplished with a recursive function that inspects the
  4242. \code{data} field of each node and then constructs the corresponding
  4243. AST node, using recursion to handle its children. The following is an
  4244. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4245. \begin{center}
  4246. \begin{minipage}{0.95\textwidth}
  4247. \begin{lstlisting}
  4248. def parse_tree_to_ast(e):
  4249. if e.data == 'int':
  4250. return Constant(int(e.children[0].value))
  4251. elif e.data == 'input_int':
  4252. return Call(Name('input_int'), [])
  4253. elif e.data == 'add':
  4254. e1, e2 = e.children
  4255. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4256. ...
  4257. else:
  4258. raise Exception('unhandled parse tree', e)
  4259. \end{lstlisting}
  4260. \end{minipage}
  4261. \end{center}
  4262. \begin{exercise}
  4263. \normalfont\normalsize
  4264. %
  4265. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4266. default parsing algorithm (Earley) with the \code{ambiguity} option
  4267. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4268. output will include multiple parse trees that will indicate to you
  4269. that there is a problem with your grammar. Your parser should ignore
  4270. white space, so we recommend using Lark's \code{\%ignore} directive
  4271. as follows.
  4272. \begin{lstlisting}
  4273. %import common.WS_INLINE
  4274. %ignore WS_INLINE
  4275. \end{lstlisting}
  4276. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4277. Lark parser instead of using the \code{parse} function from
  4278. the \code{ast} module. Test your compiler on all the \LangVar{}
  4279. programs that you have created, and create four additional programs
  4280. that test for ambiguities in your grammar.
  4281. \end{exercise}
  4282. \section{Earley's Algorithm}
  4283. \label{sec:earley}
  4284. In this section we discuss the parsing algorithm of
  4285. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4286. algorithm is powerful in that it can handle any context-free grammar,
  4287. which makes it easy to use, but it is not a particularly
  4288. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4289. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4290. the number of tokens in the input
  4291. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4292. learn about the LALR(1) algorithm, which is more efficient but cannot
  4293. handle all context-free grammars.
  4294. Earley's algorithm can be viewed as an interpreter; it treats the
  4295. grammar as the program being interpreted, and it treats the concrete
  4296. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4297. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4298. keep track of its progress and to store its results. The chart is an
  4299. array with one slot for each position in the input string, where
  4300. position $0$ is before the first character and position $n$ is
  4301. immediately after the last character. So, the array has length $n+1$
  4302. for an input string of length $n$. Each slot in the chart contains a
  4303. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4304. with a period indicating how much of its right-hand side has already
  4305. been parsed. For example, the dotted rule
  4306. \begin{lstlisting}
  4307. exp: exp "+" . exp_hi
  4308. \end{lstlisting}
  4309. represents a partial parse that has matched an \code{exp} followed by
  4310. \code{+} but has not yet parsed an \code{exp} to the right of
  4311. \code{+}.
  4312. %
  4313. Earley's algorithm starts with an initialization phase and then
  4314. repeats three actions---prediction, scanning, and completion---for as
  4315. long as opportunities arise. We demonstrate Earley's algorithm on a
  4316. running example, parsing the following program:
  4317. \begin{lstlisting}
  4318. print(1 + 3)
  4319. \end{lstlisting}
  4320. The algorithm's initialization phase creates dotted rules for all the
  4321. grammar rules whose left-hand side is the start symbol and places them
  4322. in slot $0$ of the chart. We also record the starting position of the
  4323. dotted rule in parentheses on the right. For example, given the
  4324. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4325. \begin{lstlisting}
  4326. lang_int: . stmt_list (0)
  4327. \end{lstlisting}
  4328. in slot $0$ of the chart. The algorithm then proceeds with
  4329. \emph{prediction} actions in which it adds more dotted rules to the
  4330. chart based on the nonterminals that come immediately after a period. In
  4331. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4332. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4333. period at the beginning of their right-hand sides, as follows:
  4334. \begin{lstlisting}
  4335. stmt_list: . (0)
  4336. stmt_list: . stmt NEWLINE stmt_list (0)
  4337. \end{lstlisting}
  4338. We continue to perform prediction actions as more opportunities
  4339. arise. For example, the \code{stmt} nonterminal now appears after a
  4340. period, so we add all the rules for \code{stmt}.
  4341. \begin{lstlisting}
  4342. stmt: . "print" "(" exp ")" (0)
  4343. stmt: . exp (0)
  4344. \end{lstlisting}
  4345. This reveals yet more opportunities for prediction, so we add the grammar
  4346. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4347. \begin{lstlisting}[escapechar=$]
  4348. exp: . exp "+" exp_hi (0)
  4349. exp: . exp "-" exp_hi (0)
  4350. exp: . exp_hi (0)
  4351. exp_hi: . INT (0)
  4352. exp_hi: . "input_int" "(" ")" (0)
  4353. exp_hi: . "-" exp_hi (0)
  4354. exp_hi: . "(" exp ")" (0)
  4355. \end{lstlisting}
  4356. We have exhausted the opportunities for prediction, so the algorithm
  4357. proceeds to \emph{scanning}, in which we inspect the next input token
  4358. and look for a dotted rule at the current position that has a matching
  4359. terminal immediately following the period. In our running example, the
  4360. first input token is \code{"print"}, so we identify the rule in slot
  4361. $0$ of the chart where \code{"print"} follows the period:
  4362. \begin{lstlisting}
  4363. stmt: . "print" "(" exp ")" (0)
  4364. \end{lstlisting}
  4365. We advance the period past \code{"print"} and add the resulting rule
  4366. to slot $1$:
  4367. \begin{lstlisting}
  4368. stmt: "print" . "(" exp ")" (0)
  4369. \end{lstlisting}
  4370. If the new dotted rule had a nonterminal after the period, we would
  4371. need to carry out a prediction action, adding more dotted rules to
  4372. slot $1$. That is not the case, so we continue scanning. The next
  4373. input token is \code{"("}, so we add the following to slot $2$ of the
  4374. chart.
  4375. \begin{lstlisting}
  4376. stmt: "print" "(" . exp ")" (0)
  4377. \end{lstlisting}
  4378. Now we have a nonterminal after the period, so we carry out several
  4379. prediction actions, adding dotted rules for \code{exp} and
  4380. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4381. starting position $2$.
  4382. \begin{lstlisting}[escapechar=$]
  4383. exp: . exp "+" exp_hi (2)
  4384. exp: . exp "-" exp_hi (2)
  4385. exp: . exp_hi (2)
  4386. exp_hi: . INT (2)
  4387. exp_hi: . "input_int" "(" ")" (2)
  4388. exp_hi: . "-" exp_hi (2)
  4389. exp_hi: . "(" exp ")" (2)
  4390. \end{lstlisting}
  4391. With this prediction complete, we return to scanning, noting that the
  4392. next input token is \code{"1"}, which the lexer parses as an
  4393. \code{INT}. There is a matching rule in slot $2$:
  4394. \begin{lstlisting}
  4395. exp_hi: . INT (2)
  4396. \end{lstlisting}
  4397. so we advance the period and put the following rule into slot $3$.
  4398. \begin{lstlisting}
  4399. exp_hi: INT . (2)
  4400. \end{lstlisting}
  4401. This brings us to \emph{completion} actions. When the period reaches
  4402. the end of a dotted rule, we recognize that the substring
  4403. has matched the nonterminal on the left-hand side of the rule, in this case
  4404. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4405. rules into slot $2$ (the starting position for the finished rule) if
  4406. the period is immediately followed by \code{exp\_hi}. So we identify
  4407. \begin{lstlisting}
  4408. exp: . exp_hi (2)
  4409. \end{lstlisting}
  4410. and add the following dotted rule to slot $3$
  4411. \begin{lstlisting}
  4412. exp: exp_hi . (2)
  4413. \end{lstlisting}
  4414. This triggers another completion step for the nonterminal \code{exp},
  4415. adding two more dotted rules to slot $3$.
  4416. \begin{lstlisting}[escapechar=$]
  4417. exp: exp . "+" exp_hi (2)
  4418. exp: exp . "-" exp_hi (2)
  4419. \end{lstlisting}
  4420. Returning to scanning, the next input token is \code{"+"}, so
  4421. we add the following to slot $4$.
  4422. \begin{lstlisting}[escapechar=$]
  4423. exp: exp "+" . exp_hi (2)
  4424. \end{lstlisting}
  4425. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4426. the following dotted rules to slot $4$ of the chart.
  4427. \begin{lstlisting}[escapechar=$]
  4428. exp_hi: . INT (4)
  4429. exp_hi: . "input_int" "(" ")" (4)
  4430. exp_hi: . "-" exp_hi (4)
  4431. exp_hi: . "(" exp ")" (4)
  4432. \end{lstlisting}
  4433. The next input token is \code{"3"} which the lexer categorized as an
  4434. \code{INT}, so we advance the period past \code{INT} for the rules in
  4435. slot $4$, of which there is just one, and put the following into slot $5$.
  4436. \begin{lstlisting}[escapechar=$]
  4437. exp_hi: INT . (4)
  4438. \end{lstlisting}
  4439. The period at the end of the rule triggers a completion action for the
  4440. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4441. So we advance the period and put the following into slot $5$.
  4442. \begin{lstlisting}[escapechar=$]
  4443. exp: exp "+" exp_hi . (2)
  4444. \end{lstlisting}
  4445. This triggers another completion action for the rules in slot $2$ that
  4446. have a period before \code{exp}.
  4447. \begin{lstlisting}[escapechar=$]
  4448. stmt: "print" "(" exp . ")" (0)
  4449. exp: exp . "+" exp_hi (2)
  4450. exp: exp . "-" exp_hi (2)
  4451. \end{lstlisting}
  4452. We scan the next input token \code{")"}, placing the following dotted
  4453. rule into slot $6$.
  4454. \begin{lstlisting}[escapechar=$]
  4455. stmt: "print" "(" exp ")" . (0)
  4456. \end{lstlisting}
  4457. This triggers the completion of \code{stmt} in slot $0$
  4458. \begin{lstlisting}
  4459. stmt_list: stmt . NEWLINE stmt_list (0)
  4460. \end{lstlisting}
  4461. The last input token is a \code{NEWLINE}, so we advance the period
  4462. and place the new dotted rule into slot $7$.
  4463. \begin{lstlisting}
  4464. stmt_list: stmt NEWLINE . stmt_list (0)
  4465. \end{lstlisting}
  4466. We are close to the end of parsing the input!
  4467. The period is before the \code{stmt\_list} nonterminal, so we
  4468. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4469. \begin{lstlisting}
  4470. stmt_list: . (7)
  4471. stmt_list: . stmt NEWLINE stmt_list (7)
  4472. stmt: . "print" "(" exp ")" (7)
  4473. stmt: . exp (7)
  4474. \end{lstlisting}
  4475. There is immediately an opportunity for completion of \code{stmt\_list},
  4476. so we add the following to slot $7$.
  4477. \begin{lstlisting}
  4478. stmt_list: stmt NEWLINE stmt_list . (0)
  4479. \end{lstlisting}
  4480. This triggers another completion action for \code{stmt\_list} in slot $0$
  4481. \begin{lstlisting}
  4482. lang_int: stmt_list . (0)
  4483. \end{lstlisting}
  4484. which in turn completes \code{lang\_int}, the start symbol of the
  4485. grammar, so the parsing of the input is complete.
  4486. For reference, we give a general description of Earley's
  4487. algorithm.
  4488. \begin{enumerate}
  4489. \item The algorithm begins by initializing slot $0$ of the chart with the
  4490. grammar rule for the start symbol, placing a period at the beginning
  4491. of the right-hand side, and recording its starting position as $0$.
  4492. \item The algorithm repeatedly applies the following three kinds of
  4493. actions for as long as there are opportunities to do so.
  4494. \begin{itemize}
  4495. \item Prediction: If there is a rule in slot $k$ whose period comes
  4496. before a nonterminal, add the rules for that nonterminal into slot
  4497. $k$, placing a period at the beginning of their right-hand sides
  4498. and recording their starting position as $k$.
  4499. \item Scanning: If the token at position $k$ of the input string
  4500. matches the symbol after the period in a dotted rule in slot $k$
  4501. of the chart, advance the period in the dotted rule, adding
  4502. the result to slot $k+1$.
  4503. \item Completion: If a dotted rule in slot $k$ has a period at the
  4504. end, inspect the rules in the slot corresponding to the starting
  4505. position of the completed rule. If any of those rules have a
  4506. nonterminal following their period that matches the left-hand side
  4507. of the completed rule, then advance their period, placing the new
  4508. dotted rule in slot $k$.
  4509. \end{itemize}
  4510. While repeating these three actions, take care never to add
  4511. duplicate dotted rules to the chart.
  4512. \end{enumerate}
  4513. We have described how Earley's algorithm recognizes that an input
  4514. string matches a grammar, but we have not described how it builds a
  4515. parse tree. The basic idea is simple, but building parse trees in an
  4516. efficient way is more complex, requiring a data structure called a
  4517. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4518. to attach a partial parse tree to every dotted rule in the chart.
  4519. Initially, the node associated with a dotted rule has no
  4520. children. As the period moves to the right, the nodes from the
  4521. subparses are added as children to the node.
  4522. As mentioned at the beginning of this section, Earley's algorithm is
  4523. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4524. files that contain thousands of tokens in a reasonable amount of time,
  4525. but not millions.
  4526. %
  4527. In the next section we discuss the LALR(1) parsing algorithm, which is
  4528. efficient enough to use with even the largest of input files.
  4529. \section{The LALR(1) Algorithm}
  4530. \label{sec:lalr}
  4531. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4532. two-phase approach in which it first compiles the grammar into a state
  4533. machine and then runs the state machine to parse an input string. The
  4534. second phase has time complexity $O(n)$ where $n$ is the number of
  4535. tokens in the input, so LALR(1) is the best one could hope for with
  4536. respect to efficiency.
  4537. %
  4538. A particularly influential implementation of LALR(1) is the
  4539. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4540. \texttt{yacc} stands for ``yet another compiler compiler.''
  4541. %
  4542. The LALR(1) state machine uses a stack to record its progress in
  4543. parsing the input string. Each element of the stack is a pair: a
  4544. state number and a grammar symbol (a terminal or a nonterminal). The
  4545. symbol characterizes the input that has been parsed so far, and the
  4546. state number is used to remember how to proceed once the next
  4547. symbol's worth of input has been parsed. Each state in the machine
  4548. represents where the parser stands in the parsing process with respect
  4549. to certain grammar rules. In particular, each state is associated with
  4550. a set of dotted rules.
  4551. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4552. (also called parse table) for the following simple but ambiguous
  4553. grammar:
  4554. \begin{lstlisting}[escapechar=$]
  4555. exp: INT
  4556. | exp "+" exp
  4557. stmt: "print" exp
  4558. start: stmt
  4559. \end{lstlisting}
  4560. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4561. read in a \lstinline{"print"} token, so the top of the stack is
  4562. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4563. the input according to grammar rule 1, which is signified by showing
  4564. rule 1 with a period after the \code{"print"} token and before the
  4565. \code{exp} nonterminal. There are two rules that could apply next,
  4566. rules 2 and 3, so state 1 also shows those rules with a period at
  4567. the beginning of their right-hand sides. The edges between states
  4568. indicate which transitions the machine should make depending on the
  4569. next input token. So, for example, if the next input token is
  4570. \code{INT} then the parser will push \code{INT} and the target state 4
  4571. on the stack and transition to state 4. Suppose that we are now at the end
  4572. of the input. State 4 says that we should reduce by rule 3, so we pop
  4573. from the stack the same number of items as the number of symbols in
  4574. the right-hand side of the rule, in this case just one. We then
  4575. momentarily jump to the state at the top of the stack (state 1) and
  4576. then follow the goto edge that corresponds to the left-hand side of
  4577. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4578. state 3. (A slightly longer example parse is shown in
  4579. figure~\ref{fig:shift-reduce}.)
  4580. \begin{figure}[tbp]
  4581. \centering
  4582. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4583. \caption{An LALR(1) parse table and a trace of an example run.}
  4584. \label{fig:shift-reduce}
  4585. \end{figure}
  4586. In general, the algorithm works as follows. First, set the current state to
  4587. state $0$. Then repeat the following, looking at the next input token.
  4588. \begin{itemize}
  4589. \item If there there is a shift edge for the input token in the
  4590. current state, push the edge's target state and the input token onto
  4591. the stack and proceed to the edge's target state.
  4592. \item If there is a reduce action for the input token in the current
  4593. state, pop $k$ elements from the stack, where $k$ is the number of
  4594. symbols in the right-hand side of the rule being reduced. Jump to
  4595. the state at the top of the stack and then follow the goto edge for
  4596. the nonterminal that matches the left-hand side of the rule that we
  4597. are reducing by. Push the edge's target state and the nonterminal on the
  4598. stack.
  4599. \end{itemize}
  4600. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4601. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4602. algorithm does not know which action to take in this case. When a
  4603. state has both a shift and a reduce action for the same token, we say
  4604. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4605. will arise, for example, in trying to parse the input
  4606. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4607. the parser will be in state 6 and will not know whether to
  4608. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4609. to proceed by shifting the next \lstinline{+} from the input.
  4610. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4611. arises when there are two reduce actions in a state for the same
  4612. token. To understand which grammars give rise to shift/reduce and
  4613. reduce/reduce conflicts, it helps to know how the parse table is
  4614. generated from the grammar, which we discuss next.
  4615. The parse table is generated one state at a time. State 0 represents
  4616. the start of the parser. We add the grammar rule for the start symbol
  4617. to this state with a period at the beginning of the right-hand side,
  4618. similarly to the initialization phase of the Earley parser. If the
  4619. period appears immediately before another nonterminal, we add all the
  4620. rules with that nonterminal on the left-hand side. Again, we place a
  4621. period at the beginning of the right-hand side of each new
  4622. rule. This process, called \emph{state closure}, is continued
  4623. until there are no more rules to add (similarly to the prediction
  4624. actions of an Earley parser). We then examine each dotted rule in the
  4625. current state $I$. Suppose that a dotted rule has the form $A ::=
  4626. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4627. are sequences of symbols. We create a new state and call it $J$. If $X$
  4628. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4629. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4630. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4631. state $J$. We start by adding all dotted rules from state $I$ that
  4632. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4633. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4634. the period moved past the $X$. (This is analogous to completion in
  4635. Earley's algorithm.) We then perform state closure on $J$. This
  4636. process repeats until there are no more states or edges to add.
  4637. We then mark states as accepting states if they have a dotted rule
  4638. that is the start rule with a period at the end. Also, to add
  4639. the reduce actions, we look for any state containing a dotted rule
  4640. with a period at the end. Let $n$ be the rule number for this dotted
  4641. rule. We then put a reduce $n$ action into that state for every token
  4642. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4643. dotted rule with a period at the end. We therefore put a reduce by
  4644. rule 3 action into state 4 for every
  4645. token.
  4646. When inserting reduce actions, take care to spot any shift/reduce or
  4647. reduce/reduce conflicts. If there are any, abort the construction of
  4648. the parse table.
  4649. \begin{exercise}
  4650. \normalfont\normalsize
  4651. %
  4652. Working on paper, walk through the parse table generation process for
  4653. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4654. your results against the parse table shown in
  4655. figure~\ref{fig:shift-reduce}.
  4656. \end{exercise}
  4657. \begin{exercise}
  4658. \normalfont\normalsize
  4659. %
  4660. Change the parser in your compiler for \LangVar{} to set the
  4661. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4662. all the \LangVar{} programs that you have created. In doing so, Lark
  4663. may signal an error due to shift/reduce or reduce/reduce conflicts
  4664. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4665. remove those conflicts.
  4666. \end{exercise}
  4667. \section{Further Reading}
  4668. In this chapter we have just scratched the surface of the field of
  4669. parsing, with the study of a very general but less efficient algorithm
  4670. (Earley) and with a more limited but highly efficient algorithm
  4671. (LALR). There are many more algorithms and classes of grammars that
  4672. fall between these two ends of the spectrum. We recommend to the reader
  4673. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4674. Regarding lexical analysis, we have described the specification
  4675. language, which are the regular expressions, but not the algorithms
  4676. for recognizing them. In short, regular expressions can be translated
  4677. to nondeterministic finite automata, which in turn are translated to
  4678. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4679. all the details on lexical analysis.
  4680. \fi}
  4681. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4682. \chapter{Register Allocation}
  4683. \label{ch:register-allocation-Lvar}
  4684. \setcounter{footnote}{0}
  4685. \index{subject}{register allocation}
  4686. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4687. storing variables on the procedure call stack. The CPU may require tens
  4688. to hundreds of cycles to access a location on the stack, whereas
  4689. accessing a register takes only a single cycle. In this chapter we
  4690. improve the efficiency of our generated code by storing some variables
  4691. in registers. The goal of register allocation is to fit as many
  4692. variables into registers as possible. Some programs have more
  4693. variables than registers, so we cannot always map each variable to a
  4694. different register. Fortunately, it is common for different variables
  4695. to be in use during different periods of time during program
  4696. execution, and in those cases we can map multiple variables to the
  4697. same register.
  4698. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4699. example. The source program is on the left and the output of
  4700. instruction selection\index{subject}{instruction selection}
  4701. is on the right. The program is almost
  4702. completely in the x86 assembly language, but it still uses variables.
  4703. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4704. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4705. the other hand, is used only after this point, so \code{x} and
  4706. \code{z} could share the same register.
  4707. \begin{figure}
  4708. \begin{tcolorbox}[colback=white]
  4709. \begin{minipage}{0.45\textwidth}
  4710. Example \LangVar{} program:
  4711. % var_test_28.rkt
  4712. {\if\edition\racketEd
  4713. \begin{lstlisting}
  4714. (let ([v 1])
  4715. (let ([w 42])
  4716. (let ([x (+ v 7)])
  4717. (let ([y x])
  4718. (let ([z (+ x w)])
  4719. (+ z (- y)))))))
  4720. \end{lstlisting}
  4721. \fi}
  4722. {\if\edition\pythonEd\pythonColor
  4723. \begin{lstlisting}
  4724. v = 1
  4725. w = 42
  4726. x = v + 7
  4727. y = x
  4728. z = x + w
  4729. print(z + (- y))
  4730. \end{lstlisting}
  4731. \fi}
  4732. \end{minipage}
  4733. \begin{minipage}{0.45\textwidth}
  4734. After instruction selection:
  4735. {\if\edition\racketEd
  4736. \begin{lstlisting}
  4737. locals-types:
  4738. x : Integer, y : Integer,
  4739. z : Integer, t : Integer,
  4740. v : Integer, w : Integer
  4741. start:
  4742. movq $1, v
  4743. movq $42, w
  4744. movq v, x
  4745. addq $7, x
  4746. movq x, y
  4747. movq x, z
  4748. addq w, z
  4749. movq y, t
  4750. negq t
  4751. movq z, %rax
  4752. addq t, %rax
  4753. jmp conclusion
  4754. \end{lstlisting}
  4755. \fi}
  4756. {\if\edition\pythonEd\pythonColor
  4757. \begin{lstlisting}
  4758. movq $1, v
  4759. movq $42, w
  4760. movq v, x
  4761. addq $7, x
  4762. movq x, y
  4763. movq x, z
  4764. addq w, z
  4765. movq y, tmp_0
  4766. negq tmp_0
  4767. movq z, tmp_1
  4768. addq tmp_0, tmp_1
  4769. movq tmp_1, %rdi
  4770. callq print_int
  4771. \end{lstlisting}
  4772. \fi}
  4773. \end{minipage}
  4774. \end{tcolorbox}
  4775. \caption{A running example for register allocation.}
  4776. \label{fig:reg-eg}
  4777. \end{figure}
  4778. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4779. compute where a variable is in use. Once we have that information, we
  4780. compute which variables are in use at the same time, that is, which ones
  4781. \emph{interfere}\index{subject}{interfere} with each other, and
  4782. represent this relation as an undirected graph whose vertices are
  4783. variables and edges indicate when two variables interfere
  4784. (section~\ref{sec:build-interference}). We then model register
  4785. allocation as a graph coloring problem
  4786. (section~\ref{sec:graph-coloring}).
  4787. If we run out of registers despite these efforts, we place the
  4788. remaining variables on the stack, similarly to how we handled
  4789. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4790. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4791. location. The decision to spill a variable is handled as part of the
  4792. graph coloring process.
  4793. We make the simplifying assumption that each variable is assigned to
  4794. one location (a register or stack address). A more sophisticated
  4795. approach is to assign a variable to one or more locations in different
  4796. regions of the program. For example, if a variable is used many times
  4797. in short sequence and then used again only after many other
  4798. instructions, it could be more efficient to assign the variable to a
  4799. register during the initial sequence and then move it to the stack for
  4800. the rest of its lifetime. We refer the interested reader to
  4801. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4802. approach.
  4803. % discuss prioritizing variables based on how much they are used.
  4804. \section{Registers and Calling Conventions}
  4805. \label{sec:calling-conventions}
  4806. \index{subject}{calling conventions}
  4807. As we perform register allocation, we must be aware of the
  4808. \emph{calling conventions} \index{subject}{calling conventions} that
  4809. govern how function calls are performed in x86.
  4810. %
  4811. Even though \LangVar{} does not include programmer-defined functions,
  4812. our generated code includes a \code{main} function that is called by
  4813. the operating system and our generated code contains calls to the
  4814. \code{read\_int} function.
  4815. Function calls require coordination between two pieces of code that
  4816. may be written by different programmers or generated by different
  4817. compilers. Here we follow the System V calling conventions that are
  4818. used by the GNU C compiler on Linux and
  4819. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4820. %
  4821. The calling conventions include rules about how functions share the
  4822. use of registers. In particular, the caller is responsible for freeing
  4823. some registers prior to the function call for use by the callee.
  4824. These are called the \emph{caller-saved registers}
  4825. \index{subject}{caller-saved registers}
  4826. and they are
  4827. \begin{lstlisting}
  4828. rax rcx rdx rsi rdi r8 r9 r10 r11
  4829. \end{lstlisting}
  4830. On the other hand, the callee is responsible for preserving the values
  4831. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4832. which are
  4833. \begin{lstlisting}
  4834. rsp rbp rbx r12 r13 r14 r15
  4835. \end{lstlisting}
  4836. We can think about this caller/callee convention from two points of
  4837. view, the caller view and the callee view, as follows:
  4838. \begin{itemize}
  4839. \item The caller should assume that all the caller-saved registers get
  4840. overwritten with arbitrary values by the callee. On the other hand,
  4841. the caller can safely assume that all the callee-saved registers
  4842. retain their original values.
  4843. \item The callee can freely use any of the caller-saved registers.
  4844. However, if the callee wants to use a callee-saved register, the
  4845. callee must arrange to put the original value back in the register
  4846. prior to returning to the caller. This can be accomplished by saving
  4847. the value to the stack in the prelude of the function and restoring
  4848. the value in the conclusion of the function.
  4849. \end{itemize}
  4850. In x86, registers are also used for passing arguments to a function
  4851. and for the return value. In particular, the first six arguments of a
  4852. function are passed in the following six registers, in this order.
  4853. \begin{lstlisting}
  4854. rdi rsi rdx rcx r8 r9
  4855. \end{lstlisting}
  4856. We refer to these six registers are the argument-passing registers
  4857. \index{subject}{argument-passing registers}.
  4858. If there are more than six arguments, the convention is to use space
  4859. on the frame of the caller for the rest of the arguments. In
  4860. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4861. argument and the rest of the arguments, which simplifies the treatment
  4862. of efficient tail calls.
  4863. %
  4864. \racket{For now, the only function we care about is \code{read\_int},
  4865. which takes zero arguments.}
  4866. %
  4867. \python{For now, the only functions we care about are \code{read\_int}
  4868. and \code{print\_int}, which take zero and one argument, respectively.}
  4869. %
  4870. The register \code{rax} is used for the return value of a function.
  4871. The next question is how these calling conventions impact register
  4872. allocation. Consider the \LangVar{} program presented in
  4873. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4874. example from the caller point of view and then from the callee point
  4875. of view. We refer to a variable that is in use during a function call
  4876. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4877. The program makes two calls to \READOP{}. The variable \code{x} is
  4878. call-live because it is in use during the second call to \READOP{}; we
  4879. must ensure that the value in \code{x} does not get overwritten during
  4880. the call to \READOP{}. One obvious approach is to save all the values
  4881. that reside in caller-saved registers to the stack prior to each
  4882. function call and to restore them after each call. That way, if the
  4883. register allocator chooses to assign \code{x} to a caller-saved
  4884. register, its value will be preserved across the call to \READOP{}.
  4885. However, saving and restoring to the stack is relatively slow. If
  4886. \code{x} is not used many times, it may be better to assign \code{x}
  4887. to a stack location in the first place. Or better yet, if we can
  4888. arrange for \code{x} to be placed in a callee-saved register, then it
  4889. won't need to be saved and restored during function calls.
  4890. We recommend an approach that captures these issues in the
  4891. interference graph, without complicating the graph coloring algorithm.
  4892. During liveness analysis we know which variables are call-live because
  4893. we compute which variables are in use at every instruction
  4894. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4895. interference graph (section~\ref{sec:build-interference}), we can
  4896. place an edge in the interference graph between each call-live
  4897. variable and the caller-saved registers. This will prevent the graph
  4898. coloring algorithm from assigning call-live variables to caller-saved
  4899. registers.
  4900. On the other hand, for variables that are not call-live, we prefer
  4901. placing them in caller-saved registers to leave more room for
  4902. call-live variables in the callee-saved registers. This can also be
  4903. implemented without complicating the graph coloring algorithm. We
  4904. recommend that the graph coloring algorithm assign variables to
  4905. natural numbers, choosing the lowest number for which there is no
  4906. interference. After the coloring is complete, we map the numbers to
  4907. registers and stack locations: mapping the lowest numbers to
  4908. caller-saved registers, the next lowest to callee-saved registers, and
  4909. the largest numbers to stack locations. This ordering gives preference
  4910. to registers over stack locations and to caller-saved registers over
  4911. callee-saved registers.
  4912. Returning to the example in
  4913. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4914. generated x86 code on the right-hand side. Variable \code{x} is
  4915. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4916. in a safe place during the second call to \code{read\_int}. Next,
  4917. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4918. because \code{y} is not a call-live variable.
  4919. We have completed the analysis from the caller point of view, so now
  4920. we switch to the callee point of view, focusing on the prelude and
  4921. conclusion of the \code{main} function. As usual, the prelude begins
  4922. with saving the \code{rbp} register to the stack and setting the
  4923. \code{rbp} to the current stack pointer. We now know why it is
  4924. necessary to save the \code{rbp}: it is a callee-saved register. The
  4925. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4926. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4927. (\code{x}). The other callee-saved registers are not saved in the
  4928. prelude because they are not used. The prelude subtracts 8 bytes from
  4929. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4930. conclusion, we see that \code{rbx} is restored from the stack with a
  4931. \code{popq} instruction.
  4932. \index{subject}{prelude}\index{subject}{conclusion}
  4933. \begin{figure}[tp]
  4934. \begin{tcolorbox}[colback=white]
  4935. \begin{minipage}{0.45\textwidth}
  4936. Example \LangVar{} program:
  4937. %var_test_14.rkt
  4938. {\if\edition\racketEd
  4939. \begin{lstlisting}
  4940. (let ([x (read)])
  4941. (let ([y (read)])
  4942. (+ (+ x y) 42)))
  4943. \end{lstlisting}
  4944. \fi}
  4945. {\if\edition\pythonEd\pythonColor
  4946. \begin{lstlisting}
  4947. x = input_int()
  4948. y = input_int()
  4949. print((x + y) + 42)
  4950. \end{lstlisting}
  4951. \fi}
  4952. \end{minipage}
  4953. \begin{minipage}{0.45\textwidth}
  4954. Generated x86 assembly:
  4955. {\if\edition\racketEd
  4956. \begin{lstlisting}
  4957. start:
  4958. callq read_int
  4959. movq %rax, %rbx
  4960. callq read_int
  4961. movq %rax, %rcx
  4962. addq %rcx, %rbx
  4963. movq %rbx, %rax
  4964. addq $42, %rax
  4965. jmp conclusion
  4966. .globl main
  4967. main:
  4968. pushq %rbp
  4969. movq %rsp, %rbp
  4970. pushq %rbx
  4971. subq $8, %rsp
  4972. jmp start
  4973. conclusion:
  4974. addq $8, %rsp
  4975. popq %rbx
  4976. popq %rbp
  4977. retq
  4978. \end{lstlisting}
  4979. \fi}
  4980. {\if\edition\pythonEd\pythonColor
  4981. \begin{lstlisting}
  4982. .globl main
  4983. main:
  4984. pushq %rbp
  4985. movq %rsp, %rbp
  4986. pushq %rbx
  4987. subq $8, %rsp
  4988. callq read_int
  4989. movq %rax, %rbx
  4990. callq read_int
  4991. movq %rax, %rcx
  4992. movq %rbx, %rdx
  4993. addq %rcx, %rdx
  4994. movq %rdx, %rcx
  4995. addq $42, %rcx
  4996. movq %rcx, %rdi
  4997. callq print_int
  4998. addq $8, %rsp
  4999. popq %rbx
  5000. popq %rbp
  5001. retq
  5002. \end{lstlisting}
  5003. \fi}
  5004. \end{minipage}
  5005. \end{tcolorbox}
  5006. \caption{An example with function calls.}
  5007. \label{fig:example-calling-conventions}
  5008. \end{figure}
  5009. %\clearpage
  5010. \section{Liveness Analysis}
  5011. \label{sec:liveness-analysis-Lvar}
  5012. \index{subject}{liveness analysis}
  5013. The \code{uncover\_live} \racket{pass}\python{function} performs
  5014. \emph{liveness analysis}; that is, it discovers which variables are
  5015. in use in different regions of a program.
  5016. %
  5017. A variable or register is \emph{live} at a program point if its
  5018. current value is used at some later point in the program. We refer to
  5019. variables, stack locations, and registers collectively as
  5020. \emph{locations}.
  5021. %
  5022. Consider the following code fragment in which there are two writes to
  5023. \code{b}. Are variables \code{a} and \code{b} both live at the same
  5024. time?
  5025. \begin{center}
  5026. \begin{minipage}{0.85\textwidth}
  5027. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5028. movq $5, a
  5029. movq $30, b
  5030. movq a, c
  5031. movq $10, b
  5032. addq b, c
  5033. \end{lstlisting}
  5034. \end{minipage}
  5035. \end{center}
  5036. The answer is no, because \code{a} is live from line 1 to 3 and
  5037. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  5038. line 2 is never used because it is overwritten (line 4) before the
  5039. next read (line 5).
  5040. The live locations for each instruction can be computed by traversing
  5041. the instruction sequence back to front (i.e., backward in execution
  5042. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5043. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5044. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5045. locations before instruction $I_k$. \racket{We recommend representing
  5046. these sets with the Racket \code{set} data structure described in
  5047. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5048. with the Python
  5049. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5050. data structure.}
  5051. {\if\edition\racketEd
  5052. \begin{figure}[tp]
  5053. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5054. \small
  5055. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5056. A \emph{set} is an unordered collection of elements without duplicates.
  5057. Here are some of the operations defined on sets.
  5058. \index{subject}{set}
  5059. \begin{description}
  5060. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5061. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5062. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5063. difference of the two sets.
  5064. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5065. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5066. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5067. \end{description}
  5068. \end{tcolorbox}
  5069. %\end{wrapfigure}
  5070. \caption{The \code{set} data structure.}
  5071. \label{fig:set}
  5072. \end{figure}
  5073. \fi}
  5074. % TODO: add a python version of the reference box for sets. -Jeremy
  5075. The locations that are live after an instruction are its
  5076. \emph{live-after}\index{subject}{live-after} set, and the locations
  5077. that are live before an instruction are its
  5078. \emph{live-before}\index{subject}{live-before} set. The live-after
  5079. set of an instruction is always the same as the live-before set of the
  5080. next instruction.
  5081. \begin{equation} \label{eq:live-after-before-next}
  5082. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5083. \end{equation}
  5084. To start things off, there are no live locations after the last
  5085. instruction, so
  5086. \begin{equation}\label{eq:live-last-empty}
  5087. L_{\mathsf{after}}(n) = \emptyset
  5088. \end{equation}
  5089. We then apply the following rule repeatedly, traversing the
  5090. instruction sequence back to front.
  5091. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5092. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5093. \end{equation}
  5094. where $W(k)$ are the locations written to by instruction $I_k$, and
  5095. $R(k)$ are the locations read by instruction $I_k$.
  5096. {\if\edition\racketEd
  5097. %
  5098. There is a special case for \code{jmp} instructions. The locations
  5099. that are live before a \code{jmp} should be the locations in
  5100. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5101. maintaining an alist named \code{label->live} that maps each label to
  5102. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5103. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5104. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5105. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5106. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5107. %
  5108. \fi}
  5109. Let us walk through the previous example, applying these formulas
  5110. starting with the instruction on line 5 of the code fragment. We
  5111. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5112. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5113. $\emptyset$ because it is the last instruction
  5114. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5115. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5116. variables \code{b} and \code{c}
  5117. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5118. \[
  5119. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5120. \]
  5121. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5122. the live-before set from line 5 to be the live-after set for this
  5123. instruction (formula~\eqref{eq:live-after-before-next}).
  5124. \[
  5125. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5126. \]
  5127. This move instruction writes to \code{b} and does not read from any
  5128. variables, so we have the following live-before set
  5129. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5130. \[
  5131. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5132. \]
  5133. The live-before for instruction \code{movq a, c}
  5134. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5135. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5136. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5137. variable that is not live and does not read from a variable.
  5138. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5139. because it writes to variable \code{a}.
  5140. \begin{figure}[tbp]
  5141. \centering
  5142. \begin{tcolorbox}[colback=white]
  5143. \hspace{10pt}
  5144. \begin{minipage}{0.4\textwidth}
  5145. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5146. movq $5, a
  5147. movq $30, b
  5148. movq a, c
  5149. movq $10, b
  5150. addq b, c
  5151. \end{lstlisting}
  5152. \end{minipage}
  5153. \vrule\hspace{10pt}
  5154. \begin{minipage}{0.45\textwidth}
  5155. \begin{align*}
  5156. L_{\mathsf{before}}(1)= \emptyset,
  5157. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5158. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5159. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5160. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5161. L_{\mathsf{after}}(3)= \{\ttm{c}\}\\
  5162. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5163. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5164. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5165. L_{\mathsf{after}}(5)= \emptyset
  5166. \end{align*}
  5167. \end{minipage}
  5168. \end{tcolorbox}
  5169. \caption{Example output of liveness analysis on a short example.}
  5170. \label{fig:liveness-example-0}
  5171. \end{figure}
  5172. \begin{exercise}\normalfont\normalsize
  5173. Perform liveness analysis by hand on the running example in
  5174. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5175. sets for each instruction. Compare your answers to the solution
  5176. shown in figure~\ref{fig:live-eg}.
  5177. \end{exercise}
  5178. \begin{figure}[tp]
  5179. \hspace{20pt}
  5180. \begin{minipage}{0.55\textwidth}
  5181. \begin{tcolorbox}[colback=white]
  5182. {\if\edition\racketEd
  5183. \begin{lstlisting}
  5184. |$\{\ttm{rsp}\}$|
  5185. movq $1, v
  5186. |$\{\ttm{v},\ttm{rsp}\}$|
  5187. movq $42, w
  5188. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5189. movq v, x
  5190. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5191. addq $7, x
  5192. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5193. movq x, y
  5194. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5195. movq x, z
  5196. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5197. addq w, z
  5198. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5199. movq y, t
  5200. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5201. negq t
  5202. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5203. movq z, %rax
  5204. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5205. addq t, %rax
  5206. |$\{\ttm{rax},\ttm{rsp}\}$|
  5207. jmp conclusion
  5208. \end{lstlisting}
  5209. \fi}
  5210. {\if\edition\pythonEd\pythonColor
  5211. \begin{lstlisting}
  5212. movq $1, v
  5213. |$\{\ttm{v}\}$|
  5214. movq $42, w
  5215. |$\{\ttm{w}, \ttm{v}\}$|
  5216. movq v, x
  5217. |$\{\ttm{w}, \ttm{x}\}$|
  5218. addq $7, x
  5219. |$\{\ttm{w}, \ttm{x}\}$|
  5220. movq x, y
  5221. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5222. movq x, z
  5223. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5224. addq w, z
  5225. |$\{\ttm{y}, \ttm{z}\}$|
  5226. movq y, tmp_0
  5227. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5228. negq tmp_0
  5229. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5230. movq z, tmp_1
  5231. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5232. addq tmp_0, tmp_1
  5233. |$\{\ttm{tmp\_1}\}$|
  5234. movq tmp_1, %rdi
  5235. |$\{\ttm{rdi}\}$|
  5236. callq print_int
  5237. |$\{\}$|
  5238. \end{lstlisting}
  5239. \fi}
  5240. \end{tcolorbox}
  5241. \end{minipage}
  5242. \caption{The running example annotated with live-after sets.}
  5243. \label{fig:live-eg}
  5244. \end{figure}
  5245. \begin{exercise}\normalfont\normalsize
  5246. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5247. %
  5248. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5249. field of the \code{Block} structure.}
  5250. %
  5251. \python{Return a dictionary that maps each instruction to its
  5252. live-after set.}
  5253. %
  5254. \racket{We recommend creating an auxiliary function that takes a list
  5255. of instructions and an initial live-after set (typically empty) and
  5256. returns the list of live-after sets.}
  5257. %
  5258. We recommend creating auxiliary functions to (1) compute the set
  5259. of locations that appear in an \Arg{}, (2) compute the locations read
  5260. by an instruction (the $R$ function), and (3) the locations written by
  5261. an instruction (the $W$ function). The \code{callq} instruction should
  5262. include all the caller-saved registers in its write set $W$ because
  5263. the calling convention says that those registers may be written to
  5264. during the function call. Likewise, the \code{callq} instruction
  5265. should include the appropriate argument-passing registers in its
  5266. read set $R$, depending on the arity of the function being
  5267. called. (This is why the abstract syntax for \code{callq} includes the
  5268. arity.)
  5269. \end{exercise}
  5270. %\clearpage
  5271. \section{Build the Interference Graph}
  5272. \label{sec:build-interference}
  5273. {\if\edition\racketEd
  5274. \begin{figure}[tp]
  5275. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5276. \small
  5277. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5278. A \emph{graph} is a collection of vertices and edges where each
  5279. edge connects two vertices. A graph is \emph{directed} if each
  5280. edge points from a source to a target. Otherwise the graph is
  5281. \emph{undirected}.
  5282. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5283. \begin{description}
  5284. %% We currently don't use directed graphs. We instead use
  5285. %% directed multi-graphs. -Jeremy
  5286. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5287. directed graph from a list of edges. Each edge is a list
  5288. containing the source and target vertex.
  5289. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5290. undirected graph from a list of edges. Each edge is represented by
  5291. a list containing two vertices.
  5292. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5293. inserts a vertex into the graph.
  5294. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5295. inserts an edge between the two vertices.
  5296. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5297. returns a sequence of vertices adjacent to the vertex.
  5298. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5299. returns a sequence of all vertices in the graph.
  5300. \end{description}
  5301. \end{tcolorbox}
  5302. %\end{wrapfigure}
  5303. \caption{The Racket \code{graph} package.}
  5304. \label{fig:graph}
  5305. \end{figure}
  5306. \fi}
  5307. On the basis of the liveness analysis, we know where each location is
  5308. live. However, during register allocation, we need to answer
  5309. questions of the specific form: are locations $u$ and $v$ live at the
  5310. same time? (If so, they cannot be assigned to the same register.) To
  5311. make this question more efficient to answer, we create an explicit
  5312. data structure, an \emph{interference
  5313. graph}\index{subject}{interference graph}. An interference graph is
  5314. an undirected graph that has a node for every variable and register
  5315. and has an edge between two nodes if they are
  5316. live at the same time, that is, if they interfere with each other.
  5317. %
  5318. \racket{We recommend using the Racket \code{graph} package
  5319. (figure~\ref{fig:graph}) to represent the interference graph.}
  5320. %
  5321. \python{We provide implementations of directed and undirected graph
  5322. data structures in the file \code{graph.py} of the support code.}
  5323. A straightforward way to compute the interference graph is to look at
  5324. the set of live locations between each instruction and add an edge to
  5325. the graph for every pair of variables in the same set. This approach
  5326. is less than ideal for two reasons. First, it can be expensive because
  5327. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5328. locations. Second, in the special case in which two locations hold the
  5329. same value (because one was assigned to the other), they can be live
  5330. at the same time without interfering with each other.
  5331. A better way to compute the interference graph is to focus on
  5332. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5333. must not overwrite something in a live location. So for each
  5334. instruction, we create an edge between the locations being written to
  5335. and the live locations. (However, a location never interferes with
  5336. itself.) For the \key{callq} instruction, we consider all the
  5337. caller-saved registers to have been written to, so an edge is added
  5338. between every live variable and every caller-saved register. Also, for
  5339. \key{movq} there is the special case of two variables holding the same
  5340. value. If a live variable $v$ is the same as the source of the
  5341. \key{movq}, then there is no need to add an edge between $v$ and the
  5342. destination, because they both hold the same value.
  5343. %
  5344. Hence we have the following two rules:
  5345. \begin{enumerate}
  5346. \item If instruction $I_k$ is a move instruction of the form
  5347. \key{movq} $s$\key{,} $d$, then for every $v \in
  5348. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5349. $(d,v)$.
  5350. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5351. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5352. $(d,v)$.
  5353. \end{enumerate}
  5354. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5355. these rules to each instruction. We highlight a few of the
  5356. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5357. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5358. so \code{v} interferes with \code{rsp}.}
  5359. %
  5360. \python{The first instruction is \lstinline{movq $1, v}, and the
  5361. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5362. no interference because $\ttm{v}$ is the destination of the move.}
  5363. %
  5364. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5365. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5366. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5367. %
  5368. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5369. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5370. $\ttm{x}$ interferes with \ttm{w}.}
  5371. %
  5372. \racket{The next instruction is \lstinline{movq x, y}, and the
  5373. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5374. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5375. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5376. \ttm{x} and \ttm{y} hold the same value.}
  5377. %
  5378. \python{The next instruction is \lstinline{movq x, y}, and the
  5379. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5380. applies, so \ttm{y} interferes with \ttm{w} but not
  5381. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5382. \ttm{x} and \ttm{y} hold the same value.}
  5383. %
  5384. Figure~\ref{fig:interference-results} lists the interference results
  5385. for all the instructions, and the resulting interference graph is
  5386. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5387. the interference graph in figure~\ref{fig:interfere} because there
  5388. were no interference edges involving registers and we did not wish to
  5389. clutter the graph, but in general one needs to include all the
  5390. registers in the interference graph.
  5391. \begin{figure}[tbp]
  5392. \begin{tcolorbox}[colback=white]
  5393. \begin{quote}
  5394. {\if\edition\racketEd
  5395. \begin{tabular}{ll}
  5396. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5397. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5398. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5399. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5400. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5401. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5402. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5403. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5404. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5405. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5406. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5407. \lstinline!jmp conclusion!& no interference.
  5408. \end{tabular}
  5409. \fi}
  5410. {\if\edition\pythonEd\pythonColor
  5411. \begin{tabular}{ll}
  5412. \lstinline!movq $1, v!& no interference\\
  5413. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5414. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5415. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5416. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5417. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5418. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5419. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5420. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5421. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5422. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5423. \lstinline!movq tmp_1, %rdi! & no interference \\
  5424. \lstinline!callq print_int!& no interference.
  5425. \end{tabular}
  5426. \fi}
  5427. \end{quote}
  5428. \end{tcolorbox}
  5429. \caption{Interference results for the running example.}
  5430. \label{fig:interference-results}
  5431. \end{figure}
  5432. \begin{figure}[tbp]
  5433. \begin{tcolorbox}[colback=white]
  5434. \large
  5435. {\if\edition\racketEd
  5436. \[
  5437. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5438. \node (rax) at (0,0) {$\ttm{rax}$};
  5439. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5440. \node (t1) at (0,2) {$\ttm{t}$};
  5441. \node (z) at (3,2) {$\ttm{z}$};
  5442. \node (x) at (6,2) {$\ttm{x}$};
  5443. \node (y) at (3,0) {$\ttm{y}$};
  5444. \node (w) at (6,0) {$\ttm{w}$};
  5445. \node (v) at (9,0) {$\ttm{v}$};
  5446. \draw (t1) to (rax);
  5447. \draw (t1) to (z);
  5448. \draw (z) to (y);
  5449. \draw (z) to (w);
  5450. \draw (x) to (w);
  5451. \draw (y) to (w);
  5452. \draw (v) to (w);
  5453. \draw (v) to (rsp);
  5454. \draw (w) to (rsp);
  5455. \draw (x) to (rsp);
  5456. \draw (y) to (rsp);
  5457. \path[-.,bend left=15] (z) edge node {} (rsp);
  5458. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5459. \draw (rax) to (rsp);
  5460. \end{tikzpicture}
  5461. \]
  5462. \fi}
  5463. {\if\edition\pythonEd\pythonColor
  5464. \[
  5465. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5466. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5467. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5468. \node (z) at (3,2) {$\ttm{z}$};
  5469. \node (x) at (6,2) {$\ttm{x}$};
  5470. \node (y) at (3,0) {$\ttm{y}$};
  5471. \node (w) at (6,0) {$\ttm{w}$};
  5472. \node (v) at (9,0) {$\ttm{v}$};
  5473. \draw (t0) to (t1);
  5474. \draw (t0) to (z);
  5475. \draw (z) to (y);
  5476. \draw (z) to (w);
  5477. \draw (x) to (w);
  5478. \draw (y) to (w);
  5479. \draw (v) to (w);
  5480. \end{tikzpicture}
  5481. \]
  5482. \fi}
  5483. \end{tcolorbox}
  5484. \caption{The interference graph of the example program.}
  5485. \label{fig:interfere}
  5486. \end{figure}
  5487. \begin{exercise}\normalfont\normalsize
  5488. \racket{Implement the compiler pass named \code{build\_interference} according
  5489. to the algorithm suggested here. We recommend using the Racket
  5490. \code{graph} package to create and inspect the interference graph.
  5491. The output graph of this pass should be stored in the $\itm{info}$ field of
  5492. the program, under the key \code{conflicts}.}
  5493. %
  5494. \python{Implement a function named \code{build\_interference}
  5495. according to the algorithm suggested above that
  5496. returns the interference graph.}
  5497. \end{exercise}
  5498. \section{Graph Coloring via Sudoku}
  5499. \label{sec:graph-coloring}
  5500. \index{subject}{graph coloring}
  5501. \index{subject}{sudoku}
  5502. \index{subject}{color}
  5503. We come to the main event discussed in this chapter, mapping variables
  5504. to registers and stack locations. Variables that interfere with each
  5505. other must be mapped to different locations. In terms of the
  5506. interference graph, this means that adjacent vertices must be mapped
  5507. to different locations. If we think of locations as colors, the
  5508. register allocation problem becomes the graph coloring
  5509. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5510. The reader may be more familiar with the graph coloring problem than he
  5511. or she realizes; the popular game of sudoku is an instance of the
  5512. graph coloring problem. The following describes how to build a graph
  5513. out of an initial sudoku board.
  5514. \begin{itemize}
  5515. \item There is one vertex in the graph for each sudoku square.
  5516. \item There is an edge between two vertices if the corresponding squares
  5517. are in the same row, in the same column, or in the same $3\times 3$ region.
  5518. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5519. \item On the basis of the initial assignment of numbers to squares on the
  5520. sudoku board, assign the corresponding colors to the corresponding
  5521. vertices in the graph.
  5522. \end{itemize}
  5523. If you can color the remaining vertices in the graph with the nine
  5524. colors, then you have also solved the corresponding game of sudoku.
  5525. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5526. the corresponding graph with colored vertices. Here we use a
  5527. monochrome representation of colors, mapping the sudoku number 1 to
  5528. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5529. of the vertices (the colored ones) because showing edges for all the
  5530. vertices would make the graph unreadable.
  5531. \begin{figure}[tbp]
  5532. \begin{tcolorbox}[colback=white]
  5533. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5534. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5535. \end{tcolorbox}
  5536. \caption{A sudoku game board and the corresponding colored graph.}
  5537. \label{fig:sudoku-graph}
  5538. \end{figure}
  5539. Some techniques for playing sudoku correspond to heuristics used in
  5540. graph coloring algorithms. For example, one of the basic techniques
  5541. for sudoku is called Pencil Marks. The idea is to use a process of
  5542. elimination to determine what numbers are no longer available for a
  5543. square and to write those numbers in the square (writing very
  5544. small). For example, if the number $1$ is assigned to a square, then
  5545. write the pencil mark $1$ in all the squares in the same row, column,
  5546. and region to indicate that $1$ is no longer an option for those other
  5547. squares.
  5548. %
  5549. The Pencil Marks technique corresponds to the notion of
  5550. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5551. saturation of a vertex, in sudoku terms, is the set of numbers that
  5552. are no longer available. In graph terminology, we have the following
  5553. definition:
  5554. \begin{equation*}
  5555. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5556. \text{ and } \mathrm{color}(v) = c \}
  5557. \end{equation*}
  5558. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5559. edge with $u$.
  5560. The Pencil Marks technique leads to a simple strategy for filling in
  5561. numbers: if there is a square with only one possible number left, then
  5562. choose that number! But what if there are no squares with only one
  5563. possibility left? One brute-force approach is to try them all: choose
  5564. the first one, and if that ultimately leads to a solution, great. If
  5565. not, backtrack and choose the next possibility. One good thing about
  5566. Pencil Marks is that it reduces the degree of branching in the search
  5567. tree. Nevertheless, backtracking can be terribly time consuming. One
  5568. way to reduce the amount of backtracking is to use the
  5569. most-constrained-first heuristic (aka minimum remaining
  5570. values)~\citep{Russell2003}. That is, in choosing a square, always
  5571. choose one with the fewest possibilities left (the vertex with the
  5572. highest saturation). The idea is that choosing highly constrained
  5573. squares earlier rather than later is better, because later on there may
  5574. not be any possibilities left in the highly saturated squares.
  5575. However, register allocation is easier than sudoku, because the
  5576. register allocator can fall back to assigning variables to stack
  5577. locations when the registers run out. Thus, it makes sense to replace
  5578. backtracking with greedy search: make the best choice at the time and
  5579. keep going. We still wish to minimize the number of colors needed, so
  5580. we use the most-constrained-first heuristic in the greedy search.
  5581. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5582. algorithm for register allocation based on saturation and the
  5583. most-constrained-first heuristic. It is roughly equivalent to the
  5584. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5585. sudoku, the algorithm represents colors with integers. The integers
  5586. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5587. register allocation. In particular, we recommend the following
  5588. correspondence, with $k=11$.
  5589. \begin{lstlisting}
  5590. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5591. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5592. \end{lstlisting}
  5593. The integers $k$ and larger correspond to stack locations. The
  5594. registers that are not used for register allocation, such as
  5595. \code{rax}, are assigned to negative integers. In particular, we
  5596. recommend the following correspondence.
  5597. \begin{lstlisting}
  5598. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5599. \end{lstlisting}
  5600. \begin{figure}[btp]
  5601. \begin{tcolorbox}[colback=white]
  5602. \centering
  5603. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5604. Algorithm: DSATUR
  5605. Input: A graph |$G$|
  5606. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5607. |$W \gets \mathrm{vertices}(G)$|
  5608. while |$W \neq \emptyset$| do
  5609. pick a vertex |$u$| from |$W$| with the highest saturation,
  5610. breaking ties randomly
  5611. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5612. |$\mathrm{color}[u] \gets c$|
  5613. |$W \gets W - \{u\}$|
  5614. \end{lstlisting}
  5615. \end{tcolorbox}
  5616. \caption{The saturation-based greedy graph coloring algorithm.}
  5617. \label{fig:satur-algo}
  5618. \end{figure}
  5619. {\if\edition\racketEd
  5620. With the DSATUR algorithm in hand, let us return to the running
  5621. example and consider how to color the interference graph shown in
  5622. figure~\ref{fig:interfere}.
  5623. %
  5624. We start by assigning each register node to its own color. For
  5625. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5626. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5627. (To reduce clutter in the interference graph, we elide nodes
  5628. that do not have interference edges, such as \code{rcx}.)
  5629. The variables are not yet colored, so they are annotated with a dash. We
  5630. then update the saturation for vertices that are adjacent to a
  5631. register, obtaining the following annotated graph. For example, the
  5632. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5633. \code{rax} and \code{rsp}.
  5634. \[
  5635. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5636. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5637. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5638. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5639. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5640. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5641. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5642. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5643. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5644. \draw (t1) to (rax);
  5645. \draw (t1) to (z);
  5646. \draw (z) to (y);
  5647. \draw (z) to (w);
  5648. \draw (x) to (w);
  5649. \draw (y) to (w);
  5650. \draw (v) to (w);
  5651. \draw (v) to (rsp);
  5652. \draw (w) to (rsp);
  5653. \draw (x) to (rsp);
  5654. \draw (y) to (rsp);
  5655. \path[-.,bend left=15] (z) edge node {} (rsp);
  5656. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5657. \draw (rax) to (rsp);
  5658. \end{tikzpicture}
  5659. \]
  5660. The algorithm says to select a maximally saturated vertex. So, we pick
  5661. $\ttm{t}$ and color it with the first available integer, which is
  5662. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5663. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5664. \[
  5665. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5666. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5667. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5668. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5669. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5670. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5671. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5672. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5673. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5674. \draw (t1) to (rax);
  5675. \draw (t1) to (z);
  5676. \draw (z) to (y);
  5677. \draw (z) to (w);
  5678. \draw (x) to (w);
  5679. \draw (y) to (w);
  5680. \draw (v) to (w);
  5681. \draw (v) to (rsp);
  5682. \draw (w) to (rsp);
  5683. \draw (x) to (rsp);
  5684. \draw (y) to (rsp);
  5685. \path[-.,bend left=15] (z) edge node {} (rsp);
  5686. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5687. \draw (rax) to (rsp);
  5688. \end{tikzpicture}
  5689. \]
  5690. We repeat the process, selecting a maximally saturated vertex,
  5691. choosing \code{z}, and coloring it with the first available number, which
  5692. is $1$. We add $1$ to the saturation for the neighboring vertices
  5693. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5694. \[
  5695. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5696. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5697. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5698. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5699. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5700. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5701. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5702. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5703. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5704. \draw (t1) to (rax);
  5705. \draw (t1) to (z);
  5706. \draw (z) to (y);
  5707. \draw (z) to (w);
  5708. \draw (x) to (w);
  5709. \draw (y) to (w);
  5710. \draw (v) to (w);
  5711. \draw (v) to (rsp);
  5712. \draw (w) to (rsp);
  5713. \draw (x) to (rsp);
  5714. \draw (y) to (rsp);
  5715. \path[-.,bend left=15] (z) edge node {} (rsp);
  5716. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5717. \draw (rax) to (rsp);
  5718. \end{tikzpicture}
  5719. \]
  5720. The most saturated vertices are now \code{w} and \code{y}. We color
  5721. \code{w} with the first available color, which is $0$.
  5722. \[
  5723. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5724. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5725. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5726. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5727. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5728. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5729. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5730. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5731. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5732. \draw (t1) to (rax);
  5733. \draw (t1) to (z);
  5734. \draw (z) to (y);
  5735. \draw (z) to (w);
  5736. \draw (x) to (w);
  5737. \draw (y) to (w);
  5738. \draw (v) to (w);
  5739. \draw (v) to (rsp);
  5740. \draw (w) to (rsp);
  5741. \draw (x) to (rsp);
  5742. \draw (y) to (rsp);
  5743. \path[-.,bend left=15] (z) edge node {} (rsp);
  5744. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5745. \draw (rax) to (rsp);
  5746. \end{tikzpicture}
  5747. \]
  5748. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5749. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5750. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5751. and \code{z}, whose colors are $0$ and $1$ respectively.
  5752. \[
  5753. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5754. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5755. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5756. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5757. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5758. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5759. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5760. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5761. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5762. \draw (t1) to (rax);
  5763. \draw (t1) to (z);
  5764. \draw (z) to (y);
  5765. \draw (z) to (w);
  5766. \draw (x) to (w);
  5767. \draw (y) to (w);
  5768. \draw (v) to (w);
  5769. \draw (v) to (rsp);
  5770. \draw (w) to (rsp);
  5771. \draw (x) to (rsp);
  5772. \draw (y) to (rsp);
  5773. \path[-.,bend left=15] (z) edge node {} (rsp);
  5774. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5775. \draw (rax) to (rsp);
  5776. \end{tikzpicture}
  5777. \]
  5778. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5779. \[
  5780. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5781. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5782. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5783. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5784. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5785. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5786. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5787. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5788. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5789. \draw (t1) to (rax);
  5790. \draw (t1) to (z);
  5791. \draw (z) to (y);
  5792. \draw (z) to (w);
  5793. \draw (x) to (w);
  5794. \draw (y) to (w);
  5795. \draw (v) to (w);
  5796. \draw (v) to (rsp);
  5797. \draw (w) to (rsp);
  5798. \draw (x) to (rsp);
  5799. \draw (y) to (rsp);
  5800. \path[-.,bend left=15] (z) edge node {} (rsp);
  5801. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5802. \draw (rax) to (rsp);
  5803. \end{tikzpicture}
  5804. \]
  5805. In the last step of the algorithm, we color \code{x} with $1$.
  5806. \[
  5807. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5808. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5809. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5810. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5811. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5812. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5813. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5814. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5815. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5816. \draw (t1) to (rax);
  5817. \draw (t1) to (z);
  5818. \draw (z) to (y);
  5819. \draw (z) to (w);
  5820. \draw (x) to (w);
  5821. \draw (y) to (w);
  5822. \draw (v) to (w);
  5823. \draw (v) to (rsp);
  5824. \draw (w) to (rsp);
  5825. \draw (x) to (rsp);
  5826. \draw (y) to (rsp);
  5827. \path[-.,bend left=15] (z) edge node {} (rsp);
  5828. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5829. \draw (rax) to (rsp);
  5830. \end{tikzpicture}
  5831. \]
  5832. So, we obtain the following coloring:
  5833. \[
  5834. \{
  5835. \ttm{rax} \mapsto -1,
  5836. \ttm{rsp} \mapsto -2,
  5837. \ttm{t} \mapsto 0,
  5838. \ttm{z} \mapsto 1,
  5839. \ttm{x} \mapsto 1,
  5840. \ttm{y} \mapsto 2,
  5841. \ttm{w} \mapsto 0,
  5842. \ttm{v} \mapsto 1
  5843. \}
  5844. \]
  5845. \fi}
  5846. %
  5847. {\if\edition\pythonEd\pythonColor
  5848. %
  5849. With the DSATUR algorithm in hand, let us return to the running
  5850. example and consider how to color the interference graph shown in
  5851. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5852. to indicate that it has not yet been assigned a color. Each register
  5853. node (not shown) should be assigned the number that the register
  5854. corresponds to, for example, color \code{rcx} with the number \code{0}
  5855. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5856. each node; all of them start as the empty set.
  5857. %
  5858. \[
  5859. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5860. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5861. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5862. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5863. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5864. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5865. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5866. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5867. \draw (t0) to (t1);
  5868. \draw (t0) to (z);
  5869. \draw (z) to (y);
  5870. \draw (z) to (w);
  5871. \draw (x) to (w);
  5872. \draw (y) to (w);
  5873. \draw (v) to (w);
  5874. \end{tikzpicture}
  5875. \]
  5876. The algorithm says to select a maximally saturated vertex, but they
  5877. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5878. and then we color it with the first available integer, which is $0$. We mark
  5879. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5880. they interfere with $\ttm{tmp\_0}$.
  5881. \[
  5882. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5883. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5884. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5885. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5886. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5887. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5888. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5889. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5890. \draw (t0) to (t1);
  5891. \draw (t0) to (z);
  5892. \draw (z) to (y);
  5893. \draw (z) to (w);
  5894. \draw (x) to (w);
  5895. \draw (y) to (w);
  5896. \draw (v) to (w);
  5897. \end{tikzpicture}
  5898. \]
  5899. We repeat the process. The most saturated vertices are \code{z} and
  5900. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5901. available number, which is $1$. We add $1$ to the saturation for the
  5902. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5903. \[
  5904. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5905. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5906. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5907. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5908. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5909. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5910. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5911. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5912. \draw (t0) to (t1);
  5913. \draw (t0) to (z);
  5914. \draw (z) to (y);
  5915. \draw (z) to (w);
  5916. \draw (x) to (w);
  5917. \draw (y) to (w);
  5918. \draw (v) to (w);
  5919. \end{tikzpicture}
  5920. \]
  5921. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5922. \code{y}. We color \code{w} with the first available color, which
  5923. is $0$.
  5924. \[
  5925. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5926. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5927. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5928. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5929. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5930. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5931. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5932. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5933. \draw (t0) to (t1);
  5934. \draw (t0) to (z);
  5935. \draw (z) to (y);
  5936. \draw (z) to (w);
  5937. \draw (x) to (w);
  5938. \draw (y) to (w);
  5939. \draw (v) to (w);
  5940. \end{tikzpicture}
  5941. \]
  5942. Now \code{y} is the most saturated, so we color it with $2$.
  5943. \[
  5944. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5945. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5946. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5947. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5948. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5949. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5950. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5951. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5952. \draw (t0) to (t1);
  5953. \draw (t0) to (z);
  5954. \draw (z) to (y);
  5955. \draw (z) to (w);
  5956. \draw (x) to (w);
  5957. \draw (y) to (w);
  5958. \draw (v) to (w);
  5959. \end{tikzpicture}
  5960. \]
  5961. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5962. We choose to color \code{v} with $1$.
  5963. \[
  5964. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5965. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5966. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5967. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5968. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5969. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5970. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5971. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5972. \draw (t0) to (t1);
  5973. \draw (t0) to (z);
  5974. \draw (z) to (y);
  5975. \draw (z) to (w);
  5976. \draw (x) to (w);
  5977. \draw (y) to (w);
  5978. \draw (v) to (w);
  5979. \end{tikzpicture}
  5980. \]
  5981. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5982. \[
  5983. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5984. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5985. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5986. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5987. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5988. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5989. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5990. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5991. \draw (t0) to (t1);
  5992. \draw (t0) to (z);
  5993. \draw (z) to (y);
  5994. \draw (z) to (w);
  5995. \draw (x) to (w);
  5996. \draw (y) to (w);
  5997. \draw (v) to (w);
  5998. \end{tikzpicture}
  5999. \]
  6000. So, we obtain the following coloring:
  6001. \[
  6002. \{ \ttm{tmp\_0} \mapsto 0,
  6003. \ttm{tmp\_1} \mapsto 1,
  6004. \ttm{z} \mapsto 1,
  6005. \ttm{x} \mapsto 1,
  6006. \ttm{y} \mapsto 2,
  6007. \ttm{w} \mapsto 0,
  6008. \ttm{v} \mapsto 1 \}
  6009. \]
  6010. \fi}
  6011. We recommend creating an auxiliary function named \code{color\_graph}
  6012. that takes an interference graph and a list of all the variables in
  6013. the program. This function should return a mapping of variables to
  6014. their colors (represented as natural numbers). By creating this helper
  6015. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  6016. when we add support for functions.
  6017. To prioritize the processing of highly saturated nodes inside the
  6018. \code{color\_graph} function, we recommend using the priority queue
  6019. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  6020. addition, you will need to maintain a mapping from variables to their
  6021. handles in the priority queue so that you can notify the priority
  6022. queue when their saturation changes.}
  6023. {\if\edition\racketEd
  6024. \begin{figure}[tp]
  6025. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6026. \small
  6027. \begin{tcolorbox}[title=Priority Queue]
  6028. A \emph{priority queue}\index{subject}{priority queue}
  6029. is a collection of items in which the
  6030. removal of items is governed by priority. In a \emph{min} queue,
  6031. lower priority items are removed first. An implementation is in
  6032. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6033. \begin{description}
  6034. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6035. priority queue that uses the $\itm{cmp}$ predicate to determine
  6036. whether its first argument has lower or equal priority to its
  6037. second argument.
  6038. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6039. items in the queue.
  6040. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6041. the item into the queue and returns a handle for the item in the
  6042. queue.
  6043. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6044. the lowest priority.
  6045. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6046. notifies the queue that the priority has decreased for the item
  6047. associated with the given handle.
  6048. \end{description}
  6049. \end{tcolorbox}
  6050. %\end{wrapfigure}
  6051. \caption{The priority queue data structure.}
  6052. \label{fig:priority-queue}
  6053. \end{figure}
  6054. \fi}
  6055. With the coloring complete, we finalize the assignment of variables to
  6056. registers and stack locations. We map the first $k$ colors to the $k$
  6057. registers and the rest of the colors to stack locations. Suppose for
  6058. the moment that we have just one register to use for register
  6059. allocation, \key{rcx}. Then we have the following assignment.
  6060. \[
  6061. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6062. \]
  6063. Composing this mapping with the coloring, we arrive at the following
  6064. assignment of variables to locations.
  6065. {\if\edition\racketEd
  6066. \begin{gather*}
  6067. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6068. \ttm{w} \mapsto \key{\%rcx}, \,
  6069. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6070. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6071. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6072. \ttm{t} \mapsto \key{\%rcx} \}
  6073. \end{gather*}
  6074. \fi}
  6075. {\if\edition\pythonEd\pythonColor
  6076. \begin{gather*}
  6077. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6078. \ttm{w} \mapsto \key{\%rcx}, \,
  6079. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6080. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6081. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6082. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6083. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6084. \end{gather*}
  6085. \fi}
  6086. Adapt the code from the \code{assign\_homes} pass
  6087. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6088. assigned location. Applying this assignment to our running
  6089. example shown next, on the left, yields the program on the right.
  6090. \begin{center}
  6091. {\if\edition\racketEd
  6092. \begin{minipage}{0.35\textwidth}
  6093. \begin{lstlisting}
  6094. movq $1, v
  6095. movq $42, w
  6096. movq v, x
  6097. addq $7, x
  6098. movq x, y
  6099. movq x, z
  6100. addq w, z
  6101. movq y, t
  6102. negq t
  6103. movq z, %rax
  6104. addq t, %rax
  6105. jmp conclusion
  6106. \end{lstlisting}
  6107. \end{minipage}
  6108. $\Rightarrow\qquad$
  6109. \begin{minipage}{0.45\textwidth}
  6110. \begin{lstlisting}
  6111. movq $1, -8(%rbp)
  6112. movq $42, %rcx
  6113. movq -8(%rbp), -8(%rbp)
  6114. addq $7, -8(%rbp)
  6115. movq -8(%rbp), -16(%rbp)
  6116. movq -8(%rbp), -8(%rbp)
  6117. addq %rcx, -8(%rbp)
  6118. movq -16(%rbp), %rcx
  6119. negq %rcx
  6120. movq -8(%rbp), %rax
  6121. addq %rcx, %rax
  6122. jmp conclusion
  6123. \end{lstlisting}
  6124. \end{minipage}
  6125. \fi}
  6126. {\if\edition\pythonEd\pythonColor
  6127. \begin{minipage}{0.35\textwidth}
  6128. \begin{lstlisting}
  6129. movq $1, v
  6130. movq $42, w
  6131. movq v, x
  6132. addq $7, x
  6133. movq x, y
  6134. movq x, z
  6135. addq w, z
  6136. movq y, tmp_0
  6137. negq tmp_0
  6138. movq z, tmp_1
  6139. addq tmp_0, tmp_1
  6140. movq tmp_1, %rdi
  6141. callq print_int
  6142. \end{lstlisting}
  6143. \end{minipage}
  6144. $\Rightarrow\qquad$
  6145. \begin{minipage}{0.45\textwidth}
  6146. \begin{lstlisting}
  6147. movq $1, -8(%rbp)
  6148. movq $42, %rcx
  6149. movq -8(%rbp), -8(%rbp)
  6150. addq $7, -8(%rbp)
  6151. movq -8(%rbp), -16(%rbp)
  6152. movq -8(%rbp), -8(%rbp)
  6153. addq %rcx, -8(%rbp)
  6154. movq -16(%rbp), %rcx
  6155. negq %rcx
  6156. movq -8(%rbp), -8(%rbp)
  6157. addq %rcx, -8(%rbp)
  6158. movq -8(%rbp), %rdi
  6159. callq print_int
  6160. \end{lstlisting}
  6161. \end{minipage}
  6162. \fi}
  6163. \end{center}
  6164. \begin{exercise}\normalfont\normalsize
  6165. Implement the \code{allocate\_registers} \racket{pass}\python{function}.
  6166. Create five programs that exercise all aspects of the register
  6167. allocation algorithm, including spilling variables to the stack.
  6168. %
  6169. {\if\edition\racketEd
  6170. Replace \code{assign\_homes} in the list of \code{passes} in the
  6171. \code{run-tests.rkt} script with the three new passes:
  6172. \code{uncover\_live}, \code{build\_interference}, and
  6173. \code{allocate\_registers}.
  6174. Temporarily remove the call to \code{compiler-tests}.
  6175. Run the script to test the register allocator.
  6176. \fi}
  6177. %
  6178. {\if\edition\pythonEd\pythonColor
  6179. Update the \code{assign\_homes} pass to make use of
  6180. the functions you have created to perform register allocation:
  6181. \code{uncover\_live}, \code{build\_interference}, and
  6182. \code{allocate\_registers}.
  6183. Run the \code{run-tests.py} script to check whether the
  6184. output programs produce the same result as the input programs.
  6185. Inspect the generated x86 programs to make sure that some variables
  6186. are assigned to registers.
  6187. \fi}
  6188. \end{exercise}
  6189. \section{Patch Instructions}
  6190. \label{sec:patch-instructions}
  6191. The remaining step in the compilation to x86 is to ensure that the
  6192. instructions have at most one argument that is a memory access.
  6193. %
  6194. In the running example, the instruction \code{movq -8(\%rbp),
  6195. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6196. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6197. then move \code{rax} into \code{-16(\%rbp)}.
  6198. %
  6199. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6200. problematic, but they can simply be deleted. In general, we recommend
  6201. deleting all the trivial moves whose source and destination are the
  6202. same location.
  6203. %
  6204. The following is the output of \code{patch\_instructions} on the
  6205. running example.
  6206. \begin{center}
  6207. {\if\edition\racketEd
  6208. \begin{minipage}{0.35\textwidth}
  6209. \begin{lstlisting}
  6210. movq $1, -8(%rbp)
  6211. movq $42, %rcx
  6212. movq -8(%rbp), -8(%rbp)
  6213. addq $7, -8(%rbp)
  6214. movq -8(%rbp), -16(%rbp)
  6215. movq -8(%rbp), -8(%rbp)
  6216. addq %rcx, -8(%rbp)
  6217. movq -16(%rbp), %rcx
  6218. negq %rcx
  6219. movq -8(%rbp), %rax
  6220. addq %rcx, %rax
  6221. jmp conclusion
  6222. \end{lstlisting}
  6223. \end{minipage}
  6224. $\Rightarrow\qquad$
  6225. \begin{minipage}{0.45\textwidth}
  6226. \begin{lstlisting}
  6227. movq $1, -8(%rbp)
  6228. movq $42, %rcx
  6229. addq $7, -8(%rbp)
  6230. movq -8(%rbp), %rax
  6231. movq %rax, -16(%rbp)
  6232. addq %rcx, -8(%rbp)
  6233. movq -16(%rbp), %rcx
  6234. negq %rcx
  6235. movq -8(%rbp), %rax
  6236. addq %rcx, %rax
  6237. jmp conclusion
  6238. \end{lstlisting}
  6239. \end{minipage}
  6240. \fi}
  6241. {\if\edition\pythonEd\pythonColor
  6242. \begin{minipage}{0.35\textwidth}
  6243. \begin{lstlisting}
  6244. movq $1, -8(%rbp)
  6245. movq $42, %rcx
  6246. movq -8(%rbp), -8(%rbp)
  6247. addq $7, -8(%rbp)
  6248. movq -8(%rbp), -16(%rbp)
  6249. movq -8(%rbp), -8(%rbp)
  6250. addq %rcx, -8(%rbp)
  6251. movq -16(%rbp), %rcx
  6252. negq %rcx
  6253. movq -8(%rbp), -8(%rbp)
  6254. addq %rcx, -8(%rbp)
  6255. movq -8(%rbp), %rdi
  6256. callq print_int
  6257. \end{lstlisting}
  6258. \end{minipage}
  6259. $\Rightarrow\qquad$
  6260. \begin{minipage}{0.45\textwidth}
  6261. \begin{lstlisting}
  6262. movq $1, -8(%rbp)
  6263. movq $42, %rcx
  6264. addq $7, -8(%rbp)
  6265. movq -8(%rbp), %rax
  6266. movq %rax, -16(%rbp)
  6267. addq %rcx, -8(%rbp)
  6268. movq -16(%rbp), %rcx
  6269. negq %rcx
  6270. addq %rcx, -8(%rbp)
  6271. movq -8(%rbp), %rdi
  6272. callq print_int
  6273. \end{lstlisting}
  6274. \end{minipage}
  6275. \fi}
  6276. \end{center}
  6277. \begin{exercise}\normalfont\normalsize
  6278. %
  6279. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6280. %
  6281. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6282. %in the \code{run-tests.rkt} script.
  6283. %
  6284. Run the script to test the \code{patch\_instructions} pass.
  6285. \end{exercise}
  6286. \section{Generate Prelude and Conclusion}
  6287. \label{sec:print-x86-reg-alloc}
  6288. \index{subject}{calling conventions}
  6289. \index{subject}{prelude}\index{subject}{conclusion}
  6290. Recall that this pass generates the prelude and conclusion
  6291. instructions to satisfy the x86 calling conventions
  6292. (section~\ref{sec:calling-conventions}). With the addition of the
  6293. register allocator, the callee-saved registers used by the register
  6294. allocator must be saved in the prelude and restored in the conclusion.
  6295. In the \code{allocate\_registers} pass,
  6296. %
  6297. \racket{add an entry to the \itm{info}
  6298. of \code{X86Program} named \code{used\_callee}}
  6299. %
  6300. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6301. %
  6302. that stores the set of callee-saved registers that were assigned to
  6303. variables. The \code{prelude\_and\_conclusion} pass can then access
  6304. this information to decide which callee-saved registers need to be
  6305. saved and restored.
  6306. %
  6307. When calculating the amount to adjust the \code{rsp} in the prelude,
  6308. make sure to take into account the space used for saving the
  6309. callee-saved registers. Also, remember that the frame needs to be a
  6310. multiple of 16 bytes! We recommend using the following equation for
  6311. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6312. of stack locations used by spilled variables\footnote{Sometimes two or
  6313. more spilled variables are assigned to the same stack location, so
  6314. $S$ can be less than the number of spilled variables.} and $C$ be
  6315. the number of callee-saved registers that were
  6316. allocated\index{subject}{allocate} to
  6317. variables. The $\itm{align}$ function rounds a number up to the
  6318. nearest 16 bytes.
  6319. \[
  6320. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6321. \]
  6322. The reason we subtract $8\itm{C}$ in this equation is that the
  6323. prelude uses \code{pushq} to save each of the callee-saved registers,
  6324. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6325. \racket{An overview of all the passes involved in register
  6326. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6327. {\if\edition\racketEd
  6328. \begin{figure}[tbp]
  6329. \begin{tcolorbox}[colback=white]
  6330. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6331. \node (Lvar) at (0,2) {\large \LangVar{}};
  6332. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6333. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6334. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6335. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6336. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6337. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6338. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6339. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6340. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6341. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6342. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6343. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6344. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6345. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6346. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6347. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6348. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6349. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6350. \end{tikzpicture}
  6351. \end{tcolorbox}
  6352. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6353. \label{fig:reg-alloc-passes}
  6354. \end{figure}
  6355. \fi}
  6356. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6357. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6358. use of registers and the stack, we limit the register allocator for
  6359. this example to use just two registers: \code{rcx} (color $0$) and
  6360. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6361. \code{main} function, we push \code{rbx} onto the stack because it is
  6362. a callee-saved register and it was assigned to a variable by the
  6363. register allocator. We subtract \code{8} from the \code{rsp} at the
  6364. end of the prelude to reserve space for the one spilled variable.
  6365. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6366. Moving on to the program proper, we see how the registers were
  6367. allocated.
  6368. %
  6369. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6370. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6371. %
  6372. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6373. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6374. were assigned to \code{rbx}.}
  6375. %
  6376. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6377. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6378. callee-save register \code{rbx} onto the stack. The spilled variables
  6379. must be placed lower on the stack than the saved callee-save
  6380. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6381. \code{-16(\%rbp)}.
  6382. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6383. done in the prelude. We move the stack pointer up by \code{8} bytes
  6384. (the room for spilled variables), then pop the old values of
  6385. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6386. \code{retq} to return control to the operating system.
  6387. \begin{figure}[tbp]
  6388. \begin{minipage}{0.55\textwidth}
  6389. \begin{tcolorbox}[colback=white]
  6390. % var_test_28.rkt
  6391. % (use-minimal-set-of-registers! #t)
  6392. % 0 -> rcx
  6393. % 1 -> rbx
  6394. %
  6395. % t 0 rcx
  6396. % z 1 rbx
  6397. % w 0 rcx
  6398. % y 2 rbp -16
  6399. % v 1 rbx
  6400. % x 1 rbx
  6401. {\if\edition\racketEd
  6402. \begin{lstlisting}
  6403. start:
  6404. movq $1, %rbx
  6405. movq $42, %rcx
  6406. addq $7, %rbx
  6407. movq %rbx, -16(%rbp)
  6408. addq %rcx, %rbx
  6409. movq -16(%rbp), %rcx
  6410. negq %rcx
  6411. movq %rbx, %rax
  6412. addq %rcx, %rax
  6413. jmp conclusion
  6414. .globl main
  6415. main:
  6416. pushq %rbp
  6417. movq %rsp, %rbp
  6418. pushq %rbx
  6419. subq $8, %rsp
  6420. jmp start
  6421. conclusion:
  6422. addq $8, %rsp
  6423. popq %rbx
  6424. popq %rbp
  6425. retq
  6426. \end{lstlisting}
  6427. \fi}
  6428. {\if\edition\pythonEd\pythonColor
  6429. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6430. \begin{lstlisting}
  6431. .globl main
  6432. main:
  6433. pushq %rbp
  6434. movq %rsp, %rbp
  6435. pushq %rbx
  6436. subq $8, %rsp
  6437. movq $1, %rcx
  6438. movq $42, %rbx
  6439. addq $7, %rcx
  6440. movq %rcx, -16(%rbp)
  6441. addq %rbx, -16(%rbp)
  6442. negq %rcx
  6443. movq -16(%rbp), %rbx
  6444. addq %rcx, %rbx
  6445. movq %rbx, %rdi
  6446. callq print_int
  6447. addq $8, %rsp
  6448. popq %rbx
  6449. popq %rbp
  6450. retq
  6451. \end{lstlisting}
  6452. \fi}
  6453. \end{tcolorbox}
  6454. \end{minipage}
  6455. \caption{The x86 output from the running example
  6456. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6457. and \code{rcx}.}
  6458. \label{fig:running-example-x86}
  6459. \end{figure}
  6460. \begin{exercise}\normalfont\normalsize
  6461. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6462. %
  6463. \racket{
  6464. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6465. list of passes and the call to \code{compiler-tests}.}
  6466. %
  6467. Run the script to test the complete compiler for \LangVar{} that
  6468. performs register allocation.
  6469. \end{exercise}
  6470. \section{Challenge: Move Biasing}
  6471. \label{sec:move-biasing}
  6472. \index{subject}{move biasing}
  6473. This section describes an enhancement to the register allocator,
  6474. called move biasing, for students who are looking for an extra
  6475. challenge.
  6476. {\if\edition\racketEd
  6477. To motivate the need for move biasing we return to the running example,
  6478. but this time we use all the general purpose registers. So, we have
  6479. the following mapping of color numbers to registers.
  6480. \[
  6481. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6482. \]
  6483. Using the same assignment of variables to color numbers that was
  6484. produced by the register allocator described in the last section, we
  6485. get the following program.
  6486. \begin{center}
  6487. \begin{minipage}{0.35\textwidth}
  6488. \begin{lstlisting}
  6489. movq $1, v
  6490. movq $42, w
  6491. movq v, x
  6492. addq $7, x
  6493. movq x, y
  6494. movq x, z
  6495. addq w, z
  6496. movq y, t
  6497. negq t
  6498. movq z, %rax
  6499. addq t, %rax
  6500. jmp conclusion
  6501. \end{lstlisting}
  6502. \end{minipage}
  6503. $\Rightarrow\qquad$
  6504. \begin{minipage}{0.45\textwidth}
  6505. \begin{lstlisting}
  6506. movq $1, %rdx
  6507. movq $42, %rcx
  6508. movq %rdx, %rdx
  6509. addq $7, %rdx
  6510. movq %rdx, %rsi
  6511. movq %rdx, %rdx
  6512. addq %rcx, %rdx
  6513. movq %rsi, %rcx
  6514. negq %rcx
  6515. movq %rdx, %rax
  6516. addq %rcx, %rax
  6517. jmp conclusion
  6518. \end{lstlisting}
  6519. \end{minipage}
  6520. \end{center}
  6521. In this output code there are two \key{movq} instructions that
  6522. can be removed because their source and target are the same. However,
  6523. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6524. register, we could instead remove three \key{movq} instructions. We
  6525. can accomplish this by taking into account which variables appear in
  6526. \key{movq} instructions with which other variables.
  6527. \fi}
  6528. {\if\edition\pythonEd\pythonColor
  6529. %
  6530. To motivate the need for move biasing we return to the running example
  6531. and recall that in section~\ref{sec:patch-instructions} we were able to
  6532. remove three trivial move instructions from the running
  6533. example. However, we could remove another trivial move if we were able
  6534. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6535. We say that two variables $p$ and $q$ are \emph{move
  6536. related}\index{subject}{move related} if they participate together in
  6537. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6538. \key{movq} $q$\key{,} $p$.
  6539. %
  6540. Recall that we color variables that are more saturated before coloring
  6541. variables that are less saturated, and in the case of equally
  6542. saturated variables, we choose randomly. Now we break such ties by
  6543. giving preference to variables that have an available color that is
  6544. the same as the color of a move-related variable.
  6545. %
  6546. Furthermore, when the register allocator chooses a color for a
  6547. variable, it should prefer a color that has already been used for a
  6548. move-related variable if one exists (and assuming that they do not
  6549. interfere). This preference should not override the preference for
  6550. registers over stack locations. So, this preference should be used as
  6551. a tie breaker in choosing between two registers or in choosing between
  6552. two stack locations.
  6553. We recommend representing the move relationships in a graph, similarly
  6554. to how we represented interference. The following is the \emph{move
  6555. graph} for our example.
  6556. {\if\edition\racketEd
  6557. \[
  6558. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6559. \node (rax) at (0,0) {$\ttm{rax}$};
  6560. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6561. \node (t) at (0,2) {$\ttm{t}$};
  6562. \node (z) at (3,2) {$\ttm{z}$};
  6563. \node (x) at (6,2) {$\ttm{x}$};
  6564. \node (y) at (3,0) {$\ttm{y}$};
  6565. \node (w) at (6,0) {$\ttm{w}$};
  6566. \node (v) at (9,0) {$\ttm{v}$};
  6567. \draw (v) to (x);
  6568. \draw (x) to (y);
  6569. \draw (x) to (z);
  6570. \draw (y) to (t);
  6571. \end{tikzpicture}
  6572. \]
  6573. \fi}
  6574. %
  6575. {\if\edition\pythonEd\pythonColor
  6576. \[
  6577. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6578. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6579. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6580. \node (z) at (3,2) {$\ttm{z}$};
  6581. \node (x) at (6,2) {$\ttm{x}$};
  6582. \node (y) at (3,0) {$\ttm{y}$};
  6583. \node (w) at (6,0) {$\ttm{w}$};
  6584. \node (v) at (9,0) {$\ttm{v}$};
  6585. \draw (y) to (t0);
  6586. \draw (z) to (x);
  6587. \draw (z) to (t1);
  6588. \draw (x) to (y);
  6589. \draw (x) to (v);
  6590. \end{tikzpicture}
  6591. \]
  6592. \fi}
  6593. {\if\edition\racketEd
  6594. Now we replay the graph coloring, pausing to see the coloring of
  6595. \code{y}. Recall the following configuration. The most saturated vertices
  6596. were \code{w} and \code{y}.
  6597. \[
  6598. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6599. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6600. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6601. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6602. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6603. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6604. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6605. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6606. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6607. \draw (t1) to (rax);
  6608. \draw (t1) to (z);
  6609. \draw (z) to (y);
  6610. \draw (z) to (w);
  6611. \draw (x) to (w);
  6612. \draw (y) to (w);
  6613. \draw (v) to (w);
  6614. \draw (v) to (rsp);
  6615. \draw (w) to (rsp);
  6616. \draw (x) to (rsp);
  6617. \draw (y) to (rsp);
  6618. \path[-.,bend left=15] (z) edge node {} (rsp);
  6619. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6620. \draw (rax) to (rsp);
  6621. \end{tikzpicture}
  6622. \]
  6623. %
  6624. The last time, we chose to color \code{w} with $0$. This time, we see
  6625. that \code{w} is not move-related to any vertex, but \code{y} is
  6626. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6627. the same color as \code{t}.
  6628. \[
  6629. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6630. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6631. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6632. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6633. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6634. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6635. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6636. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6637. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6638. \draw (t1) to (rax);
  6639. \draw (t1) to (z);
  6640. \draw (z) to (y);
  6641. \draw (z) to (w);
  6642. \draw (x) to (w);
  6643. \draw (y) to (w);
  6644. \draw (v) to (w);
  6645. \draw (v) to (rsp);
  6646. \draw (w) to (rsp);
  6647. \draw (x) to (rsp);
  6648. \draw (y) to (rsp);
  6649. \path[-.,bend left=15] (z) edge node {} (rsp);
  6650. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6651. \draw (rax) to (rsp);
  6652. \end{tikzpicture}
  6653. \]
  6654. Now \code{w} is the most saturated, so we color it $2$.
  6655. \[
  6656. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6657. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6658. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6659. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6660. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6661. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6662. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6663. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6664. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6665. \draw (t1) to (rax);
  6666. \draw (t1) to (z);
  6667. \draw (z) to (y);
  6668. \draw (z) to (w);
  6669. \draw (x) to (w);
  6670. \draw (y) to (w);
  6671. \draw (v) to (w);
  6672. \draw (v) to (rsp);
  6673. \draw (w) to (rsp);
  6674. \draw (x) to (rsp);
  6675. \draw (y) to (rsp);
  6676. \path[-.,bend left=15] (z) edge node {} (rsp);
  6677. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6678. \draw (rax) to (rsp);
  6679. \end{tikzpicture}
  6680. \]
  6681. At this point, vertices \code{x} and \code{v} are most saturated, but
  6682. \code{x} is move related to \code{y} and \code{z}, so we color
  6683. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6684. \[
  6685. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6686. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6687. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6688. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6689. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6690. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6691. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6692. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6693. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6694. \draw (t1) to (rax);
  6695. \draw (t) to (z);
  6696. \draw (z) to (y);
  6697. \draw (z) to (w);
  6698. \draw (x) to (w);
  6699. \draw (y) to (w);
  6700. \draw (v) to (w);
  6701. \draw (v) to (rsp);
  6702. \draw (w) to (rsp);
  6703. \draw (x) to (rsp);
  6704. \draw (y) to (rsp);
  6705. \path[-.,bend left=15] (z) edge node {} (rsp);
  6706. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6707. \draw (rax) to (rsp);
  6708. \end{tikzpicture}
  6709. \]
  6710. \fi}
  6711. %
  6712. {\if\edition\pythonEd\pythonColor
  6713. Now we replay the graph coloring, pausing before the coloring of
  6714. \code{w}. Recall the following configuration. The most saturated vertices
  6715. were \code{tmp\_1}, \code{w}, and \code{y}.
  6716. \[
  6717. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6718. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6719. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6720. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6721. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6722. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6723. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6724. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6725. \draw (t0) to (t1);
  6726. \draw (t0) to (z);
  6727. \draw (z) to (y);
  6728. \draw (z) to (w);
  6729. \draw (x) to (w);
  6730. \draw (y) to (w);
  6731. \draw (v) to (w);
  6732. \end{tikzpicture}
  6733. \]
  6734. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6735. or \code{y}. Note, however, that \code{w} is not move related to any
  6736. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6737. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6738. \code{y} and color it $0$, we can delete another move instruction.
  6739. \[
  6740. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6741. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6742. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6743. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6744. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6745. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6746. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6747. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6748. \draw (t0) to (t1);
  6749. \draw (t0) to (z);
  6750. \draw (z) to (y);
  6751. \draw (z) to (w);
  6752. \draw (x) to (w);
  6753. \draw (y) to (w);
  6754. \draw (v) to (w);
  6755. \end{tikzpicture}
  6756. \]
  6757. Now \code{w} is the most saturated, so we color it $2$.
  6758. \[
  6759. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6760. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6761. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6762. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6763. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6764. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6765. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6766. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6767. \draw (t0) to (t1);
  6768. \draw (t0) to (z);
  6769. \draw (z) to (y);
  6770. \draw (z) to (w);
  6771. \draw (x) to (w);
  6772. \draw (y) to (w);
  6773. \draw (v) to (w);
  6774. \end{tikzpicture}
  6775. \]
  6776. To finish the coloring, \code{x} and \code{v} get $0$ and
  6777. \code{tmp\_1} gets $1$.
  6778. \[
  6779. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6780. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6781. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6782. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6783. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6784. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6785. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6786. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6787. \draw (t0) to (t1);
  6788. \draw (t0) to (z);
  6789. \draw (z) to (y);
  6790. \draw (z) to (w);
  6791. \draw (x) to (w);
  6792. \draw (y) to (w);
  6793. \draw (v) to (w);
  6794. \end{tikzpicture}
  6795. \]
  6796. \fi}
  6797. So, we have the following assignment of variables to registers.
  6798. {\if\edition\racketEd
  6799. \begin{gather*}
  6800. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6801. \ttm{w} \mapsto \key{\%rsi}, \,
  6802. \ttm{x} \mapsto \key{\%rcx}, \,
  6803. \ttm{y} \mapsto \key{\%rcx}, \,
  6804. \ttm{z} \mapsto \key{\%rdx}, \,
  6805. \ttm{t} \mapsto \key{\%rcx} \}
  6806. \end{gather*}
  6807. \fi}
  6808. {\if\edition\pythonEd\pythonColor
  6809. \begin{gather*}
  6810. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6811. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6812. \ttm{x} \mapsto \key{\%rcx}, \,
  6813. \ttm{y} \mapsto \key{\%rcx}, \\
  6814. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6815. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6816. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6817. \end{gather*}
  6818. \fi}
  6819. %
  6820. We apply this register assignment to the running example shown next,
  6821. on the left, to obtain the code in the middle. The
  6822. \code{patch\_instructions} then deletes the trivial moves to obtain
  6823. the code on the right.
  6824. {\if\edition\racketEd
  6825. \begin{center}
  6826. \begin{minipage}{0.2\textwidth}
  6827. \begin{lstlisting}
  6828. movq $1, v
  6829. movq $42, w
  6830. movq v, x
  6831. addq $7, x
  6832. movq x, y
  6833. movq x, z
  6834. addq w, z
  6835. movq y, t
  6836. negq t
  6837. movq z, %rax
  6838. addq t, %rax
  6839. jmp conclusion
  6840. \end{lstlisting}
  6841. \end{minipage}
  6842. $\Rightarrow\qquad$
  6843. \begin{minipage}{0.25\textwidth}
  6844. \begin{lstlisting}
  6845. movq $1, %rcx
  6846. movq $42, %rsi
  6847. movq %rcx, %rcx
  6848. addq $7, %rcx
  6849. movq %rcx, %rcx
  6850. movq %rcx, %rdx
  6851. addq %rsi, %rdx
  6852. movq %rcx, %rcx
  6853. negq %rcx
  6854. movq %rdx, %rax
  6855. addq %rcx, %rax
  6856. jmp conclusion
  6857. \end{lstlisting}
  6858. \end{minipage}
  6859. $\Rightarrow\qquad$
  6860. \begin{minipage}{0.23\textwidth}
  6861. \begin{lstlisting}
  6862. movq $1, %rcx
  6863. movq $42, %rsi
  6864. addq $7, %rcx
  6865. movq %rcx, %rdx
  6866. addq %rsi, %rdx
  6867. negq %rcx
  6868. movq %rdx, %rax
  6869. addq %rcx, %rax
  6870. jmp conclusion
  6871. \end{lstlisting}
  6872. \end{minipage}
  6873. \end{center}
  6874. \fi}
  6875. {\if\edition\pythonEd\pythonColor
  6876. \begin{center}
  6877. \begin{minipage}{0.20\textwidth}
  6878. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6879. movq $1, v
  6880. movq $42, w
  6881. movq v, x
  6882. addq $7, x
  6883. movq x, y
  6884. movq x, z
  6885. addq w, z
  6886. movq y, tmp_0
  6887. negq tmp_0
  6888. movq z, tmp_1
  6889. addq tmp_0, tmp_1
  6890. movq tmp_1, %rdi
  6891. callq _print_int
  6892. \end{lstlisting}
  6893. \end{minipage}
  6894. ${\Rightarrow\qquad}$
  6895. \begin{minipage}{0.35\textwidth}
  6896. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6897. movq $1, %rcx
  6898. movq $42, -16(%rbp)
  6899. movq %rcx, %rcx
  6900. addq $7, %rcx
  6901. movq %rcx, %rcx
  6902. movq %rcx, -8(%rbp)
  6903. addq -16(%rbp), -8(%rbp)
  6904. movq %rcx, %rcx
  6905. negq %rcx
  6906. movq -8(%rbp), -8(%rbp)
  6907. addq %rcx, -8(%rbp)
  6908. movq -8(%rbp), %rdi
  6909. callq _print_int
  6910. \end{lstlisting}
  6911. \end{minipage}
  6912. ${\Rightarrow\qquad}$
  6913. \begin{minipage}{0.20\textwidth}
  6914. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6915. movq $1, %rcx
  6916. movq $42, -16(%rbp)
  6917. addq $7, %rcx
  6918. movq %rcx, -8(%rbp)
  6919. movq -16(%rbp), %rax
  6920. addq %rax, -8(%rbp)
  6921. negq %rcx
  6922. addq %rcx, -8(%rbp)
  6923. movq -8(%rbp), %rdi
  6924. callq print_int
  6925. \end{lstlisting}
  6926. \end{minipage}
  6927. \end{center}
  6928. \fi}
  6929. \begin{exercise}\normalfont\normalsize
  6930. Change your implementation of \code{allocate\_registers} to take move
  6931. biasing into account. Create two new tests that include at least one
  6932. opportunity for move biasing, and visually inspect the output x86
  6933. programs to make sure that your move biasing is working properly. Make
  6934. sure that your compiler still passes all the tests.
  6935. \end{exercise}
  6936. %To do: another neat challenge would be to do
  6937. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6938. %% \subsection{Output of the Running Example}
  6939. %% \label{sec:reg-alloc-output}
  6940. % challenge: prioritize variables based on execution frequencies
  6941. % and the number of uses of a variable
  6942. % challenge: enhance the coloring algorithm using Chaitin's
  6943. % approach of prioritizing high-degree variables
  6944. % by removing low-degree variables (coloring them later)
  6945. % from the interference graph
  6946. \section{Further Reading}
  6947. \label{sec:register-allocation-further-reading}
  6948. Early register allocation algorithms were developed for Fortran
  6949. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6950. of graph coloring began in the late 1970s and early 1980s with the
  6951. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6952. algorithm is based on the following observation of
  6953. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6954. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6955. $v$ removed is also $k$ colorable. To see why, suppose that the
  6956. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6957. different colors, but because there are fewer than $k$ neighbors, there
  6958. will be one or more colors left over to use for coloring $v$ in $G$.
  6959. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6960. less than $k$ from the graph and recursively colors the rest of the
  6961. graph. Upon returning from the recursion, it colors $v$ with one of
  6962. the available colors and returns. \citet{Chaitin:1982vn} augments
  6963. this algorithm to handle spilling as follows. If there are no vertices
  6964. of degree lower than $k$ then pick a vertex at random, spill it,
  6965. remove it from the graph, and proceed recursively to color the rest of
  6966. the graph.
  6967. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6968. move-related and that don't interfere with each other, in a process
  6969. called \emph{coalescing}. Although coalescing decreases the number of
  6970. moves, it can make the graph more difficult to
  6971. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6972. which two variables are merged only if they have fewer than $k$
  6973. neighbors of high degree. \citet{George:1996aa} observes that
  6974. conservative coalescing is sometimes too conservative and made it more
  6975. aggressive by iterating the coalescing with the removal of low-degree
  6976. vertices.
  6977. %
  6978. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6979. also proposed \emph{biased coloring}, in which a variable is assigned to
  6980. the same color as another move-related variable if possible, as
  6981. discussed in section~\ref{sec:move-biasing}.
  6982. %
  6983. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6984. performs coalescing, graph coloring, and spill code insertion until
  6985. all variables have been assigned a location.
  6986. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6987. spilled variables that don't have to be: a high-degree variable can be
  6988. colorable if many of its neighbors are assigned the same color.
  6989. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6990. high-degree vertex is not immediately spilled. Instead the decision is
  6991. deferred until after the recursive call, when it is apparent whether
  6992. there is an available color or not. We observe that this algorithm is
  6993. equivalent to the smallest-last ordering
  6994. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6995. be registers and the rest to be stack locations.
  6996. %% biased coloring
  6997. Earlier editions of the compiler course at Indiana University
  6998. \citep{Dybvig:2010aa} were based on the algorithm of
  6999. \citet{Briggs:1994kx}.
  7000. The smallest-last ordering algorithm is one of many \emph{greedy}
  7001. coloring algorithms. A greedy coloring algorithm visits all the
  7002. vertices in a particular order and assigns each one the first
  7003. available color. An \emph{offline} greedy algorithm chooses the
  7004. ordering up front, prior to assigning colors. The algorithm of
  7005. \citet{Chaitin:1981vl} should be considered offline because the vertex
  7006. ordering does not depend on the colors assigned. Other orderings are
  7007. possible. For example, \citet{Chow:1984ys} ordered variables according
  7008. to an estimate of runtime cost.
  7009. An \emph{online} greedy coloring algorithm uses information about the
  7010. current assignment of colors to influence the order in which the
  7011. remaining vertices are colored. The saturation-based algorithm
  7012. described in this chapter is one such algorithm. We choose to use
  7013. saturation-based coloring because it is fun to introduce graph
  7014. coloring via sudoku!
  7015. A register allocator may choose to map each variable to just one
  7016. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  7017. variable to one or more locations. The latter can be achieved by
  7018. \emph{live range splitting}, where a variable is replaced by several
  7019. variables that each handle part of its live
  7020. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  7021. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  7022. %% replacement algorithm, bottom-up local
  7023. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  7024. %% Cooper: top-down (priority bassed), bottom-up
  7025. %% top-down
  7026. %% order variables by priority (estimated cost)
  7027. %% caveat: split variables into two groups:
  7028. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  7029. %% color the constrained ones first
  7030. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7031. %% cite J. Cocke for an algorithm that colors variables
  7032. %% in a high-degree first ordering
  7033. %Register Allocation via Usage Counts, Freiburghouse CACM
  7034. \citet{Palsberg:2007si} observes that many of the interference graphs
  7035. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7036. that is, every cycle with four or more edges has an edge that is not
  7037. part of the cycle but that connects two vertices on the cycle. Such
  7038. graphs can be optimally colored by the greedy algorithm with a vertex
  7039. ordering determined by maximum cardinality search.
  7040. In situations in which compile time is of utmost importance, such as
  7041. in just-in-time compilers, graph coloring algorithms can be too
  7042. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7043. be more appropriate.
  7044. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7045. {\if\edition\racketEd
  7046. \addtocontents{toc}{\newpage}
  7047. \fi}
  7048. \chapter{Booleans and Conditionals}
  7049. \label{ch:Lif}
  7050. \setcounter{footnote}{0}
  7051. The \LangVar{} language has only a single kind of value, the
  7052. integers. In this chapter we add a second kind of value, the Booleans,
  7053. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7054. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7055. are written
  7056. \TRUE{}\index{subject}{True@\TRUE{}} and
  7057. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7058. language includes several operations that involve Booleans
  7059. (\key{and}\index{subject}{and@\ANDNAME{}},
  7060. \key{or}\index{subject}{or@\ORNAME{}},
  7061. \key{not}\index{subject}{not@\NOTNAME{}},
  7062. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7063. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7064. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7065. conditional expression\index{subject}{conditional expression}%
  7066. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7067. With the addition of \key{if}, programs can have
  7068. nontrivial control flow\index{subject}{control flow}, which
  7069. %
  7070. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7071. %
  7072. \python{impacts liveness analysis and motivates a new pass named
  7073. \code{explicate\_control}.}
  7074. %
  7075. Also, because we now have two kinds of values, we need to handle
  7076. programs that apply an operation to the wrong kind of value, such as
  7077. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7078. There are two language design options for such situations. One option
  7079. is to signal an error and the other is to provide a wider
  7080. interpretation of the operation. \racket{The Racket
  7081. language}\python{Python} uses a mixture of these two options,
  7082. depending on the operation and the kind of value. For example, the
  7083. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7084. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7085. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7086. %
  7087. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7088. in Racket because \code{car} expects a pair.}
  7089. %
  7090. \python{On the other hand, \code{1[0]} results in a runtime error
  7091. in Python because an ``\code{int} object is not subscriptable.''}
  7092. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7093. design choices as \racket{Racket}\python{Python}, except that much of the
  7094. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7095. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7096. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7097. \python{MyPy} reports a compile-time error
  7098. %
  7099. \racket{because Racket expects the type of the argument to be of the form
  7100. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7101. %
  7102. \python{stating that a ``value of type \code{int} is not indexable.''}
  7103. The \LangIf{} language performs type checking during compilation just as
  7104. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7105. the alternative choice, that is, a dynamically typed language like
  7106. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7107. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7108. restrictive, for example, rejecting \racket{\code{(not
  7109. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7110. fairly simple because the focus of this book is on compilation and not
  7111. type systems, about which there are already several excellent
  7112. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7113. This chapter is organized as follows. We begin by defining the syntax
  7114. and interpreter for the \LangIf{} language
  7115. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7116. checking (aka semantic analysis\index{subject}{semantic analysis})
  7117. and define a type checker for \LangIf{}
  7118. (section~\ref{sec:type-check-Lif}).
  7119. %
  7120. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7121. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7122. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7123. %
  7124. The remaining sections of this chapter discuss how Booleans and
  7125. conditional control flow require changes to the existing compiler
  7126. passes and the addition of new ones. We introduce the \code{shrink}
  7127. pass to translate some operators into others, thereby reducing the
  7128. number of operators that need to be handled in later passes.
  7129. %
  7130. The main event of this chapter is the \code{explicate\_control} pass
  7131. that is responsible for translating \code{if}s into conditional
  7132. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7133. %
  7134. Regarding register allocation, there is the interesting question of
  7135. how to handle conditional \code{goto}s during liveness analysis.
  7136. \section{The \LangIf{} Language}
  7137. \label{sec:lang-if}
  7138. Definitions of the concrete syntax and abstract syntax of the
  7139. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7140. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7141. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7142. literals\index{subject}{literals}
  7143. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7144. \python{, and the \code{if} statement}. We expand the set of
  7145. operators to include
  7146. \begin{enumerate}
  7147. \item the logical operators \key{and}, \key{or}, and \key{not},
  7148. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7149. for comparing integers or Booleans for equality, and
  7150. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7151. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7152. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7153. comparing integers.
  7154. \end{enumerate}
  7155. \racket{We reorganize the abstract syntax for the primitive
  7156. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7157. rule for all of them. This means that the grammar no longer checks
  7158. whether the arity of an operator matches the number of
  7159. arguments. That responsibility is moved to the type checker for
  7160. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7161. \newcommand{\LifGrammarRacket}{
  7162. \begin{array}{lcl}
  7163. \Type &::=& \key{Boolean} \\
  7164. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7165. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7166. \Exp &::=& \itm{bool}
  7167. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7168. \MID (\key{not}\;\Exp) \\
  7169. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7170. \end{array}
  7171. }
  7172. \newcommand{\LifASTRacket}{
  7173. \begin{array}{lcl}
  7174. \Type &::=& \key{Boolean} \\
  7175. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7176. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7177. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7178. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7179. \end{array}
  7180. }
  7181. \newcommand{\LintOpAST}{
  7182. \begin{array}{rcl}
  7183. \Type &::=& \key{Integer} \\
  7184. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7185. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7186. \end{array}
  7187. }
  7188. \newcommand{\LifGrammarPython}{
  7189. \begin{array}{rcl}
  7190. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7191. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7192. \MID \key{not}~\Exp \\
  7193. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7194. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7195. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7196. \end{array}
  7197. }
  7198. \newcommand{\LifASTPython}{
  7199. \begin{array}{lcl}
  7200. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7201. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7202. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7203. \Exp &::=& \BOOL{\itm{bool}}
  7204. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7205. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7206. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7207. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  7208. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7209. \end{array}
  7210. }
  7211. \begin{figure}[tp]
  7212. \centering
  7213. \begin{tcolorbox}[colback=white]
  7214. {\if\edition\racketEd
  7215. \[
  7216. \begin{array}{l}
  7217. \gray{\LintGrammarRacket{}} \\ \hline
  7218. \gray{\LvarGrammarRacket{}} \\ \hline
  7219. \LifGrammarRacket{} \\
  7220. \begin{array}{lcl}
  7221. \LangIfM{} &::=& \Exp
  7222. \end{array}
  7223. \end{array}
  7224. \]
  7225. \fi}
  7226. {\if\edition\pythonEd\pythonColor
  7227. \[
  7228. \begin{array}{l}
  7229. \gray{\LintGrammarPython} \\ \hline
  7230. \gray{\LvarGrammarPython} \\ \hline
  7231. \LifGrammarPython \\
  7232. \begin{array}{rcl}
  7233. \LangIfM{} &::=& \Stmt^{*}
  7234. \end{array}
  7235. \end{array}
  7236. \]
  7237. \fi}
  7238. \end{tcolorbox}
  7239. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7240. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7241. \label{fig:Lif-concrete-syntax}
  7242. \index{subject}{Lif@\LangIf{} concrete syntax}
  7243. \end{figure}
  7244. \begin{figure}[tp]
  7245. %\begin{minipage}{0.66\textwidth}
  7246. \begin{tcolorbox}[colback=white]
  7247. \centering
  7248. {\if\edition\racketEd
  7249. \[
  7250. \begin{array}{l}
  7251. \gray{\LintOpAST} \\ \hline
  7252. \gray{\LvarASTRacket{}} \\ \hline
  7253. \LifASTRacket{} \\
  7254. \begin{array}{lcl}
  7255. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7256. \end{array}
  7257. \end{array}
  7258. \]
  7259. \fi}
  7260. {\if\edition\pythonEd\pythonColor
  7261. \[
  7262. \begin{array}{l}
  7263. \gray{\LintASTPython} \\ \hline
  7264. \gray{\LvarASTPython} \\ \hline
  7265. \LifASTPython \\
  7266. \begin{array}{lcl}
  7267. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7268. \end{array}
  7269. \end{array}
  7270. \]
  7271. \fi}
  7272. \end{tcolorbox}
  7273. %\end{minipage}
  7274. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7275. \python{
  7276. \index{subject}{BoolOp@\texttt{BoolOp}}
  7277. \index{subject}{Compare@\texttt{Compare}}
  7278. \index{subject}{Lt@\texttt{Lt}}
  7279. \index{subject}{LtE@\texttt{LtE}}
  7280. \index{subject}{Gt@\texttt{Gt}}
  7281. \index{subject}{GtE@\texttt{GtE}}
  7282. }
  7283. \caption{The abstract syntax of \LangIf{}.}
  7284. \label{fig:Lif-syntax}
  7285. \index{subject}{Lif@\LangIf{} abstract syntax}
  7286. \end{figure}
  7287. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7288. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7289. (figure~\ref{fig:interp-Lvar}). The constants \TRUE{} and \FALSE{}
  7290. evaluate to the corresponding Boolean values, behavior that is
  7291. inherited from the interpreter for \LangInt{}
  7292. (figure~\ref{fig:interp-Lint-class}).
  7293. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7294. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7295. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7296. \code{and}, \code{or}, and \code{not} behave according to propositional
  7297. logic. In addition, the \code{and} and \code{or} operations perform
  7298. \emph{short-circuit evaluation}.
  7299. %
  7300. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7301. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7302. %
  7303. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7304. evaluated if $e_1$ evaluates to \TRUE{}.
  7305. \racket{With the increase in the number of primitive operations, the
  7306. interpreter would become repetitive without some care. We refactor
  7307. the case for \code{Prim}, moving the code that differs with each
  7308. operation into the \code{interp\_op} method shown in
  7309. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7310. \code{or} operations separately because of their short-circuiting
  7311. behavior.}
  7312. \begin{figure}[tbp]
  7313. \begin{tcolorbox}[colback=white]
  7314. {\if\edition\racketEd
  7315. \begin{lstlisting}
  7316. (define interp-Lif-class
  7317. (class interp-Lvar-class
  7318. (super-new)
  7319. (define/public (interp_op op) ...)
  7320. (define/override ((interp_exp env) e)
  7321. (define recur (interp_exp env))
  7322. (match e
  7323. [(Bool b) b]
  7324. [(If cnd thn els)
  7325. (match (recur cnd)
  7326. [#t (recur thn)]
  7327. [#f (recur els)])]
  7328. [(Prim 'and (list e1 e2))
  7329. (match (recur e1)
  7330. [#t (match (recur e2) [#t #t] [#f #f])]
  7331. [#f #f])]
  7332. [(Prim 'or (list e1 e2))
  7333. (define v1 (recur e1))
  7334. (match v1
  7335. [#t #t]
  7336. [#f (match (recur e2) [#t #t] [#f #f])])]
  7337. [(Prim op args)
  7338. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7339. [else ((super interp_exp env) e)]))
  7340. ))
  7341. (define (interp_Lif p)
  7342. (send (new interp-Lif-class) interp_program p))
  7343. \end{lstlisting}
  7344. \fi}
  7345. {\if\edition\pythonEd\pythonColor
  7346. \begin{lstlisting}
  7347. class InterpLif(InterpLvar):
  7348. def interp_exp(self, e, env):
  7349. match e:
  7350. case IfExp(test, body, orelse):
  7351. if self.interp_exp(test, env):
  7352. return self.interp_exp(body, env)
  7353. else:
  7354. return self.interp_exp(orelse, env)
  7355. case UnaryOp(Not(), v):
  7356. return not self.interp_exp(v, env)
  7357. case BoolOp(And(), values):
  7358. if self.interp_exp(values[0], env):
  7359. return self.interp_exp(values[1], env)
  7360. else:
  7361. return False
  7362. case BoolOp(Or(), values):
  7363. if self.interp_exp(values[0], env):
  7364. return True
  7365. else:
  7366. return self.interp_exp(values[1], env)
  7367. case Compare(left, [cmp], [right]):
  7368. l = self.interp_exp(left, env)
  7369. r = self.interp_exp(right, env)
  7370. return self.interp_cmp(cmp)(l, r)
  7371. case _:
  7372. return super().interp_exp(e, env)
  7373. def interp_stmt(self, s, env, cont):
  7374. match s:
  7375. case If(test, body, orelse):
  7376. match self.interp_exp(test, env):
  7377. case True:
  7378. return self.interp_stmts(body + cont, env)
  7379. case False:
  7380. return self.interp_stmts(orelse + cont, env)
  7381. case _:
  7382. return super().interp_stmt(s, env, cont)
  7383. ...
  7384. \end{lstlisting}
  7385. \fi}
  7386. \end{tcolorbox}
  7387. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7388. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7389. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7390. \label{fig:interp-Lif}
  7391. \end{figure}
  7392. {\if\edition\racketEd
  7393. \begin{figure}[tbp]
  7394. \begin{tcolorbox}[colback=white]
  7395. \begin{lstlisting}
  7396. (define/public (interp_op op)
  7397. (match op
  7398. ['+ fx+]
  7399. ['- fx-]
  7400. ['read read-fixnum]
  7401. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7402. ['eq? (lambda (v1 v2)
  7403. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7404. (and (boolean? v1) (boolean? v2))
  7405. (and (vector? v1) (vector? v2)))
  7406. (eq? v1 v2)]))]
  7407. ['< (lambda (v1 v2)
  7408. (cond [(and (fixnum? v1) (fixnum? v2))
  7409. (< v1 v2)]))]
  7410. ['<= (lambda (v1 v2)
  7411. (cond [(and (fixnum? v1) (fixnum? v2))
  7412. (<= v1 v2)]))]
  7413. ['> (lambda (v1 v2)
  7414. (cond [(and (fixnum? v1) (fixnum? v2))
  7415. (> v1 v2)]))]
  7416. ['>= (lambda (v1 v2)
  7417. (cond [(and (fixnum? v1) (fixnum? v2))
  7418. (>= v1 v2)]))]
  7419. [else (error 'interp_op "unknown operator")]))
  7420. \end{lstlisting}
  7421. \end{tcolorbox}
  7422. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7423. \label{fig:interp-op-Lif}
  7424. \end{figure}
  7425. \fi}
  7426. {\if\edition\pythonEd\pythonColor
  7427. \begin{figure}
  7428. \begin{tcolorbox}[colback=white]
  7429. \begin{lstlisting}
  7430. class InterpLif(InterpLvar):
  7431. ...
  7432. def interp_cmp(self, cmp):
  7433. match cmp:
  7434. case Lt():
  7435. return lambda x, y: x < y
  7436. case LtE():
  7437. return lambda x, y: x <= y
  7438. case Gt():
  7439. return lambda x, y: x > y
  7440. case GtE():
  7441. return lambda x, y: x >= y
  7442. case Eq():
  7443. return lambda x, y: x == y
  7444. case NotEq():
  7445. return lambda x, y: x != y
  7446. \end{lstlisting}
  7447. \end{tcolorbox}
  7448. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7449. \label{fig:interp-cmp-Lif}
  7450. \end{figure}
  7451. \fi}
  7452. \section{Type Checking \LangIf{} Programs}
  7453. \label{sec:type-check-Lif}
  7454. It is helpful to think about type checking\index{subject}{type
  7455. checking} in two complementary ways. A type checker predicts the
  7456. type of value that will be produced by each expression in the program.
  7457. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7458. type checker should predict that {\if\edition\racketEd
  7459. \begin{lstlisting}
  7460. (+ 10 (- (+ 12 20)))
  7461. \end{lstlisting}
  7462. \fi}
  7463. {\if\edition\pythonEd\pythonColor
  7464. \begin{lstlisting}
  7465. 10 + -(12 + 20)
  7466. \end{lstlisting}
  7467. \fi}
  7468. \noindent produces a value of type \INTTY{}, whereas
  7469. {\if\edition\racketEd
  7470. \begin{lstlisting}
  7471. (and (not #f) #t)
  7472. \end{lstlisting}
  7473. \fi}
  7474. {\if\edition\pythonEd\pythonColor
  7475. \begin{lstlisting}
  7476. (not False) and True
  7477. \end{lstlisting}
  7478. \fi}
  7479. \noindent produces a value of type \BOOLTY{}.
  7480. A second way to think about type checking is that it enforces a set of
  7481. rules about which operators can be applied to which kinds of
  7482. values. For example, our type checker for \LangIf{} signals an error
  7483. for the following expression:
  7484. %
  7485. {\if\edition\racketEd
  7486. \begin{lstlisting}
  7487. (not (+ 10 (- (+ 12 20))))
  7488. \end{lstlisting}
  7489. \fi}
  7490. {\if\edition\pythonEd\pythonColor
  7491. \begin{lstlisting}
  7492. not (10 + -(12 + 20))
  7493. \end{lstlisting}
  7494. \fi}
  7495. \noindent The subexpression
  7496. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7497. \python{\code{(10 + -(12 + 20))}}
  7498. has type \INTTY{}, but the type checker enforces the rule that the
  7499. argument of \code{not} must be an expression of type \BOOLTY{}.
  7500. We implement type checking using classes and methods because they
  7501. provide the open recursion needed to reuse code as we extend the type
  7502. checker in subsequent chapters, analogous to the use of classes and methods
  7503. for the interpreters (section~\ref{sec:extensible-interp}).
  7504. We separate the type checker for the \LangVar{} subset into its own
  7505. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7506. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7507. from the type checker for \LangVar{}. These type checkers are in the
  7508. files
  7509. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7510. and
  7511. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7512. of the support code.
  7513. %
  7514. Each type checker is a structurally recursive function over the AST.
  7515. Given an input expression \code{e}, the type checker either signals an
  7516. error or returns \racket{an expression and its type.}\python{its type.}
  7517. %
  7518. \racket{It returns an expression because there are situations in which
  7519. we want to change or update the expression.}
  7520. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7521. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7522. constant is \INTTY{}. To handle variables, the type checker uses the
  7523. environment \code{env} to map variables to types.
  7524. %
  7525. \racket{Consider the case for \key{let}. We type check the
  7526. initializing expression to obtain its type \key{T} and then
  7527. associate type \code{T} with the variable \code{x} in the
  7528. environment used to type check the body of the \key{let}. Thus,
  7529. when the type checker encounters a use of variable \code{x}, it can
  7530. find its type in the environment.}
  7531. %
  7532. \python{Consider the case for assignment. We type check the
  7533. initializing expression to obtain its type \key{t}. If the variable
  7534. \code{id} is already in the environment because there was a
  7535. prior assignment, we check that this initializer has the same type
  7536. as the prior one. If this is the first assignment to the variable,
  7537. we associate type \code{t} with the variable \code{id} in the
  7538. environment. Thus, when the type checker encounters a use of
  7539. variable \code{x}, it can find its type in the environment.}
  7540. %
  7541. \racket{Regarding primitive operators, we recursively analyze the
  7542. arguments and then invoke \code{type\_check\_op} to check whether
  7543. the argument types are allowed.}
  7544. %
  7545. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7546. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7547. \racket{Several auxiliary methods are used in the type checker. The
  7548. method \code{operator-types} defines a dictionary that maps the
  7549. operator names to their parameter and return types. The
  7550. \code{type-equal?} method determines whether two types are equal,
  7551. which for now simply dispatches to \code{equal?} (deep
  7552. equality). The \code{check-type-equal?} method triggers an error if
  7553. the two types are not equal. The \code{type-check-op} method looks
  7554. up the operator in the \code{operator-types} dictionary and then
  7555. checks whether the argument types are equal to the parameter types.
  7556. The result is the return type of the operator.}
  7557. %
  7558. \python{The auxiliary method \code{check\_type\_equal} triggers
  7559. an error if the two types are not equal.}
  7560. \begin{figure}[tbp]
  7561. \begin{tcolorbox}[colback=white]
  7562. {\if\edition\racketEd
  7563. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7564. (define type-check-Lvar-class
  7565. (class object%
  7566. (super-new)
  7567. (define/public (operator-types)
  7568. '((+ . ((Integer Integer) . Integer))
  7569. (- . ((Integer Integer) . Integer))
  7570. (read . (() . Integer))))
  7571. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7572. (define/public (check-type-equal? t1 t2 e)
  7573. (unless (type-equal? t1 t2)
  7574. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7575. (define/public (type-check-op op arg-types e)
  7576. (match (dict-ref (operator-types) op)
  7577. [`(,param-types . ,return-type)
  7578. (for ([at arg-types] [pt param-types])
  7579. (check-type-equal? at pt e))
  7580. return-type]
  7581. [else (error 'type-check-op "unrecognized ~a" op)]))
  7582. (define/public (type-check-exp env)
  7583. (lambda (e)
  7584. (match e
  7585. [(Int n) (values (Int n) 'Integer)]
  7586. [(Var x) (values (Var x) (dict-ref env x))]
  7587. [(Let x e body)
  7588. (define-values (e^ Te) ((type-check-exp env) e))
  7589. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7590. (values (Let x e^ b) Tb)]
  7591. [(Prim op es)
  7592. (define-values (new-es ts)
  7593. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7594. (values (Prim op new-es) (type-check-op op ts e))]
  7595. [else (error 'type-check-exp "couldn't match" e)])))
  7596. (define/public (type-check-program e)
  7597. (match e
  7598. [(Program info body)
  7599. (define-values (body^ Tb) ((type-check-exp '()) body))
  7600. (check-type-equal? Tb 'Integer body)
  7601. (Program info body^)]
  7602. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7603. ))
  7604. (define (type-check-Lvar p)
  7605. (send (new type-check-Lvar-class) type-check-program p))
  7606. \end{lstlisting}
  7607. \fi}
  7608. {\if\edition\pythonEd\pythonColor
  7609. \begin{lstlisting}[escapechar=`]
  7610. class TypeCheckLvar:
  7611. def check_type_equal(self, t1, t2, e):
  7612. if t1 != t2:
  7613. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7614. raise Exception(msg)
  7615. def type_check_exp(self, e, env):
  7616. match e:
  7617. case BinOp(left, (Add() | Sub()), right):
  7618. l = self.type_check_exp(left, env)
  7619. check_type_equal(l, int, left)
  7620. r = self.type_check_exp(right, env)
  7621. check_type_equal(r, int, right)
  7622. return int
  7623. case UnaryOp(USub(), v):
  7624. t = self.type_check_exp(v, env)
  7625. check_type_equal(t, int, v)
  7626. return int
  7627. case Name(id):
  7628. return env[id]
  7629. case Constant(value) if isinstance(value, int):
  7630. return int
  7631. case Call(Name('input_int'), []):
  7632. return int
  7633. def type_check_stmts(self, ss, env):
  7634. if len(ss) == 0:
  7635. return
  7636. match ss[0]:
  7637. case Assign([Name(id)], value):
  7638. t = self.type_check_exp(value, env)
  7639. if id in env:
  7640. check_type_equal(env[id], t, value)
  7641. else:
  7642. env[id] = t
  7643. return self.type_check_stmts(ss[1:], env)
  7644. case Expr(Call(Name('print'), [arg])):
  7645. t = self.type_check_exp(arg, env)
  7646. check_type_equal(t, int, arg)
  7647. return self.type_check_stmts(ss[1:], env)
  7648. case Expr(value):
  7649. self.type_check_exp(value, env)
  7650. return self.type_check_stmts(ss[1:], env)
  7651. def type_check_P(self, p):
  7652. match p:
  7653. case Module(body):
  7654. self.type_check_stmts(body, {})
  7655. \end{lstlisting}
  7656. \fi}
  7657. \end{tcolorbox}
  7658. \caption{Type checker for the \LangVar{} language.}
  7659. \label{fig:type-check-Lvar}
  7660. \end{figure}
  7661. \begin{figure}[tbp]
  7662. \begin{tcolorbox}[colback=white]
  7663. {\if\edition\racketEd
  7664. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7665. (define type-check-Lif-class
  7666. (class type-check-Lvar-class
  7667. (super-new)
  7668. (inherit check-type-equal?)
  7669. (define/override (operator-types)
  7670. (append '((and . ((Boolean Boolean) . Boolean))
  7671. (or . ((Boolean Boolean) . Boolean))
  7672. (< . ((Integer Integer) . Boolean))
  7673. (<= . ((Integer Integer) . Boolean))
  7674. (> . ((Integer Integer) . Boolean))
  7675. (>= . ((Integer Integer) . Boolean))
  7676. (not . ((Boolean) . Boolean)))
  7677. (super operator-types)))
  7678. (define/override (type-check-exp env)
  7679. (lambda (e)
  7680. (match e
  7681. [(Bool b) (values (Bool b) 'Boolean)]
  7682. [(Prim 'eq? (list e1 e2))
  7683. (define-values (e1^ T1) ((type-check-exp env) e1))
  7684. (define-values (e2^ T2) ((type-check-exp env) e2))
  7685. (check-type-equal? T1 T2 e)
  7686. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7687. [(If cnd thn els)
  7688. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7689. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7690. (define-values (els^ Te) ((type-check-exp env) els))
  7691. (check-type-equal? Tc 'Boolean e)
  7692. (check-type-equal? Tt Te e)
  7693. (values (If cnd^ thn^ els^) Te)]
  7694. [else ((super type-check-exp env) e)])))
  7695. ))
  7696. (define (type-check-Lif p)
  7697. (send (new type-check-Lif-class) type-check-program p))
  7698. \end{lstlisting}
  7699. \fi}
  7700. {\if\edition\pythonEd\pythonColor
  7701. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7702. class TypeCheckLif(TypeCheckLvar):
  7703. def type_check_exp(self, e, env):
  7704. match e:
  7705. case Constant(value) if isinstance(value, bool):
  7706. return bool
  7707. case BinOp(left, Sub(), right):
  7708. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7709. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7710. return int
  7711. case UnaryOp(Not(), v):
  7712. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7713. return bool
  7714. case BoolOp(op, values):
  7715. left = values[0] ; right = values[1]
  7716. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7717. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7718. return bool
  7719. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7720. or isinstance(cmp, NotEq):
  7721. l = self.type_check_exp(left, env)
  7722. r = self.type_check_exp(right, env)
  7723. check_type_equal(l, r, e)
  7724. return bool
  7725. case Compare(left, [cmp], [right]):
  7726. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7727. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7728. return bool
  7729. case IfExp(test, body, orelse):
  7730. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7731. b = self.type_check_exp(body, env)
  7732. o = self.type_check_exp(orelse, env)
  7733. check_type_equal(b, o, e)
  7734. return b
  7735. case _:
  7736. return super().type_check_exp(e, env)
  7737. def type_check_stmts(self, ss, env):
  7738. if len(ss) == 0:
  7739. return
  7740. match ss[0]:
  7741. case If(test, body, orelse):
  7742. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7743. b = self.type_check_stmts(body, env)
  7744. o = self.type_check_stmts(orelse, env)
  7745. check_type_equal(b, o, ss[0])
  7746. return self.type_check_stmts(ss[1:], env)
  7747. case _:
  7748. return super().type_check_stmts(ss, env)
  7749. \end{lstlisting}
  7750. \fi}
  7751. \end{tcolorbox}
  7752. \caption{Type checker for the \LangIf{} language.}
  7753. \label{fig:type-check-Lif}
  7754. \end{figure}
  7755. The definition of the type checker for \LangIf{} is shown in
  7756. figure~\ref{fig:type-check-Lif}.
  7757. %
  7758. The type of a Boolean constant is \BOOLTY{}.
  7759. %
  7760. \racket{The \code{operator-types} function adds dictionary entries for
  7761. the new operators.}
  7762. %
  7763. \python{The logical \code{not} operator requires its argument to be a
  7764. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7765. and logical \code{or} operators.}
  7766. %
  7767. The equality operator requires the two arguments to have the same type,
  7768. and therefore we handle it separately from the other operators.
  7769. %
  7770. \python{The other comparisons (less-than, etc.) require their
  7771. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7772. %
  7773. The condition of an \code{if} must
  7774. be of \BOOLTY{} type, and the two branches must have the same type.
  7775. \begin{exercise}\normalfont\normalsize
  7776. Create ten new test programs in \LangIf{}. Half the programs should
  7777. have a type error.
  7778. \racket{For those programs, create an empty file with the
  7779. same base name and with file extension \code{.tyerr}. For example, if
  7780. the test \code{cond\_test\_14.rkt}
  7781. is expected to error, then create
  7782. an empty file named \code{cond\_test\_14.tyerr}.
  7783. This indicates to \code{interp-tests} and
  7784. \code{compiler-tests} that a type error is expected.}
  7785. %
  7786. The other half of the test programs should not have type errors.
  7787. %
  7788. \racket{In the \code{run-tests.rkt} script, change the second argument
  7789. of \code{interp-tests} and \code{compiler-tests} to
  7790. \code{type-check-Lif}, which causes the type checker to run prior to
  7791. the compiler passes. Temporarily change the \code{passes} to an
  7792. empty list and run the script, thereby checking that the new test
  7793. programs either type check or do not, as intended.}
  7794. %
  7795. Run the test script to check that these test programs type check as
  7796. expected.
  7797. \end{exercise}
  7798. \clearpage
  7799. \section{The \LangCIf{} Intermediate Language}
  7800. \label{sec:Cif}
  7801. {\if\edition\racketEd
  7802. %
  7803. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7804. comparison operators to the \Exp{} nonterminal and the literals
  7805. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7806. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7807. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7808. comparison operation and the branches are \code{goto} statements,
  7809. making it straightforward to compile \code{if} statements to x86. The
  7810. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7811. expressions. A \code{goto} statement transfers control to the $\Tail$
  7812. expression corresponding to its label.
  7813. %
  7814. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7815. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7816. defines its abstract syntax.
  7817. %
  7818. \fi}
  7819. %
  7820. {\if\edition\pythonEd\pythonColor
  7821. %
  7822. The output of \key{explicate\_control} is a language similar to the
  7823. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7824. \code{goto} statements, so we name it \LangCIf{}.
  7825. %
  7826. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7827. the arguments of operators are restricted to atomic expressions. The
  7828. \LangCIf{} language does not include \code{if} expressions, but it does
  7829. include a restricted form of \code{if} statement. The condition must be
  7830. a comparison, and the two branches may contain only \code{goto}
  7831. statements. These restrictions make it easier to translate \code{if}
  7832. statements to x86. The \LangCIf{} language also adds a \code{return}
  7833. statement to finish the program with a specified value.
  7834. %
  7835. The \key{CProgram} construct contains a dictionary mapping labels to
  7836. lists of statements that end with a \emph{tail} statement, which is
  7837. either a \code{return} statement, a \code{goto}, or an
  7838. \code{if} statement.
  7839. %
  7840. A \code{goto} transfers control to the sequence of statements
  7841. associated with its label.
  7842. %
  7843. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7844. and figure~\ref{fig:c1-syntax} shows its
  7845. abstract syntax.
  7846. %
  7847. \fi}
  7848. %
  7849. \newcommand{\CifGrammarRacket}{
  7850. \begin{array}{lcl}
  7851. \Atm &::=& \itm{bool} \\
  7852. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7853. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7854. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7855. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7856. \end{array}
  7857. }
  7858. \newcommand{\CifASTRacket}{
  7859. \begin{array}{lcl}
  7860. \Atm &::=& \BOOL{\itm{bool}} \\
  7861. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7862. \Exp &::= & \UNIOP{\key{\textquotesingle not}}{\Atm} \MID \BINOP{\key{\textquotesingle}\itm{cmp}}{\Atm}{\Atm} \\
  7863. \Tail &::= & \GOTO{\itm{label}} \\
  7864. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7865. \end{array}
  7866. }
  7867. \newcommand{\CifGrammarPython}{
  7868. \begin{array}{lcl}
  7869. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7870. \Exp &::= & \Atm \MID \CREAD{}
  7871. \MID \CUNIOP{\key{-}}{\Atm}
  7872. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7873. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7874. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7875. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7876. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7877. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7878. \end{array}
  7879. }
  7880. \newcommand{\CifASTPython}{
  7881. \begin{array}{lcl}
  7882. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7883. \Exp &::= & \Atm \MID \READ{}
  7884. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7885. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7886. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7887. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7888. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7889. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7890. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7891. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7892. \end{array}
  7893. }
  7894. \begin{figure}[tbp]
  7895. \begin{tcolorbox}[colback=white]
  7896. \small
  7897. {\if\edition\racketEd
  7898. \[
  7899. \begin{array}{l}
  7900. \gray{\CvarGrammarRacket} \\ \hline
  7901. \CifGrammarRacket \\
  7902. \begin{array}{lcl}
  7903. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7904. \end{array}
  7905. \end{array}
  7906. \]
  7907. \fi}
  7908. {\if\edition\pythonEd\pythonColor
  7909. \[
  7910. \begin{array}{l}
  7911. \CifGrammarPython \\
  7912. \begin{array}{lcl}
  7913. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7914. \end{array}
  7915. \end{array}
  7916. \]
  7917. \fi}
  7918. \end{tcolorbox}
  7919. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7920. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7921. \label{fig:c1-concrete-syntax}
  7922. \index{subject}{Cif@\LangCIf{} concrete syntax}
  7923. \end{figure}
  7924. \begin{figure}[tp]
  7925. \begin{tcolorbox}[colback=white]
  7926. \small
  7927. {\if\edition\racketEd
  7928. \[
  7929. \begin{array}{l}
  7930. \gray{\CvarASTRacket} \\ \hline
  7931. \CifASTRacket \\
  7932. \begin{array}{lcl}
  7933. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7934. \end{array}
  7935. \end{array}
  7936. \]
  7937. \fi}
  7938. {\if\edition\pythonEd\pythonColor
  7939. \[
  7940. \begin{array}{l}
  7941. \CifASTPython \\
  7942. \begin{array}{lcl}
  7943. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7944. \end{array}
  7945. \end{array}
  7946. \]
  7947. \fi}
  7948. \end{tcolorbox}
  7949. \racket{
  7950. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7951. }
  7952. \index{subject}{Goto@\texttt{Goto}}
  7953. \index{subject}{Return@\texttt{Return}}
  7954. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7955. (figure~\ref{fig:c0-syntax})}.}
  7956. \label{fig:c1-syntax}
  7957. \index{subject}{Cif@\LangCIf{} abstract syntax}
  7958. \end{figure}
  7959. \section{The \LangXIf{} Language}
  7960. \label{sec:x86-if}
  7961. \index{subject}{x86}
  7962. To implement Booleans, the new logical operations, the
  7963. comparison operations, and the \key{if} expression\python{ and
  7964. statement}, we delve further into the x86
  7965. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7966. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7967. subset of x86, which includes instructions for logical operations,
  7968. comparisons, and \racket{conditional} jumps.
  7969. %
  7970. \python{The abstract syntax for an \LangXIf{} program contains a
  7971. dictionary mapping labels to sequences of instructions, each of
  7972. which we refer to as a \emph{basic block}\index{subject}{basic
  7973. block}.}
  7974. As x86 does not provide direct support for Booleans, we take the usual
  7975. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7976. \code{False} as $0$.
  7977. Furthermore, x86 does not provide an instruction that directly
  7978. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7979. However, the \code{xorq} instruction can be used to encode \code{not}.
  7980. The \key{xorq} instruction takes two arguments, performs a pairwise
  7981. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7982. and writes the results into its second argument. Recall the following
  7983. truth table for exclusive-or:
  7984. \begin{center}
  7985. \begin{tabular}{l|cc}
  7986. & 0 & 1 \\ \hline
  7987. 0 & 0 & 1 \\
  7988. 1 & 1 & 0
  7989. \end{tabular}
  7990. \end{center}
  7991. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7992. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7993. for the bit $1$, the result is the opposite of the second bit. Thus,
  7994. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7995. the first argument, as follows, where $\Arg$ is the translation of
  7996. $\Atm$ to x86:
  7997. \[
  7998. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7999. \qquad\Rightarrow\qquad
  8000. \begin{array}{l}
  8001. \key{movq}~ \Arg\key{,} \Var\\
  8002. \key{xorq}~ \key{\$1,} \Var
  8003. \end{array}
  8004. \]
  8005. \newcommand{\GrammarXIfRacket}{
  8006. \begin{array}{lcl}
  8007. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8008. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8009. \Arg &::=& \key{\%}\itm{bytereg}\\
  8010. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8011. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8012. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8013. \MID \key{set}cc~\Arg
  8014. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8015. &\MID& \key{j}cc~\itm{label} \\
  8016. \end{array}
  8017. }
  8018. \newcommand{\GrammarXIfPython}{
  8019. \begin{array}{lcl}
  8020. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8021. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8022. \Arg &::=& \key{\%}\itm{bytereg}\\
  8023. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8024. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8025. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8026. \MID \key{set}cc~\Arg
  8027. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8028. &\MID& \key{jmp}\,\itm{label} \MID \key{j}cc~\itm{label}
  8029. \MID \itm{label}\key{:}\; \Instr
  8030. \end{array}
  8031. }
  8032. \begin{figure}[tp]
  8033. \begin{tcolorbox}[colback=white]
  8034. {\if\edition\racketEd
  8035. \[
  8036. \begin{array}{l}
  8037. \gray{\GrammarXIntRacket} \\ \hline
  8038. \GrammarXIfRacket \\
  8039. \begin{array}{lcl}
  8040. \LangXIfM{} &::= & \key{.globl main} \\
  8041. & & \key{main:} \; \Instr\ldots
  8042. \end{array}
  8043. \end{array}
  8044. \]
  8045. \fi}
  8046. {\if\edition\pythonEd
  8047. \[
  8048. \begin{array}{l}
  8049. \gray{\GrammarXIntPython} \\ \hline
  8050. \GrammarXIfPython \\
  8051. \begin{array}{lcl}
  8052. \LangXIfM{} &::= & \key{.globl main} \\
  8053. & & \key{main:} \; \Instr\ldots
  8054. \end{array}
  8055. \end{array}
  8056. \]
  8057. \fi}
  8058. \end{tcolorbox}
  8059. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  8060. \label{fig:x86-1-concrete}
  8061. \index{subject}{x86if@\LangXIf{} concrete syntax}
  8062. \end{figure}
  8063. \newcommand{\ASTXIfRacket}{
  8064. \begin{array}{lcl}
  8065. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8066. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8067. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8068. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8069. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8070. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8071. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8072. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8073. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8074. \end{array}
  8075. }
  8076. \newcommand{\ASTXIfPython}{
  8077. \begin{array}{lcl}
  8078. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8079. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8080. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8081. \MID \BYTEREG{\itm{bytereg}} \\
  8082. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8083. \Instr &::=& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8084. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8085. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8086. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8087. &\MID& \python{\JMP{\itm{label}}} \MID \JMPIF{\itm{cc}}{\itm{label}}
  8088. \end{array}
  8089. }
  8090. \begin{figure}[tp]
  8091. \begin{tcolorbox}[colback=white]
  8092. \small
  8093. {\if\edition\racketEd
  8094. \[\arraycolsep=3pt
  8095. \begin{array}{l}
  8096. \gray{\ASTXIntRacket} \\ \hline
  8097. \ASTXIfRacket \\
  8098. \begin{array}{lcl}
  8099. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8100. \end{array}
  8101. \end{array}
  8102. \]
  8103. \fi}
  8104. %
  8105. {\if\edition\pythonEd\pythonColor
  8106. \[
  8107. \begin{array}{l}
  8108. \gray{\ASTXIntPython} \\ \hline
  8109. \ASTXIfPython \\
  8110. \begin{array}{lcl}
  8111. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8112. \end{array}
  8113. \end{array}
  8114. \]
  8115. \fi}
  8116. \end{tcolorbox}
  8117. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8118. \label{fig:x86-1}
  8119. \index{subject}{x86if@\LangXIf{} abstract syntax}
  8120. \end{figure}
  8121. Next we consider the x86 instructions that are relevant for compiling
  8122. the comparison operations. The \key{cmpq} instruction compares its two
  8123. arguments to determine whether one argument is less than, equal to, or
  8124. greater than the other argument. The \key{cmpq} instruction is unusual
  8125. regarding the order of its arguments and where the result is
  8126. placed. The argument order is backward: if you want to test whether
  8127. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8128. \key{cmpq} is placed in the special EFLAGS register. This register
  8129. cannot be accessed directly, but it can be queried by a number of
  8130. instructions, including the \key{set} instruction. The instruction
  8131. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8132. depending on whether the contents of the EFLAGS register matches the
  8133. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8134. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8135. The \key{set} instruction has a quirk in that its destination argument
  8136. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8137. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8138. register. Thankfully, the \key{movzbq} instruction can be used to
  8139. move from a single-byte register to a normal 64-bit register. The
  8140. abstract syntax for the \code{set} instruction differs from the
  8141. concrete syntax in that it separates the instruction name from the
  8142. condition code.
  8143. \python{The x86 instructions for jumping are relevant to the
  8144. compilation of \key{if} expressions.}
  8145. %
  8146. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8147. counter to the address of the instruction after the specified
  8148. label.}
  8149. %
  8150. \racket{The x86 instruction for conditional jump is relevant to the
  8151. compilation of \key{if} expressions.}
  8152. %
  8153. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8154. counter to point to the instruction after \itm{label}, depending on
  8155. whether the result in the EFLAGS register matches the condition code
  8156. \itm{cc}; otherwise, the jump instruction falls through to the next
  8157. instruction. Like the abstract syntax for \code{set}, the abstract
  8158. syntax for conditional jump separates the instruction name from the
  8159. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8160. corresponds to \code{jle foo}. Because the conditional jump instruction
  8161. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8162. a \key{cmpq} instruction to set the EFLAGS register.
  8163. \section{Shrink the \LangIf{} Language}
  8164. \label{sec:shrink-Lif}
  8165. The \code{shrink} pass translates some of the language features into
  8166. other features, thereby reducing the kinds of expressions in the
  8167. language. For example, the short-circuiting nature of the \code{and}
  8168. and \code{or} logical operators can be expressed using \code{if} as
  8169. follows.
  8170. \begin{align*}
  8171. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8172. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8173. \end{align*}
  8174. By performing these translations in the front end of the compiler,
  8175. subsequent passes of the compiler can be shorter.
  8176. On the other hand, translations sometimes reduce the efficiency of the
  8177. generated code by increasing the number of instructions. For example,
  8178. expressing subtraction in terms of addition and negation
  8179. \[
  8180. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8181. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8182. \]
  8183. produces code with two x86 instructions (\code{negq} and \code{addq})
  8184. instead of just one (\code{subq}). Thus, we do not recommend
  8185. translating subtraction into addition and negation.
  8186. \begin{exercise}\normalfont\normalsize
  8187. %
  8188. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8189. the language by translating them to \code{if} expressions in \LangIf{}.
  8190. %
  8191. Create four test programs that involve these operators.
  8192. %
  8193. {\if\edition\racketEd
  8194. In the \code{run-tests.rkt} script, add the following entry for
  8195. \code{shrink} to the list of passes (it should be the only pass at
  8196. this point).
  8197. \begin{lstlisting}
  8198. (list "shrink" shrink interp_Lif type-check-Lif)
  8199. \end{lstlisting}
  8200. This instructs \code{interp-tests} to run the interpreter
  8201. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8202. output of \code{shrink}.
  8203. \fi}
  8204. %
  8205. Run the script to test your compiler on all the test programs.
  8206. \end{exercise}
  8207. {\if\edition\racketEd
  8208. \section{Uniquify Variables}
  8209. \label{sec:uniquify-Lif}
  8210. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8211. \code{if} expressions.
  8212. \begin{exercise}\normalfont\normalsize
  8213. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8214. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8215. \begin{lstlisting}
  8216. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8217. \end{lstlisting}
  8218. Run the script to test your compiler.
  8219. \end{exercise}
  8220. \fi}
  8221. \section{Remove Complex Operands}
  8222. \label{sec:remove-complex-opera-Lif}
  8223. The output language of \code{remove\_complex\_operands} is
  8224. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8225. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8226. but the \code{if} expression is not. All three subexpressions of an
  8227. \code{if} are allowed to be complex expressions, but the operands of
  8228. the \code{not} operator and comparison operators must be atomic.
  8229. %
  8230. \python{We add a new language form, the \code{Begin} expression, to aid
  8231. in the translation of \code{if} expressions. When we recursively
  8232. process the two branches of the \code{if}, we generate temporary
  8233. variables and their initializing expressions. However, these
  8234. expressions may contain side effects and should be executed only
  8235. when the condition of the \code{if} is true (for the ``then''
  8236. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8237. provides a way to initialize the temporary variables within the two branches
  8238. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8239. form executes the statements $ss$ and then returns the result of
  8240. expression $e$.}
  8241. \racket{Add cases to the \code{rco\_exp} and \code{rco\_atom}
  8242. functions for the new features in \LangIf{}. In recursively
  8243. processing subexpressions, recall that you should invoke
  8244. \code{rco\_atom} when the output needs to be an \Atm{} (as specified
  8245. in the grammar for \LangIfANF{}) and invoke \code{rco\_exp} when the
  8246. output should be \Exp{}.}
  8247. %
  8248. \python{Add cases to the \code{rco\_exp} function for the new features
  8249. in \LangIf{}. In recursively processing subexpressions, recall that
  8250. you should invoke \code{rco\_exp} with the extra argument
  8251. \code{True} when the output needs to be an \Atm{} (as specified in
  8252. the grammar for \LangIfANF{}) and \code{False} when the output
  8253. should be \Exp{}.}
  8254. %
  8255. Regarding \code{if}, it is particularly important \emph{not} to
  8256. replace its condition with a temporary variable, because that would
  8257. interfere with the generation of high-quality output in the upcoming
  8258. \code{explicate\_control} pass.
  8259. \newcommand{\LifMonadASTRacket}{
  8260. \begin{array}{rcl}
  8261. \Atm &::=& \BOOL{\itm{bool}}\\
  8262. \Exp &::=& \UNIOP{\key{\textquotesingle not}}{\Atm}
  8263. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8264. \MID \IF{\Exp}{\Exp}{\Exp}
  8265. \end{array}
  8266. }
  8267. \newcommand{\LifMonadASTPython}{
  8268. \begin{array}{rcl}
  8269. \Atm &::=& \BOOL{\itm{bool}}\\
  8270. \Exp &::=& \UNIOP{\key{Not()}}{\Atm}
  8271. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8272. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8273. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8274. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8275. \end{array}
  8276. }
  8277. \begin{figure}[tp]
  8278. \centering
  8279. \begin{tcolorbox}[colback=white]
  8280. {\if\edition\racketEd
  8281. \[
  8282. \begin{array}{l}
  8283. \gray{\LvarMonadASTRacket} \\ \hline
  8284. \LifMonadASTRacket \\
  8285. \begin{array}{rcl}
  8286. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8287. \end{array}
  8288. \end{array}
  8289. \]
  8290. \fi}
  8291. {\if\edition\pythonEd\pythonColor
  8292. \[
  8293. \begin{array}{l}
  8294. \gray{\LvarMonadASTPython} \\ \hline
  8295. \LifMonadASTPython \\
  8296. \begin{array}{rcl}
  8297. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8298. \end{array}
  8299. \end{array}
  8300. \]
  8301. \fi}
  8302. \end{tcolorbox}
  8303. \python{\index{subject}{Begin@\texttt{Begin}}}
  8304. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8305. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8306. \label{fig:Lif-anf-syntax}
  8307. \index{subject}{Lifmon@\LangIfANF{} abstract syntax}
  8308. \end{figure}
  8309. \begin{exercise}\normalfont\normalsize
  8310. %
  8311. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8312. and \code{rco\_exp} functions.
  8313. %
  8314. Create three new \LangIf{} programs that exercise the interesting
  8315. code in this pass.
  8316. %
  8317. {\if\edition\racketEd
  8318. In the \code{run-tests.rkt} script, add the following entry to the
  8319. list of \code{passes} and then run the script to test your compiler.
  8320. \begin{lstlisting}
  8321. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8322. \end{lstlisting}
  8323. \fi}
  8324. \end{exercise}
  8325. \section{Explicate Control}
  8326. \label{sec:explicate-control-Lif}
  8327. \racket{Recall that the purpose of \code{explicate\_control} is to
  8328. make the order of evaluation explicit in the syntax of the program.
  8329. With the addition of \key{if}, this becomes more interesting.}
  8330. %
  8331. The \code{explicate\_control} pass translates from \LangIfANF{} to \LangCIf{}.
  8332. %
  8333. The main challenge to overcome is that the condition of an \key{if}
  8334. can be an arbitrary expression in \LangIfANF{}, whereas in \LangCIf{} the
  8335. condition must be a comparison.
  8336. As a motivating example, consider the following program that has an
  8337. \key{if} expression nested in the condition of another \key{if}:%
  8338. \python{\footnote{Programmers rarely write nested \code{if}
  8339. expressions, but they do write nested expressions involving
  8340. logical \code{and}, which, as we have seen, translates to
  8341. \code{if}.}}
  8342. % cond_test_41.rkt, if_lt_eq.py
  8343. \begin{center}
  8344. \begin{minipage}{0.96\textwidth}
  8345. {\if\edition\racketEd
  8346. \begin{lstlisting}
  8347. (let ([x (read)])
  8348. (let ([y (read)])
  8349. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8350. (+ y 2)
  8351. (+ y 10))))
  8352. \end{lstlisting}
  8353. \fi}
  8354. {\if\edition\pythonEd\pythonColor
  8355. \begin{lstlisting}
  8356. x = input_int()
  8357. y = input_int()
  8358. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8359. \end{lstlisting}
  8360. \fi}
  8361. \end{minipage}
  8362. \end{center}
  8363. %
  8364. The naive way to compile \key{if} and the comparison operations would
  8365. be to handle each of them in isolation, regardless of their context.
  8366. Each comparison would be translated into a \key{cmpq} instruction
  8367. followed by several instructions to move the result from the EFLAGS
  8368. register into a general purpose register or stack location. Each
  8369. \key{if} would be translated into a \key{cmpq} instruction followed by
  8370. a conditional jump. The generated code for the inner \key{if} in this
  8371. example would be as follows:
  8372. \begin{center}
  8373. \begin{minipage}{0.96\textwidth}
  8374. \begin{lstlisting}
  8375. cmpq $1, x
  8376. setl %al
  8377. movzbq %al, tmp
  8378. cmpq $1, tmp
  8379. je then_branch_1
  8380. jmp else_branch_1
  8381. \end{lstlisting}
  8382. \end{minipage}
  8383. \end{center}
  8384. Notice that the three instructions starting with \code{setl} are
  8385. redundant; the conditional jump could come immediately after the first
  8386. \code{cmpq}.
  8387. Our goal is to compile \key{if} expressions so that the relevant
  8388. comparison instruction appears directly before the conditional jump.
  8389. For example, we want to generate the following code for the inner
  8390. \code{if}:
  8391. \begin{center}
  8392. \begin{minipage}{0.96\textwidth}
  8393. \begin{lstlisting}
  8394. cmpq $1, x
  8395. jl then_branch_1
  8396. jmp else_branch_1
  8397. \end{lstlisting}
  8398. \end{minipage}
  8399. \end{center}
  8400. One way to achieve this goal is to reorganize the code at the level of
  8401. \LangIf{} or \LangIfANF{}, pushing the outer \key{if} inside the inner one, yielding
  8402. the following code:
  8403. \begin{center}
  8404. \begin{minipage}{0.96\textwidth}
  8405. {\if\edition\racketEd
  8406. \begin{lstlisting}
  8407. (let ([x (read)])
  8408. (let ([y (read)])
  8409. (if (< x 1)
  8410. (if (eq? x 0)
  8411. (+ y 2)
  8412. (+ y 10))
  8413. (if (eq? x 2)
  8414. (+ y 2)
  8415. (+ y 10)))))
  8416. \end{lstlisting}
  8417. \fi}
  8418. {\if\edition\pythonEd\pythonColor
  8419. \begin{lstlisting}
  8420. x = input_int()
  8421. y = input_int()
  8422. print(((y + 2) if x == 0 else (y + 10)) \
  8423. if (x < 1) \
  8424. else ((y + 2) if (x == 2) else (y + 10)))
  8425. \end{lstlisting}
  8426. \fi}
  8427. \end{minipage}
  8428. \end{center}
  8429. Unfortunately, this approach duplicates the two branches from the
  8430. outer \code{if}, and a compiler must never duplicate code! After all,
  8431. the two branches could be very large expressions.
  8432. How can we apply this transformation without duplicating code? In
  8433. other words, how can two different parts of a program refer to one
  8434. piece of code?
  8435. %
  8436. The answer is that we must move away from abstract syntax \emph{trees}
  8437. and instead use \emph{graphs}.
  8438. %
  8439. At the level of x86 assembly, this is straightforward because we can
  8440. label the code for each branch and insert jumps in all the places that
  8441. need to execute the branch. In this way, jump instructions are edges
  8442. in the graph and the basic blocks are the nodes.
  8443. %
  8444. Likewise, our language \LangCIf{} provides the ability to label a
  8445. sequence of statements and to jump to a label via \code{goto}.
  8446. As a preview of what \code{explicate\_control} will do,
  8447. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8448. \code{explicate\_control} on this example. Note how the condition of
  8449. every \code{if} is a comparison operation and that we have not
  8450. duplicated any code but instead have used labels and \code{goto} to
  8451. enable sharing of code.
  8452. \begin{figure}[tbp]
  8453. \begin{tcolorbox}[colback=white]
  8454. {\if\edition\racketEd
  8455. \begin{tabular}{lll}
  8456. \begin{minipage}{0.4\textwidth}
  8457. % cond_test_41.rkt
  8458. \begin{lstlisting}
  8459. (let ([x (read)])
  8460. (let ([y (read)])
  8461. (if (if (< x 1)
  8462. (eq? x 0)
  8463. (eq? x 2))
  8464. (+ y 2)
  8465. (+ y 10))))
  8466. \end{lstlisting}
  8467. \end{minipage}
  8468. &
  8469. $\Rightarrow$
  8470. &
  8471. \begin{minipage}{0.55\textwidth}
  8472. \begin{lstlisting}
  8473. start:
  8474. x = (read);
  8475. y = (read);
  8476. if (< x 1)
  8477. goto block_4;
  8478. else
  8479. goto block_5;
  8480. block_4:
  8481. if (eq? x 0)
  8482. goto block_2;
  8483. else
  8484. goto block_3;
  8485. block_5:
  8486. if (eq? x 2)
  8487. goto block_2;
  8488. else
  8489. goto block_3;
  8490. block_2:
  8491. return (+ y 2);
  8492. block_3:
  8493. return (+ y 10);
  8494. \end{lstlisting}
  8495. \end{minipage}
  8496. \end{tabular}
  8497. \fi}
  8498. {\if\edition\pythonEd\pythonColor
  8499. \begin{tabular}{lll}
  8500. \begin{minipage}{0.4\textwidth}
  8501. % tests/if/if_lt_eq.py
  8502. \begin{lstlisting}
  8503. x = input_int()
  8504. y = input_int()
  8505. tmp_0 = y + 2 \
  8506. if (x == 0 \
  8507. if x < 1 \
  8508. else x == 2) \
  8509. else y + 10
  8510. print(tmp_0)
  8511. \end{lstlisting}
  8512. \end{minipage}
  8513. &
  8514. $\Rightarrow\qquad$
  8515. &
  8516. \begin{minipage}{0.55\textwidth}
  8517. \begin{lstlisting}
  8518. start:
  8519. x = input_int()
  8520. y = input_int()
  8521. if x < 1:
  8522. goto block_6
  8523. else:
  8524. goto block_7
  8525. block_6:
  8526. if x == 0:
  8527. goto block_4
  8528. else:
  8529. goto block_5
  8530. block_7:
  8531. if x == 2:
  8532. goto block_4
  8533. else:
  8534. goto block_5
  8535. block_4:
  8536. tmp_0 = (y + 2)
  8537. goto block_3
  8538. block_5:
  8539. tmp_0 = (y + 10)
  8540. goto block_3
  8541. block_3:
  8542. print(tmp_0)
  8543. return 0
  8544. \end{lstlisting}
  8545. \end{minipage}
  8546. \end{tabular}
  8547. \fi}
  8548. \end{tcolorbox}
  8549. \caption{Translation from \LangIfANF{} to \LangCIf{}
  8550. via the \code{explicate\_control}.}
  8551. \label{fig:explicate-control-s1-38}
  8552. \end{figure}
  8553. {\if\edition\racketEd
  8554. %
  8555. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8556. \code{explicate\_control} for \LangVarANF{} using two recursive
  8557. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8558. former function translates expressions in tail position, whereas the
  8559. latter function translates expressions on the right-hand side of a
  8560. \key{let}. With the addition of \key{if} expression to \LangIfANF{} we
  8561. have a new kind of position to deal with: the predicate position of
  8562. the \key{if}. We need another function, \code{explicate\_pred}, that
  8563. decides how to compile an \key{if} by analyzing its condition. So,
  8564. \code{explicate\_pred} takes an \LangIfANF{} expression and two
  8565. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8566. and outputs a tail. In the following paragraphs we discuss specific
  8567. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8568. \code{explicate\_pred} functions.
  8569. %
  8570. \fi}
  8571. %
  8572. {\if\edition\pythonEd\pythonColor
  8573. %
  8574. We recommend implementing \code{explicate\_control} using the
  8575. following four auxiliary functions.
  8576. \begin{description}
  8577. \item[\code{explicate\_effect}] generates code for expressions as
  8578. statements, so their result is ignored and only their side effects
  8579. matter.
  8580. \item[\code{explicate\_assign}] generates code for expressions
  8581. on the right-hand side of an assignment.
  8582. \item[\code{explicate\_pred}] generates code for an \code{if}
  8583. expression or statement by analyzing the condition expression.
  8584. \item[\code{explicate\_stmt}] generates code for statements.
  8585. \end{description}
  8586. These four functions should build the dictionary of basic blocks. The
  8587. following auxiliary function \code{create\_block} is used to create a
  8588. new basic block from a list of statements. If the list just contains a
  8589. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8590. \code{create\_block} creates a new basic block and returns a
  8591. \code{goto} to its label.
  8592. \begin{center}
  8593. \begin{minipage}{\textwidth}
  8594. \begin{lstlisting}
  8595. def create_block(stmts, basic_blocks):
  8596. match stmts:
  8597. case [Goto(l)]:
  8598. return stmts
  8599. case _:
  8600. label = label_name(generate_name('block'))
  8601. basic_blocks[label] = stmts
  8602. return [Goto(label)]
  8603. \end{lstlisting}
  8604. \end{minipage}
  8605. \end{center}
  8606. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8607. \code{explicate\_control} pass.
  8608. The \code{explicate\_effect} function has three parameters: (1) the
  8609. expression to be compiled; (2) the already-compiled code for this
  8610. expression's \emph{continuation}, that is, the list of statements that
  8611. should execute after this expression; and (3) the dictionary of
  8612. generated basic blocks. The \code{explicate\_effect} function returns
  8613. a list of \LangCIf{} statements and it may add to the dictionary of
  8614. basic blocks.
  8615. %
  8616. Let's consider a few of the cases for the expression to be compiled.
  8617. If the expression to be compiled is a constant, then it can be
  8618. discarded because it has no side effects. If it's a \CREAD{}, then it
  8619. has a side effect and should be preserved. So the expression should be
  8620. translated into a statement using the \code{Expr} AST class. If the
  8621. expression to be compiled is an \code{if} expression, we translate the
  8622. two branches using \code{explicate\_effect} and then translate the
  8623. condition expression using \code{explicate\_pred}, which generates
  8624. code for the entire \code{if}.
  8625. The \code{explicate\_assign} function has four parameters: (1) the
  8626. right-hand side of the assignment, (2) the left-hand side of the
  8627. assignment (the variable), (3) the continuation, and (4) the dictionary
  8628. of basic blocks. The \code{explicate\_assign} function returns a list
  8629. of \LangCIf{} statements, and it may add to the dictionary of basic
  8630. blocks.
  8631. When the right-hand side is an \code{if} expression, there is some
  8632. work to do. In particular, the two branches should be translated using
  8633. \code{explicate\_assign}, and the condition expression should be
  8634. translated using \code{explicate\_pred}. Otherwise we can simply
  8635. generate an assignment statement, with the given left- and right-hand
  8636. sides, concatenated with its continuation.
  8637. \begin{figure}[tbp]
  8638. \begin{tcolorbox}[colback=white]
  8639. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8640. def explicate_effect(e, cont, basic_blocks):
  8641. match e:
  8642. case IfExp(test, body, orelse):
  8643. ...
  8644. case Call(func, args):
  8645. ...
  8646. case Begin(body, result):
  8647. ...
  8648. case _:
  8649. ...
  8650. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8651. match rhs:
  8652. case IfExp(test, body, orelse):
  8653. ...
  8654. case Begin(body, result):
  8655. ...
  8656. case _:
  8657. return [Assign([lhs], rhs)] + cont
  8658. def explicate_pred(cnd, thn, els, basic_blocks):
  8659. match cnd:
  8660. case Compare(left, [op], [right]):
  8661. goto_thn = create_block(thn, basic_blocks)
  8662. goto_els = create_block(els, basic_blocks)
  8663. return [If(cnd, goto_thn, goto_els)]
  8664. case Constant(True):
  8665. return thn;
  8666. case Constant(False):
  8667. return els;
  8668. case UnaryOp(Not(), operand):
  8669. ...
  8670. case IfExp(test, body, orelse):
  8671. ...
  8672. case Begin(body, result):
  8673. ...
  8674. case _:
  8675. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8676. create_block(els, basic_blocks),
  8677. create_block(thn, basic_blocks))]
  8678. def explicate_stmt(s, cont, basic_blocks):
  8679. match s:
  8680. case Assign([lhs], rhs):
  8681. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8682. case Expr(value):
  8683. return explicate_effect(value, cont, basic_blocks)
  8684. case If(test, body, orelse):
  8685. ...
  8686. def explicate_control(p):
  8687. match p:
  8688. case Module(body):
  8689. new_body = [Return(Constant(0))]
  8690. basic_blocks = {}
  8691. for s in reversed(body):
  8692. new_body = explicate_stmt(s, new_body, basic_blocks)
  8693. basic_blocks[label_name('start')] = new_body
  8694. return CProgram(basic_blocks)
  8695. \end{lstlisting}
  8696. \end{tcolorbox}
  8697. \caption{Skeleton for the \code{explicate\_control} pass.}
  8698. \label{fig:explicate-control-Lif}
  8699. \end{figure}
  8700. \fi}
  8701. {\if\edition\racketEd
  8702. \subsection{Explicate Tail and Assign}
  8703. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8704. additional cases for Boolean constants and \key{if}. The cases for
  8705. \code{if} should recursively compile the two branches using either
  8706. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8707. cases should then invoke \code{explicate\_pred} on the condition
  8708. expression, passing in the generated code for the two branches. For
  8709. example, consider the following program with an \code{if} in tail
  8710. position.
  8711. % cond_test_6.rkt
  8712. \begin{lstlisting}
  8713. (let ([x (read)])
  8714. (if (eq? x 0) 42 777))
  8715. \end{lstlisting}
  8716. The two branches are recursively compiled to return statements. We
  8717. then delegate to \code{explicate\_pred}, passing the condition
  8718. \code{(eq? x 0)} and the two return statements. We return to this
  8719. example shortly when we discuss \code{explicate\_pred}.
  8720. Next let us consider a program with an \code{if} on the right-hand
  8721. side of a \code{let}.
  8722. \begin{lstlisting}
  8723. (let ([y (read)])
  8724. (let ([x (if (eq? y 0) 40 777)])
  8725. (+ x 2)))
  8726. \end{lstlisting}
  8727. Note that the body of the inner \code{let} will have already been
  8728. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8729. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8730. to recursively process both branches of the \code{if}, and we do not
  8731. want to duplicate code, so we generate the following block using an
  8732. auxiliary function named \code{create\_block}, discussed in the next
  8733. section.
  8734. \begin{lstlisting}
  8735. block_6:
  8736. return (+ x 2)
  8737. \end{lstlisting}
  8738. We then use \code{goto block\_6;} as the \code{cont} argument for
  8739. compiling the branches. So the two branches compile to
  8740. \begin{center}
  8741. \begin{minipage}{0.2\textwidth}
  8742. \begin{lstlisting}
  8743. x = 40;
  8744. goto block_6;
  8745. \end{lstlisting}
  8746. \end{minipage}
  8747. \hspace{0.5in} and \hspace{0.5in}
  8748. \begin{minipage}{0.2\textwidth}
  8749. \begin{lstlisting}
  8750. x = 777;
  8751. goto block_6;
  8752. \end{lstlisting}
  8753. \end{minipage}
  8754. \end{center}
  8755. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8756. \code{(eq? y 0)} and the previously presented code for the branches.
  8757. \subsection{Create Block}
  8758. We recommend implementing the \code{create\_block} auxiliary function
  8759. as follows, using a global variable \code{basic-blocks} to store a
  8760. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8761. that \code{create\_block} generates a new label and then associates
  8762. the given \code{tail} with the new label in the \code{basic-blocks}
  8763. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8764. new label. However, if the given \code{tail} is already a \code{Goto},
  8765. then there is no need to generate a new label and entry in
  8766. \code{basic-blocks}; we can simply return that \code{Goto}.
  8767. %
  8768. \begin{lstlisting}
  8769. (define (create_block tail)
  8770. (match tail
  8771. [(Goto label) (Goto label)]
  8772. [else
  8773. (let ([label (gensym 'block)])
  8774. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8775. (Goto label))]))
  8776. \end{lstlisting}
  8777. \fi}
  8778. {\if\edition\racketEd
  8779. \subsection{Explicate Predicate}
  8780. The skeleton for the \code{explicate\_pred} function is given in
  8781. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8782. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8783. the code generated by explicate for the \emph{then} branch; and (3)
  8784. \code{els}, the code generated by explicate for the \emph{else}
  8785. branch. The \code{explicate\_pred} function should match on
  8786. \code{cnd} with a case for every kind of expression that can have type
  8787. \BOOLTY{}.
  8788. \begin{figure}[tbp]
  8789. \begin{tcolorbox}[colback=white]
  8790. \begin{lstlisting}
  8791. (define (explicate_pred cnd thn els)
  8792. (match cnd
  8793. [(Var x) ___]
  8794. [(Let x rhs body) ___]
  8795. [(Prim 'not (list e)) ___]
  8796. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8797. (IfStmt (Prim op es) (create_block thn)
  8798. (create_block els))]
  8799. [(Bool b) (if b thn els)]
  8800. [(If cnd^ thn^ els^) ___]
  8801. [else (error "explicate_pred unhandled case" cnd)]))
  8802. \end{lstlisting}
  8803. \end{tcolorbox}
  8804. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8805. \label{fig:explicate-pred}
  8806. \end{figure}
  8807. \fi}
  8808. %
  8809. {\if\edition\pythonEd\pythonColor
  8810. The \code{explicate\_pred} function has four parameters: (1) the
  8811. condition expression, (2) the generated statements for the \emph{then}
  8812. branch, (3) the generated statements for the \emph{else} branch, and
  8813. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8814. function returns a list of statements, and it adds to the dictionary
  8815. of basic blocks.
  8816. \fi}
  8817. Consider the case for comparison operators. We translate the
  8818. comparison to an \code{if} statement whose branches are \code{goto}
  8819. statements created by applying \code{create\_block} to the \code{thn}
  8820. and \code{els} parameters. Let us illustrate this translation by
  8821. returning to the program with an \code{if} expression in tail
  8822. position, shown next. We invoke \code{explicate\_pred} on its
  8823. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8824. %
  8825. {\if\edition\racketEd
  8826. \begin{lstlisting}
  8827. (let ([x (read)])
  8828. (if (eq? x 0) 42 777))
  8829. \end{lstlisting}
  8830. \fi}
  8831. %
  8832. {\if\edition\pythonEd\pythonColor
  8833. \begin{lstlisting}
  8834. x = input_int()
  8835. 42 if x == 0 else 777
  8836. \end{lstlisting}
  8837. \fi}
  8838. %
  8839. \noindent The two branches \code{42} and \code{777} were already
  8840. compiled to \code{return} statements, from which we now create the
  8841. following blocks:
  8842. %
  8843. \begin{center}
  8844. \begin{minipage}{\textwidth}
  8845. \begin{lstlisting}
  8846. block_1:
  8847. return 42;
  8848. block_2:
  8849. return 777;
  8850. \end{lstlisting}
  8851. \end{minipage}
  8852. \end{center}
  8853. %
  8854. After that, \code{explicate\_pred} compiles the comparison
  8855. \racket{\code{(eq? x 0)}}
  8856. \python{\code{x == 0}}
  8857. to the following \code{if} statement:
  8858. %
  8859. {\if\edition\racketEd
  8860. \begin{center}
  8861. \begin{minipage}{\textwidth}
  8862. \begin{lstlisting}
  8863. if (eq? x 0)
  8864. goto block_1;
  8865. else
  8866. goto block_2;
  8867. \end{lstlisting}
  8868. \end{minipage}
  8869. \end{center}
  8870. \fi}
  8871. {\if\edition\pythonEd\pythonColor
  8872. \begin{center}
  8873. \begin{minipage}{\textwidth}
  8874. \begin{lstlisting}
  8875. if x == 0:
  8876. goto block_1;
  8877. else
  8878. goto block_2;
  8879. \end{lstlisting}
  8880. \end{minipage}
  8881. \end{center}
  8882. \fi}
  8883. Next consider the case for Boolean constants. We perform a kind of
  8884. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8885. either the \code{thn} or \code{els} parameter, depending on whether the
  8886. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8887. following program:
  8888. {\if\edition\racketEd
  8889. \begin{lstlisting}
  8890. (if #t 42 777)
  8891. \end{lstlisting}
  8892. \fi}
  8893. {\if\edition\pythonEd\pythonColor
  8894. \begin{lstlisting}
  8895. 42 if True else 777
  8896. \end{lstlisting}
  8897. \fi}
  8898. %
  8899. \noindent Again, the two branches \code{42} and \code{777} were
  8900. compiled to \code{return} statements, so \code{explicate\_pred}
  8901. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8902. code for the \emph{then} branch.
  8903. \begin{lstlisting}
  8904. return 42;
  8905. \end{lstlisting}
  8906. This case demonstrates that we sometimes discard the \code{thn} or
  8907. \code{els} blocks that are input to \code{explicate\_pred}.
  8908. The case for \key{if} expressions in \code{explicate\_pred} is
  8909. particularly illuminating because it deals with the challenges
  8910. discussed previously regarding nested \key{if} expressions
  8911. (figure~\ref{fig:explicate-control-s1-38}). The
  8912. \racket{\lstinline{thn^}}\python{\code{body}} and
  8913. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8914. \key{if} inherit their context from the current one, that is,
  8915. predicate context. So, you should recursively apply
  8916. \code{explicate\_pred} to the
  8917. \racket{\lstinline{thn^}}\python{\code{body}} and
  8918. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8919. those recursive calls, pass \code{thn} and \code{els} as the extra
  8920. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8921. inside each recursive call. As discussed previously, to avoid
  8922. duplicating code, we need to add them to the dictionary of basic
  8923. blocks so that we can instead refer to them by name and execute them
  8924. with a \key{goto}.
  8925. {\if\edition\pythonEd\pythonColor
  8926. %
  8927. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8928. three parameters: (1) the statement to be compiled, (2) the code for its
  8929. continuation, and (3) the dictionary of basic blocks. The
  8930. \code{explicate\_stmt} returns a list of statements, and it may add to
  8931. the dictionary of basic blocks. The cases for assignment and an
  8932. expression-statement are given in full in the skeleton code: they
  8933. simply dispatch to \code{explicate\_assign} and
  8934. \code{explicate\_effect}, respectively. The case for \code{if}
  8935. statements is not given; it is similar to the case for \code{if}
  8936. expressions.
  8937. The \code{explicate\_control} function itself is given in
  8938. figure~\ref{fig:explicate-control-Lif}. It applies
  8939. \code{explicate\_stmt} to each statement in the program, from back to
  8940. front. Thus, the result so far, stored in \code{new\_body}, can be
  8941. used as the continuation parameter in the next call to
  8942. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8943. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8944. the dictionary of basic blocks, labeling it the ``start'' block.
  8945. %
  8946. \fi}
  8947. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8948. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8949. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8950. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8951. %% results from the two recursive calls. We complete the case for
  8952. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8953. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8954. %% the result $B_5$.
  8955. %% \[
  8956. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8957. %% \quad\Rightarrow\quad
  8958. %% B_5
  8959. %% \]
  8960. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8961. %% inherit the current context, so they are in tail position. Thus, the
  8962. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8963. %% \code{explicate\_tail}.
  8964. %% %
  8965. %% We need to pass $B_0$ as the accumulator argument for both of these
  8966. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8967. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8968. %% to the control-flow graph and obtain a promised goto $G_0$.
  8969. %% %
  8970. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8971. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8972. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8973. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8974. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8975. %% \[
  8976. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8977. %% \]
  8978. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8979. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8980. %% should not be confused with the labels for the blocks that appear in
  8981. %% the generated code. We initially construct unlabeled blocks; we only
  8982. %% attach labels to blocks when we add them to the control-flow graph, as
  8983. %% we see in the next case.
  8984. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8985. %% function. The context of the \key{if} is an assignment to some
  8986. %% variable $x$ and then the control continues to some promised block
  8987. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8988. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8989. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8990. %% branches of the \key{if} inherit the current context, so they are in
  8991. %% assignment positions. Let $B_2$ be the result of applying
  8992. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8993. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8994. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8995. %% the result of applying \code{explicate\_pred} to the predicate
  8996. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8997. %% translates to the promise $B_4$.
  8998. %% \[
  8999. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  9000. %% \]
  9001. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  9002. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  9003. \code{remove\_complex\_operands} pass and then the
  9004. \code{explicate\_control} pass on the example program. We walk through
  9005. the output program.
  9006. %
  9007. Following the order of evaluation in the output of
  9008. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  9009. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  9010. in the predicate of the inner \key{if}. In the output of
  9011. \code{explicate\_control}, in the
  9012. block labeled \code{start}, two assignment statements are followed by an
  9013. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  9014. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  9015. The blocks associated with those labels contain the
  9016. translations of the code
  9017. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  9018. and
  9019. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  9020. respectively. In particular, we start
  9021. \racket{\code{block\_4}}\python{\code{block\_6}}
  9022. with the comparison
  9023. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  9024. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  9025. or \racket{\code{block\_3}}\python{\code{block\_5}},
  9026. which correspond to the two branches of the outer \key{if}, that is,
  9027. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  9028. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  9029. %
  9030. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  9031. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  9032. %
  9033. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  9034. {\if\edition\racketEd
  9035. \subsection{Interactions between Explicate and Shrink}
  9036. The way in which the \code{shrink} pass transforms logical operations
  9037. such as \code{and} and \code{or} can impact the quality of code
  9038. generated by \code{explicate\_control}. For example, consider the
  9039. following program:
  9040. % cond_test_21.rkt, and_eq_input.py
  9041. \begin{lstlisting}
  9042. (if (and (eq? (read) 0) (eq? (read) 1))
  9043. 0
  9044. 42)
  9045. \end{lstlisting}
  9046. The \code{and} operation should transform into something that the
  9047. \code{explicate\_pred} function can analyze and descend through to
  9048. reach the underlying \code{eq?} conditions. Ideally, for this program
  9049. your \code{explicate\_control} pass should generate code similar to
  9050. the following:
  9051. \begin{center}
  9052. \begin{minipage}{\textwidth}
  9053. \begin{lstlisting}
  9054. start:
  9055. tmp1 = (read);
  9056. if (eq? tmp1 0) goto block40;
  9057. else goto block39;
  9058. block40:
  9059. tmp2 = (read);
  9060. if (eq? tmp2 1) goto block38;
  9061. else goto block39;
  9062. block38:
  9063. return 0;
  9064. block39:
  9065. return 42;
  9066. \end{lstlisting}
  9067. \end{minipage}
  9068. \end{center}
  9069. \fi}
  9070. \begin{exercise}\normalfont\normalsize
  9071. \racket{
  9072. Implement the pass \code{explicate\_control} by adding the cases for
  9073. Boolean constants and \key{if} to the \code{explicate\_tail} and
  9074. \code{explicate\_assign} functions. Implement the auxiliary function
  9075. \code{explicate\_pred} for predicate contexts.}
  9076. \python{Implement \code{explicate\_control} pass with its
  9077. four auxiliary functions.}
  9078. %
  9079. Create test cases that exercise all the new cases in the code for
  9080. this pass.
  9081. %
  9082. {\if\edition\racketEd
  9083. Add the following entry to the list of \code{passes} in
  9084. \code{run-tests.rkt}:
  9085. \begin{lstlisting}
  9086. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9087. \end{lstlisting}
  9088. and then run \code{run-tests.rkt} to test your compiler.
  9089. \fi}
  9090. \end{exercise}
  9091. \section{Select Instructions}
  9092. \label{sec:select-Lif}
  9093. \index{subject}{select instructions}
  9094. The \code{select\_instructions} pass translates \LangCIf{} to
  9095. \LangXIfVar{}.
  9096. %
  9097. \racket{Recall that we implement this pass using three auxiliary
  9098. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9099. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9100. %
  9101. \racket{For $\Atm$, we have new cases for the Booleans.}
  9102. %
  9103. \python{We begin with the Boolean constants.}
  9104. As previously discussed, we encode them as integers.
  9105. \[
  9106. \TRUE{} \quad\Rightarrow\quad \key{1}
  9107. \qquad\qquad
  9108. \FALSE{} \quad\Rightarrow\quad \key{0}
  9109. \]
  9110. For translating statements, we discuss some of the cases. The
  9111. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9112. discussed at the beginning of this section. Given an assignment, if
  9113. the left-hand-side variable is the same as the argument of \code{not},
  9114. then just the \code{xorq} instruction suffices.
  9115. \[
  9116. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9117. \quad\Rightarrow\quad
  9118. \key{xorq}~\key{\$}1\key{,}~\Var
  9119. \]
  9120. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9121. semantics of x86. In the following translation, let $\Arg$ be the
  9122. result of translating $\Atm$ to x86.
  9123. \[
  9124. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9125. \quad\Rightarrow\quad
  9126. \begin{array}{l}
  9127. \key{movq}~\Arg\key{,}~\Var\\
  9128. \key{xorq}~\key{\$}1\key{,}~\Var
  9129. \end{array}
  9130. \]
  9131. Next consider the cases for equality comparisons. Translating this
  9132. operation to x86 is slightly involved due to the unusual nature of the
  9133. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9134. We recommend translating an assignment with an equality on the
  9135. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9136. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9137. \begin{tabular}{lll}
  9138. \begin{minipage}{0.4\textwidth}
  9139. $\CASSIGN{\Var}{ \CEQ{\Atm_1}{\Atm_2} }$
  9140. \end{minipage}
  9141. &
  9142. $\Rightarrow$
  9143. &
  9144. \begin{minipage}{0.4\textwidth}
  9145. \begin{lstlisting}
  9146. cmpq |$\Arg_2$|, |$\Arg_1$|
  9147. sete %al
  9148. movzbq %al, |$\Var$|
  9149. \end{lstlisting}
  9150. \end{minipage}
  9151. \end{tabular} \\
  9152. The translations for the other comparison operators are similar to
  9153. this but use different condition codes for the \code{set} instruction.
  9154. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9155. \key{goto} and \key{if} statements. Both are straightforward to
  9156. translate to x86.}
  9157. %
  9158. A \key{goto} statement becomes a jump instruction.
  9159. \[
  9160. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9161. \]
  9162. %
  9163. An \key{if} statement becomes a compare instruction followed by a
  9164. conditional jump (for the \emph{then} branch), and the fall-through is to
  9165. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9166. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9167. \begin{tabular}{lll}
  9168. \begin{minipage}{0.4\textwidth}
  9169. \begin{lstlisting}
  9170. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9171. goto |$\ell_1$||$\racket{\key{;}}$|
  9172. else|$\python{\key{:}}$|
  9173. goto |$\ell_2$||$\racket{\key{;}}$|
  9174. \end{lstlisting}
  9175. \end{minipage}
  9176. &
  9177. $\Rightarrow$
  9178. &
  9179. \begin{minipage}{0.4\textwidth}
  9180. \begin{lstlisting}
  9181. cmpq |$\Arg_2$|, |$\Arg_1$|
  9182. je |$\ell_1$|
  9183. jmp |$\ell_2$|
  9184. \end{lstlisting}
  9185. \end{minipage}
  9186. \end{tabular} \\
  9187. Again, the translations for the other comparison operators are similar to this
  9188. but use different condition codes for the conditional jump instruction.
  9189. \python{Regarding the \key{return} statement, we recommend treating it
  9190. as an assignment to the \key{rax} register followed by a jump to the
  9191. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9192. \begin{exercise}\normalfont\normalsize
  9193. Expand your \code{select\_instructions} pass to handle the new
  9194. features of the \LangCIf{} language.
  9195. %
  9196. {\if\edition\racketEd
  9197. Add the following entry to the list of \code{passes} in
  9198. \code{run-tests.rkt}
  9199. \begin{lstlisting}
  9200. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9201. \end{lstlisting}
  9202. \fi}
  9203. %
  9204. Run the script to test your compiler on all the test programs.
  9205. \end{exercise}
  9206. \section{Register Allocation}
  9207. \label{sec:register-allocation-Lif}
  9208. \index{subject}{register allocation}
  9209. The changes required for compiling \LangIf{} affect liveness analysis,
  9210. building the interference graph, and assigning homes, but the graph
  9211. coloring algorithm itself does not change.
  9212. \subsection{Liveness Analysis}
  9213. \label{sec:liveness-analysis-Lif}
  9214. \index{subject}{liveness analysis}
  9215. Recall that for \LangVar{} we implemented liveness analysis for a
  9216. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9217. the addition of \key{if} expressions to \LangIf{},
  9218. \code{explicate\_control} produces many basic blocks.
  9219. %% We recommend that you create a new auxiliary function named
  9220. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9221. %% control-flow graph.
  9222. The first question is, in what order should we process the basic blocks?
  9223. Recall that to perform liveness analysis on a basic block we need to
  9224. know the live-after set for the last instruction in the block. If a
  9225. basic block has no successors (i.e., contains no jumps to other
  9226. blocks), then it has an empty live-after set and we can immediately
  9227. apply liveness analysis to it. If a basic block has some successors,
  9228. then we need to complete liveness analysis on those blocks
  9229. first. These ordering constraints are the reverse of a
  9230. \emph{topological order}\index{subject}{topological order} on a graph
  9231. representation of the program. In particular, the \emph{control flow
  9232. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9233. of a program has a node for each basic block and an edge for each jump
  9234. from one block to another. It is straightforward to generate a CFG
  9235. from the dictionary of basic blocks. One then transposes the CFG and
  9236. applies the topological sort algorithm.
  9237. %
  9238. %
  9239. \racket{We recommend using the \code{tsort} and \code{transpose}
  9240. functions of the Racket \code{graph} package to accomplish this.}
  9241. %
  9242. \python{We provide implementations of \code{topological\_sort} and
  9243. \code{transpose} in the file \code{graph.py} of the support code.}
  9244. %
  9245. As an aside, a topological ordering is only guaranteed to exist if the
  9246. graph does not contain any cycles. This is the case for the
  9247. control-flow graphs that we generate from \LangIf{} programs.
  9248. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9249. and learn how to handle cycles in the control-flow graph.
  9250. \racket{You need to construct a directed graph to represent the
  9251. control-flow graph. Do not use the \code{directed-graph} of the
  9252. \code{graph} package because that allows at most one edge
  9253. between each pair of vertices, whereas a control-flow graph may have
  9254. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9255. file in the support code implements a graph representation that
  9256. allows multiple edges between a pair of vertices.}
  9257. {\if\edition\racketEd
  9258. The next question is how to analyze jump instructions. Recall that in
  9259. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9260. \code{label->live} that maps each label to the set of live locations
  9261. at the beginning of its block. We use \code{label->live} to determine
  9262. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9263. that we have many basic blocks, \code{label->live} needs to be updated
  9264. as we process the blocks. In particular, after performing liveness
  9265. analysis on a block, we take the live-before set of its first
  9266. instruction and associate that with the block's label in the
  9267. \code{label->live} alist.
  9268. \fi}
  9269. %
  9270. {\if\edition\pythonEd\pythonColor
  9271. %
  9272. The next question is how to analyze jump instructions. The locations
  9273. that are live before a \code{jmp} should be the locations in
  9274. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9275. maintaining a dictionary named \code{live\_before\_block} that maps each
  9276. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9277. block. After performing liveness analysis on each block, we take the
  9278. live-before set of its first instruction and associate that with the
  9279. block's label in the \code{live\_before\_block} dictionary.
  9280. %
  9281. \fi}
  9282. In \LangXIfVar{} we also have the conditional jump
  9283. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9284. this instruction is particularly interesting because during
  9285. compilation, we do not know which way a conditional jump will go. Thus
  9286. we do not know whether to use the live-before set for the block
  9287. associated with the $\itm{label}$ or the live-before set for the
  9288. following instruction. So we use both, by taking the union of the
  9289. live-before sets from the following instruction and from the mapping
  9290. for $\itm{label}$ in
  9291. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9292. The auxiliary functions for computing the variables in an
  9293. instruction's argument and for computing the variables read-from ($R$)
  9294. or written-to ($W$) by an instruction need to be updated to handle the
  9295. new kinds of arguments and instructions in \LangXIfVar{}.
  9296. \begin{exercise}\normalfont\normalsize
  9297. {\if\edition\racketEd
  9298. %
  9299. Update the \code{uncover\_live} pass to apply liveness analysis to
  9300. every basic block in the program.
  9301. %
  9302. Add the following entry to the list of \code{passes} in the
  9303. \code{run-tests.rkt} script:
  9304. \begin{lstlisting}
  9305. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9306. \end{lstlisting}
  9307. \fi}
  9308. {\if\edition\pythonEd\pythonColor
  9309. %
  9310. Update the \code{uncover\_live} function to perform liveness analysis,
  9311. in reverse topological order, on all the basic blocks in the
  9312. program.
  9313. %
  9314. \fi}
  9315. % Check that the live-after sets that you generate for
  9316. % example X matches the following... -Jeremy
  9317. \end{exercise}
  9318. \subsection{Build the Interference Graph}
  9319. \label{sec:build-interference-Lif}
  9320. Many of the new instructions in \LangXIfVar{} can be handled in the
  9321. same way as the instructions in \LangXVar{}.
  9322. % Thus, if your code was
  9323. % already quite general, it will not need to be changed to handle the
  9324. % new instructions. If your code is not general enough, we recommend that
  9325. % you change your code to be more general. For example, you can factor
  9326. % out the computing of the the read and write sets for each kind of
  9327. % instruction into auxiliary functions.
  9328. %
  9329. Some instructions, such as the \key{movzbq} instruction, require special care,
  9330. similar to the \key{movq} instruction. Refer to rule number 1 in
  9331. section~\ref{sec:build-interference}.
  9332. \begin{exercise}\normalfont\normalsize
  9333. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9334. {\if\edition\racketEd
  9335. Add the following entries to the list of \code{passes} in the
  9336. \code{run-tests.rkt} script:
  9337. \begin{lstlisting}
  9338. (list "build_interference" build_interference interp-pseudo-x86-1)
  9339. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9340. \end{lstlisting}
  9341. \fi}
  9342. % Check that the interference graph that you generate for
  9343. % example X matches the following graph G... -Jeremy
  9344. \end{exercise}
  9345. \section{Patch Instructions}
  9346. The new instructions \key{cmpq} and \key{movzbq} have some special
  9347. restrictions that need to be handled in the \code{patch\_instructions}
  9348. pass.
  9349. %
  9350. The second argument of the \key{cmpq} instruction must not be an
  9351. immediate value (such as an integer). So, if you are comparing two
  9352. immediates, we recommend inserting a \key{movq} instruction to put the
  9353. second argument in \key{rax}. On the other hand, if you implemented
  9354. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9355. update it for \LangIf{} and then this situation would not arise.
  9356. %
  9357. As usual, \key{cmpq} may have at most one memory reference.
  9358. %
  9359. The second argument of the \key{movzbq} must be a register.
  9360. \begin{exercise}\normalfont\normalsize
  9361. %
  9362. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9363. %
  9364. {\if\edition\racketEd
  9365. Add the following entry to the list of \code{passes} in
  9366. \code{run-tests.rkt}, and then run this script to test your compiler.
  9367. \begin{lstlisting}
  9368. (list "patch_instructions" patch_instructions interp-x86-1)
  9369. \end{lstlisting}
  9370. \fi}
  9371. \end{exercise}
  9372. {\if\edition\pythonEd\pythonColor
  9373. \section{Generate Prelude and Conclusion}
  9374. \label{sec:prelude-conclusion-cond}
  9375. The generation of the \code{main} function with its prelude and
  9376. conclusion must change to accommodate how the program now consists of
  9377. one or more basic blocks. After the prelude in \code{main}, jump to
  9378. the \code{start} block. Place the conclusion in a basic block labeled
  9379. with \code{conclusion}.
  9380. \fi}
  9381. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9382. \LangIf{} translated to x86, showing the results of
  9383. \code{explicate\_control}, \code{select\_instructions}, and the final
  9384. x86 assembly.
  9385. \begin{figure}[tbp]
  9386. \begin{tcolorbox}[colback=white]
  9387. {\if\edition\racketEd
  9388. \begin{tabular}{lll}
  9389. \begin{minipage}{0.4\textwidth}
  9390. % cond_test_20.rkt, eq_input.py
  9391. \begin{lstlisting}
  9392. (if (eq? (read) 1) 42 0)
  9393. \end{lstlisting}
  9394. $\Downarrow$
  9395. \begin{lstlisting}
  9396. start:
  9397. tmp7951 = (read);
  9398. if (eq? tmp7951 1)
  9399. goto block7952;
  9400. else
  9401. goto block7953;
  9402. block7952:
  9403. return 42;
  9404. block7953:
  9405. return 0;
  9406. \end{lstlisting}
  9407. $\Downarrow$
  9408. \begin{lstlisting}
  9409. start:
  9410. callq read_int
  9411. movq %rax, tmp7951
  9412. cmpq $1, tmp7951
  9413. je block7952
  9414. jmp block7953
  9415. block7953:
  9416. movq $0, %rax
  9417. jmp conclusion
  9418. block7952:
  9419. movq $42, %rax
  9420. jmp conclusion
  9421. \end{lstlisting}
  9422. \end{minipage}
  9423. &
  9424. $\Rightarrow\qquad$
  9425. \begin{minipage}{0.4\textwidth}
  9426. \begin{lstlisting}
  9427. start:
  9428. callq read_int
  9429. movq %rax, %rcx
  9430. cmpq $1, %rcx
  9431. je block7952
  9432. jmp block7953
  9433. block7953:
  9434. movq $0, %rax
  9435. jmp conclusion
  9436. block7952:
  9437. movq $42, %rax
  9438. jmp conclusion
  9439. .globl main
  9440. main:
  9441. pushq %rbp
  9442. movq %rsp, %rbp
  9443. pushq %r13
  9444. pushq %r12
  9445. pushq %rbx
  9446. pushq %r14
  9447. subq $0, %rsp
  9448. jmp start
  9449. conclusion:
  9450. addq $0, %rsp
  9451. popq %r14
  9452. popq %rbx
  9453. popq %r12
  9454. popq %r13
  9455. popq %rbp
  9456. retq
  9457. \end{lstlisting}
  9458. \end{minipage}
  9459. \end{tabular}
  9460. \fi}
  9461. {\if\edition\pythonEd\pythonColor
  9462. \begin{tabular}{lll}
  9463. \begin{minipage}{0.4\textwidth}
  9464. % cond_test_20.rkt, eq_input.py
  9465. \begin{lstlisting}
  9466. print(42 if input_int() == 1 else 0)
  9467. \end{lstlisting}
  9468. $\Downarrow$
  9469. \begin{lstlisting}
  9470. start:
  9471. tmp_0 = input_int()
  9472. if tmp_0 == 1:
  9473. goto block_3
  9474. else:
  9475. goto block_4
  9476. block_3:
  9477. tmp_1 = 42
  9478. goto block_2
  9479. block_4:
  9480. tmp_1 = 0
  9481. goto block_2
  9482. block_2:
  9483. print(tmp_1)
  9484. return 0
  9485. \end{lstlisting}
  9486. $\Downarrow$
  9487. \begin{lstlisting}
  9488. start:
  9489. callq read_int
  9490. movq %rax, tmp_0
  9491. cmpq 1, tmp_0
  9492. je block_3
  9493. jmp block_4
  9494. block_3:
  9495. movq 42, tmp_1
  9496. jmp block_2
  9497. block_4:
  9498. movq 0, tmp_1
  9499. jmp block_2
  9500. block_2:
  9501. movq tmp_1, %rdi
  9502. callq print_int
  9503. movq 0, %rax
  9504. jmp conclusion
  9505. \end{lstlisting}
  9506. \end{minipage}
  9507. &
  9508. $\Rightarrow\qquad$
  9509. \begin{minipage}{0.4\textwidth}
  9510. \begin{lstlisting}
  9511. .globl main
  9512. main:
  9513. pushq %rbp
  9514. movq %rsp, %rbp
  9515. subq $0, %rsp
  9516. jmp start
  9517. start:
  9518. callq read_int
  9519. movq %rax, %rcx
  9520. cmpq $1, %rcx
  9521. je block_3
  9522. jmp block_4
  9523. block_3:
  9524. movq $42, %rcx
  9525. jmp block_2
  9526. block_4:
  9527. movq $0, %rcx
  9528. jmp block_2
  9529. block_2:
  9530. movq %rcx, %rdi
  9531. callq print_int
  9532. movq $0, %rax
  9533. jmp conclusion
  9534. conclusion:
  9535. addq $0, %rsp
  9536. popq %rbp
  9537. retq
  9538. \end{lstlisting}
  9539. \end{minipage}
  9540. \end{tabular}
  9541. \fi}
  9542. \end{tcolorbox}
  9543. \caption{Example compilation of an \key{if} expression to x86, showing
  9544. the results of \code{explicate\_control},
  9545. \code{select\_instructions}, and the final x86 assembly code. }
  9546. \label{fig:if-example-x86}
  9547. \end{figure}
  9548. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9549. compilation of \LangIf{}.
  9550. \begin{figure}[htbp]
  9551. \begin{tcolorbox}[colback=white]
  9552. {\if\edition\racketEd
  9553. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9554. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9555. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9556. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9557. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9558. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9559. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9560. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9561. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9562. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9563. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9564. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9565. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9566. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9567. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9568. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9569. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9570. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9571. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9572. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9573. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9574. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9575. \end{tikzpicture}
  9576. \fi}
  9577. {\if\edition\pythonEd\pythonColor
  9578. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9579. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9580. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9581. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9582. \node (C-1) at (0,0) {\large \LangCIf{}};
  9583. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9584. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9585. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9586. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9587. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9588. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9589. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9590. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9591. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9592. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9593. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9594. \end{tikzpicture}
  9595. \fi}
  9596. \end{tcolorbox}
  9597. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9598. \label{fig:Lif-passes}
  9599. \end{figure}
  9600. \section{Challenge: Optimize Blocks and Remove Jumps}
  9601. \label{sec:opt-jumps}
  9602. We discuss two challenges that involve optimizing the control-flow of
  9603. the program.
  9604. \subsection{Optimize Blocks}
  9605. The algorithm for \code{explicate\_control} that we discussed in
  9606. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9607. blocks. It creates a block whenever a continuation \emph{might} get
  9608. used more than once (for example, whenever the \code{cont} parameter
  9609. is passed into two or more recursive calls). However, some
  9610. continuation arguments may not be used at all. Consider the case for
  9611. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9612. the \code{els} continuation.
  9613. %
  9614. {\if\edition\racketEd
  9615. The following example program falls into this
  9616. case, and it creates two unused blocks.
  9617. \begin{center}
  9618. \begin{tabular}{lll}
  9619. \begin{minipage}{0.4\textwidth}
  9620. % cond_test_82.rkt
  9621. \begin{lstlisting}
  9622. (let ([y (if #t
  9623. (read)
  9624. (if (eq? (read) 0)
  9625. 777
  9626. (let ([x (read)])
  9627. (+ 1 x))))])
  9628. (+ y 2))
  9629. \end{lstlisting}
  9630. \end{minipage}
  9631. &
  9632. $\Rightarrow$
  9633. &
  9634. \begin{minipage}{0.4\textwidth}
  9635. \begin{lstlisting}
  9636. start:
  9637. y = (read);
  9638. goto block_5;
  9639. block_5:
  9640. return (+ y 2);
  9641. block_6:
  9642. y = 777;
  9643. goto block_5;
  9644. block_7:
  9645. x = (read);
  9646. y = (+ 1 x2);
  9647. goto block_5;
  9648. \end{lstlisting}
  9649. \end{minipage}
  9650. \end{tabular}
  9651. \end{center}
  9652. \fi}
  9653. {\if\edition\pythonEd
  9654. The following example program falls into this
  9655. case, and it creates the unused \code{block\_9}.
  9656. \begin{center}
  9657. \begin{minipage}{0.4\textwidth}
  9658. % if/if_true.py
  9659. \begin{lstlisting}
  9660. if True:
  9661. print(0)
  9662. else:
  9663. x = 1 if False else 2
  9664. print(x)
  9665. \end{lstlisting}
  9666. \end{minipage}
  9667. $\Rightarrow\qquad\qquad$
  9668. \begin{minipage}{0.4\textwidth}
  9669. \begin{lstlisting}
  9670. start:
  9671. print(0)
  9672. goto block_8
  9673. block_9:
  9674. print(x)
  9675. goto block_8
  9676. block_8:
  9677. return 0
  9678. \end{lstlisting}
  9679. \end{minipage}
  9680. \end{center}
  9681. \fi}
  9682. The question is, how can we decide whether to create a basic block?
  9683. \emph{Lazy evaluation}\index{subject}{lazy
  9684. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9685. delaying the creation of a basic block until the point in time at which
  9686. we know that it will be used.
  9687. %
  9688. {\if\edition\racketEd
  9689. %
  9690. Racket provides support for
  9691. lazy evaluation with the
  9692. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9693. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9694. \index{subject}{delay} creates a
  9695. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9696. expressions is postponed. When \key{(force}
  9697. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9698. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9699. result of $e_n$ is cached in the promise and returned. If \code{force}
  9700. is applied again to the same promise, then the cached result is
  9701. returned. If \code{force} is applied to an argument that is not a
  9702. promise, \code{force} simply returns the argument.
  9703. %
  9704. \fi}
  9705. %
  9706. {\if\edition\pythonEd\pythonColor
  9707. %
  9708. Although Python does not provide direct support for lazy evaluation,
  9709. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9710. by wrapping it inside a function with no parameters. We \emph{force}
  9711. its evaluation by calling the function. However, we might need to
  9712. force multiple times, so we store the result of calling the
  9713. function instead of recomputing it each time. The following
  9714. \code{Promise} class handles this memoization process.
  9715. \begin{minipage}{0.8\textwidth}
  9716. \begin{lstlisting}
  9717. @dataclass
  9718. class Promise:
  9719. fun : typing.Any
  9720. cache : list[stmt] = None
  9721. def force(self):
  9722. if self.cache is None:
  9723. self.cache = self.fun(); return self.cache
  9724. else:
  9725. return self.cache
  9726. \end{lstlisting}
  9727. \end{minipage}
  9728. \noindent However, in some cases of \code{explicate\_pred}, we return
  9729. a list of statements, and in other cases we return a function that
  9730. computes a list of statements. To uniformly deal with both regular
  9731. data and promises, we define the following \code{force} function that
  9732. checks whether its input is delayed (i.e., whether it is a
  9733. \code{Promise}) and then either (1) forces the promise or (2) returns
  9734. the input.
  9735. %
  9736. \begin{lstlisting}
  9737. def force(promise):
  9738. if isinstance(promise, Promise):
  9739. return promise.force()
  9740. else:
  9741. return promise
  9742. \end{lstlisting}
  9743. %
  9744. \fi}
  9745. We use promises for the input and output of the functions
  9746. \code{explicate\_pred}, \code{explicate\_assign},
  9747. %
  9748. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9749. %
  9750. So, instead of taking and returning \racket{$\Tail$
  9751. expressions}\python{lists of statements}, they take and return
  9752. promises. Furthermore, when we come to a situation in which a
  9753. continuation might be used more than once, as in the case for
  9754. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9755. that creates a basic block for each continuation (if there is not
  9756. already one) and then returns a \code{goto} statement to that basic
  9757. block. When we come to a situation in which we have a promise but need an
  9758. actual piece of code, for example, to create a larger piece of code with a
  9759. constructor such as \code{Seq}, then insert a call to \code{force}.
  9760. %
  9761. {\if\edition\racketEd
  9762. %
  9763. Also, we must modify the \code{create\_block} function to begin with
  9764. \code{delay} to create a promise. When forced, this promise forces the
  9765. original promise. If that returns a \code{Goto} (because the block was
  9766. already added to \code{basic-blocks}), then we return the
  9767. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9768. return a \code{Goto} to the new label.
  9769. \begin{center}
  9770. \begin{minipage}{\textwidth}
  9771. \begin{lstlisting}
  9772. (define (create_block tail)
  9773. (delay
  9774. (define t (force tail))
  9775. (match t
  9776. [(Goto label) (Goto label)]
  9777. [else
  9778. (let ([label (gensym 'block)])
  9779. (set! basic-blocks (cons (cons label t) basic-blocks))
  9780. (Goto label))])))
  9781. \end{lstlisting}
  9782. \end{minipage}
  9783. \end{center}
  9784. \fi}
  9785. {\if\edition\pythonEd\pythonColor
  9786. %
  9787. Here is the new version of the \code{create\_block} auxiliary function
  9788. that delays the creation of the new basic block.\\
  9789. \begin{minipage}{\textwidth}
  9790. \begin{lstlisting}
  9791. def create_block(promise, basic_blocks):
  9792. def delay():
  9793. stmts = force(promise)
  9794. match stmts:
  9795. case [Goto(l)]:
  9796. return [Goto(l)]
  9797. case _:
  9798. label = label_name(generate_name('block'))
  9799. basic_blocks[label] = stmts
  9800. return [Goto(label)]
  9801. return Promise(delay)
  9802. \end{lstlisting}
  9803. \end{minipage}
  9804. \fi}
  9805. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9806. improved \code{explicate\_control} on this example.
  9807. \racket{As you can see, the number of basic blocks has been reduced
  9808. from four blocks to two blocks.}%
  9809. \python{As you can see, the number of basic blocks has been reduced
  9810. from three blocks to two blocks.}
  9811. \begin{figure}[tbp]
  9812. \begin{tcolorbox}[colback=white]
  9813. {\if\edition\racketEd
  9814. \begin{tabular}{lll}
  9815. \begin{minipage}{0.45\textwidth}
  9816. % cond_test_82.rkt
  9817. \begin{lstlisting}
  9818. (let ([y (if #t
  9819. (read)
  9820. (if (eq? (read) 0)
  9821. 777
  9822. (let ([x (read)])
  9823. (+ 1 x))))])
  9824. (+ y 2))
  9825. \end{lstlisting}
  9826. \end{minipage}
  9827. &
  9828. $\quad\Rightarrow\quad$
  9829. &
  9830. \begin{minipage}{0.4\textwidth}
  9831. \begin{lstlisting}
  9832. start:
  9833. y = (read);
  9834. goto block_5;
  9835. block_5:
  9836. return (+ y 2);
  9837. \end{lstlisting}
  9838. \end{minipage}
  9839. \end{tabular}
  9840. \fi}
  9841. {\if\edition\pythonEd\pythonColor
  9842. \begin{tabular}{lll}
  9843. \begin{minipage}{0.4\textwidth}
  9844. % if/if_true.py
  9845. \begin{lstlisting}
  9846. if True:
  9847. print(0)
  9848. else:
  9849. x = 1 if False else 2
  9850. print(x)
  9851. \end{lstlisting}
  9852. \end{minipage}
  9853. &
  9854. $\Rightarrow$
  9855. &
  9856. \begin{minipage}{0.55\textwidth}
  9857. \begin{lstlisting}
  9858. start:
  9859. print(0)
  9860. goto block_4
  9861. block_4:
  9862. return 0
  9863. \end{lstlisting}
  9864. \end{minipage}
  9865. \end{tabular}
  9866. \fi}
  9867. \end{tcolorbox}
  9868. \caption{Translation from \LangIf{} to \LangCIf{}
  9869. via the improved \code{explicate\_control}.}
  9870. \label{fig:explicate-control-challenge}
  9871. \end{figure}
  9872. %% Recall that in the example output of \code{explicate\_control} in
  9873. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9874. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9875. %% block. The first goal of this challenge assignment is to remove those
  9876. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9877. %% \code{explicate\_control} on the left and shows the result of bypassing
  9878. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9879. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9880. %% \code{block55}. The optimized code on the right of
  9881. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9882. %% \code{then} branch jumping directly to \code{block55}. The story is
  9883. %% similar for the \code{else} branch, as well as for the two branches in
  9884. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9885. %% have been optimized in this way, there are no longer any jumps to
  9886. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9887. %% \begin{figure}[tbp]
  9888. %% \begin{tabular}{lll}
  9889. %% \begin{minipage}{0.4\textwidth}
  9890. %% \begin{lstlisting}
  9891. %% block62:
  9892. %% tmp54 = (read);
  9893. %% if (eq? tmp54 2) then
  9894. %% goto block59;
  9895. %% else
  9896. %% goto block60;
  9897. %% block61:
  9898. %% tmp53 = (read);
  9899. %% if (eq? tmp53 0) then
  9900. %% goto block57;
  9901. %% else
  9902. %% goto block58;
  9903. %% block60:
  9904. %% goto block56;
  9905. %% block59:
  9906. %% goto block55;
  9907. %% block58:
  9908. %% goto block56;
  9909. %% block57:
  9910. %% goto block55;
  9911. %% block56:
  9912. %% return (+ 700 77);
  9913. %% block55:
  9914. %% return (+ 10 32);
  9915. %% start:
  9916. %% tmp52 = (read);
  9917. %% if (eq? tmp52 1) then
  9918. %% goto block61;
  9919. %% else
  9920. %% goto block62;
  9921. %% \end{lstlisting}
  9922. %% \end{minipage}
  9923. %% &
  9924. %% $\Rightarrow$
  9925. %% &
  9926. %% \begin{minipage}{0.55\textwidth}
  9927. %% \begin{lstlisting}
  9928. %% block62:
  9929. %% tmp54 = (read);
  9930. %% if (eq? tmp54 2) then
  9931. %% goto block55;
  9932. %% else
  9933. %% goto block56;
  9934. %% block61:
  9935. %% tmp53 = (read);
  9936. %% if (eq? tmp53 0) then
  9937. %% goto block55;
  9938. %% else
  9939. %% goto block56;
  9940. %% block56:
  9941. %% return (+ 700 77);
  9942. %% block55:
  9943. %% return (+ 10 32);
  9944. %% start:
  9945. %% tmp52 = (read);
  9946. %% if (eq? tmp52 1) then
  9947. %% goto block61;
  9948. %% else
  9949. %% goto block62;
  9950. %% \end{lstlisting}
  9951. %% \end{minipage}
  9952. %% \end{tabular}
  9953. %% \caption{Optimize jumps by removing trivial blocks.}
  9954. %% \label{fig:optimize-jumps}
  9955. %% \end{figure}
  9956. %% The name of this pass is \code{optimize-jumps}. We recommend
  9957. %% implementing this pass in two phases. The first phrase builds a hash
  9958. %% table that maps labels to possibly improved labels. The second phase
  9959. %% changes the target of each \code{goto} to use the improved label. If
  9960. %% the label is for a trivial block, then the hash table should map the
  9961. %% label to the first non-trivial block that can be reached from this
  9962. %% label by jumping through trivial blocks. If the label is for a
  9963. %% non-trivial block, then the hash table should map the label to itself;
  9964. %% we do not want to change jumps to non-trivial blocks.
  9965. %% The first phase can be accomplished by constructing an empty hash
  9966. %% table, call it \code{short-cut}, and then iterating over the control
  9967. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9968. %% then update the hash table, mapping the block's source to the target
  9969. %% of the \code{goto}. Also, the hash table may already have mapped some
  9970. %% labels to the block's source, to you must iterate through the hash
  9971. %% table and update all of those so that they instead map to the target
  9972. %% of the \code{goto}.
  9973. %% For the second phase, we recommend iterating through the $\Tail$ of
  9974. %% each block in the program, updating the target of every \code{goto}
  9975. %% according to the mapping in \code{short-cut}.
  9976. \begin{exercise}\normalfont\normalsize
  9977. Implement the improvements to the \code{explicate\_control} pass.
  9978. Check that it removes trivial blocks in a few example programs. Then
  9979. check that your compiler still passes all your tests.
  9980. \end{exercise}
  9981. \subsection{Remove Jumps}
  9982. There is an opportunity for removing jumps that is apparent in the
  9983. example of figure~\ref{fig:explicate-control-challenge}. The
  9984. \code{start} block ends with a jump to
  9985. \racket{\code{block\_5}}\python{\code{block\_4}}, and there are no
  9986. other jumps to \racket{\code{block\_5}}\python{\code{block\_4}} in
  9987. the rest of the program. In this situation we can avoid the runtime
  9988. overhead of this jump by merging
  9989. \racket{\code{block\_5}}\python{\code{block\_4}} into the preceding
  9990. block, which in this case is the \code{start} block.
  9991. Figure~\ref{fig:remove-jumps} shows the output of
  9992. \code{allocate\_registers} on the left and the result of this
  9993. optimization on the right.
  9994. \begin{figure}[tbp]
  9995. \begin{tcolorbox}[colback=white]
  9996. {\if\edition\racketEd
  9997. \begin{tabular}{lll}
  9998. \begin{minipage}{0.5\textwidth}
  9999. % cond_test_82.rkt
  10000. \begin{lstlisting}
  10001. start:
  10002. callq read_int
  10003. movq %rax, %rcx
  10004. jmp block_5
  10005. block_5:
  10006. movq %rcx, %rax
  10007. addq $2, %rax
  10008. jmp conclusion
  10009. \end{lstlisting}
  10010. \end{minipage}
  10011. &
  10012. $\Rightarrow\qquad$
  10013. \begin{minipage}{0.4\textwidth}
  10014. \begin{lstlisting}
  10015. start:
  10016. callq read_int
  10017. movq %rax, %rcx
  10018. movq %rcx, %rax
  10019. addq $2, %rax
  10020. jmp conclusion
  10021. \end{lstlisting}
  10022. \end{minipage}
  10023. \end{tabular}
  10024. \fi}
  10025. {\if\edition\pythonEd\pythonColor
  10026. \begin{tabular}{lll}
  10027. \begin{minipage}{0.5\textwidth}
  10028. % cond_test_20.rkt
  10029. \begin{lstlisting}
  10030. start:
  10031. callq read_int
  10032. movq %rax, tmp_0
  10033. cmpq 1, tmp_0
  10034. je block_3
  10035. jmp block_4
  10036. block_3:
  10037. movq 42, tmp_1
  10038. jmp block_2
  10039. block_4:
  10040. movq 0, tmp_1
  10041. jmp block_2
  10042. block_2:
  10043. movq tmp_1, %rdi
  10044. callq print_int
  10045. movq 0, %rax
  10046. jmp conclusion
  10047. \end{lstlisting}
  10048. \end{minipage}
  10049. &
  10050. $\Rightarrow\qquad$
  10051. \begin{minipage}{0.4\textwidth}
  10052. \begin{lstlisting}
  10053. start:
  10054. callq read_int
  10055. movq %rax, tmp_0
  10056. cmpq 1, tmp_0
  10057. je block_3
  10058. movq 0, tmp_1
  10059. jmp block_2
  10060. block_3:
  10061. movq 42, tmp_1
  10062. jmp block_2
  10063. block_2:
  10064. movq tmp_1, %rdi
  10065. callq print_int
  10066. movq 0, %rax
  10067. jmp conclusion
  10068. \end{lstlisting}
  10069. \end{minipage}
  10070. \end{tabular}
  10071. \fi}
  10072. \end{tcolorbox}
  10073. \caption{Merging basic blocks by removing unnecessary jumps.}
  10074. \label{fig:remove-jumps}
  10075. \end{figure}
  10076. \begin{exercise}\normalfont\normalsize
  10077. %
  10078. Implement a pass named \code{remove\_jumps} that merges basic blocks
  10079. into their preceding basic block, when there is only one preceding
  10080. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  10081. %
  10082. {\if\edition\racketEd
  10083. In the \code{run-tests.rkt} script, add the following entry to the
  10084. list of \code{passes} between \code{allocate\_registers}
  10085. and \code{patch\_instructions}:
  10086. \begin{lstlisting}
  10087. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  10088. \end{lstlisting}
  10089. \fi}
  10090. %
  10091. Run the script to test your compiler.
  10092. %
  10093. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10094. blocks on several test programs.
  10095. \end{exercise}
  10096. \section{Further Reading}
  10097. \label{sec:cond-further-reading}
  10098. The algorithm for \code{explicate\_control} is based on the
  10099. \code{expose-basic-blocks} pass in the course notes of
  10100. \citet{Dybvig:2010aa}.
  10101. %
  10102. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10103. \citet{Appel:2003fk}, and is related to translations into continuation
  10104. passing
  10105. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10106. %
  10107. The treatment of conditionals in the \code{explicate\_control} pass is
  10108. similar to short-cut Boolean
  10109. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10110. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10111. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10112. \chapter{Loops and Dataflow Analysis}
  10113. \label{ch:Lwhile}
  10114. \setcounter{footnote}{0}
  10115. % TODO: define R'_8
  10116. % TODO: multi-graph
  10117. {\if\edition\racketEd
  10118. %
  10119. In this chapter we study two features that are the hallmarks of
  10120. imperative programming languages: loops and assignments to local
  10121. variables. The following example demonstrates these new features by
  10122. computing the sum of the first five positive integers:
  10123. % similar to loop_test_1.rkt
  10124. \begin{lstlisting}
  10125. (let ([sum 0])
  10126. (let ([i 5])
  10127. (begin
  10128. (while (> i 0)
  10129. (begin
  10130. (set! sum (+ sum i))
  10131. (set! i (- i 1))))
  10132. sum)))
  10133. \end{lstlisting}
  10134. The \code{while} loop consists of a condition and a
  10135. body.\footnote{The \code{while} loop is not a built-in
  10136. feature of the Racket language, but Racket includes many looping
  10137. constructs and it is straightforward to define \code{while} as a
  10138. macro.} The body is evaluated repeatedly so long as the condition
  10139. remains true.
  10140. %
  10141. The \code{set!} consists of a variable and a right-hand side
  10142. expression. The \code{set!} updates value of the variable to the
  10143. value of the right-hand side.
  10144. %
  10145. The primary purpose of both the \code{while} loop and \code{set!} is
  10146. to cause side effects, so they do not give a meaningful result
  10147. value. Instead, their result is the \code{\#<void>} value. The
  10148. expression \code{(void)} is an explicit way to create the
  10149. \code{\#<void>} value, and it has type \code{Void}. The
  10150. \code{\#<void>} value can be passed around just like other values
  10151. inside an \LangLoop{} program, and it can be compared for equality with
  10152. another \code{\#<void>} value. However, there are no other operations
  10153. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10154. Racket defines the \code{void?} predicate that returns \code{\#t}
  10155. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10156. %
  10157. \footnote{Racket's \code{Void} type corresponds to what is often
  10158. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10159. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10160. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10161. %
  10162. With the addition of side effect-producing features such as
  10163. \code{while} loop and \code{set!}, it is helpful to include a language
  10164. feature for sequencing side effects: the \code{begin} expression. It
  10165. consists of one or more subexpressions that are evaluated
  10166. left to right.
  10167. %
  10168. \fi}
  10169. {\if\edition\pythonEd\pythonColor
  10170. %
  10171. In this chapter we study loops, one of the hallmarks of imperative
  10172. programming languages. The following example demonstrates the
  10173. \code{while} loop by computing the sum of the first five positive
  10174. integers.
  10175. \begin{lstlisting}
  10176. sum = 0
  10177. i = 5
  10178. while i > 0:
  10179. sum = sum + i
  10180. i = i - 1
  10181. print(sum)
  10182. \end{lstlisting}
  10183. The \code{while} loop consists of a condition and a body (a sequence
  10184. of statements). The body is evaluated repeatedly so long as the
  10185. condition remains true.
  10186. %
  10187. \fi}
  10188. \section{The \LangLoop{} Language}
  10189. \newcommand{\LwhileGrammarRacket}{
  10190. \begin{array}{lcl}
  10191. \Type &::=& \key{Void}\\
  10192. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10193. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10194. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10195. \end{array}
  10196. }
  10197. \newcommand{\LwhileASTRacket}{
  10198. \begin{array}{lcl}
  10199. \Type &::=& \key{Void}\\
  10200. \Exp &::=& \SETBANG{\Var}{\Exp}
  10201. \MID \BEGIN{\Exp^{*}}{\Exp}
  10202. \MID \WHILE{\Exp}{\Exp}
  10203. \MID \VOID{}
  10204. \end{array}
  10205. }
  10206. \newcommand{\LwhileGrammarPython}{
  10207. \begin{array}{rcl}
  10208. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10209. \end{array}
  10210. }
  10211. \newcommand{\LwhileASTPython}{
  10212. \begin{array}{lcl}
  10213. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10214. \end{array}
  10215. }
  10216. \begin{figure}[tp]
  10217. \centering
  10218. \begin{tcolorbox}[colback=white]
  10219. \small
  10220. {\if\edition\racketEd
  10221. \[
  10222. \begin{array}{l}
  10223. \gray{\LintGrammarRacket{}} \\ \hline
  10224. \gray{\LvarGrammarRacket{}} \\ \hline
  10225. \gray{\LifGrammarRacket{}} \\ \hline
  10226. \LwhileGrammarRacket \\
  10227. \begin{array}{lcl}
  10228. \LangLoopM{} &::=& \Exp
  10229. \end{array}
  10230. \end{array}
  10231. \]
  10232. \fi}
  10233. {\if\edition\pythonEd\pythonColor
  10234. \[
  10235. \begin{array}{l}
  10236. \gray{\LintGrammarPython} \\ \hline
  10237. \gray{\LvarGrammarPython} \\ \hline
  10238. \gray{\LifGrammarPython} \\ \hline
  10239. \LwhileGrammarPython \\
  10240. \begin{array}{rcl}
  10241. \LangLoopM{} &::=& \Stmt^{*}
  10242. \end{array}
  10243. \end{array}
  10244. \]
  10245. \fi}
  10246. \end{tcolorbox}
  10247. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10248. \label{fig:Lwhile-concrete-syntax}
  10249. \index{subject}{Lwhile@\LangLoop{} concrete syntax}
  10250. \end{figure}
  10251. \begin{figure}[tp]
  10252. \centering
  10253. \begin{tcolorbox}[colback=white]
  10254. \small
  10255. {\if\edition\racketEd
  10256. \[
  10257. \begin{array}{l}
  10258. \gray{\LintOpAST} \\ \hline
  10259. \gray{\LvarASTRacket{}} \\ \hline
  10260. \gray{\LifASTRacket{}} \\ \hline
  10261. \LwhileASTRacket{} \\
  10262. \begin{array}{lcl}
  10263. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10264. \end{array}
  10265. \end{array}
  10266. \]
  10267. \fi}
  10268. {\if\edition\pythonEd\pythonColor
  10269. \[
  10270. \begin{array}{l}
  10271. \gray{\LintASTPython} \\ \hline
  10272. \gray{\LvarASTPython} \\ \hline
  10273. \gray{\LifASTPython} \\ \hline
  10274. \LwhileASTPython \\
  10275. \begin{array}{lcl}
  10276. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10277. \end{array}
  10278. \end{array}
  10279. \]
  10280. \fi}
  10281. \end{tcolorbox}
  10282. \python{
  10283. \index{subject}{While@\texttt{While}}
  10284. }
  10285. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10286. \label{fig:Lwhile-syntax}
  10287. \index{subject}{Lwhile@\LangLoop{} abstract syntax}
  10288. \end{figure}
  10289. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10290. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10291. shows the definition of its abstract syntax.
  10292. %
  10293. The definitional interpreter for \LangLoop{} is shown in
  10294. figure~\ref{fig:interp-Lwhile}.
  10295. %
  10296. {\if\edition\racketEd
  10297. %
  10298. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10299. and \code{Void}, and we make changes to the cases for \code{Var} and
  10300. \code{Let} regarding variables. To support assignment to variables and
  10301. to make their lifetimes indefinite (see the second example in
  10302. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10303. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10304. value.
  10305. %
  10306. Now we discuss the new cases. For \code{SetBang}, we find the
  10307. variable in the environment to obtain a boxed value, and then we change
  10308. it using \code{set-box!} to the result of evaluating the right-hand
  10309. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10310. %
  10311. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10312. if the result is true, (2) evaluate the body.
  10313. The result value of a \code{while} loop is also \code{\#<void>}.
  10314. %
  10315. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10316. subexpressions \itm{es} for their effects and then evaluates
  10317. and returns the result from \itm{body}.
  10318. %
  10319. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10320. %
  10321. \fi}
  10322. {\if\edition\pythonEd\pythonColor
  10323. %
  10324. We add a new case for \code{While} in the \code{interp\_stmts}
  10325. function, in which we repeatedly interpret the \code{body} so long as the
  10326. \code{test} expression remains true.
  10327. %
  10328. \fi}
  10329. \begin{figure}[tbp]
  10330. \begin{tcolorbox}[colback=white]
  10331. {\if\edition\racketEd
  10332. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10333. (define interp-Lwhile-class
  10334. (class interp-Lif-class
  10335. (super-new)
  10336. (define/override ((interp-exp env) e)
  10337. (define recur (interp-exp env))
  10338. (match e
  10339. [(Let x e body)
  10340. (define new-env (dict-set env x (box (recur e))))
  10341. ((interp-exp new-env) body)]
  10342. [(Var x) (unbox (dict-ref env x))]
  10343. [(SetBang x rhs)
  10344. (set-box! (dict-ref env x) (recur rhs))]
  10345. [(WhileLoop cnd body)
  10346. (define (loop)
  10347. (cond [(recur cnd) (recur body) (loop)]
  10348. [else (void)]))
  10349. (loop)]
  10350. [(Begin es body)
  10351. (for ([e es]) (recur e))
  10352. (recur body)]
  10353. [(Void) (void)]
  10354. [else ((super interp-exp env) e)]))
  10355. ))
  10356. (define (interp-Lwhile p)
  10357. (send (new interp-Lwhile-class) interp-program p))
  10358. \end{lstlisting}
  10359. \fi}
  10360. {\if\edition\pythonEd\pythonColor
  10361. \begin{lstlisting}
  10362. class InterpLwhile(InterpLif):
  10363. def interp_stmt(self, s, env, cont):
  10364. match s:
  10365. case While(test, body, []):
  10366. if self.interp_exp(test, env):
  10367. self.interp_stmts(body + [s] + cont, env)
  10368. else:
  10369. return self.interp_stmts(cont, env)
  10370. case _:
  10371. return super().interp_stmt(s, env, cont)
  10372. \end{lstlisting}
  10373. \fi}
  10374. \end{tcolorbox}
  10375. \caption{Interpreter for \LangLoop{}.}
  10376. \label{fig:interp-Lwhile}
  10377. \end{figure}
  10378. The definition of the type checker for \LangLoop{} is shown in
  10379. figure~\ref{fig:type-check-Lwhile}.
  10380. %
  10381. {\if\edition\racketEd
  10382. %
  10383. The type checking of the \code{SetBang} expression requires the type
  10384. of the variable and the right-hand side to agree. The result type is
  10385. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10386. and the result type is \code{Void}. For \code{Begin}, the result type
  10387. is the type of its last subexpression.
  10388. %
  10389. \fi}
  10390. %
  10391. {\if\edition\pythonEd\pythonColor
  10392. %
  10393. A \code{while} loop is well typed if the type of the \code{test}
  10394. expression is \code{bool} and the statements in the \code{body} are
  10395. well typed.
  10396. %
  10397. \fi}
  10398. \begin{figure}[tbp]
  10399. \begin{tcolorbox}[colback=white]
  10400. {\if\edition\racketEd
  10401. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10402. (define type-check-Lwhile-class
  10403. (class type-check-Lif-class
  10404. (super-new)
  10405. (inherit check-type-equal?)
  10406. (define/override (type-check-exp env)
  10407. (lambda (e)
  10408. (define recur (type-check-exp env))
  10409. (match e
  10410. [(SetBang x rhs)
  10411. (define-values (rhs^ rhsT) (recur rhs))
  10412. (define varT (dict-ref env x))
  10413. (check-type-equal? rhsT varT e)
  10414. (values (SetBang x rhs^) 'Void)]
  10415. [(WhileLoop cnd body)
  10416. (define-values (cnd^ Tc) (recur cnd))
  10417. (check-type-equal? Tc 'Boolean e)
  10418. (define-values (body^ Tbody) ((type-check-exp env) body))
  10419. (values (WhileLoop cnd^ body^) 'Void)]
  10420. [(Begin es body)
  10421. (define-values (es^ ts)
  10422. (for/lists (l1 l2) ([e es]) (recur e)))
  10423. (define-values (body^ Tbody) (recur body))
  10424. (values (Begin es^ body^) Tbody)]
  10425. [else ((super type-check-exp env) e)])))
  10426. ))
  10427. (define (type-check-Lwhile p)
  10428. (send (new type-check-Lwhile-class) type-check-program p))
  10429. \end{lstlisting}
  10430. \fi}
  10431. {\if\edition\pythonEd\pythonColor
  10432. \begin{lstlisting}
  10433. class TypeCheckLwhile(TypeCheckLif):
  10434. def type_check_stmts(self, ss, env):
  10435. if len(ss) == 0:
  10436. return
  10437. match ss[0]:
  10438. case While(test, body, []):
  10439. test_t = self.type_check_exp(test, env)
  10440. check_type_equal(bool, test_t, test)
  10441. body_t = self.type_check_stmts(body, env)
  10442. return self.type_check_stmts(ss[1:], env)
  10443. case _:
  10444. return super().type_check_stmts(ss, env)
  10445. \end{lstlisting}
  10446. \fi}
  10447. \end{tcolorbox}
  10448. \caption{Type checker for the \LangLoop{} language.}
  10449. \label{fig:type-check-Lwhile}
  10450. \end{figure}
  10451. {\if\edition\racketEd
  10452. %
  10453. At first glance, the translation of these language features to x86
  10454. seems straightforward because the \LangCIf{} intermediate language
  10455. already supports all the ingredients that we need: assignment,
  10456. \code{goto}, conditional branching, and sequencing. However,
  10457. complications arise, which we discuss in the next section. After
  10458. that we introduce the changes necessary to the existing passes.
  10459. %
  10460. \fi}
  10461. {\if\edition\pythonEd\pythonColor
  10462. %
  10463. At first glance, the translation of \code{while} loops to x86 seems
  10464. straightforward because the \LangCIf{} intermediate language already
  10465. supports \code{goto} and conditional branching. However, there are
  10466. complications that arise, which we discuss in the next section. After
  10467. that we introduce the changes necessary to the existing passes.
  10468. %
  10469. \fi}
  10470. \section{Cyclic Control Flow and Dataflow Analysis}
  10471. \label{sec:dataflow-analysis}
  10472. Up until this point, the programs generated in
  10473. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10474. \code{while} loop introduces a cycle. Does that matter?
  10475. %
  10476. Indeed, it does. Recall that for register allocation, the compiler
  10477. performs liveness analysis to determine which variables can share the
  10478. same register. To accomplish this, we analyzed the control-flow graph
  10479. in reverse topological order
  10480. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10481. well defined only for acyclic graphs.
  10482. Let us return to the example of computing the sum of the first five
  10483. positive integers. Here is the program after instruction
  10484. selection\index{subject}{instruction selection} but before register
  10485. allocation.
  10486. \begin{center}
  10487. {\if\edition\racketEd
  10488. \begin{minipage}{0.45\textwidth}
  10489. \begin{lstlisting}
  10490. (define (main) : Integer
  10491. mainstart:
  10492. movq $0, sum
  10493. movq $5, i
  10494. jmp block5
  10495. block5:
  10496. movq i, tmp3
  10497. cmpq tmp3, $0
  10498. jl block7
  10499. jmp block8
  10500. \end{lstlisting}
  10501. \end{minipage}
  10502. \begin{minipage}{0.45\textwidth}
  10503. \begin{lstlisting}
  10504. block7:
  10505. addq i, sum
  10506. movq $1, tmp4
  10507. negq tmp4
  10508. addq tmp4, i
  10509. jmp block5
  10510. block8:
  10511. movq $27, %rax
  10512. addq sum, %rax
  10513. jmp mainconclusion)
  10514. \end{lstlisting}
  10515. \end{minipage}
  10516. \fi}
  10517. {\if\edition\pythonEd\pythonColor
  10518. \begin{minipage}{0.45\textwidth}
  10519. \begin{lstlisting}
  10520. mainstart:
  10521. movq $0, sum
  10522. movq $5, i
  10523. jmp block5
  10524. block5:
  10525. cmpq $0, i
  10526. jg block7
  10527. jmp block8
  10528. \end{lstlisting}
  10529. \end{minipage}
  10530. \begin{minipage}{0.45\textwidth}
  10531. \begin{lstlisting}
  10532. block7:
  10533. addq i, sum
  10534. subq $1, i
  10535. jmp block5
  10536. block8:
  10537. movq sum, %rdi
  10538. callq print_int
  10539. movq $0, %rax
  10540. jmp mainconclusion
  10541. \end{lstlisting}
  10542. \end{minipage}
  10543. \fi}
  10544. \end{center}
  10545. Recall that liveness analysis works backward, starting at the end
  10546. of each function. For this example we could start with \code{block8}
  10547. because we know what is live at the beginning of the conclusion:
  10548. only \code{rax} and \code{rsp}. So the live-before set
  10549. for \code{block8} is \code{\{rsp,sum\}}.
  10550. %
  10551. Next we might try to analyze \code{block5} or \code{block7}, but
  10552. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10553. we are stuck.
  10554. The way out of this impasse is to realize that we can compute an
  10555. underapproximation of each live-before set by starting with empty
  10556. live-after sets. By \emph{underapproximation}, we mean that the set
  10557. contains only variables that are live for some execution of the
  10558. program, but the set may be missing some variables that are live.
  10559. Next, the underapproximations for each block can be improved by (1)
  10560. updating the live-after set for each block using the approximate
  10561. live-before sets from the other blocks, and (2) performing liveness
  10562. analysis again on each block. In fact, by iterating this process, the
  10563. underapproximations eventually become the correct solutions!
  10564. %
  10565. This approach of iteratively analyzing a control-flow graph is
  10566. applicable to many static analysis problems and goes by the name
  10567. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10568. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10569. Washington.
  10570. Let us apply this approach to the previously presented example. We use
  10571. the empty set for the initial live-before set for each block. Let
  10572. $m_0$ be the following mapping from label names to sets of locations
  10573. (variables and registers):
  10574. \begin{center}
  10575. \begin{lstlisting}
  10576. mainstart: {}, block5: {}, block7: {}, block8: {}
  10577. \end{lstlisting}
  10578. \end{center}
  10579. Using the above live-before approximations, we determine the
  10580. live-after for each block and then apply liveness analysis to each
  10581. block. This produces our next approximation $m_1$ of the live-before
  10582. sets.
  10583. \begin{center}
  10584. \begin{lstlisting}
  10585. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10586. \end{lstlisting}
  10587. \end{center}
  10588. For the second round, the live-after for \code{mainstart} is the
  10589. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10590. the liveness analysis for \code{mainstart} computes the empty set. The
  10591. live-after for \code{block5} is the union of the live-before sets for
  10592. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10593. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10594. sum\}}. The live-after for \code{block7} is the live-before for
  10595. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10596. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10597. Together these yield the following approximation $m_2$ of
  10598. the live-before sets:
  10599. \begin{center}
  10600. \begin{lstlisting}
  10601. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10602. \end{lstlisting}
  10603. \end{center}
  10604. In the preceding iteration, only \code{block5} changed, so we can
  10605. limit our attention to \code{mainstart} and \code{block7}, the two
  10606. blocks that jump to \code{block5}. As a result, the live-before sets
  10607. for \code{mainstart} and \code{block7} are updated to include
  10608. \code{rsp}, yielding the following approximation $m_3$:
  10609. \begin{center}
  10610. \begin{lstlisting}
  10611. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10612. \end{lstlisting}
  10613. \end{center}
  10614. Because \code{block7} changed, we analyze \code{block5} once more, but
  10615. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10616. our approximations have converged, so $m_3$ is the solution.
  10617. This iteration process is guaranteed to converge to a solution by the
  10618. Kleene fixed-point theorem, a general theorem about functions on
  10619. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10620. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10621. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10622. join operator
  10623. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10624. will be working with join semilattices.} When two elements are
  10625. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10626. as much information as $m_i$, so we can think of $m_j$ as a
  10627. better-than-or-equal-to approximation in relation to $m_i$. The
  10628. bottom element $\bot$ represents the complete lack of information,
  10629. that is, the worst approximation. The join operator takes two lattice
  10630. elements and combines their information; that is, it produces the
  10631. least upper bound of the two.\index{subject}{least upper bound}
  10632. A dataflow analysis typically involves two lattices: one lattice to
  10633. represent abstract states and another lattice that aggregates the
  10634. abstract states of all the blocks in the control-flow graph. For
  10635. liveness analysis, an abstract state is a set of locations. We form
  10636. the lattice $L$ by taking its elements to be sets of locations, the
  10637. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10638. set, and the join operator to be set union.
  10639. %
  10640. We form a second lattice $M$ by taking its elements to be mappings
  10641. from the block labels to sets of locations (elements of $L$). We
  10642. order the mappings point-wise, using the ordering of $L$. So, given any
  10643. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10644. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10645. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10646. to the empty set, $\bot_M(\ell) = \emptyset$.
  10647. We can think of one iteration of liveness analysis applied to the
  10648. whole program as being a function $f$ on the lattice $M$. It takes a
  10649. mapping as input and computes a new mapping.
  10650. \[
  10651. f(m_i) = m_{i+1}
  10652. \]
  10653. Next let us think for a moment about what a final solution $m_s$
  10654. should look like. If we perform liveness analysis using the solution
  10655. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10656. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10657. \[
  10658. f(m_s) = m_s
  10659. \]
  10660. Furthermore, the solution should include only locations that are
  10661. forced to be there by performing liveness analysis on the program, so
  10662. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10663. The Kleene fixed-point theorem states that if a function $f$ is
  10664. monotone (better inputs produce better outputs), then the least fixed
  10665. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10666. chain} that starts at $\bot$ and iterates $f$ as
  10667. follows:\index{subject}{Kleene fixed-point theorem}
  10668. \[
  10669. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10670. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10671. \]
  10672. When a lattice contains only finitely long ascending chains, then
  10673. every Kleene chain tops out at some fixed point after some number of
  10674. iterations of $f$.
  10675. \[
  10676. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10677. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10678. \]
  10679. The liveness analysis is indeed a monotone function and the lattice
  10680. $M$ has finitely long ascending chains because there are only a
  10681. finite number of variables and blocks in the program. Thus we are
  10682. guaranteed that iteratively applying liveness analysis to all blocks
  10683. in the program will eventually produce the least fixed point solution.
  10684. Next let us consider dataflow analysis in general and discuss the
  10685. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10686. %
  10687. The algorithm has four parameters: the control-flow graph \code{G}, a
  10688. function \code{transfer} that applies the analysis to one block, and the
  10689. \code{bottom} and \code{join} operators for the lattice of abstract
  10690. states. The \code{analyze\_dataflow} function is formulated as a
  10691. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10692. function come from the predecessor nodes in the control-flow
  10693. graph. However, liveness analysis is a \emph{backward} dataflow
  10694. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10695. function with the transpose of the control-flow graph.
  10696. The algorithm begins by creating the bottom mapping, represented by a
  10697. hash table. It then pushes all the nodes in the control-flow graph
  10698. onto the work list (a queue). The algorithm repeats the \code{while}
  10699. loop as long as there are items in the work list. In each iteration, a
  10700. node is popped from the work list and processed. The \code{input} for
  10701. the node is computed by taking the join of the abstract states of all
  10702. the predecessor nodes. The \code{transfer} function is then applied to
  10703. obtain the \code{output} abstract state. If the output differs from
  10704. the previous state for this block, the mapping for this block is
  10705. updated and its successor nodes are pushed onto the work list.
  10706. \begin{figure}[tb]
  10707. \begin{tcolorbox}[colback=white]
  10708. {\if\edition\racketEd
  10709. \begin{lstlisting}
  10710. (define (analyze_dataflow G transfer bottom join)
  10711. (define mapping (make-hash))
  10712. (for ([v (in-vertices G)])
  10713. (dict-set! mapping v bottom))
  10714. (define worklist (make-queue))
  10715. (for ([v (in-vertices G)])
  10716. (enqueue! worklist v))
  10717. (define trans-G (transpose G))
  10718. (while (not (queue-empty? worklist))
  10719. (define node (dequeue! worklist))
  10720. (define input (for/fold ([state bottom])
  10721. ([pred (in-neighbors trans-G node)])
  10722. (join state (dict-ref mapping pred))))
  10723. (define output (transfer node input))
  10724. (cond [(not (equal? output (dict-ref mapping node)))
  10725. (dict-set! mapping node output)
  10726. (for ([v (in-neighbors G node)])
  10727. (enqueue! worklist v))]))
  10728. mapping)
  10729. \end{lstlisting}
  10730. \fi}
  10731. {\if\edition\pythonEd\pythonColor
  10732. \begin{lstlisting}
  10733. def analyze_dataflow(G, transfer, bottom, join):
  10734. trans_G = transpose(G)
  10735. mapping = dict((v, bottom) for v in G.vertices())
  10736. worklist = deque(G.vertices)
  10737. while worklist:
  10738. node = worklist.pop()
  10739. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10740. input = reduce(join, inputs, bottom)
  10741. output = transfer(node, input)
  10742. if output != mapping[node]:
  10743. mapping[node] = output
  10744. worklist.extend(G.adjacent(node))
  10745. \end{lstlisting}
  10746. \fi}
  10747. \end{tcolorbox}
  10748. \caption{Generic work list algorithm for dataflow analysis.}
  10749. \label{fig:generic-dataflow}
  10750. \end{figure}
  10751. {\if\edition\racketEd
  10752. \section{Mutable Variables and Remove Complex Operands}
  10753. There is a subtle interaction between the
  10754. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10755. and the left-to-right order of evaluation of Racket. Consider the
  10756. following example:
  10757. \begin{lstlisting}
  10758. (let ([x 2])
  10759. (+ x (begin (set! x 40) x)))
  10760. \end{lstlisting}
  10761. The result of this program is \code{42} because the first read from
  10762. \code{x} produces \code{2} and the second produces \code{40}. However,
  10763. if we naively apply the \code{remove\_complex\_operands} pass to this
  10764. example we obtain the following program whose result is \code{80}!
  10765. \begin{lstlisting}
  10766. (let ([x 2])
  10767. (let ([tmp (begin (set! x 40) x)])
  10768. (+ x tmp)))
  10769. \end{lstlisting}
  10770. The problem is that with mutable variables, the ordering between
  10771. reads and writes is important, and the
  10772. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10773. before the first read of \code{x}.
  10774. We recommend solving this problem by giving special treatment to reads
  10775. from mutable variables, that is, variables that occur on the left-hand
  10776. side of a \code{set!}. We mark each read from a mutable variable with
  10777. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10778. that the read operation is effectful in that it can produce different
  10779. results at different points in time. Let's apply this idea to the
  10780. following variation that also involves a variable that is not mutated:
  10781. % loop_test_24.rkt
  10782. \begin{lstlisting}
  10783. (let ([x 2])
  10784. (let ([y 0])
  10785. (+ y (+ x (begin (set! x 40) x)))))
  10786. \end{lstlisting}
  10787. We first analyze this program to discover that variable \code{x}
  10788. is mutable but \code{y} is not. We then transform the program as
  10789. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10790. \begin{lstlisting}
  10791. (let ([x 2])
  10792. (let ([y 0])
  10793. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10794. \end{lstlisting}
  10795. Now that we have a clear distinction between reads from mutable and
  10796. immutable variables, we can apply the \code{remove\_complex\_operands}
  10797. pass, where reads from immutable variables are still classified as
  10798. atomic expressions but reads from mutable variables are classified as
  10799. complex. Thus, \code{remove\_complex\_operands} yields the following
  10800. program:\\
  10801. \begin{minipage}{\textwidth}
  10802. \begin{lstlisting}
  10803. (let ([x 2])
  10804. (let ([y 0])
  10805. (let ([t1 x])
  10806. (let ([t2 (begin (set! x 40) x)])
  10807. (let ([t3 (+ t1 t2)])
  10808. (+ y t3))))))
  10809. \end{lstlisting}
  10810. \end{minipage}
  10811. The temporary variable \code{t1} gets the value of \code{x} before the
  10812. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10813. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10814. do not generate a temporary variable for the occurrence of \code{y}
  10815. because it's an immutable variable. We want to avoid such unnecessary
  10816. extra temporaries because they would needlessly increase the number of
  10817. variables, making it more likely for some of them to be spilled. The
  10818. result of this program is \code{42}, the same as the result prior to
  10819. \code{remove\_complex\_operands}.
  10820. The approach that we've sketched requires only a small
  10821. modification to \code{remove\_complex\_operands} to handle
  10822. \code{get!}. However, it requires a new pass, called
  10823. \code{uncover-get!}, that we discuss in
  10824. section~\ref{sec:uncover-get-bang}.
  10825. As an aside, this problematic interaction between \code{set!} and the
  10826. pass \code{remove\_complex\_operands} is particular to Racket and not
  10827. its predecessor, the Scheme language. The key difference is that
  10828. Scheme does not specify an order of evaluation for the arguments of an
  10829. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10830. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10831. would be correct results for the example program. Interestingly,
  10832. Racket is implemented on top of the Chez Scheme
  10833. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10834. presented in this section (using extra \code{let} bindings to control
  10835. the order of evaluation) is used in the translation from Racket to
  10836. Scheme~\citep{Flatt:2019tb}.
  10837. \fi} % racket
  10838. Having discussed the complications that arise from adding support for
  10839. assignment and loops, we turn to discussing the individual compilation
  10840. passes.
  10841. {\if\edition\racketEd
  10842. \section{Uncover \texttt{get!}}
  10843. \label{sec:uncover-get-bang}
  10844. The goal of this pass is to mark uses of mutable variables so that
  10845. \code{remove\_complex\_operands} can treat them as complex expressions
  10846. and thereby preserve their ordering relative to the side effects in
  10847. other operands. So, the first step is to collect all the mutable
  10848. variables. We recommend creating an auxiliary function for this,
  10849. named \code{collect-set!}, that recursively traverses expressions,
  10850. returning the set of all variables that occur on the left-hand side of a
  10851. \code{set!}. Here's an excerpt of its implementation.
  10852. \begin{center}
  10853. \begin{minipage}{\textwidth}
  10854. \begin{lstlisting}
  10855. (define (collect-set! e)
  10856. (match e
  10857. [(Var x) (set)]
  10858. [(Int n) (set)]
  10859. [(Let x rhs body)
  10860. (set-union (collect-set! rhs) (collect-set! body))]
  10861. [(SetBang var rhs)
  10862. (set-union (set var) (collect-set! rhs))]
  10863. ...))
  10864. \end{lstlisting}
  10865. \end{minipage}
  10866. \end{center}
  10867. By placing this pass after \code{uniquify}, we need not worry about
  10868. variable shadowing, and our logic for \code{Let} can remain simple, as
  10869. in this excerpt.
  10870. The second step is to mark the occurrences of the mutable variables
  10871. with the new \code{GetBang} AST node (\code{get!} in concrete
  10872. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10873. function, which takes two parameters: the set of mutable variables
  10874. \code{set!-vars} and the expression \code{e} to be processed. The
  10875. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10876. mutable variable or leaves it alone if not.
  10877. \begin{center}
  10878. \begin{minipage}{\textwidth}
  10879. \begin{lstlisting}
  10880. (define ((uncover-get!-exp set!-vars) e)
  10881. (match e
  10882. [(Var x)
  10883. (if (set-member? set!-vars x)
  10884. (GetBang x)
  10885. (Var x))]
  10886. ...))
  10887. \end{lstlisting}
  10888. \end{minipage}
  10889. \end{center}
  10890. To wrap things up, define the \code{uncover-get!} function for
  10891. processing a whole program, using \code{collect-set!} to obtain the
  10892. set of mutable variables and then \code{uncover-get!-exp} to replace
  10893. their occurrences with \code{GetBang}.
  10894. \fi}
  10895. \section{Remove Complex Operands}
  10896. \label{sec:rco-loop}
  10897. {\if\edition\racketEd
  10898. %
  10899. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10900. \code{while} are all complex expressions. The subexpressions of
  10901. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10902. %
  10903. \fi}
  10904. {\if\edition\pythonEd\pythonColor
  10905. %
  10906. The change needed for this pass is to add a case for the \code{while}
  10907. statement. The condition of a loop is allowed to be a complex
  10908. expression, just like the condition of the \code{if} statement.
  10909. %
  10910. \fi}
  10911. %
  10912. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10913. \LangLoopANF{} of this pass.
  10914. \newcommand{\LwhileMonadASTRacket}{
  10915. \begin{array}{rcl}
  10916. \Atm &::=& \VOID{} \\
  10917. \Exp &::=& \GETBANG{\Var}
  10918. \MID \SETBANG{\Var}{\Exp}
  10919. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10920. &\MID& \WHILE{\Exp}{\Exp}
  10921. \end{array}
  10922. }
  10923. \newcommand{\LwhileMonadASTPython}{
  10924. \begin{array}{rcl}
  10925. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10926. \end{array}
  10927. }
  10928. \begin{figure}[tp]
  10929. \centering
  10930. \begin{tcolorbox}[colback=white]
  10931. \small
  10932. {\if\edition\racketEd
  10933. \[
  10934. \begin{array}{l}
  10935. \gray{\LvarMonadASTRacket} \\ \hline
  10936. \gray{\LifMonadASTRacket} \\ \hline
  10937. \LwhileMonadASTRacket \\
  10938. \begin{array}{rcl}
  10939. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10940. \end{array}
  10941. \end{array}
  10942. \]
  10943. \fi}
  10944. {\if\edition\pythonEd\pythonColor
  10945. \[
  10946. \begin{array}{l}
  10947. \gray{\LvarMonadASTPython} \\ \hline
  10948. \gray{\LifMonadASTPython} \\ \hline
  10949. \LwhileMonadASTPython \\
  10950. \begin{array}{rcl}
  10951. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10952. \end{array}
  10953. \end{array}
  10954. \]
  10955. \fi}
  10956. \end{tcolorbox}
  10957. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10958. \label{fig:Lwhile-anf-syntax}
  10959. \index{subject}{Lwhilemon@\LangLoopANF{} abstract syntax}
  10960. \end{figure}
  10961. {\if\edition\racketEd
  10962. %
  10963. As usual, when a complex expression appears in a grammar position that
  10964. needs to be atomic, such as the argument of a primitive operator, we
  10965. must introduce a temporary variable and bind it to the complex
  10966. expression. This approach applies, unchanged, to handle the new
  10967. language forms. For example, in the following code there are two
  10968. \code{begin} expressions appearing as arguments to the \code{+}
  10969. operator. The output of \code{rco\_exp} is then shown, in which the
  10970. \code{begin} expressions have been bound to temporary
  10971. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10972. allowed to have arbitrary expressions in their right-hand side
  10973. expression, so it is fine to place \code{begin} there.
  10974. %
  10975. \begin{center}
  10976. \begin{tabular}{lcl}
  10977. \begin{minipage}{0.4\textwidth}
  10978. \begin{lstlisting}
  10979. (let ([x2 10])
  10980. (let ([y3 0])
  10981. (+ (+ (begin
  10982. (set! y3 (read))
  10983. (get! x2))
  10984. (begin
  10985. (set! x2 (read))
  10986. (get! y3)))
  10987. (get! x2))))
  10988. \end{lstlisting}
  10989. \end{minipage}
  10990. &
  10991. $\Rightarrow$
  10992. &
  10993. \begin{minipage}{0.4\textwidth}
  10994. \begin{lstlisting}
  10995. (let ([x2 10])
  10996. (let ([y3 0])
  10997. (let ([tmp4 (begin
  10998. (set! y3 (read))
  10999. x2)])
  11000. (let ([tmp5 (begin
  11001. (set! x2 (read))
  11002. y3)])
  11003. (let ([tmp6 (+ tmp4 tmp5)])
  11004. (let ([tmp7 x2])
  11005. (+ tmp6 tmp7)))))))
  11006. \end{lstlisting}
  11007. \end{minipage}
  11008. \end{tabular}
  11009. \end{center}
  11010. \fi}
  11011. \section{Explicate Control \racket{and \LangCLoop{}}}
  11012. \label{sec:explicate-loop}
  11013. \newcommand{\CloopASTRacket}{
  11014. \begin{array}{lcl}
  11015. \Atm &::=& \VOID \\
  11016. \Stmt &::=& \READ{}
  11017. \end{array}
  11018. }
  11019. {\if\edition\racketEd
  11020. Recall that in the \code{explicate\_control} pass we define one helper
  11021. function for each kind of position in the program. For the \LangVarANF{}
  11022. language of integers and variables, we needed assignment and tail
  11023. positions. The \code{if} expressions of \LangIfANF{} introduced predicate
  11024. positions. For \LangLoopANF{}, the \code{begin} expression introduces yet
  11025. another kind of position: effect position. Except for the last
  11026. subexpression, the subexpressions inside a \code{begin} are evaluated
  11027. only for their effect. Their result values are discarded. We can
  11028. generate better code by taking this fact into account.
  11029. The output language of \code{explicate\_control} is \LangCLoop{}
  11030. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  11031. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  11032. and that \code{read} may appear as a statement. The most significant
  11033. difference between the programs generated by \code{explicate\_control}
  11034. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  11035. chapter is that the control-flow graphs of the latter may contain
  11036. cycles.
  11037. \begin{figure}[tp]
  11038. \begin{tcolorbox}[colback=white]
  11039. \small
  11040. \[
  11041. \begin{array}{l}
  11042. \gray{\CvarASTRacket} \\ \hline
  11043. \gray{\CifASTRacket} \\ \hline
  11044. \CloopASTRacket \\
  11045. \begin{array}{lcl}
  11046. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11047. \end{array}
  11048. \end{array}
  11049. \]
  11050. \end{tcolorbox}
  11051. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  11052. \label{fig:c7-syntax}
  11053. \index{subject}{Cwhile@\LangCLoop{} abstract syntax}
  11054. \end{figure}
  11055. The new auxiliary function \code{explicate\_effect} takes an
  11056. expression (in an effect position) and the code for its
  11057. continuation. The function returns a $\Tail$ that includes the
  11058. generated code for the input expression followed by the
  11059. continuation. If the expression is obviously pure, that is, never
  11060. causes side effects, then the expression can be removed, so the result
  11061. is just the continuation.
  11062. %
  11063. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  11064. interesting; the generated code is depicted in the following diagram:
  11065. \begin{center}
  11066. \begin{minipage}{0.3\textwidth}
  11067. \xymatrix{
  11068. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  11069. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  11070. & *+[F]{\txt{\itm{cont}}} \\
  11071. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  11072. }
  11073. \end{minipage}
  11074. \end{center}
  11075. We start by creating a fresh label $\itm{loop}$ for the top of the
  11076. loop. Next, recursively process the \itm{body} (in effect position)
  11077. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  11078. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  11079. \itm{body'} as the \emph{then} branch and the continuation block as the
  11080. \emph{else} branch. The result should be added to the dictionary of
  11081. \code{basic-blocks} with the label \itm{loop}. The result for the
  11082. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  11083. The auxiliary functions for tail, assignment, and predicate positions
  11084. need to be updated. The three new language forms, \code{while},
  11085. \code{set!}, and \code{begin}, can appear in assignment and tail
  11086. positions. Only \code{begin} may appear in predicate positions; the
  11087. other two have result type \code{Void}.
  11088. \fi}
  11089. %
  11090. {\if\edition\pythonEd\pythonColor
  11091. %
  11092. The output of this pass is the language \LangCIf{}. No new language
  11093. features are needed in the output, because a \code{while} loop can be
  11094. expressed in terms of \code{goto} and \code{if} statements, which are
  11095. already in \LangCIf{}.
  11096. %
  11097. Add a case for the \code{while} statement to the
  11098. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11099. the condition expression.
  11100. %
  11101. \fi}
  11102. {\if\edition\racketEd
  11103. \section{Select Instructions}
  11104. \label{sec:select-instructions-loop}
  11105. \index{subject}{select instructions}
  11106. Only two small additions are needed in the \code{select\_instructions}
  11107. pass to handle the changes to \LangCLoop{}. First, to handle the
  11108. addition of \VOID{} we simply translate it to \code{0}. Second,
  11109. \code{read} may appear as a stand-alone statement instead of
  11110. appearing only on the right-hand side of an assignment statement. The code
  11111. generation is nearly identical to the one for assignment; just leave
  11112. off the instruction for moving the result into the left-hand side.
  11113. \fi}
  11114. \section{Register Allocation}
  11115. \label{sec:register-allocation-loop}
  11116. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11117. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11118. which complicates the liveness analysis needed for register
  11119. allocation.
  11120. %
  11121. We recommend using the generic \code{analyze\_dataflow} function that
  11122. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11123. perform liveness analysis, replacing the code in
  11124. \code{uncover\_live} that processed the basic blocks in topological
  11125. order (section~\ref{sec:liveness-analysis-Lif}).
  11126. The \code{analyze\_dataflow} function has the following four parameters.
  11127. \begin{enumerate}
  11128. \item The first parameter \code{G} should be passed the transpose
  11129. of the control-flow graph.
  11130. \item The second parameter \code{transfer} should be passed a function
  11131. that applies liveness analysis to a basic block. It takes two
  11132. parameters: the label for the block to analyze and the live-after
  11133. set for that block. The transfer function should return the
  11134. live-before set for the block.
  11135. %
  11136. \racket{Also, as a side effect, it should update the block's
  11137. $\itm{info}$ with the liveness information for each instruction.}
  11138. %
  11139. \python{Also, as a side effect, it should update the live-before and
  11140. live-after sets for each instruction.}
  11141. %
  11142. To implement the \code{transfer} function, you should be able to
  11143. reuse the code you already have for analyzing basic blocks.
  11144. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11145. \code{bottom} and \code{join} for the lattice of abstract states,
  11146. that is, sets of locations. For liveness analysis, the bottom of the
  11147. lattice is the empty set, and the join operator is set union.
  11148. \end{enumerate}
  11149. \begin{figure}[tp]
  11150. \begin{tcolorbox}[colback=white]
  11151. {\if\edition\racketEd
  11152. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11153. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11154. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11155. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11156. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11157. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11158. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11159. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11160. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11161. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11162. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11163. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11164. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11165. \path[->,bend left=15] (Lfun) edge [above] node
  11166. {\ttfamily\footnotesize shrink} (Lfun-2);
  11167. \path[->,bend left=15] (Lfun-2) edge [above] node
  11168. {\ttfamily\footnotesize uniquify} (F1-4);
  11169. \path[->,bend left=15] (F1-4) edge [above] node
  11170. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11171. \path[->,bend left=15] (F1-5) edge [left] node
  11172. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11173. \path[->,bend left=10] (F1-6) edge [above] node
  11174. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11175. \path[->,bend left=15] (C3-2) edge [right] node
  11176. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11177. \path[->,bend right=15] (x86-2) edge [right] node
  11178. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11179. \path[->,bend right=15] (x86-2-1) edge [below] node
  11180. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11181. \path[->,bend right=15] (x86-2-2) edge [right] node
  11182. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11183. \path[->,bend left=15] (x86-3) edge [above] node
  11184. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11185. \path[->,bend left=15] (x86-4) edge [right] node
  11186. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11187. \end{tikzpicture}
  11188. \fi}
  11189. {\if\edition\pythonEd\pythonColor
  11190. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11191. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11192. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11193. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11194. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11195. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11196. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11197. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11198. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11199. \path[->,bend left=15] (Lfun) edge [above] node
  11200. {\ttfamily\footnotesize shrink} (Lfun-2);
  11201. \path[->,bend left=15] (Lfun-2) edge [above] node
  11202. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11203. \path[->,bend left=10] (F1-6) edge [right] node
  11204. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11205. \path[->,bend right=15] (C3-2) edge [right] node
  11206. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11207. \path[->,bend right=15] (x86-2) edge [below] node
  11208. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11209. \path[->,bend left=15] (x86-3) edge [above] node
  11210. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11211. \path[->,bend right=15] (x86-4) edge [below] node
  11212. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11213. \end{tikzpicture}
  11214. \fi}
  11215. \end{tcolorbox}
  11216. \caption{Diagram of the passes for \LangLoop{}.}
  11217. \label{fig:Lwhile-passes}
  11218. \end{figure}
  11219. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11220. for the compilation of \LangLoop{}.
  11221. % Further Reading: dataflow analysis
  11222. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11223. \chapter{Tuples and Garbage Collection}
  11224. \label{ch:Lvec}
  11225. \index{subject}{tuple}
  11226. \index{subject}{vector}
  11227. \setcounter{footnote}{0}
  11228. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11229. %% all the IR grammars are spelled out! \\ --Jeremy}
  11230. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11231. %% the root stack. \\ --Jeremy}
  11232. In this chapter we study the implementation of tuples\racket{, called
  11233. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11234. in which each element may have a different type.
  11235. %
  11236. This language feature is the first to use the computer's
  11237. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11238. indefinite; that is, a tuple lives forever from the programmer's
  11239. viewpoint. Of course, from an implementer's viewpoint, it is important
  11240. to reclaim the space associated with a tuple when it is no longer
  11241. needed, which is why we also study \emph{garbage collection}
  11242. \index{subject}{garbage collection} techniques in this chapter.
  11243. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11244. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11245. language (chapter~\ref{ch:Lwhile}) with tuples.
  11246. %
  11247. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11248. copying live tuples back and forth between two halves of the heap. The
  11249. garbage collector requires coordination with the compiler so that it
  11250. can find all the live tuples.
  11251. %
  11252. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11253. discuss the necessary changes and additions to the compiler passes,
  11254. including a new compiler pass named \code{expose\_allocation}.
  11255. \section{The \LangVec{} Language}
  11256. \label{sec:r3}
  11257. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11258. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11259. the definition of the abstract syntax.
  11260. %
  11261. \racket{The \LangVec{} language includes the forms \code{vector} for
  11262. creating a tuple, \code{vector-ref} for reading an element of a
  11263. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11264. \code{vector-length} for obtaining the number of elements of a
  11265. tuple.}
  11266. %
  11267. \python{The \LangVec{} language adds (1) tuple creation via a
  11268. comma-separated list of expressions; (2) accessing an element of a
  11269. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11270. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11271. comparison operator; and (4) obtaining the number of elements (the
  11272. length) of a tuple. In this chapter, we restrict access indices to
  11273. constant integers.}
  11274. %
  11275. The following program shows an example of the use of tuples. It creates a tuple
  11276. \code{t} containing the elements \code{40},
  11277. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11278. contains just \code{2}. The element at index $1$ of \code{t} is
  11279. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11280. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11281. to which we add \code{2}, the element at index $0$ of the tuple.
  11282. The result of the program is \code{42}.
  11283. %
  11284. {\if\edition\racketEd
  11285. \begin{lstlisting}
  11286. (let ([t (vector 40 #t (vector 2))])
  11287. (if (vector-ref t 1)
  11288. (+ (vector-ref t 0)
  11289. (vector-ref (vector-ref t 2) 0))
  11290. 44))
  11291. \end{lstlisting}
  11292. \fi}
  11293. {\if\edition\pythonEd\pythonColor
  11294. \begin{lstlisting}
  11295. t = 40, True, (2,)
  11296. print(t[0] + t[2][0] if t[1] else 44)
  11297. \end{lstlisting}
  11298. \fi}
  11299. \newcommand{\LtupGrammarRacket}{
  11300. \begin{array}{lcl}
  11301. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11302. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11303. \MID \LP\key{vector-length}\;\Exp\RP \\
  11304. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11305. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11306. \end{array}
  11307. }
  11308. \newcommand{\LtupASTRacket}{
  11309. \begin{array}{lcl}
  11310. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11311. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11312. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11313. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11314. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11315. \end{array}
  11316. }
  11317. \newcommand{\LtupGrammarPython}{
  11318. \begin{array}{rcl}
  11319. \itm{cmp} &::= & \key{is} \\
  11320. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11321. \end{array}
  11322. }
  11323. \newcommand{\LtupASTPython}{
  11324. \begin{array}{lcl}
  11325. \itm{cmp} &::= & \code{Is()} \\
  11326. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11327. &\MID& \LEN{\Exp}
  11328. \end{array}
  11329. }
  11330. \begin{figure}[tbp]
  11331. \centering
  11332. \begin{tcolorbox}[colback=white]
  11333. \small
  11334. {\if\edition\racketEd
  11335. \[
  11336. \begin{array}{l}
  11337. \gray{\LintGrammarRacket{}} \\ \hline
  11338. \gray{\LvarGrammarRacket{}} \\ \hline
  11339. \gray{\LifGrammarRacket{}} \\ \hline
  11340. \gray{\LwhileGrammarRacket} \\ \hline
  11341. \LtupGrammarRacket \\
  11342. \begin{array}{lcl}
  11343. \LangVecM{} &::=& \Exp
  11344. \end{array}
  11345. \end{array}
  11346. \]
  11347. \fi}
  11348. {\if\edition\pythonEd\pythonColor
  11349. \[
  11350. \begin{array}{l}
  11351. \gray{\LintGrammarPython{}} \\ \hline
  11352. \gray{\LvarGrammarPython{}} \\ \hline
  11353. \gray{\LifGrammarPython{}} \\ \hline
  11354. \gray{\LwhileGrammarPython} \\ \hline
  11355. \LtupGrammarPython \\
  11356. \begin{array}{rcl}
  11357. \LangVecM{} &::=& \Stmt^{*}
  11358. \end{array}
  11359. \end{array}
  11360. \]
  11361. \fi}
  11362. \end{tcolorbox}
  11363. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11364. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11365. \label{fig:Lvec-concrete-syntax}
  11366. \index{subject}{Ltup@\LangVec{} concrete syntax}
  11367. \end{figure}
  11368. \begin{figure}[tp]
  11369. \centering
  11370. \begin{tcolorbox}[colback=white]
  11371. \small
  11372. {\if\edition\racketEd
  11373. \[
  11374. \begin{array}{l}
  11375. \gray{\LintOpAST} \\ \hline
  11376. \gray{\LvarASTRacket{}} \\ \hline
  11377. \gray{\LifASTRacket{}} \\ \hline
  11378. \gray{\LwhileASTRacket{}} \\ \hline
  11379. \LtupASTRacket{} \\
  11380. \begin{array}{lcl}
  11381. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11382. \end{array}
  11383. \end{array}
  11384. \]
  11385. \fi}
  11386. {\if\edition\pythonEd\pythonColor
  11387. \[
  11388. \begin{array}{l}
  11389. \gray{\LintASTPython} \\ \hline
  11390. \gray{\LvarASTPython} \\ \hline
  11391. \gray{\LifASTPython} \\ \hline
  11392. \gray{\LwhileASTPython} \\ \hline
  11393. \LtupASTPython \\
  11394. \begin{array}{lcl}
  11395. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11396. \end{array}
  11397. \end{array}
  11398. \]
  11399. \fi}
  11400. \end{tcolorbox}
  11401. \caption{The abstract syntax of \LangVec{}.}
  11402. \label{fig:Lvec-syntax}
  11403. \index{subject}{Ltup@\LangVec{} abstract syntax}
  11404. \end{figure}
  11405. Tuples raise several interesting new issues. First, variable binding
  11406. performs a shallow copy in dealing with tuples, which means that
  11407. different variables can refer to the same tuple; that is, two
  11408. variables can be \emph{aliases}\index{subject}{alias} for the same
  11409. entity. Consider the following example, in which \code{t1} and
  11410. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11411. different tuple value with equal elements. The result of the
  11412. program is \code{42}.
  11413. \begin{center}
  11414. \begin{minipage}{0.96\textwidth}
  11415. {\if\edition\racketEd
  11416. \begin{lstlisting}
  11417. (let ([t1 (vector 3 7)])
  11418. (let ([t2 t1])
  11419. (let ([t3 (vector 3 7)])
  11420. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11421. 42
  11422. 0))))
  11423. \end{lstlisting}
  11424. \fi}
  11425. {\if\edition\pythonEd\pythonColor
  11426. \begin{lstlisting}
  11427. t1 = 3, 7
  11428. t2 = t1
  11429. t3 = 3, 7
  11430. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11431. \end{lstlisting}
  11432. \fi}
  11433. \end{minipage}
  11434. \end{center}
  11435. {\if\edition\racketEd
  11436. Whether two variables are aliased or not affects what happens
  11437. when the underlying tuple is mutated\index{subject}{mutation}.
  11438. Consider the following example in which \code{t1} and \code{t2}
  11439. again refer to the same tuple value.
  11440. \begin{center}
  11441. \begin{minipage}{0.96\textwidth}
  11442. \begin{lstlisting}
  11443. (let ([t1 (vector 3 7)])
  11444. (let ([t2 t1])
  11445. (let ([_ (vector-set! t2 0 42)])
  11446. (vector-ref t1 0))))
  11447. \end{lstlisting}
  11448. \end{minipage}
  11449. \end{center}
  11450. The mutation through \code{t2} is visible in referencing the tuple
  11451. from \code{t1}, so the result of this program is \code{42}.
  11452. \fi}
  11453. The next issue concerns the lifetime of tuples. When does a tuple's
  11454. lifetime end? Notice that \LangVec{} does not include an operation
  11455. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11456. to any notion of static scoping.
  11457. %
  11458. {\if\edition\racketEd
  11459. %
  11460. For example, the following program returns \code{42} even though the
  11461. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11462. that reads from the vector to which it was bound.
  11463. \begin{center}
  11464. \begin{minipage}{0.96\textwidth}
  11465. \begin{lstlisting}
  11466. (let ([v (vector (vector 44))])
  11467. (let ([x (let ([w (vector 42)])
  11468. (let ([_ (vector-set! v 0 w)])
  11469. 0))])
  11470. (+ x (vector-ref (vector-ref v 0) 0))))
  11471. \end{lstlisting}
  11472. \end{minipage}
  11473. \end{center}
  11474. \fi}
  11475. %
  11476. {\if\edition\pythonEd\pythonColor
  11477. %
  11478. For example, the following program returns \code{42} even though the
  11479. variable \code{x} goes out of scope when the function returns, prior
  11480. to reading the tuple element at index $0$. (We study the compilation
  11481. of functions in chapter~\ref{ch:Lfun}.)
  11482. %
  11483. \begin{center}
  11484. \begin{minipage}{0.96\textwidth}
  11485. \begin{lstlisting}
  11486. def f():
  11487. x = 42, 43
  11488. return x
  11489. t = f()
  11490. print(t[0])
  11491. \end{lstlisting}
  11492. \end{minipage}
  11493. \end{center}
  11494. \fi}
  11495. %
  11496. From the perspective of programmer-observable behavior, tuples live
  11497. forever. However, if they really lived forever then many long-running
  11498. programs would run out of memory. To solve this problem, the
  11499. language's runtime system performs automatic garbage collection.
  11500. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11501. \LangVec{} language.
  11502. %
  11503. \racket{We define the \code{vector}, \code{vector-ref},
  11504. \code{vector-set!}, and \code{vector-length} operations for
  11505. \LangVec{} in terms of the corresponding operations in Racket. One
  11506. subtle point is that the \code{vector-set!} operation returns the
  11507. \code{\#<void>} value.}
  11508. %
  11509. \python{We represent tuples with Python lists in the interpreter
  11510. because we need to write to them
  11511. (section~\ref{sec:expose-allocation}). (Python tuples are
  11512. immutable.) We define element access, the \code{is} operator, and
  11513. the \code{len} operator for \LangVec{} in terms of the corresponding
  11514. operations in Python.}
  11515. \begin{figure}[tbp]
  11516. \begin{tcolorbox}[colback=white]
  11517. {\if\edition\racketEd
  11518. \begin{lstlisting}
  11519. (define interp-Lvec-class
  11520. (class interp-Lwhile-class
  11521. (super-new)
  11522. (define/override (interp-op op)
  11523. (match op
  11524. ['eq? (lambda (v1 v2)
  11525. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11526. (and (boolean? v1) (boolean? v2))
  11527. (and (vector? v1) (vector? v2))
  11528. (and (void? v1) (void? v2)))
  11529. (eq? v1 v2)]))]
  11530. ['vector vector]
  11531. ['vector-length vector-length]
  11532. ['vector-ref vector-ref]
  11533. ['vector-set! vector-set!]
  11534. [else (super interp-op op)]
  11535. ))
  11536. (define/override ((interp-exp env) e)
  11537. (match e
  11538. [(HasType e t) ((interp-exp env) e)]
  11539. [else ((super interp-exp env) e)]
  11540. ))
  11541. ))
  11542. (define (interp-Lvec p)
  11543. (send (new interp-Lvec-class) interp-program p))
  11544. \end{lstlisting}
  11545. \fi}
  11546. %
  11547. {\if\edition\pythonEd\pythonColor
  11548. \begin{lstlisting}
  11549. class InterpLtup(InterpLwhile):
  11550. def interp_cmp(self, cmp):
  11551. match cmp:
  11552. case Is():
  11553. return lambda x, y: x is y
  11554. case _:
  11555. return super().interp_cmp(cmp)
  11556. def interp_exp(self, e, env):
  11557. match e:
  11558. case Tuple(es, Load()):
  11559. return tuple([self.interp_exp(e, env) for e in es])
  11560. case Subscript(tup, index, Load()):
  11561. t = self.interp_exp(tup, env)
  11562. n = self.interp_exp(index, env)
  11563. return t[n]
  11564. case _:
  11565. return super().interp_exp(e, env)
  11566. \end{lstlisting}
  11567. \fi}
  11568. \end{tcolorbox}
  11569. \caption{Interpreter for the \LangVec{} language.}
  11570. \label{fig:interp-Lvec}
  11571. \end{figure}
  11572. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11573. \LangVec{}.
  11574. %
  11575. The type of a tuple is a
  11576. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11577. type for each of its elements.
  11578. %
  11579. \racket{To create the s-expression for the \code{Vector} type, we use the
  11580. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11581. operator} \code{,@} to insert the list \code{t*} without its usual
  11582. start and end parentheses. \index{subject}{unquote-splicing}}
  11583. %
  11584. The type of accessing the ith element of a tuple is the ith element
  11585. type of the tuple's type, if there is one. If not, an error is
  11586. signaled. Note that the index \code{i} is required to be a constant
  11587. integer (and not, for example, a call to
  11588. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11589. can determine the element's type given the tuple type.
  11590. %
  11591. \racket{
  11592. Regarding writing an element to a tuple, the element's type must
  11593. be equal to the ith element type of the tuple's type.
  11594. The result type is \code{Void}.}
  11595. %% When allocating a tuple,
  11596. %% we need to know which elements of the tuple are themselves tuples for
  11597. %% the purposes of garbage collection. We can obtain this information
  11598. %% during type checking. The type checker shown in
  11599. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11600. %% expression; it also
  11601. %% %
  11602. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11603. %% where $T$ is the tuple's type.
  11604. %
  11605. %records the type of each tuple expression in a new field named \code{has\_type}.
  11606. \begin{figure}[tp]
  11607. \begin{tcolorbox}[colback=white]
  11608. {\if\edition\racketEd
  11609. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11610. (define type-check-Lvec-class
  11611. (class type-check-Lif-class
  11612. (super-new)
  11613. (inherit check-type-equal?)
  11614. (define/override (type-check-exp env)
  11615. (lambda (e)
  11616. (define recur (type-check-exp env))
  11617. (match e
  11618. [(Prim 'vector es)
  11619. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11620. (define t `(Vector ,@t*))
  11621. (values (Prim 'vector e*) t)]
  11622. [(Prim 'vector-ref (list e1 (Int i)))
  11623. (define-values (e1^ t) (recur e1))
  11624. (match t
  11625. [`(Vector ,ts ...)
  11626. (unless (and (0 . <= . i) (i . < . (length ts)))
  11627. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11628. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11629. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11630. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11631. (define-values (e-vec t-vec) (recur e1))
  11632. (define-values (e-elt^ t-elt) (recur elt))
  11633. (match t-vec
  11634. [`(Vector ,ts ...)
  11635. (unless (and (0 . <= . i) (i . < . (length ts)))
  11636. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11637. (check-type-equal? (list-ref ts i) t-elt e)
  11638. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11639. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11640. [(Prim 'vector-length (list e))
  11641. (define-values (e^ t) (recur e))
  11642. (match t
  11643. [`(Vector ,ts ...)
  11644. (values (Prim 'vector-length (list e^)) 'Integer)]
  11645. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11646. [(Prim 'eq? (list arg1 arg2))
  11647. (define-values (e1 t1) (recur arg1))
  11648. (define-values (e2 t2) (recur arg2))
  11649. (match* (t1 t2)
  11650. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11651. [(other wise) (check-type-equal? t1 t2 e)])
  11652. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11653. [else ((super type-check-exp env) e)]
  11654. )))
  11655. ))
  11656. (define (type-check-Lvec p)
  11657. (send (new type-check-Lvec-class) type-check-program p))
  11658. \end{lstlisting}
  11659. \fi}
  11660. {\if\edition\pythonEd\pythonColor
  11661. \begin{lstlisting}
  11662. class TypeCheckLtup(TypeCheckLwhile):
  11663. def type_check_exp(self, e, env):
  11664. match e:
  11665. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11666. l = self.type_check_exp(left, env)
  11667. r = self.type_check_exp(right, env)
  11668. check_type_equal(l, r, e)
  11669. return bool
  11670. case Tuple(es, Load()):
  11671. ts = [self.type_check_exp(e, env) for e in es]
  11672. e.has_type = TupleType(ts)
  11673. return e.has_type
  11674. case Subscript(tup, Constant(i), Load()):
  11675. tup_ty = self.type_check_exp(tup, env)
  11676. i_ty = self.type_check_exp(Constant(i), env)
  11677. check_type_equal(i_ty, int, i)
  11678. match tup_ty:
  11679. case TupleType(ts):
  11680. return ts[i]
  11681. case _:
  11682. raise Exception('expected a tuple, not ' + repr(tup_ty))
  11683. case _:
  11684. return super().type_check_exp(e, env)
  11685. \end{lstlisting}
  11686. \fi}
  11687. \end{tcolorbox}
  11688. \caption{Type checker for the \LangVec{} language.}
  11689. \label{fig:type-check-Lvec}
  11690. \end{figure}
  11691. \section{Garbage Collection}
  11692. \label{sec:GC}
  11693. Garbage collection is a runtime technique for reclaiming space on the
  11694. heap that will not be used in the future of the running program. We
  11695. use the term \emph{object}\index{subject}{object} to refer to any
  11696. value that is stored in the heap, which for now includes only
  11697. tuples.%
  11698. %
  11699. \footnote{The term \emph{object} as it is used in the context of
  11700. object-oriented programming has a more specific meaning than the
  11701. way in which we use the term here.}
  11702. %
  11703. Unfortunately, it is impossible to know precisely which objects will
  11704. be accessed in the future and which will not. Instead, garbage
  11705. collectors overapproximate the set of objects that will be accessed by
  11706. identifying which objects can possibly be accessed. The running
  11707. program can directly access objects that are in registers and on the
  11708. procedure call stack. It can also transitively access the elements of
  11709. tuples, starting with a tuple whose address is in a register or on the
  11710. procedure call stack. We define the \emph{root
  11711. set}\index{subject}{root set} to be all the tuple addresses that are
  11712. in registers or on the procedure call stack. We define the \emph{live
  11713. objects}\index{subject}{live objects} to be the objects that are
  11714. reachable from the root set. Garbage collectors reclaim the space that
  11715. is allocated to objects that are no longer live. \index{subject}{allocate}
  11716. That means that some objects may not get reclaimed as soon as they could be,
  11717. but at least
  11718. garbage collectors do not reclaim the space dedicated to objects that
  11719. will be accessed in the future! The programmer can influence which
  11720. objects get reclaimed by causing them to become unreachable.
  11721. So the goal of the garbage collector is twofold:
  11722. \begin{enumerate}
  11723. \item to preserve all the live objects, and
  11724. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11725. \end{enumerate}
  11726. \subsection{Two-Space Copying Collector}
  11727. Here we study a relatively simple algorithm for garbage collection
  11728. that is the basis of many state-of-the-art garbage
  11729. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11730. particular, we describe a two-space copying
  11731. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11732. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11733. collector} \index{subject}{two-space copying collector}
  11734. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11735. what happens in a two-space collector, showing two time steps, prior
  11736. to garbage collection (on the top) and after garbage collection (on
  11737. the bottom). In a two-space collector, the heap is divided into two
  11738. parts named the FromSpace\index{subject}{FromSpace} and the
  11739. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11740. FromSpace until there is not enough room for the next allocation
  11741. request. At that point, the garbage collector goes to work to make
  11742. room for the next allocation.
  11743. A copying collector makes more room by copying all the live objects
  11744. from the FromSpace into the ToSpace and then performs a sleight of
  11745. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11746. as the new ToSpace. In the example shown in
  11747. figure~\ref{fig:copying-collector}, the root set consists of three
  11748. pointers, one in a register and two on the stack. All the live
  11749. objects have been copied to the ToSpace (the right-hand side of
  11750. figure~\ref{fig:copying-collector}) in a way that preserves the
  11751. pointer relationships. For example, the pointer in the register still
  11752. points to a tuple that in turn points to two other tuples. There are
  11753. four tuples that are not reachable from the root set and therefore do
  11754. not get copied into the ToSpace.
  11755. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11756. created by a well-typed program in \LangVec{} because it contains a
  11757. cycle. However, creating cycles will be possible once we get to
  11758. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11759. to deal with cycles to begin with, so we will not need to revisit this
  11760. issue.
  11761. \begin{figure}[tbp]
  11762. \centering
  11763. \begin{tcolorbox}[colback=white]
  11764. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11765. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11766. \\[5ex]
  11767. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11768. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11769. \end{tcolorbox}
  11770. \caption{A copying collector in action.}
  11771. \label{fig:copying-collector}
  11772. \end{figure}
  11773. \subsection{Graph Copying via Cheney's Algorithm}
  11774. \label{sec:cheney}
  11775. \index{subject}{Cheney's algorithm}
  11776. Let us take a closer look at the copying of the live objects. The
  11777. allocated\index{subject}{allocate} objects and pointers can be viewed
  11778. as a graph, and we need to copy the part of the graph that is
  11779. reachable from the root set. To make sure that we copy all the
  11780. reachable vertices in the graph, we need an exhaustive graph traversal
  11781. algorithm, such as depth-first search or breadth-first
  11782. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11783. take into account the possibility of cycles by marking which vertices
  11784. have already been visited, so to ensure termination of the
  11785. algorithm. These search algorithms also use a data structure such as a
  11786. stack or queue as a to-do list to keep track of the vertices that need
  11787. to be visited. We use breadth-first search and a trick due to
  11788. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11789. copying tuples into the ToSpace.
  11790. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11791. copy progresses. The queue is represented by a chunk of contiguous
  11792. memory at the beginning of the ToSpace, using two pointers to track
  11793. the front and the back of the queue, called the \emph{free pointer}
  11794. and the \emph{scan pointer}, respectively. The algorithm starts by
  11795. copying all tuples that are immediately reachable from the root set
  11796. into the ToSpace to form the initial queue. When we copy a tuple, we
  11797. mark the old tuple to indicate that it has been visited. We discuss
  11798. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11799. that any pointers inside the copied tuples in the queue still point
  11800. back to the FromSpace. Once the initial queue has been created, the
  11801. algorithm enters a loop in which it repeatedly processes the tuple at
  11802. the front of the queue and pops it off the queue. To process a tuple,
  11803. the algorithm copies all the objects that are directly reachable from it
  11804. to the ToSpace, placing them at the back of the queue. The algorithm
  11805. then updates the pointers in the popped tuple so that they point to the
  11806. newly copied objects.
  11807. \begin{figure}[tbp]
  11808. \centering
  11809. \begin{tcolorbox}[colback=white]
  11810. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11811. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11812. \end{tcolorbox}
  11813. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11814. \label{fig:cheney}
  11815. \end{figure}
  11816. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11817. tuple whose second element is $42$ to the back of the queue. The other
  11818. pointer goes to a tuple that has already been copied, so we do not
  11819. need to copy it again, but we do need to update the pointer to the new
  11820. location. This can be accomplished by storing a \emph{forwarding
  11821. pointer}\index{subject}{forwarding pointer} to the new location in the
  11822. old tuple, when we initially copied the tuple into the
  11823. ToSpace. This completes one step of the algorithm. The algorithm
  11824. continues in this way until the queue is empty; that is, when the scan
  11825. pointer catches up with the free pointer.
  11826. \subsection{Data Representation}
  11827. \label{sec:data-rep-gc}
  11828. The garbage collector places some requirements on the data
  11829. representations used by our compiler. First, the garbage collector
  11830. needs to distinguish between pointers and other kinds of data such as
  11831. integers. The following are three ways to accomplish this:
  11832. \begin{enumerate}
  11833. \item Attach a tag to each object that identifies what type of
  11834. object it is~\citep{McCarthy:1960dz}.
  11835. \item Store different types of objects in different
  11836. regions~\citep{Steele:1977ab}.
  11837. \item Use type information from the program to either (a) generate
  11838. type-specific code for collecting, or (b) generate tables that
  11839. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11840. \end{enumerate}
  11841. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11842. need to tag objects in any case, so option 1 is a natural choice for those
  11843. languages. However, \LangVec{} is a statically typed language, so it
  11844. would be unfortunate to require tags on every object, especially small
  11845. and pervasive objects like integers and Booleans. Option 3 is the
  11846. best-performing choice for statically typed languages, but it comes with
  11847. a relatively high implementation complexity. To keep this chapter
  11848. within a reasonable scope of complexity, we recommend a combination of options
  11849. 1 and 2, using separate strategies for the stack and the heap.
  11850. Regarding the stack, we recommend using a separate stack for pointers,
  11851. which we call the \emph{root stack}\index{subject}{root stack}
  11852. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11853. That is, when a local variable needs to be spilled and is of type
  11854. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11855. root stack instead of putting it on the procedure call
  11856. stack. Furthermore, we always spill tuple-typed variables if they are
  11857. live during a call to the collector, thereby ensuring that no pointers
  11858. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11859. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11860. contrasts it with the data layout using a root stack. The root stack
  11861. contains the two pointers from the regular stack and also the pointer
  11862. in the second register.
  11863. \begin{figure}[tbp]
  11864. \centering
  11865. \begin{tcolorbox}[colback=white]
  11866. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11867. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11868. \end{tcolorbox}
  11869. \caption{Maintaining a root stack to facilitate garbage collection.}
  11870. \label{fig:shadow-stack}
  11871. \end{figure}
  11872. The problem of distinguishing between pointers and other kinds of data
  11873. also arises inside each tuple on the heap. We solve this problem by
  11874. attaching a tag, an extra 64 bits, to each
  11875. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11876. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11877. Note that we have drawn the bits in a big-endian way, from right to left,
  11878. with bit location 0 (the least significant bit) on the far right,
  11879. which corresponds to the direction of the x86 shifting instructions
  11880. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11881. is dedicated to specifying which elements of the tuple are pointers,
  11882. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11883. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11884. data. The pointer mask starts at bit location 7. We limit tuples to a
  11885. maximum size of fifty elements, so we need 50 bits for the pointer
  11886. mask.%
  11887. %
  11888. \footnote{A production-quality compiler would handle
  11889. arbitrarily sized tuples and use a more complex approach.}
  11890. %
  11891. The tag also contains two other pieces of information. The length of
  11892. the tuple (number of elements) is stored in bits at locations 1 through
  11893. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11894. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11895. has not yet been copied. If the bit has value 0, then the entire tag
  11896. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11897. zero in any case, because our tuples are 8-byte aligned.)
  11898. \begin{figure}[tbp]
  11899. \centering
  11900. \begin{tcolorbox}[colback=white]
  11901. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11902. \end{tcolorbox}
  11903. \caption{Representation of tuples in the heap.}
  11904. \label{fig:tuple-rep}
  11905. \end{figure}
  11906. \subsection{Implementation of the Garbage Collector}
  11907. \label{sec:organize-gz}
  11908. \index{subject}{prelude}
  11909. An implementation of the copying collector is provided in the
  11910. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11911. interface to the garbage collector that is used by the compiler. The
  11912. \code{initialize} function creates the FromSpace, ToSpace, and root
  11913. stack and should be called in the prelude of the \code{main}
  11914. function. The arguments of \code{initialize} are the root stack size
  11915. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11916. good choice for both. The \code{initialize} function puts the address
  11917. of the beginning of the FromSpace into the global variable
  11918. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11919. the address that is one past the last element of the FromSpace. We use
  11920. half-open intervals to represent chunks of
  11921. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11922. points to the first element of the root stack.
  11923. As long as there is room left in the FromSpace, your generated code
  11924. can allocate\index{subject}{allocate} tuples simply by moving the
  11925. \code{free\_ptr} forward.
  11926. %
  11927. The amount of room left in the FromSpace is the difference between the
  11928. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11929. function should be called when there is not enough room left in the
  11930. FromSpace for the next allocation. The \code{collect} function takes
  11931. a pointer to the current top of the root stack (one past the last item
  11932. that was pushed) and the number of bytes that need to be
  11933. allocated. The \code{collect} function performs the copying collection
  11934. and leaves the heap in a state such that there is enough room for the
  11935. next allocation.
  11936. \begin{figure}[tbp]
  11937. \begin{tcolorbox}[colback=white]
  11938. \begin{lstlisting}
  11939. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11940. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11941. int64_t* free_ptr;
  11942. int64_t* fromspace_begin;
  11943. int64_t* fromspace_end;
  11944. int64_t** rootstack_begin;
  11945. \end{lstlisting}
  11946. \end{tcolorbox}
  11947. \caption{The compiler's interface to the garbage collector.}
  11948. \label{fig:gc-header}
  11949. \end{figure}
  11950. %% \begin{exercise}
  11951. %% In the file \code{runtime.c} you will find the implementation of
  11952. %% \code{initialize} and a partial implementation of \code{collect}.
  11953. %% The \code{collect} function calls another function, \code{cheney},
  11954. %% to perform the actual copy, and that function is left to the reader
  11955. %% to implement. The following is the prototype for \code{cheney}.
  11956. %% \begin{lstlisting}
  11957. %% static void cheney(int64_t** rootstack_ptr);
  11958. %% \end{lstlisting}
  11959. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11960. %% rootstack (which is an array of pointers). The \code{cheney} function
  11961. %% also communicates with \code{collect} through the global
  11962. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11963. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11964. %% the ToSpace:
  11965. %% \begin{lstlisting}
  11966. %% static int64_t* tospace_begin;
  11967. %% static int64_t* tospace_end;
  11968. %% \end{lstlisting}
  11969. %% The job of the \code{cheney} function is to copy all the live
  11970. %% objects (reachable from the root stack) into the ToSpace, update
  11971. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11972. %% update the root stack so that it points to the objects in the
  11973. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11974. %% and ToSpace.
  11975. %% \end{exercise}
  11976. The introduction of garbage collection has a nontrivial impact on our
  11977. compiler passes. We introduce a new compiler pass named
  11978. \code{expose\_allocation} that elaborates the code for allocating
  11979. tuples. We also make significant changes to
  11980. \code{select\_instructions}, \code{build\_interference},
  11981. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11982. make minor changes in several more passes.
  11983. The following program serves as our running example. It creates
  11984. two tuples, one nested inside the other. Both tuples have length
  11985. one. The program accesses the element in the inner tuple.
  11986. % tests/vectors_test_17.rkt
  11987. {\if\edition\racketEd
  11988. \begin{lstlisting}
  11989. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11990. \end{lstlisting}
  11991. \fi}
  11992. % tests/tuple/get_get.py
  11993. {\if\edition\pythonEd\pythonColor
  11994. \begin{lstlisting}
  11995. v1 = (42,)
  11996. v2 = (v1,)
  11997. print(v2[0][0])
  11998. \end{lstlisting}
  11999. \fi}
  12000. %% {\if\edition\racketEd
  12001. %% \section{Shrink}
  12002. %% \label{sec:shrink-Lvec}
  12003. %% Recall that the \code{shrink} pass translates the primitives operators
  12004. %% into a smaller set of primitives.
  12005. %% %
  12006. %% This pass comes after type checking, and the type checker adds a
  12007. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  12008. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  12009. %% \fi}
  12010. \section{Expose Allocation}
  12011. \label{sec:expose-allocation}
  12012. The pass \code{expose\_allocation} lowers tuple creation into making a
  12013. conditional call to the collector followed by allocating the
  12014. appropriate amount of memory and initializing it. We choose to place
  12015. the \code{expose\_allocation} pass before
  12016. \code{remove\_complex\_operands} because it generates code that
  12017. contains complex operands. However, with some care it can also be
  12018. placed after \code{remove\_complex\_operands}, which would simplify
  12019. tuple creation by removing the need to assign the initializing
  12020. expressions to temporary variables (see below).
  12021. The output of \code{expose\_allocation} is a language \LangAlloc{}
  12022. that replaces tuple creation with new lower-level forms that we use in the
  12023. translation of tuple creation\index{subject}{Lalloc@\LangAlloc{}}.
  12024. %
  12025. {\if\edition\racketEd
  12026. \[
  12027. \begin{array}{lcl}
  12028. \Exp &::=& (\key{collect} \,\itm{int})
  12029. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  12030. \MID (\key{global-value} \,\itm{name})
  12031. \end{array}
  12032. \]
  12033. \fi}
  12034. {\if\edition\pythonEd\pythonColor
  12035. \[
  12036. \begin{array}{lcl}
  12037. \Exp &::=& \key{collect}(\itm{int})
  12038. \MID \key{allocate}(\itm{int},\itm{type})
  12039. \MID \key{global\_value}(\itm{name}) \\
  12040. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  12041. \end{array}
  12042. \]
  12043. \fi}
  12044. %
  12045. The \CCOLLECT{$n$} form runs the garbage collector, requesting that
  12046. there be $n$ bytes ready to be allocated. During instruction
  12047. selection\index{subject}{instruction selection}, the \CCOLLECT{$n$}
  12048. form will become a call to the \code{collect} function in
  12049. \code{runtime.c}.
  12050. %
  12051. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  12052. space at the front for the 64-bit tag), but the elements are not
  12053. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  12054. of the tuple:
  12055. %
  12056. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  12057. %
  12058. where $\Type_i$ is the type of the $i$th element.
  12059. %
  12060. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  12061. variable, such as \code{free\_ptr}.
  12062. \racket{
  12063. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  12064. can be obtained by running the
  12065. \code{type-check-Lvec-has-type} type checker immediately before the
  12066. \code{expose\_allocation} pass. This version of the type checker
  12067. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  12068. around each tuple creation. The concrete syntax
  12069. for \code{HasType} is \code{has-type}.}
  12070. The following shows the transformation of tuple creation into (1) a
  12071. sequence of temporary variable bindings for the initializing
  12072. expressions, (2) a conditional call to \code{collect}, (3) a call to
  12073. \code{allocate}, and (4) the initialization of the tuple. The
  12074. \itm{len} placeholder refers to the length of the tuple, and
  12075. \itm{bytes} is the total number of bytes that need to be allocated for
  12076. the tuple, which is 8 for the tag plus \itm{len} times 8.
  12077. %
  12078. \python{The \itm{type} needed for the second argument of the
  12079. \code{allocate} form can be obtained from the \code{has\_type} field
  12080. of the tuple AST node, which is stored there by running the type
  12081. checker for \LangVec{} immediately before this pass.}
  12082. %
  12083. \begin{center}
  12084. \begin{minipage}{\textwidth}
  12085. {\if\edition\racketEd
  12086. \begin{lstlisting}
  12087. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12088. |$\Longrightarrow$|
  12089. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12090. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12091. (global-value fromspace_end))
  12092. (void)
  12093. (collect |\itm{bytes}|))])
  12094. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12095. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12096. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12097. |$v$|) ... )))) ...)
  12098. \end{lstlisting}
  12099. \fi}
  12100. {\if\edition\pythonEd\pythonColor
  12101. \begin{lstlisting}
  12102. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12103. |$\Longrightarrow$|
  12104. begin:
  12105. |$x_0$| = |$e_0$|
  12106. |$\vdots$|
  12107. |$x_{n-1}$| = |$e_{n-1}$|
  12108. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12109. 0
  12110. else:
  12111. collect(|\itm{bytes}|)
  12112. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12113. |$v$|[0] = |$x_0$|
  12114. |$\vdots$|
  12115. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12116. |$v$|
  12117. \end{lstlisting}
  12118. \fi}
  12119. \end{minipage}
  12120. \end{center}
  12121. %
  12122. \noindent The sequencing of the initializing expressions
  12123. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12124. they may trigger garbage collection and we cannot have an allocated
  12125. but uninitialized tuple on the heap during a collection.
  12126. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12127. \code{expose\_allocation} pass on our running example.
  12128. \begin{figure}[tbp]
  12129. \begin{tcolorbox}[colback=white]
  12130. % tests/s2_17.rkt
  12131. {\if\edition\racketEd
  12132. \begin{lstlisting}
  12133. (vector-ref
  12134. (vector-ref
  12135. (let ([vecinit6
  12136. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12137. (global-value fromspace_end))
  12138. (void)
  12139. (collect 16))])
  12140. (let ([alloc2 (allocate 1 (Vector Integer))])
  12141. (let ([_3 (vector-set! alloc2 0 42)])
  12142. alloc2)))])
  12143. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12144. (global-value fromspace_end))
  12145. (void)
  12146. (collect 16))])
  12147. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12148. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12149. alloc5))))
  12150. 0)
  12151. 0)
  12152. \end{lstlisting}
  12153. \fi}
  12154. {\if\edition\pythonEd\pythonColor
  12155. \begin{lstlisting}
  12156. v1 = begin:
  12157. init.514 = 42
  12158. if (free_ptr + 16) < fromspace_end:
  12159. else:
  12160. collect(16)
  12161. alloc.513 = allocate(1,tuple[int])
  12162. alloc.513[0] = init.514
  12163. alloc.513
  12164. v2 = begin:
  12165. init.516 = v1
  12166. if (free_ptr + 16) < fromspace_end:
  12167. else:
  12168. collect(16)
  12169. alloc.515 = allocate(1,tuple[tuple[int]])
  12170. alloc.515[0] = init.516
  12171. alloc.515
  12172. print(v2[0][0])
  12173. \end{lstlisting}
  12174. \fi}
  12175. \end{tcolorbox}
  12176. \caption{Output of the \code{expose\_allocation} pass.}
  12177. \label{fig:expose-alloc-output}
  12178. \end{figure}
  12179. \section{Remove Complex Operands}
  12180. \label{sec:remove-complex-opera-Lvec}
  12181. {\if\edition\racketEd
  12182. %
  12183. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12184. should be treated as complex operands.
  12185. %
  12186. \fi}
  12187. %
  12188. {\if\edition\pythonEd\pythonColor
  12189. %
  12190. The expressions \code{allocate}, \code{begin},
  12191. and tuple access should be treated as complex operands. The
  12192. subexpressions of tuple access must be atomic.
  12193. The \code{global\_value} AST node is atomic.
  12194. %
  12195. \fi}
  12196. %% A new case for
  12197. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12198. %% handled carefully to prevent the \code{Prim} node from being separated
  12199. %% from its enclosing \code{HasType}.
  12200. Figure~\ref{fig:Lvec-anf-syntax}
  12201. shows the grammar for the output language \LangAllocANF{} of this
  12202. pass, which is \LangAlloc{} in monadic normal form.
  12203. \newcommand{\LtupMonadASTRacket}{
  12204. \begin{array}{rcl}
  12205. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12206. \MID \GLOBALVALUE{\Var}
  12207. \end{array}
  12208. }
  12209. \newcommand{\LtupMonadASTPython}{
  12210. \begin{array}{rcl}
  12211. \Atm &::=& \GLOBALVALUE{\Var} \\
  12212. \Exp &::=& \GET{\Atm}{\Atm}
  12213. \MID \LEN{\Atm}\\
  12214. &\MID& \ALLOCATE{\Int}{\Type}\\
  12215. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12216. &\MID& \COLLECT{\Int}
  12217. \end{array}
  12218. }
  12219. \begin{figure}[tp]
  12220. \centering
  12221. \begin{tcolorbox}[colback=white]
  12222. \small
  12223. {\if\edition\racketEd
  12224. \[
  12225. \begin{array}{l}
  12226. \gray{\LvarMonadASTRacket} \\ \hline
  12227. \gray{\LifMonadASTRacket} \\ \hline
  12228. \gray{\LwhileMonadASTRacket} \\ \hline
  12229. \LtupMonadASTRacket \\
  12230. \begin{array}{rcl}
  12231. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12232. \end{array}
  12233. \end{array}
  12234. \]
  12235. \fi}
  12236. {\if\edition\pythonEd\pythonColor
  12237. \[
  12238. \begin{array}{l}
  12239. \gray{\LvarMonadASTPython} \\ \hline
  12240. \gray{\LifMonadASTPython} \\ \hline
  12241. \gray{\LwhileMonadASTPython} \\ \hline
  12242. \LtupMonadASTPython \\
  12243. \begin{array}{rcl}
  12244. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12245. \end{array}
  12246. \end{array}
  12247. \]
  12248. \fi}
  12249. \end{tcolorbox}
  12250. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12251. \label{fig:Lvec-anf-syntax}
  12252. \index{subject}{Ltupmon@\LangAllocANF{} abstract syntax}
  12253. \end{figure}
  12254. \section{Explicate Control and the \LangCVec{} Language}
  12255. \label{sec:explicate-control-r3}
  12256. \newcommand{\CtupASTRacket}{
  12257. \begin{array}{lcl}
  12258. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12259. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12260. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12261. &\MID& \VECLEN{\Atm} \\
  12262. &\MID& \GLOBALVALUE{\Var} \\
  12263. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12264. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12265. \end{array}
  12266. }
  12267. \newcommand{\CtupASTPython}{
  12268. \begin{array}{lcl}
  12269. \Atm &::=& \GLOBALVALUE{\Var} \\
  12270. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12271. &\MID& \LEN{\Atm} \\
  12272. \Stmt &::=& \COLLECT{\Int}
  12273. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12274. \end{array}
  12275. }
  12276. \begin{figure}[tp]
  12277. \begin{tcolorbox}[colback=white]
  12278. \small
  12279. {\if\edition\racketEd
  12280. \[
  12281. \begin{array}{l}
  12282. \gray{\CvarASTRacket} \\ \hline
  12283. \gray{\CifASTRacket} \\ \hline
  12284. \gray{\CloopASTRacket} \\ \hline
  12285. \CtupASTRacket \\
  12286. \begin{array}{lcl}
  12287. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12288. \end{array}
  12289. \end{array}
  12290. \]
  12291. \fi}
  12292. {\if\edition\pythonEd\pythonColor
  12293. \[
  12294. \begin{array}{l}
  12295. \gray{\CifASTPython} \\ \hline
  12296. \CtupASTPython \\
  12297. \begin{array}{lcl}
  12298. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12299. \end{array}
  12300. \end{array}
  12301. \]
  12302. \fi}
  12303. \end{tcolorbox}
  12304. \caption{The abstract syntax of \LangCVec{}, extending
  12305. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12306. (figure~\ref{fig:c1-syntax})}.}
  12307. \label{fig:c2-syntax}
  12308. \index{subject}{Cvec@\LangCVec{} abstract syntax}
  12309. \end{figure}
  12310. The output of \code{explicate\_control} is a program in the
  12311. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12312. shows the definition of the abstract syntax.
  12313. %
  12314. %% \racket{(The concrete syntax is defined in
  12315. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12316. %
  12317. The new expressions of \LangCVec{} include \key{allocate},
  12318. %
  12319. \racket{\key{vector-ref}, and \key{vector-set!},}
  12320. %
  12321. \python{accessing tuple elements,}
  12322. %
  12323. and \key{global\_value}.
  12324. %
  12325. \python{\LangCVec{} also includes the \code{collect} statement and
  12326. assignment to a tuple element.}
  12327. %
  12328. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12329. %
  12330. The \code{explicate\_control} pass can treat these new forms much like
  12331. the other forms that we've already encountered. The output of the
  12332. \code{explicate\_control} pass on the running example is shown on the
  12333. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12334. section.
  12335. \section{Select Instructions and the \LangXGlobal{} Language}
  12336. \label{sec:select-instructions-gc}
  12337. \index{subject}{select instructions}
  12338. %% void (rep as zero)
  12339. %% allocate
  12340. %% collect (callq collect)
  12341. %% vector-ref
  12342. %% vector-set!
  12343. %% vector-length
  12344. %% global (postpone)
  12345. In this pass we generate x86 code for most of the new operations that
  12346. are needed to compile tuples, including \code{Allocate},
  12347. \code{Collect}, accessing tuple elements, and the \code{Is}
  12348. comparison.
  12349. %
  12350. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12351. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12352. \ref{fig:x86-2}). \index{subject}{x86}
  12353. The tuple read and write forms translate into \code{movq}
  12354. instructions. (The $+1$ in the offset serves to move past the tag at the
  12355. beginning of the tuple representation.)
  12356. %
  12357. \begin{center}
  12358. \begin{minipage}{\textwidth}
  12359. {\if\edition\racketEd
  12360. \begin{lstlisting}
  12361. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12362. |$\Longrightarrow$|
  12363. movq |$\itm{tup}'$|, %r11
  12364. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12365. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12366. |$\Longrightarrow$|
  12367. movq |$\itm{tup}'$|, %r11
  12368. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12369. movq $0, |$\itm{lhs'}$|
  12370. \end{lstlisting}
  12371. \fi}
  12372. {\if\edition\pythonEd\pythonColor
  12373. \begin{lstlisting}
  12374. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12375. |$\Longrightarrow$|
  12376. movq |$\itm{tup}'$|, %r11
  12377. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12378. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12379. |$\Longrightarrow$|
  12380. movq |$\itm{tup}'$|, %r11
  12381. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12382. \end{lstlisting}
  12383. \fi}
  12384. \end{minipage}
  12385. \end{center}
  12386. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12387. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12388. are obtained by translating from \LangCVec{} to x86.
  12389. %
  12390. The move of $\itm{tup}'$ to
  12391. register \code{r11} ensures that the offset expression
  12392. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12393. removing \code{r11} from consideration by the register allocator.
  12394. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12395. \code{rax}. Then the generated code for tuple assignment would be
  12396. \begin{lstlisting}
  12397. movq |$\itm{tup}'$|, %rax
  12398. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12399. \end{lstlisting}
  12400. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12401. \code{patch\_instructions} would insert a move through \code{rax}
  12402. as follows:
  12403. \begin{lstlisting}
  12404. movq |$\itm{tup}'$|, %rax
  12405. movq |$\itm{rhs}'$|, %rax
  12406. movq %rax, |$8(n+1)$|(%rax)
  12407. \end{lstlisting}
  12408. However, this sequence of instructions does not work because we're
  12409. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12410. $\itm{rhs}'$) at the same time!
  12411. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12412. be translated into a sequence of instructions that read the tag of the
  12413. tuple and extract the 6 bits that represent the tuple length, which
  12414. are the bits starting at index 1 and going up to and including bit 6.
  12415. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12416. (shift right) can be used to accomplish this.
  12417. We compile the \code{allocate} form to operations on the
  12418. \code{free\_ptr}, as shown next. This approach is called
  12419. \emph{inline allocation} because it implements allocation without a
  12420. function call by simply incrementing the allocation pointer. It is much
  12421. more efficient than calling a function for each allocation. The
  12422. address in the \code{free\_ptr} is the next free address in the
  12423. FromSpace, so we copy it into \code{r11} and then move it forward by
  12424. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12425. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12426. the tag. We then initialize the \itm{tag} and finally copy the
  12427. address in \code{r11} to the left-hand side. Refer to
  12428. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12429. %
  12430. \racket{We recommend using the Racket operations
  12431. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12432. during compilation.}
  12433. %
  12434. \python{We recommend using the bitwise-or operator \code{|} and the
  12435. shift-left operator \code{<<} to compute the tag during
  12436. compilation.}
  12437. %
  12438. The type annotation in the \code{allocate} form is used to determine
  12439. the pointer mask region of the tag.
  12440. %
  12441. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12442. address of the \code{free\_ptr} global variable using a special
  12443. instruction-pointer-relative addressing mode of the x86-64 processor.
  12444. In particular, the assembler computes the distance $d$ between the
  12445. address of \code{free\_ptr} and where the \code{rip} would be at that
  12446. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12447. \code{$d$(\%rip)}, which at runtime will compute the address of
  12448. \code{free\_ptr}.
  12449. %
  12450. {\if\edition\racketEd
  12451. \begin{lstlisting}
  12452. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12453. |$\Longrightarrow$|
  12454. movq free_ptr(%rip), %r11
  12455. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12456. movq $|$\itm{tag}$|, 0(%r11)
  12457. movq %r11, |$\itm{lhs}'$|
  12458. \end{lstlisting}
  12459. \fi}
  12460. {\if\edition\pythonEd\pythonColor
  12461. \begin{lstlisting}
  12462. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12463. |$\Longrightarrow$|
  12464. movq free_ptr(%rip), %r11
  12465. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12466. movq $|$\itm{tag}$|, 0(%r11)
  12467. movq %r11, |$\itm{lhs}'$|
  12468. \end{lstlisting}
  12469. \fi}
  12470. %
  12471. The \code{collect} form is compiled to a call to the \code{collect}
  12472. function in the runtime. The arguments to \code{collect} are (1) the
  12473. top of the root stack, and (2) the number of bytes that need to be
  12474. allocated. We use another dedicated register, \code{r15}, to store
  12475. the pointer to the top of the root stack. Therefore \code{r15} is not
  12476. available for use by the register allocator.
  12477. %
  12478. {\if\edition\racketEd
  12479. \begin{lstlisting}
  12480. (collect |$\itm{bytes}$|)
  12481. |$\Longrightarrow$|
  12482. movq %r15, %rdi
  12483. movq $|\itm{bytes}|, %rsi
  12484. callq collect
  12485. \end{lstlisting}
  12486. \fi}
  12487. {\if\edition\pythonEd\pythonColor
  12488. \begin{lstlisting}
  12489. collect(|$\itm{bytes}$|)
  12490. |$\Longrightarrow$|
  12491. movq %r15, %rdi
  12492. movq $|\itm{bytes}|, %rsi
  12493. callq collect
  12494. \end{lstlisting}
  12495. \fi}
  12496. {\if\edition\pythonEd\pythonColor
  12497. The \code{is} comparison is compiled similarly to the other comparison
  12498. operators, using the \code{cmpq} instruction. Because the value of a
  12499. tuple is its address, we can translate \code{is} into a simple check
  12500. for equality using the \code{e} condition code. \\
  12501. \begin{tabular}{lll}
  12502. \begin{minipage}{0.4\textwidth}
  12503. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12504. \end{minipage}
  12505. &
  12506. $\Rightarrow$
  12507. &
  12508. \begin{minipage}{0.4\textwidth}
  12509. \begin{lstlisting}
  12510. cmpq |$\Arg_2$|, |$\Arg_1$|
  12511. sete %al
  12512. movzbq %al, |$\Var$|
  12513. \end{lstlisting}
  12514. \end{minipage}
  12515. \end{tabular}
  12516. \fi}
  12517. \newcommand{\GrammarXGlobal}{
  12518. \begin{array}{lcl}
  12519. \Arg &::=& \itm{label} \key{(\%rip)}
  12520. \end{array}
  12521. }
  12522. \newcommand{\ASTXGlobalRacket}{
  12523. \begin{array}{lcl}
  12524. \Arg &::=& \GLOBAL{\itm{label}}
  12525. \end{array}
  12526. }
  12527. \begin{figure}[tp]
  12528. \begin{tcolorbox}[colback=white]
  12529. {\if\edition\racketEd
  12530. \[
  12531. \begin{array}{l}
  12532. \gray{\GrammarXIntRacket} \\ \hline
  12533. \gray{\GrammarXIfRacket} \\ \hline
  12534. \GrammarXGlobal \\
  12535. \begin{array}{lcl}
  12536. \LangXGlobalM{} &::= & \key{.globl main} \\
  12537. & & \key{main:} \; \Instr^{*}
  12538. \end{array}
  12539. \end{array}
  12540. \]
  12541. \fi}
  12542. {\if\edition\pythonEd\pythonColor
  12543. \[
  12544. \begin{array}{l}
  12545. \gray{\GrammarXIntPython} \\ \hline
  12546. \gray{\GrammarXIfPython} \\ \hline
  12547. \GrammarXGlobal \\
  12548. \begin{array}{lcl}
  12549. \LangXGlobalM{} &::= & \key{.globl main} \\
  12550. & & \key{main:} \; \Instr^{*}
  12551. \end{array}
  12552. \end{array}
  12553. \]
  12554. \fi}
  12555. \end{tcolorbox}
  12556. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12557. \label{fig:x86-2-concrete}
  12558. \end{figure}
  12559. \begin{figure}[tp]
  12560. \begin{tcolorbox}[colback=white]
  12561. \small
  12562. {\if\edition\racketEd
  12563. \[
  12564. \begin{array}{l}
  12565. \gray{\ASTXIntRacket} \\ \hline
  12566. \gray{\ASTXIfRacket} \\ \hline
  12567. \ASTXGlobalRacket \\
  12568. \begin{array}{lcl}
  12569. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12570. \end{array}
  12571. \end{array}
  12572. \]
  12573. \fi}
  12574. {\if\edition\pythonEd\pythonColor
  12575. \[
  12576. \begin{array}{l}
  12577. \gray{\ASTXIntPython} \\ \hline
  12578. \gray{\ASTXIfPython} \\ \hline
  12579. \ASTXGlobalRacket \\
  12580. \begin{array}{lcl}
  12581. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12582. \end{array}
  12583. \end{array}
  12584. \]
  12585. \fi}
  12586. \end{tcolorbox}
  12587. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12588. \label{fig:x86-2}
  12589. \end{figure}
  12590. The definitions of the concrete and abstract syntax of the
  12591. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12592. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12593. of global variables.
  12594. %
  12595. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12596. \code{select\_instructions} pass on the running example.
  12597. \begin{figure}[tbp]
  12598. \centering
  12599. \begin{tcolorbox}[colback=white]
  12600. {\if\edition\racketEd
  12601. % tests/s2_17.rkt
  12602. \begin{tabular}{lll}
  12603. \begin{minipage}{0.5\textwidth}
  12604. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12605. start:
  12606. tmp9 = (global-value free_ptr);
  12607. tmp0 = (+ tmp9 16);
  12608. tmp1 = (global-value fromspace_end);
  12609. if (< tmp0 tmp1)
  12610. goto block0;
  12611. else
  12612. goto block1;
  12613. block0:
  12614. _4 = (void);
  12615. goto block9;
  12616. block1:
  12617. (collect 16)
  12618. goto block9;
  12619. block9:
  12620. alloc2 = (allocate 1 (Vector Integer));
  12621. _3 = (vector-set! alloc2 0 42);
  12622. vecinit6 = alloc2;
  12623. tmp2 = (global-value free_ptr);
  12624. tmp3 = (+ tmp2 16);
  12625. tmp4 = (global-value fromspace_end);
  12626. if (< tmp3 tmp4)
  12627. goto block7;
  12628. else
  12629. goto block8;
  12630. block7:
  12631. _8 = (void);
  12632. goto block6;
  12633. block8:
  12634. (collect 16)
  12635. goto block6;
  12636. block6:
  12637. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12638. _7 = (vector-set! alloc5 0 vecinit6);
  12639. tmp5 = (vector-ref alloc5 0);
  12640. return (vector-ref tmp5 0);
  12641. \end{lstlisting}
  12642. \end{minipage}
  12643. &$\Rightarrow$&
  12644. \begin{minipage}{0.4\textwidth}
  12645. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12646. start:
  12647. movq free_ptr(%rip), tmp9
  12648. movq tmp9, tmp0
  12649. addq $16, tmp0
  12650. movq fromspace_end(%rip), tmp1
  12651. cmpq tmp1, tmp0
  12652. jl block0
  12653. jmp block1
  12654. block0:
  12655. movq $0, _4
  12656. jmp block9
  12657. block1:
  12658. movq %r15, %rdi
  12659. movq $16, %rsi
  12660. callq collect
  12661. jmp block9
  12662. block9:
  12663. movq free_ptr(%rip), %r11
  12664. addq $16, free_ptr(%rip)
  12665. movq $3, 0(%r11)
  12666. movq %r11, alloc2
  12667. movq alloc2, %r11
  12668. movq $42, 8(%r11)
  12669. movq $0, _3
  12670. movq alloc2, vecinit6
  12671. movq free_ptr(%rip), tmp2
  12672. movq tmp2, tmp3
  12673. addq $16, tmp3
  12674. movq fromspace_end(%rip), tmp4
  12675. cmpq tmp4, tmp3
  12676. jl block7
  12677. jmp block8
  12678. block7:
  12679. movq $0, _8
  12680. jmp block6
  12681. block8:
  12682. movq %r15, %rdi
  12683. movq $16, %rsi
  12684. callq collect
  12685. jmp block6
  12686. block6:
  12687. movq free_ptr(%rip), %r11
  12688. addq $16, free_ptr(%rip)
  12689. movq $131, 0(%r11)
  12690. movq %r11, alloc5
  12691. movq alloc5, %r11
  12692. movq vecinit6, 8(%r11)
  12693. movq $0, _7
  12694. movq alloc5, %r11
  12695. movq 8(%r11), tmp5
  12696. movq tmp5, %r11
  12697. movq 8(%r11), %rax
  12698. jmp conclusion
  12699. \end{lstlisting}
  12700. \end{minipage}
  12701. \end{tabular}
  12702. \fi}
  12703. {\if\edition\pythonEd
  12704. % tests/tuple/get_get.py
  12705. \begin{tabular}{lll}
  12706. \begin{minipage}{0.5\textwidth}
  12707. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12708. start:
  12709. init.514 = 42
  12710. tmp.517 = free_ptr
  12711. tmp.518 = (tmp.517 + 16)
  12712. tmp.519 = fromspace_end
  12713. if tmp.518 < tmp.519:
  12714. goto block.529
  12715. else:
  12716. goto block.530
  12717. block.529:
  12718. goto block.528
  12719. block.530:
  12720. collect(16)
  12721. goto block.528
  12722. block.528:
  12723. alloc.513 = allocate(1,tuple[int])
  12724. alloc.513:tuple[int][0] = init.514
  12725. v1 = alloc.513
  12726. init.516 = v1
  12727. tmp.520 = free_ptr
  12728. tmp.521 = (tmp.520 + 16)
  12729. tmp.522 = fromspace_end
  12730. if tmp.521 < tmp.522:
  12731. goto block.526
  12732. else:
  12733. goto block.527
  12734. block.526:
  12735. goto block.525
  12736. block.527:
  12737. collect(16)
  12738. goto block.525
  12739. block.525:
  12740. alloc.515 = allocate(1,tuple[tuple[int]])
  12741. alloc.515:tuple[tuple[int]][0] = init.516
  12742. v2 = alloc.515
  12743. tmp.523 = v2[0]
  12744. tmp.524 = tmp.523[0]
  12745. print(tmp.524)
  12746. return 0
  12747. \end{lstlisting}
  12748. \end{minipage}
  12749. &$\Rightarrow$&
  12750. \begin{minipage}{0.4\textwidth}
  12751. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12752. start:
  12753. movq $42, init.514
  12754. movq free_ptr(%rip), tmp.517
  12755. movq tmp.517, tmp.518
  12756. addq $16, tmp.518
  12757. movq fromspace_end(%rip), tmp.519
  12758. cmpq tmp.519, tmp.518
  12759. jl block.529
  12760. jmp block.530
  12761. block.529:
  12762. jmp block.528
  12763. block.530:
  12764. movq %r15, %rdi
  12765. movq $16, %rsi
  12766. callq collect
  12767. jmp block.528
  12768. block.528:
  12769. movq free_ptr(%rip), %r11
  12770. addq $16, free_ptr(%rip)
  12771. movq $3, 0(%r11)
  12772. movq %r11, alloc.513
  12773. movq alloc.513, %r11
  12774. movq init.514, 8(%r11)
  12775. movq alloc.513, v1
  12776. movq v1, init.516
  12777. movq free_ptr(%rip), tmp.520
  12778. movq tmp.520, tmp.521
  12779. addq $16, tmp.521
  12780. movq fromspace_end(%rip), tmp.522
  12781. cmpq tmp.522, tmp.521
  12782. jl block.526
  12783. jmp block.527
  12784. block.526:
  12785. jmp block.525
  12786. block.527:
  12787. movq %r15, %rdi
  12788. movq $16, %rsi
  12789. callq collect
  12790. jmp block.525
  12791. block.525:
  12792. movq free_ptr(%rip), %r11
  12793. addq $16, free_ptr(%rip)
  12794. movq $131, 0(%r11)
  12795. movq %r11, alloc.515
  12796. movq alloc.515, %r11
  12797. movq init.516, 8(%r11)
  12798. movq alloc.515, v2
  12799. movq v2, %r11
  12800. movq 8(%r11), %r11
  12801. movq %r11, tmp.523
  12802. movq tmp.523, %r11
  12803. movq 8(%r11), %r11
  12804. movq %r11, tmp.524
  12805. movq tmp.524, %rdi
  12806. callq print_int
  12807. movq $0, %rax
  12808. jmp conclusion
  12809. \end{lstlisting}
  12810. \end{minipage}
  12811. \end{tabular}
  12812. \fi}
  12813. \end{tcolorbox}
  12814. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12815. \code{select\_instructions} (\emph{right}) on the running example.}
  12816. \label{fig:select-instr-output-gc}
  12817. \end{figure}
  12818. \clearpage
  12819. \section{Register Allocation}
  12820. \label{sec:reg-alloc-gc}
  12821. \index{subject}{register allocation}
  12822. As discussed previously in this chapter, the garbage collector needs to
  12823. access all the pointers in the root set, that is, all variables that
  12824. are tuples. It will be the responsibility of the register allocator
  12825. to make sure that
  12826. \begin{enumerate}
  12827. \item the root stack is used for spilling tuple-typed variables, and
  12828. \item if a tuple-typed variable is live during a call to the
  12829. collector, it must be spilled to ensure that it is visible to the
  12830. collector.
  12831. \end{enumerate}
  12832. The latter responsibility can be handled during construction of the
  12833. interference graph, by adding interference edges between the call-live
  12834. tuple-typed variables and all the callee-saved registers. (They
  12835. already interfere with the caller-saved registers.)
  12836. %
  12837. \racket{The type information for variables is in the \code{Program}
  12838. form, so we recommend adding another parameter to the
  12839. \code{build\_interference} function to communicate this alist.}
  12840. %
  12841. \python{The type information for variables is generated by the type
  12842. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12843. the \code{CProgram} AST mode. You'll need to propagate that
  12844. information so that it is available in this pass.}
  12845. The spilling of tuple-typed variables to the root stack can be handled
  12846. after graph coloring, in choosing how to assign the colors
  12847. (integers) to registers and stack locations. The
  12848. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12849. changes to also record the number of spills to the root stack.
  12850. % build-interference
  12851. %
  12852. % callq
  12853. % extra parameter for var->type assoc. list
  12854. % update 'program' and 'if'
  12855. % allocate-registers
  12856. % allocate spilled vectors to the rootstack
  12857. % don't change color-graph
  12858. % TODO:
  12859. %\section{Patch Instructions}
  12860. %[mention that global variables are memory references]
  12861. \section{Generate Prelude and Conclusion}
  12862. \label{sec:print-x86-gc}
  12863. \label{sec:prelude-conclusion-x86-gc}
  12864. \index{subject}{prelude}\index{subject}{conclusion}
  12865. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12866. \code{prelude\_and\_conclusion} pass on the running example. In the
  12867. prelude of the \code{main} function, we allocate space
  12868. on the root stack to make room for the spills of tuple-typed
  12869. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12870. taking care that the root stack grows up instead of down. For the
  12871. running example, there was just one spill, so we increment \code{r15}
  12872. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12873. One issue that deserves special care is that there may be a call to
  12874. \code{collect} prior to the initializing assignments for all the
  12875. variables in the root stack. We do not want the garbage collector to
  12876. mistakenly determine that some uninitialized variable is a pointer that
  12877. needs to be followed. Thus, we zero out all locations on the root
  12878. stack in the prelude of \code{main}. In
  12879. figure~\ref{fig:print-x86-output-gc}, the instruction
  12880. %
  12881. \lstinline{movq $0, 0(%r15)}
  12882. %
  12883. is sufficient to accomplish this task because there is only one spill.
  12884. In general, we have to clear as many words as there are spills of
  12885. tuple-typed variables. The garbage collector tests each root to see
  12886. if it is null prior to dereferencing it.
  12887. \begin{figure}[htbp]
  12888. \begin{tcolorbox}[colback=white]
  12889. {\if\edition\racketEd
  12890. \begin{minipage}[t]{0.5\textwidth}
  12891. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12892. .globl main
  12893. main:
  12894. pushq %rbp
  12895. movq %rsp, %rbp
  12896. subq $0, %rsp
  12897. movq $65536, %rdi
  12898. movq $65536, %rsi
  12899. callq initialize
  12900. movq rootstack_begin(%rip), %r15
  12901. movq $0, 0(%r15)
  12902. addq $8, %r15
  12903. jmp start
  12904. conclusion:
  12905. subq $8, %r15
  12906. addq $0, %rsp
  12907. popq %rbp
  12908. retq
  12909. \end{lstlisting}
  12910. \end{minipage}
  12911. \fi}
  12912. {\if\edition\pythonEd
  12913. \begin{minipage}[t]{0.5\textwidth}
  12914. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12915. .globl main
  12916. main:
  12917. pushq %rbp
  12918. movq %rsp, %rbp
  12919. pushq %rbx
  12920. subq $8, %rsp
  12921. movq $65536, %rdi
  12922. movq $16, %rsi
  12923. callq initialize
  12924. movq rootstack_begin(%rip), %r15
  12925. movq $0, 0(%r15)
  12926. addq $8, %r15
  12927. jmp start
  12928. conclusion:
  12929. subq $8, %r15
  12930. addq $8, %rsp
  12931. popq %rbx
  12932. popq %rbp
  12933. retq
  12934. \end{lstlisting}
  12935. \end{minipage}
  12936. \fi}
  12937. \end{tcolorbox}
  12938. \caption{The prelude and conclusion for the running example.}
  12939. \label{fig:print-x86-output-gc}
  12940. \end{figure}
  12941. \begin{figure}[tbp]
  12942. \begin{tcolorbox}[colback=white]
  12943. {\if\edition\racketEd
  12944. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12945. \node (Lvec) at (0,2) {\large \LangVec{}};
  12946. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12947. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12948. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12949. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12950. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12951. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12952. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12953. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12954. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12955. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12956. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12957. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12958. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12959. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12960. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12961. \path[->,bend left=15] (Lvec-4) edge [right] node
  12962. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12963. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12964. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12965. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12966. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12967. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12968. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12969. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12970. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12971. \end{tikzpicture}
  12972. \fi}
  12973. {\if\edition\pythonEd\pythonColor
  12974. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12975. \node (Lvec) at (0,2) {\large \LangVec{}};
  12976. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12977. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12978. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12979. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12980. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12981. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12982. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12983. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12984. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12985. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12986. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12987. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12988. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12989. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12990. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12991. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12992. \end{tikzpicture}
  12993. \fi}
  12994. \end{tcolorbox}
  12995. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12996. \label{fig:Lvec-passes}
  12997. \end{figure}
  12998. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12999. for the compilation of \LangVec{}.
  13000. \clearpage
  13001. {\if\edition\racketEd
  13002. \section{Challenge: Simple Structures}
  13003. \label{sec:simple-structures}
  13004. \index{subject}{struct}
  13005. \index{subject}{structure}
  13006. The language \LangStruct{} extends \LangVec{} with support for simple
  13007. structures. The definition of its concrete syntax is shown in
  13008. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  13009. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  13010. in Typed Racket is a user-defined data type that contains named fields
  13011. and that is heap allocated\index{subject}{heap allocated},
  13012. similarly to a vector. The following is an
  13013. example of a structure definition, in this case the definition of a
  13014. \code{point} type:
  13015. \begin{lstlisting}
  13016. (struct point ([x : Integer] [y : Integer]) #:mutable)
  13017. \end{lstlisting}
  13018. \newcommand{\LstructGrammarRacket}{
  13019. \begin{array}{lcl}
  13020. \Type &::=& \Var \\
  13021. \Exp &::=& (\Var\;\Exp \ldots)\\
  13022. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  13023. \end{array}
  13024. }
  13025. \newcommand{\LstructASTRacket}{
  13026. \begin{array}{lcl}
  13027. \Type &::=& \VAR{\Var} \\
  13028. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  13029. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  13030. \end{array}
  13031. }
  13032. \begin{figure}[tbp]
  13033. \centering
  13034. \begin{tcolorbox}[colback=white]
  13035. \[
  13036. \begin{array}{l}
  13037. \gray{\LintGrammarRacket{}} \\ \hline
  13038. \gray{\LvarGrammarRacket{}} \\ \hline
  13039. \gray{\LifGrammarRacket{}} \\ \hline
  13040. \gray{\LwhileGrammarRacket} \\ \hline
  13041. \gray{\LtupGrammarRacket} \\ \hline
  13042. \LstructGrammarRacket \\
  13043. \begin{array}{lcl}
  13044. \LangStruct{} &::=& \Def \ldots \; \Exp
  13045. \end{array}
  13046. \end{array}
  13047. \]
  13048. \end{tcolorbox}
  13049. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  13050. (figure~\ref{fig:Lvec-concrete-syntax}).}
  13051. \label{fig:Lstruct-concrete-syntax}
  13052. \index{subject}{Lstruct@\LangStruct{} concrete syntax}
  13053. \end{figure}
  13054. \begin{figure}[tbp]
  13055. \centering
  13056. \begin{tcolorbox}[colback=white]
  13057. \small
  13058. \[
  13059. \begin{array}{l}
  13060. \gray{\LintASTRacket{}} \\ \hline
  13061. \gray{\LvarASTRacket{}} \\ \hline
  13062. \gray{\LifASTRacket{}} \\ \hline
  13063. \gray{\LwhileASTRacket} \\ \hline
  13064. \gray{\LtupASTRacket} \\ \hline
  13065. \LstructASTRacket \\
  13066. \begin{array}{lcl}
  13067. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13068. \end{array}
  13069. \end{array}
  13070. \]
  13071. \end{tcolorbox}
  13072. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  13073. (figure~\ref{fig:Lvec-syntax}).}
  13074. \label{fig:Lstruct-syntax}
  13075. \index{subject}{Lstruct@\LangStruct{} abstract syntax}
  13076. \end{figure}
  13077. An instance of a structure is created using function-call syntax, with
  13078. the name of the structure in the function position, as follows:
  13079. \begin{lstlisting}
  13080. (point 7 12)
  13081. \end{lstlisting}
  13082. Function-call syntax is also used to read a field of a structure. The
  13083. function name is formed by the structure name, a dash, and the field
  13084. name. The following example uses \code{point-x} and \code{point-y} to
  13085. access the \code{x} and \code{y} fields of two point instances:
  13086. \begin{center}
  13087. \begin{lstlisting}
  13088. (let ([pt1 (point 7 12)])
  13089. (let ([pt2 (point 4 3)])
  13090. (+ (- (point-x pt1) (point-x pt2))
  13091. (- (point-y pt1) (point-y pt2)))))
  13092. \end{lstlisting}
  13093. \end{center}
  13094. Similarly, to write to a field of a structure, use its set function,
  13095. whose name starts with \code{set-}, followed by the structure name,
  13096. then a dash, then the field name, and finally with an exclamation
  13097. mark. The following example uses \code{set-point-x!} to change the
  13098. \code{x} field from \code{7} to \code{42}:
  13099. \begin{center}
  13100. \begin{lstlisting}
  13101. (let ([pt (point 7 12)])
  13102. (let ([_ (set-point-x! pt 42)])
  13103. (point-x pt)))
  13104. \end{lstlisting}
  13105. \end{center}
  13106. \begin{exercise}\normalfont\normalsize
  13107. Create a type checker for \LangStruct{} by extending the type
  13108. checker for \LangVec{}. Extend your compiler with support for simple
  13109. structures, compiling \LangStruct{} to x86 assembly code. Create
  13110. five new test cases that use structures, and test your compiler.
  13111. \end{exercise}
  13112. % TODO: create an interpreter for L_struct
  13113. \clearpage
  13114. \fi}
  13115. \section{Challenge: Arrays}
  13116. \label{sec:arrays}
  13117. % TODO mention trapped-error
  13118. In this chapter we have studied tuples, that is, heterogeneous
  13119. sequences of elements whose length is determined at compile time. This
  13120. challenge is also about sequences, but this time the length is
  13121. determined at runtime and all the elements have the same type (they
  13122. are homogeneous). We use the traditional term \emph{array} for this
  13123. latter kind of sequence.
  13124. %
  13125. \racket{
  13126. The Racket language does not distinguish between tuples and arrays;
  13127. they are both represented by vectors. However, Typed Racket
  13128. distinguishes between tuples and arrays: the \code{Vector} type is for
  13129. tuples, and the \code{Vectorof} type is for arrays.}%
  13130. \python{Arrays correspond to the \code{list} type in the Python language.}
  13131. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13132. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13133. presents the definition of the abstract syntax, extending \LangVec{}
  13134. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13135. \racket{\code{make-vector} primitive operator for creating an array,
  13136. whose arguments are the length of the array and an initial value for
  13137. all the elements in the array.}%
  13138. \python{bracket notation for creating an array literal.}
  13139. \racket{The \code{vector-length},
  13140. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13141. for tuples become overloaded for use with arrays.}
  13142. \python{
  13143. The subscript operator becomes overloaded for use with arrays and tuples
  13144. and now may appear on the left-hand side of an assignment.
  13145. Note that the index of the subscript, when applied to an array, may be an
  13146. arbitrary expression and not exclusively a constant integer.
  13147. The \code{len} function is also applicable to arrays.
  13148. }
  13149. %
  13150. We include integer multiplication in \LangArray{} because it is
  13151. useful in many examples involving arrays such as computing the
  13152. inner product of two arrays (figure~\ref{fig:inner_product}).
  13153. \newcommand{\LarrayGrammarRacket}{
  13154. \begin{array}{lcl}
  13155. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13156. \Exp &::=& \CMUL{\Exp}{\Exp}
  13157. \MID \CMAKEVEC{\Exp}{\Exp}
  13158. \end{array}
  13159. }
  13160. \newcommand{\LarrayASTRacket}{
  13161. \begin{array}{lcl}
  13162. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13163. \Exp &::=& \MUL{\Exp}{\Exp}
  13164. \MID \MAKEVEC{\Exp}{\Exp}
  13165. \end{array}
  13166. }
  13167. \newcommand{\LarrayGrammarPython}{
  13168. \begin{array}{lcl}
  13169. \Type &::=& \key{list}\LS\Type\RS \\
  13170. \Exp &::=& \CMUL{\Exp}{\Exp}
  13171. \MID \CGET{\Exp}{\Exp}
  13172. \MID \LS \Exp \code{,} \ldots \RS \\
  13173. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13174. \end{array}
  13175. }
  13176. \newcommand{\LarrayASTPython}{
  13177. \begin{array}{lcl}
  13178. \Type &::=& \key{ListType}\LP\Type\RP \\
  13179. \Exp &::=& \MUL{\Exp}{\Exp}
  13180. \MID \GET{\Exp}{\Exp} \\
  13181. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13182. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13183. \end{array}
  13184. }
  13185. \begin{figure}[tp]
  13186. \centering
  13187. \begin{tcolorbox}[colback=white]
  13188. \small
  13189. {\if\edition\racketEd
  13190. \[
  13191. \begin{array}{l}
  13192. \gray{\LintGrammarRacket{}} \\ \hline
  13193. \gray{\LvarGrammarRacket{}} \\ \hline
  13194. \gray{\LifGrammarRacket{}} \\ \hline
  13195. \gray{\LwhileGrammarRacket} \\ \hline
  13196. \gray{\LtupGrammarRacket} \\ \hline
  13197. \LarrayGrammarRacket \\
  13198. \begin{array}{lcl}
  13199. \LangArray{} &::=& \Exp
  13200. \end{array}
  13201. \end{array}
  13202. \]
  13203. \fi}
  13204. {\if\edition\pythonEd\pythonColor
  13205. \[
  13206. \begin{array}{l}
  13207. \gray{\LintGrammarPython{}} \\ \hline
  13208. \gray{\LvarGrammarPython{}} \\ \hline
  13209. \gray{\LifGrammarPython{}} \\ \hline
  13210. \gray{\LwhileGrammarPython} \\ \hline
  13211. \gray{\LtupGrammarPython} \\ \hline
  13212. \LarrayGrammarPython \\
  13213. \begin{array}{rcl}
  13214. \LangArrayM{} &::=& \Stmt^{*}
  13215. \end{array}
  13216. \end{array}
  13217. \]
  13218. \fi}
  13219. \end{tcolorbox}
  13220. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13221. \label{fig:Lvecof-concrete-syntax}
  13222. \index{subject}{Larray@\LangArray{} concrete syntax}
  13223. \end{figure}
  13224. \begin{figure}[tp]
  13225. \centering
  13226. \begin{tcolorbox}[colback=white]
  13227. \small
  13228. {\if\edition\racketEd
  13229. \[
  13230. \begin{array}{l}
  13231. \gray{\LintASTRacket{}} \\ \hline
  13232. \gray{\LvarASTRacket{}} \\ \hline
  13233. \gray{\LifASTRacket{}} \\ \hline
  13234. \gray{\LwhileASTRacket} \\ \hline
  13235. \gray{\LtupASTRacket} \\ \hline
  13236. \LarrayASTRacket \\
  13237. \begin{array}{lcl}
  13238. \LangArray{} &::=& \Exp
  13239. \end{array}
  13240. \end{array}
  13241. \]
  13242. \fi}
  13243. {\if\edition\pythonEd\pythonColor
  13244. \[
  13245. \begin{array}{l}
  13246. \gray{\LintASTPython{}} \\ \hline
  13247. \gray{\LvarASTPython{}} \\ \hline
  13248. \gray{\LifASTPython{}} \\ \hline
  13249. \gray{\LwhileASTPython} \\ \hline
  13250. \gray{\LtupASTPython} \\ \hline
  13251. \LarrayASTPython \\
  13252. \begin{array}{rcl}
  13253. \LangArrayM{} &::=& \Stmt^{*}
  13254. \end{array}
  13255. \end{array}
  13256. \]
  13257. \fi}
  13258. \end{tcolorbox}
  13259. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13260. \label{fig:Lvecof-syntax}
  13261. \index{subject}{Larray@\LangArray{} abstract syntax}
  13262. \end{figure}
  13263. \begin{figure}[tp]
  13264. \begin{tcolorbox}[colback=white]
  13265. {\if\edition\racketEd
  13266. \begin{lstlisting}
  13267. (let ([A (make-vector 2 2)])
  13268. (let ([B (make-vector 2 3)])
  13269. (let ([i 0])
  13270. (let ([prod 0])
  13271. (begin
  13272. (while (< i (vector-length A))
  13273. (begin
  13274. (set! prod (+ prod (* (vector-ref A i)
  13275. (vector-ref B i))))
  13276. (set! i (+ i 1))))
  13277. prod)))))
  13278. \end{lstlisting}
  13279. \fi}
  13280. {\if\edition\pythonEd\pythonColor
  13281. \begin{lstlisting}
  13282. A = [2, 2]
  13283. B = [3, 3]
  13284. i = 0
  13285. prod = 0
  13286. while i != len(A):
  13287. prod = prod + A[i] * B[i]
  13288. i = i + 1
  13289. print(prod)
  13290. \end{lstlisting}
  13291. \fi}
  13292. \end{tcolorbox}
  13293. \caption{Example program that computes the inner product.}
  13294. \label{fig:inner_product}
  13295. \end{figure}
  13296. {\if\edition\racketEd
  13297. %
  13298. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13299. checker for \LangArray{}. The result type of
  13300. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13301. of the initializing expression. The length expression is required to
  13302. have type \code{Integer}. The type checking of the operators
  13303. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13304. updated to handle the situation in which the vector has type
  13305. \code{Vectorof}. In these cases we translate the operators to their
  13306. \code{vectorof} form so that later passes can easily distinguish
  13307. between operations on tuples versus arrays. We override the
  13308. \code{operator-types} method to provide the type signature for
  13309. multiplication: it takes two integers and returns an integer.
  13310. \fi}
  13311. %
  13312. {\if\edition\pythonEd\pythonColor
  13313. %
  13314. The type checker for \LangArray{} is defined in
  13315. figures~\ref{fig:type-check-Lvecof} and
  13316. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13317. is \code{list[T]}, where \code{T} is the type of the initializing
  13318. expressions. The type checking of the \code{len} function and the
  13319. subscript operator are updated to handle lists. The type checker now
  13320. also handles a subscript on the left-hand side of an assignment.
  13321. Regarding multiplication, it takes two integers and returns an
  13322. integer.
  13323. %
  13324. \fi}
  13325. \begin{figure}[tbp]
  13326. \begin{tcolorbox}[colback=white]
  13327. {\if\edition\racketEd
  13328. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13329. (define type-check-Lvecof-class
  13330. (class type-check-Lvec-class
  13331. (super-new)
  13332. (inherit check-type-equal?)
  13333. (define/override (operator-types)
  13334. (append '((* . ((Integer Integer) . Integer)))
  13335. (super operator-types)))
  13336. (define/override (type-check-exp env)
  13337. (lambda (e)
  13338. (define recur (type-check-exp env))
  13339. (match e
  13340. [(Prim 'make-vector (list e1 e2))
  13341. (define-values (e1^ t1) (recur e1))
  13342. (define-values (e2^ elt-type) (recur e2))
  13343. (define vec-type `(Vectorof ,elt-type))
  13344. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13345. [(Prim 'vector-ref (list e1 e2))
  13346. (define-values (e1^ t1) (recur e1))
  13347. (define-values (e2^ t2) (recur e2))
  13348. (match* (t1 t2)
  13349. [(`(Vectorof ,elt-type) 'Integer)
  13350. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13351. [(other wise) ((super type-check-exp env) e)])]
  13352. [(Prim 'vector-set! (list e1 e2 e3) )
  13353. (define-values (e-vec t-vec) (recur e1))
  13354. (define-values (e2^ t2) (recur e2))
  13355. (define-values (e-arg^ t-arg) (recur e3))
  13356. (match t-vec
  13357. [`(Vectorof ,elt-type)
  13358. (check-type-equal? elt-type t-arg e)
  13359. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13360. [else ((super type-check-exp env) e)])]
  13361. [(Prim 'vector-length (list e1))
  13362. (define-values (e1^ t1) (recur e1))
  13363. (match t1
  13364. [`(Vectorof ,t)
  13365. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13366. [else ((super type-check-exp env) e)])]
  13367. [else ((super type-check-exp env) e)])))
  13368. ))
  13369. (define (type-check-Lvecof p)
  13370. (send (new type-check-Lvecof-class) type-check-program p))
  13371. \end{lstlisting}
  13372. \fi}
  13373. {\if\edition\pythonEd\pythonColor
  13374. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13375. class TypeCheckLarray(TypeCheckLtup):
  13376. def type_check_exp(self, e, env):
  13377. match e:
  13378. case ast.List(es, Load()):
  13379. ts = [self.type_check_exp(e, env) for e in es]
  13380. elt_ty = ts[0]
  13381. for (ty, elt) in zip(ts, es):
  13382. self.check_type_equal(elt_ty, ty, elt)
  13383. e.has_type = ListType(elt_ty)
  13384. return e.has_type
  13385. case Call(Name('len'), [tup]):
  13386. tup_t = self.type_check_exp(tup, env)
  13387. tup.has_type = tup_t
  13388. match tup_t:
  13389. case TupleType(ts):
  13390. return IntType()
  13391. case ListType(ty):
  13392. return IntType()
  13393. case _:
  13394. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13395. case Subscript(tup, index, Load()):
  13396. tup_ty = self.type_check_exp(tup, env)
  13397. tup.has_type = tup_ty
  13398. index_ty = self.type_check_exp(index, env)
  13399. self.check_type_equal(index_ty, IntType(), index)
  13400. match tup_ty:
  13401. case TupleType(ts):
  13402. match index:
  13403. case Constant(i):
  13404. return ts[i]
  13405. case _:
  13406. raise Exception('subscript required constant integer index')
  13407. case ListType(ty):
  13408. return ty
  13409. case _:
  13410. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13411. case BinOp(left, Mult(), right):
  13412. l = self.type_check_exp(left, env)
  13413. self.check_type_equal(l, IntType(), left)
  13414. r = self.type_check_exp(right, env)
  13415. self.check_type_equal(r, IntType(), right)
  13416. return IntType()
  13417. case _:
  13418. return super().type_check_exp(e, env)
  13419. \end{lstlisting}
  13420. \fi}
  13421. \end{tcolorbox}
  13422. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13423. \label{fig:type-check-Lvecof}
  13424. \end{figure}
  13425. {\if\edition\pythonEd
  13426. \begin{figure}[tbp]
  13427. \begin{tcolorbox}[colback=white]
  13428. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13429. def type_check_stmts(self, ss, env):
  13430. if len(ss) == 0:
  13431. return VoidType()
  13432. match ss[0]:
  13433. case Assign([Subscript(tup, index, Store())], value):
  13434. tup_t = self.type_check_exp(tup, env)
  13435. tup.has_type = tup_t
  13436. value_t = self.type_check_exp(value, env)
  13437. index_ty = self.type_check_exp(index, env)
  13438. self.check_type_equal(index_ty, IntType(), index)
  13439. match tup_t:
  13440. case ListType(ty):
  13441. self.check_type_equal(ty, value_t, ss[0])
  13442. case TupleType(ts):
  13443. return self.type_check_stmts(ss, env)
  13444. case _:
  13445. raise Exception('type_check_stmts: '
  13446. 'expected tuple or list, not ' + repr(tup_t))
  13447. return self.type_check_stmts(ss[1:], env)
  13448. case _:
  13449. return super().type_check_stmts(ss, env)
  13450. \end{lstlisting}
  13451. \end{tcolorbox}
  13452. \caption{Type checker for the \LangArray{} language, part 2.}
  13453. \label{fig:type-check-Lvecof-part2}
  13454. \end{figure}
  13455. \fi}
  13456. The definition of the interpreter for \LangArray{} is shown in
  13457. \racket{figure~\ref{fig:interp-Lvecof}}
  13458. \python{figure~\ref{fig:interp-Lvecof}}.
  13459. \racket{The \code{make-vector} operator is
  13460. interpreted using Racket's \code{make-vector} function,
  13461. and multiplication is interpreted using \code{fx*},
  13462. which is multiplication for \code{fixnum} integers.
  13463. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13464. we translate array access operations
  13465. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13466. which we interpret using \code{vector} operations with additional
  13467. bounds checks that signal a \code{trapped-error}.
  13468. }
  13469. %
  13470. \python{We implement array creation with a Python list comprehension,
  13471. and multiplication is implemented with 64-bit multiplication. We
  13472. add a case for a subscript on the left-hand side of
  13473. assignment. Other uses of subscript can be handled by the existing
  13474. code for tuples.}
  13475. \begin{figure}[tbp]
  13476. \begin{tcolorbox}[colback=white]
  13477. {\if\edition\racketEd
  13478. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13479. (define interp-Lvecof-class
  13480. (class interp-Lvec-class
  13481. (super-new)
  13482. (define/override (interp-op op)
  13483. (match op
  13484. ['make-vector make-vector]
  13485. ['vectorof-length vector-length]
  13486. ['vectorof-ref
  13487. (lambda (v i)
  13488. (if (< i (vector-length v))
  13489. (vector-ref v i)
  13490. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13491. ['vectorof-set!
  13492. (lambda (v i e)
  13493. (if (< i (vector-length v))
  13494. (vector-set! v i e)
  13495. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13496. [else (super interp-op op)]))
  13497. ))
  13498. (define (interp-Lvecof p)
  13499. (send (new interp-Lvecof-class) interp-program p))
  13500. \end{lstlisting}
  13501. \fi}
  13502. {\if\edition\pythonEd\pythonColor
  13503. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13504. class InterpLarray(InterpLtup):
  13505. def interp_exp(self, e, env):
  13506. match e:
  13507. case ast.List(es, Load()):
  13508. return [self.interp_exp(e, env) for e in es]
  13509. case BinOp(left, Mult(), right):
  13510. l = self.interp_exp(left, env)
  13511. r = self.interp_exp(right, env)
  13512. return mul64(l, r)
  13513. case Subscript(tup, index, Load()):
  13514. t = self.interp_exp(tup, env)
  13515. n = self.interp_exp(index, env)
  13516. if n < len(t):
  13517. return t[n]
  13518. else:
  13519. raise TrappedError('array index out of bounds')
  13520. case _:
  13521. return super().interp_exp(e, env)
  13522. def interp_stmt(self, s, env, cont):
  13523. match s:
  13524. case Assign([Subscript(tup, index)], value):
  13525. t = self.interp_exp(tup, env)
  13526. n = self.interp_exp(index, env)
  13527. if n < len(t):
  13528. t[n] = self.interp_exp(value, env)
  13529. else:
  13530. raise TrappedError('array index out of bounds')
  13531. return self.interp_stmts(cont, env)
  13532. case _:
  13533. return super().interp_stmt(s, env, cont)
  13534. \end{lstlisting}
  13535. \fi}
  13536. \end{tcolorbox}
  13537. \caption{Interpreter for \LangArray{}.}
  13538. \label{fig:interp-Lvecof}
  13539. \end{figure}
  13540. \subsection{Data Representation}
  13541. \label{sec:array-rep}
  13542. Just as with tuples, we store arrays on the heap, which means that the
  13543. garbage collector will need to inspect arrays. An immediate thought is
  13544. to use the same representation for arrays that we use for tuples.
  13545. However, we limit tuples to a length of fifty so that their length and
  13546. pointer mask can fit into the 64-bit tag at the beginning of each
  13547. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13548. millions of elements, so we need more bits to store the length.
  13549. However, because arrays are homogeneous, we need only 1 bit for the
  13550. pointer mask instead of 1 bit per array element. Finally, the
  13551. garbage collector must be able to distinguish between tuples
  13552. and arrays, so we need to reserve one bit for that purpose. We
  13553. arrive at the following layout for the 64-bit tag at the beginning of
  13554. an array:
  13555. \begin{itemize}
  13556. \item The right-most bit is the forwarding bit, just as in a tuple.
  13557. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13558. that it is not.
  13559. \item The next bit to the left is the pointer mask. A $0$ indicates
  13560. that none of the elements are pointers, and a $1$ indicates that all
  13561. the elements are pointers.
  13562. \item The next $60$ bits store the length of the array.
  13563. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13564. and an array ($1$).
  13565. \item The left-most bit is reserved as explained in
  13566. chapter~\ref{ch:Lgrad}.
  13567. \end{itemize}
  13568. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13569. %% differentiate the kinds of values that have been injected into the
  13570. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13571. %% to indicate that the value is an array.
  13572. In the following subsections we provide hints regarding how to update
  13573. the passes to handle arrays.
  13574. \subsection{Overload Resolution}
  13575. \label{sec:array-resolution}
  13576. As noted previously, with the addition of arrays, several operators
  13577. have become \emph{overloaded}; that is, they can be applied to values
  13578. of more than one type. In this case, the element access and length
  13579. operators can be applied to both tuples and arrays. This kind of
  13580. overloading is quite common in programming languages, so many
  13581. compilers perform \emph{overload resolution}\index{subject}{overload
  13582. resolution} to handle it. The idea is to translate each overloaded
  13583. operator into different operators for the different types.
  13584. Implement a new pass named \code{resolve}.
  13585. Translate the reading of an array element to
  13586. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13587. and the writing of an array element to
  13588. \racket{\code{vectorof-set!}}\python{\code{array\_store}}.
  13589. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13590. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13591. When these operators are applied to tuples, leave them as is.
  13592. %
  13593. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13594. field, which can be inspected to determine whether the operator
  13595. is applied to a tuple or an array.}
  13596. \subsection{Bounds Checking}
  13597. Recall that the interpreter for \LangArray{} signals a
  13598. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13599. when there is an array access that is out of
  13600. bounds. Therefore your compiler is obliged to also catch these errors
  13601. during execution and halt, signaling an error. We recommend inserting
  13602. a new pass named \code{check\_bounds} that inserts code around each
  13603. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13604. \python{subscript} operation to ensure that the index is greater than
  13605. or equal to zero and less than the array's length. If not, the program
  13606. should halt, for which we recommend using a new primitive operation
  13607. named \code{exit}.
  13608. %% \subsection{Reveal Casts}
  13609. %% The array-access operators \code{vectorof-ref} and
  13610. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13611. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13612. %% that the type checker cannot tell whether the index will be in bounds,
  13613. %% so the bounds check must be performed at run time. Recall that the
  13614. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13615. %% an \code{If} around a vector reference for update to check whether
  13616. %% the index is less than the length. You should do the same for
  13617. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13618. %% In addition, the handling of the \code{any-vector} operators in
  13619. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13620. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13621. %% generated code should test whether the tag is for tuples (\code{010})
  13622. %% or arrays (\code{110}) and then dispatch to either
  13623. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13624. %% we add a case in \code{select\_instructions} to generate the
  13625. %% appropriate instructions for accessing the array length from the
  13626. %% header of an array.
  13627. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13628. %% the generated code needs to check that the index is less than the
  13629. %% vector length, so like the code for \code{any-vector-length}, check
  13630. %% the tag to determine whether to use \code{any-vector-length} or
  13631. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13632. %% is complete, the generated code can use \code{any-vector-ref} and
  13633. %% \code{any-vector-set!} for both tuples and arrays because the
  13634. %% instructions used for those operators do not look at the tag at the
  13635. %% front of the tuple or array.
  13636. \subsection{Expose Allocation}
  13637. % TODO: add figure for C_array
  13638. This pass should translate array creation into lower-level
  13639. operations. In particular, the new AST node \ALLOCARRAY{\Int}{\Type}
  13640. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13641. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13642. array. The \code{AllocateArray} AST node allocates an array of the
  13643. length specified by the $\Exp$ (of type \INTTY), but does not
  13644. initialize the elements of the array. Generate code in this pass to
  13645. initialize the elements analogous to the case for tuples.
  13646. {\if\edition\racketEd
  13647. \subsection{Uncover \texttt{get!}}
  13648. \label{sec:uncover-get-bang-vecof}
  13649. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13650. \code{uncover-get!-exp}.
  13651. \fi}
  13652. \subsection{Remove Complex Operands}
  13653. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13654. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13655. complex, and its subexpression must be atomic.
  13656. \subsection{Explicate Control}
  13657. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13658. \code{explicate\_assign}.
  13659. \subsection{Select Instructions}
  13660. \index{subject}{select instructions}
  13661. Generate instructions for \code{AllocateArray} similar to those for
  13662. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13663. except that the tag at the front of the array should instead use the
  13664. representation discussed in section~\ref{sec:array-rep}.
  13665. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13666. extract the length from the tag.
  13667. The instructions generated for accessing an element of an array differ
  13668. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13669. that the index is not a constant so you need to generate instructions
  13670. that compute the offset at runtime.
  13671. Compile the \code{exit} primitive into a call to the \code{exit}
  13672. function of the C standard library, with an argument of $255$.
  13673. %% Also, note that assignment to an array element may appear in
  13674. %% as a stand-alone statement, so make sure to handle that situation in
  13675. %% this pass.
  13676. %% Finally, the instructions for \code{any-vectorof-length} should be
  13677. %% similar to those for \code{vectorof-length}, except that one must
  13678. %% first project the array by writing zeroes into the $3$-bit tag
  13679. \begin{exercise}\normalfont\normalsize
  13680. Implement a compiler for the \LangArray{} language by extending your
  13681. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13682. programs, including the one shown in figure~\ref{fig:inner_product}
  13683. and also a program that multiplies two matrices. Note that although
  13684. matrices are two-dimensional arrays, they can be encoded into
  13685. one-dimensional arrays by laying out each row in the array, one after
  13686. the next.
  13687. \end{exercise}
  13688. {\if\edition\racketEd
  13689. \section{Challenge: Generational Collection}
  13690. The copying collector described in section~\ref{sec:GC} can incur
  13691. significant runtime overhead because the call to \code{collect} takes
  13692. time proportional to all the live data. One way to reduce this
  13693. overhead is to reduce how much data is inspected in each call to
  13694. \code{collect}. In particular, researchers have observed that recently
  13695. allocated data is more likely to become garbage than data that has
  13696. survived one or more previous calls to \code{collect}. This insight
  13697. motivated the creation of \emph{generational garbage collectors}
  13698. \index{subject}{generational garbage collector} that
  13699. (1) segregate data according to its age into two or more generations;
  13700. (2) allocate less space for younger generations, so collecting them is
  13701. faster, and more space for the older generations; and (3) perform
  13702. collection on the younger generations more frequently than on older
  13703. generations~\citep{Wilson:1992fk}.
  13704. For this challenge assignment, the goal is to adapt the copying
  13705. collector implemented in \code{runtime.c} to use two generations, one
  13706. for young data and one for old data. Each generation consists of a
  13707. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13708. \code{collect} function to use the two generations:
  13709. \begin{enumerate}
  13710. \item Copy the young generation's FromSpace to its ToSpace and then
  13711. switch the role of the ToSpace and FromSpace.
  13712. \item If there is enough space for the requested number of bytes in
  13713. the young FromSpace, then return from \code{collect}.
  13714. \item If there is not enough space in the young FromSpace for the
  13715. requested bytes, then move the data from the young generation to the
  13716. old one with the following steps:
  13717. \begin{enumerate}
  13718. \item[a.] If there is enough room in the old FromSpace, copy the young
  13719. FromSpace to the old FromSpace and then return.
  13720. \item[b.] If there is not enough room in the old FromSpace, then collect
  13721. the old generation by copying the old FromSpace to the old ToSpace
  13722. and swap the roles of the old FromSpace and ToSpace.
  13723. \item[c.] If there is enough room now, copy the young FromSpace to the
  13724. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13725. and ToSpace for the old generation. Copy the young FromSpace and
  13726. the old FromSpace into the larger FromSpace for the old
  13727. generation and then return.
  13728. \end{enumerate}
  13729. \end{enumerate}
  13730. We recommend that you generalize the \code{cheney} function so that it
  13731. can be used for all the copies mentioned: between the young FromSpace
  13732. and ToSpace, between the old FromSpace and ToSpace, and between the
  13733. young FromSpace and old FromSpace. This can be accomplished by adding
  13734. parameters to \code{cheney} that replace its use of the global
  13735. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13736. \code{tospace\_begin}, and \code{tospace\_end}.
  13737. Note that the collection of the young generation does not traverse the
  13738. old generation. This introduces a potential problem: there may be
  13739. young data that is reachable only through pointers in the old
  13740. generation. If these pointers are not taken into account, the
  13741. collector could throw away young data that is live! One solution,
  13742. called \emph{pointer recording}, is to maintain a set of all the
  13743. pointers from the old generation into the new generation and consider
  13744. this set as part of the root set. To maintain this set, the compiler
  13745. must insert extra instructions around every \code{vector-set!}. If the
  13746. vector being modified is in the old generation, and if the value being
  13747. written is a pointer into the new generation, then that pointer must
  13748. be added to the set. Also, if the value being overwritten was a
  13749. pointer into the new generation, then that pointer should be removed
  13750. from the set.
  13751. \begin{exercise}\normalfont\normalsize
  13752. Adapt the \code{collect} function in \code{runtime.c} to implement
  13753. generational garbage collection, as outlined in this section.
  13754. Update the code generation for \code{vector-set!} to implement
  13755. pointer recording. Make sure that your new compiler and runtime
  13756. execute without error on your test suite.
  13757. \end{exercise}
  13758. \fi}
  13759. \section{Further Reading}
  13760. \citet{Appel90} describes many data representation approaches
  13761. including the ones used in the compilation of Standard ML.
  13762. There are many alternatives to copying collectors (and their bigger
  13763. siblings, the generational collectors) with regard to garbage
  13764. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13765. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13766. collectors are that allocation is fast (just a comparison and pointer
  13767. increment), there is no fragmentation, cyclic garbage is collected,
  13768. and the time complexity of collection depends only on the amount of
  13769. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13770. main disadvantages of a two-space copying collector is that it uses a
  13771. lot of extra space and takes a long time to perform the copy, though
  13772. these problems are ameliorated in generational collectors.
  13773. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13774. small objects and generate a lot of garbage, so copying and
  13775. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13776. Garbage collection is an active research topic, especially concurrent
  13777. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13778. developing new techniques and revisiting old
  13779. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13780. meet every year at the International Symposium on Memory Management to
  13781. present these findings.
  13782. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13783. \chapter{Functions}
  13784. \label{ch:Lfun}
  13785. \index{subject}{function}
  13786. \setcounter{footnote}{0}
  13787. This chapter studies the compilation of a subset of \racket{Typed
  13788. Racket}\python{Python} in which only top-level function definitions
  13789. are allowed. This kind of function appears in the C programming
  13790. language, and it serves as an important stepping-stone to implementing
  13791. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13792. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13793. \section{The \LangFun{} Language}
  13794. The concrete syntax and abstract syntax for function definitions and
  13795. function application are shown in
  13796. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13797. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13798. with zero or more function definitions. The function names from these
  13799. definitions are in scope for the entire program, including all the
  13800. function definitions, and therefore the ordering of function
  13801. definitions does not matter.
  13802. %
  13803. \python{The abstract syntax for function parameters in
  13804. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13805. consists of a parameter name and its type. This design differs from
  13806. Python's \code{ast} module, which has a more complex structure for
  13807. function parameters to handle keyword parameters,
  13808. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13809. complex Python abstract syntax into the simpler syntax shown in
  13810. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13811. \code{FunctionDef} constructor are for decorators and a type
  13812. comment, neither of which are used by our compiler. We recommend
  13813. replacing them with \code{None} in the \code{shrink} pass.
  13814. }
  13815. %
  13816. The concrete syntax for function application
  13817. \index{subject}{function application}
  13818. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13819. where the first expression
  13820. must evaluate to a function and the remaining expressions are the arguments. The
  13821. abstract syntax for function application is
  13822. $\APPLY{\Exp}{\Exp^*}$.
  13823. %% The syntax for function application does not include an explicit
  13824. %% keyword, which is error prone when using \code{match}. To alleviate
  13825. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13826. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13827. Functions are first-class in the sense that a function pointer
  13828. \index{subject}{function pointer} is data and can be stored in memory or passed
  13829. as a parameter to another function. Thus, there is a function
  13830. type, written
  13831. {\if\edition\racketEd
  13832. \begin{lstlisting}
  13833. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13834. \end{lstlisting}
  13835. \fi}
  13836. {\if\edition\pythonEd\pythonColor
  13837. \begin{lstlisting}
  13838. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13839. \end{lstlisting}
  13840. \fi}
  13841. %
  13842. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13843. through $\Type_n$ and whose return type is $\Type_R$. The main
  13844. limitation of these functions (with respect to
  13845. \racket{Racket}\python{Python} functions) is that they are not
  13846. lexically scoped. That is, the only external entities that can be
  13847. referenced from inside a function body are other globally defined
  13848. functions. The syntax of \LangFun{} prevents function definitions from
  13849. being nested inside each other.
  13850. \newcommand{\LfunGrammarRacket}{
  13851. \begin{array}{lcl}
  13852. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13853. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13854. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13855. \end{array}
  13856. }
  13857. \newcommand{\LfunASTRacket}{
  13858. \begin{array}{lcl}
  13859. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13860. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13861. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13862. \end{array}
  13863. }
  13864. \newcommand{\LfunGrammarPython}{
  13865. \begin{array}{lcl}
  13866. \Type &::=& \key{int}
  13867. \MID \key{bool} \MID \key{void}
  13868. \MID \key{tuple}\LS \Type^+ \RS
  13869. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13870. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13871. \Stmt &::=& \CRETURN{\Exp} \\
  13872. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13873. \end{array}
  13874. }
  13875. \newcommand{\LfunASTPython}{
  13876. \begin{array}{lcl}
  13877. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13878. \MID \key{TupleType}\LS\Type^+\RS\\
  13879. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13880. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13881. \Stmt &::=& \RETURN{\Exp} \\
  13882. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13883. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13884. \end{array}
  13885. }
  13886. \begin{figure}[tp]
  13887. \centering
  13888. \begin{tcolorbox}[colback=white]
  13889. \small
  13890. {\if\edition\racketEd
  13891. \[
  13892. \begin{array}{l}
  13893. \gray{\LintGrammarRacket{}} \\ \hline
  13894. \gray{\LvarGrammarRacket{}} \\ \hline
  13895. \gray{\LifGrammarRacket{}} \\ \hline
  13896. \gray{\LwhileGrammarRacket} \\ \hline
  13897. \gray{\LtupGrammarRacket} \\ \hline
  13898. \LfunGrammarRacket \\
  13899. \begin{array}{lcl}
  13900. \LangFunM{} &::=& \Def \ldots \; \Exp
  13901. \end{array}
  13902. \end{array}
  13903. \]
  13904. \fi}
  13905. {\if\edition\pythonEd\pythonColor
  13906. \[
  13907. \begin{array}{l}
  13908. \gray{\LintGrammarPython{}} \\ \hline
  13909. \gray{\LvarGrammarPython{}} \\ \hline
  13910. \gray{\LifGrammarPython{}} \\ \hline
  13911. \gray{\LwhileGrammarPython} \\ \hline
  13912. \gray{\LtupGrammarPython} \\ \hline
  13913. \LfunGrammarPython \\
  13914. \begin{array}{rcl}
  13915. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13916. \end{array}
  13917. \end{array}
  13918. \]
  13919. \fi}
  13920. \end{tcolorbox}
  13921. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13922. \label{fig:Lfun-concrete-syntax}
  13923. \index{subject}{Lfun@\LangFun{} concrete syntax}
  13924. \end{figure}
  13925. \begin{figure}[tp]
  13926. \centering
  13927. \begin{tcolorbox}[colback=white]
  13928. \small
  13929. {\if\edition\racketEd
  13930. \[
  13931. \begin{array}{l}
  13932. \gray{\LintOpAST} \\ \hline
  13933. \gray{\LvarASTRacket{}} \\ \hline
  13934. \gray{\LifASTRacket{}} \\ \hline
  13935. \gray{\LwhileASTRacket{}} \\ \hline
  13936. \gray{\LtupASTRacket{}} \\ \hline
  13937. \LfunASTRacket \\
  13938. \begin{array}{lcl}
  13939. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13940. \end{array}
  13941. \end{array}
  13942. \]
  13943. \fi}
  13944. {\if\edition\pythonEd\pythonColor
  13945. \[
  13946. \begin{array}{l}
  13947. \gray{\LintASTPython{}} \\ \hline
  13948. \gray{\LvarASTPython{}} \\ \hline
  13949. \gray{\LifASTPython{}} \\ \hline
  13950. \gray{\LwhileASTPython} \\ \hline
  13951. \gray{\LtupASTPython} \\ \hline
  13952. \LfunASTPython \\
  13953. \begin{array}{rcl}
  13954. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13955. \end{array}
  13956. \end{array}
  13957. \]
  13958. \fi}
  13959. \end{tcolorbox}
  13960. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13961. \label{fig:Lfun-syntax}
  13962. \index{subject}{Lfun@\LangFun{} abstract syntax}
  13963. \end{figure}
  13964. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13965. representative example of defining and using functions in \LangFun{}.
  13966. We define a function \code{map} that applies some other function
  13967. \code{f} to both elements of a tuple and returns a new tuple
  13968. containing the results. We also define a function \code{inc}. The
  13969. program applies \code{map} to \code{inc} and
  13970. %
  13971. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13972. %
  13973. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13974. %
  13975. from which we return \code{42}.
  13976. \begin{figure}[tbp]
  13977. \begin{tcolorbox}[colback=white]
  13978. {\if\edition\racketEd
  13979. \begin{lstlisting}
  13980. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13981. : (Vector Integer Integer)
  13982. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13983. (define (inc [x : Integer]) : Integer
  13984. (+ x 1))
  13985. (vector-ref (map inc (vector 0 41)) 1)
  13986. \end{lstlisting}
  13987. \fi}
  13988. {\if\edition\pythonEd\pythonColor
  13989. \begin{lstlisting}
  13990. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13991. return f(v[0]), f(v[1])
  13992. def inc(x : int) -> int:
  13993. return x + 1
  13994. print(map(inc, (0, 41))[1])
  13995. \end{lstlisting}
  13996. \fi}
  13997. \end{tcolorbox}
  13998. \caption{Example of using functions in \LangFun{}.}
  13999. \label{fig:Lfun-function-example}
  14000. \end{figure}
  14001. The definitional interpreter for \LangFun{} is shown in
  14002. figure~\ref{fig:interp-Lfun}. The case for the
  14003. %
  14004. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14005. %
  14006. AST is responsible for setting up the mutual recursion between the
  14007. top-level function definitions.
  14008. %
  14009. \racket{We use the classic back-patching
  14010. \index{subject}{back-patching} approach that uses mutable variables
  14011. and makes two passes over the function
  14012. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  14013. top-level environment using a mutable cons cell for each function
  14014. definition. Note that the \code{lambda}\index{subject}{lambda} value
  14015. for each function is incomplete; it does not yet include the environment.
  14016. Once the top-level environment has been constructed, we iterate over it and
  14017. update the \code{lambda} values to use the top-level environment.}
  14018. %
  14019. \python{We create a dictionary named \code{env} and fill it in
  14020. by mapping each function name to a new \code{Function} value,
  14021. each of which stores a reference to the \code{env}.
  14022. (We define the class \code{Function} for this purpose.)}
  14023. %
  14024. To interpret a function \racket{application}\python{call}, we match
  14025. the result of the function expression to obtain a function value. We
  14026. then extend the function's environment with the mapping of parameters to
  14027. argument values. Finally, we interpret the body of the function in
  14028. this extended environment.
  14029. \begin{figure}[tp]
  14030. \begin{tcolorbox}[colback=white]
  14031. {\if\edition\racketEd
  14032. \begin{lstlisting}
  14033. (define interp-Lfun-class
  14034. (class interp-Lvec-class
  14035. (super-new)
  14036. (define/override ((interp-exp env) e)
  14037. (define recur (interp-exp env))
  14038. (match e
  14039. [(Apply fun args)
  14040. (define fun-val (recur fun))
  14041. (define arg-vals (for/list ([e args]) (recur e)))
  14042. (match fun-val
  14043. [`(function (,xs ...) ,body ,fun-env)
  14044. (define params-args (for/list ([x xs] [arg arg-vals])
  14045. (cons x (box arg))))
  14046. (define new-env (append params-args fun-env))
  14047. ((interp-exp new-env) body)]
  14048. [else
  14049. (error 'interp-exp "expected function, not ~a" fun-val)])]
  14050. [else ((super interp-exp env) e)]
  14051. ))
  14052. (define/public (interp-def d)
  14053. (match d
  14054. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  14055. (cons f (box `(function ,xs ,body ())))]))
  14056. (define/override (interp-program p)
  14057. (match p
  14058. [(ProgramDefsExp info ds body)
  14059. (let ([top-level (for/list ([d ds]) (interp-def d))])
  14060. (for/list ([f (in-dict-values top-level)])
  14061. (set-box! f (match (unbox f)
  14062. [`(function ,xs ,body ())
  14063. `(function ,xs ,body ,top-level)])))
  14064. ((interp-exp top-level) body))]))
  14065. ))
  14066. (define (interp-Lfun p)
  14067. (send (new interp-Lfun-class) interp-program p))
  14068. \end{lstlisting}
  14069. \fi}
  14070. {\if\edition\pythonEd\pythonColor
  14071. \begin{lstlisting}
  14072. class InterpLfun(InterpLtup):
  14073. def apply_fun(self, fun, args, e):
  14074. match fun:
  14075. case Function(name, xs, body, env):
  14076. new_env = env.copy().update(zip(xs, args))
  14077. return self.interp_stmts(body, new_env)
  14078. case _:
  14079. raise Exception('apply_fun: unexpected: ' + repr(fun))
  14080. def interp_exp(self, e, env):
  14081. match e:
  14082. case Call(Name('input_int'), []):
  14083. return super().interp_exp(e, env)
  14084. case Call(func, args):
  14085. f = self.interp_exp(func, env)
  14086. vs = [self.interp_exp(arg, env) for arg in args]
  14087. return self.apply_fun(f, vs, e)
  14088. case _:
  14089. return super().interp_exp(e, env)
  14090. def interp_stmt(self, s, env, cont):
  14091. match s:
  14092. case Return(value):
  14093. return self.interp_exp(value, env)
  14094. case FunctionDef(name, params, bod, dl, returns, comment):
  14095. if isinstance(params, ast.arguments):
  14096. ps = [p.arg for p in params.args]
  14097. else:
  14098. ps = [x for (x,t) in params]
  14099. env[name] = Function(name, ps, bod, env)
  14100. return self.interp_stmts(cont, env)
  14101. case _:
  14102. return super().interp_stmt(s, env, cont)
  14103. def interp(self, p):
  14104. match p:
  14105. case Module(ss):
  14106. env = {}
  14107. self.interp_stmts(ss, env)
  14108. if 'main' in env.keys():
  14109. self.apply_fun(env['main'], [], None)
  14110. case _:
  14111. raise Exception('interp: unexpected ' + repr(p))
  14112. \end{lstlisting}
  14113. \fi}
  14114. \end{tcolorbox}
  14115. \caption{Interpreter for the \LangFun{} language.}
  14116. \label{fig:interp-Lfun}
  14117. \end{figure}
  14118. %\margincomment{TODO: explain type checker}
  14119. The type checker for \LangFun{} is shown in
  14120. figure~\ref{fig:type-check-Lfun}.
  14121. %
  14122. \python{(We omit the code that parses function parameters into the
  14123. simpler abstract syntax.)}
  14124. %
  14125. Similarly to the interpreter, the case for the
  14126. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14127. %
  14128. AST is responsible for setting up the mutual recursion between the
  14129. top-level function definitions. We begin by creating a mapping
  14130. \code{env} from every function name to its type. We then type check
  14131. the program using this mapping.
  14132. %
  14133. \python{To check a function definition, we copy and extend the
  14134. \code{env} with the parameters of the function. We then type check
  14135. the body of the function and obtain the actual return type
  14136. \code{rt}, which is either the type of the expression in a
  14137. \code{return} statement or the \code{VoidType} if control reaches
  14138. the end of the function without a \code{return} statement. (If
  14139. there are multiple \code{return} statements, the types of their
  14140. expressions must agree.) Finally, we check that the actual return
  14141. type \code{rt} is equal to the declared return type \code{returns}.}
  14142. %
  14143. To check a function \racket{application}\python{call}, we match
  14144. the type of the function expression to a function type and check that
  14145. the types of the argument expressions are equal to the function's
  14146. parameter types. The type of the \racket{application}\python{call} as
  14147. a whole is the return type from the function type.
  14148. \begin{figure}[tp]
  14149. \begin{tcolorbox}[colback=white]
  14150. {\if\edition\racketEd
  14151. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14152. (define type-check-Lfun-class
  14153. (class type-check-Lvec-class
  14154. (super-new)
  14155. (inherit check-type-equal?)
  14156. (define/public (type-check-apply env e es)
  14157. (define-values (e^ ty) ((type-check-exp env) e))
  14158. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14159. ((type-check-exp env) e)))
  14160. (match ty
  14161. [`(,ty^* ... -> ,rt)
  14162. (for ([arg-ty ty*] [param-ty ty^*])
  14163. (check-type-equal? arg-ty param-ty (Apply e es)))
  14164. (values e^ e* rt)]))
  14165. (define/override (type-check-exp env)
  14166. (lambda (e)
  14167. (match e
  14168. [(FunRef f n)
  14169. (values (FunRef f n) (dict-ref env f))]
  14170. [(Apply e es)
  14171. (define-values (e^ es^ rt) (type-check-apply env e es))
  14172. (values (Apply e^ es^) rt)]
  14173. [(Call e es)
  14174. (define-values (e^ es^ rt) (type-check-apply env e es))
  14175. (values (Call e^ es^) rt)]
  14176. [else ((super type-check-exp env) e)])))
  14177. (define/public (type-check-def env)
  14178. (lambda (e)
  14179. (match e
  14180. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14181. (define new-env (append (map cons xs ps) env))
  14182. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14183. (check-type-equal? ty^ rt body)
  14184. (Def f p:t* rt info body^)])))
  14185. (define/public (fun-def-type d)
  14186. (match d
  14187. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14188. (define/override (type-check-program e)
  14189. (match e
  14190. [(ProgramDefsExp info ds body)
  14191. (define env (for/list ([d ds])
  14192. (cons (Def-name d) (fun-def-type d))))
  14193. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14194. (define-values (body^ ty) ((type-check-exp env) body))
  14195. (check-type-equal? ty 'Integer body)
  14196. (ProgramDefsExp info ds^ body^)]))))
  14197. (define (type-check-Lfun p)
  14198. (send (new type-check-Lfun-class) type-check-program p))
  14199. \end{lstlisting}
  14200. \fi}
  14201. {\if\edition\pythonEd\pythonColor
  14202. \begin{lstlisting}
  14203. class TypeCheckLfun(TypeCheckLtup):
  14204. def type_check_exp(self, e, env):
  14205. match e:
  14206. case Call(Name('input_int'), []):
  14207. return super().type_check_exp(e, env)
  14208. case Call(func, args):
  14209. func_t = self.type_check_exp(func, env)
  14210. args_t = [self.type_check_exp(arg, env) for arg in args]
  14211. match func_t:
  14212. case FunctionType(params_t, return_t):
  14213. for (arg_t, param_t) in zip(args_t, params_t):
  14214. check_type_equal(param_t, arg_t, e)
  14215. return return_t
  14216. case _:
  14217. raise Exception('type_check_exp: in call, unexpected ' +
  14218. repr(func_t))
  14219. case _:
  14220. return super().type_check_exp(e, env)
  14221. def type_check_stmts(self, ss, env):
  14222. if len(ss) == 0:
  14223. return VoidType()
  14224. match ss[0]:
  14225. case FunctionDef(name, params, body, dl, returns, comment):
  14226. new_env = env.copy().update(params)
  14227. rt = self.type_check_stmts(body, new_env)
  14228. check_type_equal(returns, rt, ss[0])
  14229. return self.type_check_stmts(ss[1:], env)
  14230. case Return(value):
  14231. return self.type_check_exp(value, env)
  14232. case _:
  14233. return super().type_check_stmts(ss, env)
  14234. def type_check(self, p):
  14235. match p:
  14236. case Module(body):
  14237. env = {}
  14238. for s in body:
  14239. match s:
  14240. case FunctionDef(name, params, bod, dl, returns, comment):
  14241. if name in env:
  14242. raise Exception('type_check: function ' +
  14243. repr(name) + ' defined twice')
  14244. params_t = [t for (x,t) in params]
  14245. env[name] = FunctionType(params_t, returns)
  14246. self.type_check_stmts(body, env)
  14247. case _:
  14248. raise Exception('type_check: unexpected ' + repr(p))
  14249. \end{lstlisting}
  14250. \fi}
  14251. \end{tcolorbox}
  14252. \caption{Type checker for the \LangFun{} language.}
  14253. \label{fig:type-check-Lfun}
  14254. \end{figure}
  14255. \clearpage
  14256. \section{Functions in x86}
  14257. \label{sec:fun-x86}
  14258. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14259. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14260. %% \margincomment{\tiny Talk about the return address on the
  14261. %% stack and what callq and retq does.\\ --Jeremy }
  14262. The x86 architecture provides a few features to support the
  14263. implementation of functions. We have already seen that there are
  14264. labels in x86 so that one can refer to the location of an instruction,
  14265. as is needed for jump instructions. Labels can also be used to mark
  14266. the beginning of the instructions for a function. Going further, we
  14267. can obtain the address of a label by using the \key{leaq}
  14268. instruction. For example, the following puts the address of the
  14269. \code{inc} label into the \code{rbx} register:
  14270. \begin{lstlisting}
  14271. leaq inc(%rip), %rbx
  14272. \end{lstlisting}
  14273. Recall from section~\ref{sec:select-instructions-gc} that
  14274. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14275. addressing.
  14276. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14277. to functions whose locations were given by a label, such as
  14278. \code{read\_int}. To support function calls in this chapter we instead
  14279. jump to functions whose location are given by an address in
  14280. a register; that is, we use \emph{indirect function calls}. The
  14281. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14282. before the register name.\index{subject}{indirect function call}
  14283. \begin{lstlisting}
  14284. callq *%rbx
  14285. \end{lstlisting}
  14286. \subsection{Calling Conventions}
  14287. \label{sec:calling-conventions-fun}
  14288. \index{subject}{calling conventions}
  14289. The \code{callq} instruction provides partial support for implementing
  14290. functions: it pushes the return address on the stack and it jumps to
  14291. the target. However, \code{callq} does not handle
  14292. \begin{enumerate}
  14293. \item parameter passing,
  14294. \item pushing frames on the procedure call stack and popping them off,
  14295. or
  14296. \item determining how registers are shared by different functions.
  14297. \end{enumerate}
  14298. Regarding parameter passing, recall that the x86-64 calling
  14299. convention for Unix-based systems uses the following six registers to
  14300. pass arguments to a function, in the given order:
  14301. \begin{lstlisting}
  14302. rdi rsi rdx rcx r8 r9
  14303. \end{lstlisting}
  14304. If there are more than six arguments, then the calling convention
  14305. mandates using space on the frame of the caller for the rest of the
  14306. arguments. However, to ease the implementation of efficient tail calls
  14307. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14308. arguments.
  14309. %
  14310. The return value of the function is stored in register \code{rax}.
  14311. Regarding frames \index{subject}{frame} and the procedure call stack,
  14312. \index{subject}{procedure call stack} recall from
  14313. section~\ref{sec:x86} that the stack grows down and each function call
  14314. uses a chunk of space on the stack called a frame. The caller sets the
  14315. stack pointer, register \code{rsp}, to the last data item in its
  14316. frame. The callee must not change anything in the caller's frame, that
  14317. is, anything that is at or above the stack pointer. The callee is free
  14318. to use locations that are below the stack pointer.
  14319. Recall that we store variables of tuple type on the root stack. So,
  14320. the prelude\index{subject}{prelude} of a function needs to move the
  14321. root stack pointer \code{r15} up according to the number of variables
  14322. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14323. move the root stack pointer back down. Also, the prelude must
  14324. initialize to \code{0} this frame's slots in the root stack to signal
  14325. to the garbage collector that those slots do not yet contain a valid
  14326. pointer. Otherwise the garbage collector will interpret the garbage
  14327. bits in those slots as memory addresses and try to traverse them,
  14328. causing serious mayhem!
  14329. Regarding the sharing of registers between different functions, recall
  14330. from section~\ref{sec:calling-conventions} that the registers are
  14331. divided into two groups, the caller-saved registers and the
  14332. callee-saved registers. The caller should assume that all the
  14333. caller-saved registers are overwritten with arbitrary values by the
  14334. callee. For that reason we recommend in
  14335. section~\ref{sec:calling-conventions} that variables that are live
  14336. during a function call should not be assigned to caller-saved
  14337. registers.
  14338. On the flip side, if the callee wants to use a callee-saved register,
  14339. the callee must save the contents of those registers on their stack
  14340. frame and then put them back prior to returning to the caller. For
  14341. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14342. the register allocator assigns a variable to a callee-saved register,
  14343. then the prelude of the \code{main} function must save that register
  14344. to the stack and the conclusion of \code{main} must restore it. This
  14345. recommendation now generalizes to all functions.
  14346. Recall that the base pointer, register \code{rbp}, is used as a
  14347. point of reference within a frame, so that each local variable can be
  14348. accessed at a fixed offset from the base pointer
  14349. (section~\ref{sec:x86}).
  14350. %
  14351. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14352. frames.
  14353. \begin{figure}[tbp]
  14354. \centering
  14355. \begin{tcolorbox}[colback=white]
  14356. \begin{tabular}{r|r|l|l} \hline
  14357. Caller View & Callee View & Contents & Frame \\ \hline
  14358. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14359. 0(\key{\%rbp}) & & old \key{rbp} \\
  14360. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14361. \ldots & & \ldots \\
  14362. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14363. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14364. \ldots & & \ldots \\
  14365. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14366. %% & & \\
  14367. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14368. %% & \ldots & \ldots \\
  14369. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14370. \hline
  14371. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14372. & 0(\key{\%rbp}) & old \key{rbp} \\
  14373. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14374. & \ldots & \ldots \\
  14375. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14376. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14377. & \ldots & \ldots \\
  14378. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14379. \end{tabular}
  14380. \end{tcolorbox}
  14381. \caption{Memory layout of caller and callee frames.}
  14382. \label{fig:call-frames}
  14383. \end{figure}
  14384. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14385. %% local variables and for storing the values of callee-saved registers
  14386. %% (we shall refer to all of these collectively as ``locals''), and that
  14387. %% at the beginning of a function we move the stack pointer \code{rsp}
  14388. %% down to make room for them.
  14389. %% We recommend storing the local variables
  14390. %% first and then the callee-saved registers, so that the local variables
  14391. %% can be accessed using \code{rbp} the same as before the addition of
  14392. %% functions.
  14393. %% To make additional room for passing arguments, we shall
  14394. %% move the stack pointer even further down. We count how many stack
  14395. %% arguments are needed for each function call that occurs inside the
  14396. %% body of the function and find their maximum. Adding this number to the
  14397. %% number of locals gives us how much the \code{rsp} should be moved at
  14398. %% the beginning of the function. In preparation for a function call, we
  14399. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14400. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14401. %% so on.
  14402. %% Upon calling the function, the stack arguments are retrieved by the
  14403. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14404. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14405. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14406. %% the layout of the caller and callee frames. Notice how important it is
  14407. %% that we correctly compute the maximum number of arguments needed for
  14408. %% function calls; if that number is too small then the arguments and
  14409. %% local variables will smash into each other!
  14410. \subsection{Efficient Tail Calls}
  14411. \label{sec:tail-call}
  14412. In general, the amount of stack space used by a program is determined
  14413. by the longest chain of nested function calls. That is, if function
  14414. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14415. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14416. large if functions are recursive. However, in some cases we can
  14417. arrange to use only a constant amount of space for a long chain of
  14418. nested function calls.
  14419. A \emph{tail call}\index{subject}{tail call} is a function call that
  14420. happens as the last action in a function body. For example, in the
  14421. following program, the recursive call to \code{tail\_sum} is a tail
  14422. call:
  14423. \begin{center}
  14424. {\if\edition\racketEd
  14425. \begin{lstlisting}
  14426. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14427. (if (eq? n 0)
  14428. r
  14429. (tail_sum (- n 1) (+ n r))))
  14430. (+ (tail_sum 3 0) 36)
  14431. \end{lstlisting}
  14432. \fi}
  14433. {\if\edition\pythonEd\pythonColor
  14434. \begin{lstlisting}
  14435. def tail_sum(n : int, r : int) -> int:
  14436. if n == 0:
  14437. return r
  14438. else:
  14439. return tail_sum(n - 1, n + r)
  14440. print(tail_sum(3, 0) + 36)
  14441. \end{lstlisting}
  14442. \fi}
  14443. \end{center}
  14444. At a tail call, the frame of the caller is no longer needed, so we can
  14445. pop the caller's frame before making the tail
  14446. call. \index{subject}{frame} With this approach, a recursive function
  14447. that makes only tail calls ends up using a constant amount of stack
  14448. space. \racket{Functional languages like Racket rely heavily on
  14449. recursive functions, so the definition of Racket \emph{requires}
  14450. that all tail calls be optimized in this way.}
  14451. Some care is needed with regard to argument passing in tail calls. As
  14452. mentioned, for arguments beyond the sixth, the convention is to use
  14453. space in the caller's frame for passing arguments. However, for a
  14454. tail call we pop the caller's frame and can no longer use it. An
  14455. alternative is to use space in the callee's frame for passing
  14456. arguments. However, this option is also problematic because the caller
  14457. and callee's frames overlap in memory. As we begin to copy the
  14458. arguments from their sources in the caller's frame, the target
  14459. locations in the callee's frame might collide with the sources for
  14460. later arguments! We solve this problem by using the heap instead of
  14461. the stack for passing more than six arguments
  14462. (section~\ref{sec:limit-functions-r4}).
  14463. As mentioned, for a tail call we pop the caller's frame prior to
  14464. making the tail call. The instructions for popping a frame are the
  14465. instructions that we usually place in the conclusion of a
  14466. function. Thus, we also need to place such code immediately before
  14467. each tail call. These instructions include restoring the callee-saved
  14468. registers, so it is fortunate that the argument passing registers are
  14469. all caller-saved registers.
  14470. One note remains regarding which instruction to use to make the tail
  14471. call. When the callee is finished, it should not return to the current
  14472. function but instead return to the function that called the current
  14473. one. Thus, the return address that is already on the stack is the
  14474. right one, and we should not use \key{callq} to make the tail call
  14475. because that would overwrite the return address. Instead we simply use
  14476. the \key{jmp} instruction. As with the indirect function call, we write
  14477. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14478. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14479. jump target because the conclusion can overwrite just about everything
  14480. else.
  14481. \begin{lstlisting}
  14482. jmp *%rax
  14483. \end{lstlisting}
  14484. \section{Shrink \LangFun{}}
  14485. \label{sec:shrink-r4}
  14486. The \code{shrink} pass performs a minor modification to ease the
  14487. later passes. This pass introduces an explicit \code{main} function
  14488. that gobbles up all the top-level statements of the module.
  14489. %
  14490. \racket{It also changes the top \code{ProgramDefsExp} form to
  14491. \code{ProgramDefs}.}
  14492. {\if\edition\racketEd
  14493. \begin{lstlisting}
  14494. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14495. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14496. \end{lstlisting}
  14497. where $\itm{mainDef}$ is
  14498. \begin{lstlisting}
  14499. (Def 'main '() 'Integer '() |$\Exp'$|)
  14500. \end{lstlisting}
  14501. \fi}
  14502. {\if\edition\pythonEd\pythonColor
  14503. \begin{lstlisting}
  14504. Module(|$\Def\ldots\Stmt\ldots$|)
  14505. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14506. \end{lstlisting}
  14507. where $\itm{mainDef}$ is
  14508. \begin{lstlisting}
  14509. FunctionDef('main', [], |$\Stmt\ldots$|Return(Constant(0)), None, IntType(), None)
  14510. \end{lstlisting}
  14511. \fi}
  14512. \section{Reveal Functions and the \LangFunRef{} Language}
  14513. \label{sec:reveal-functions-r4}
  14514. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14515. in that it conflates the use of function names and local
  14516. variables. This is a problem because we need to compile the use of a
  14517. function name differently from the use of a local variable. In
  14518. particular, we use \code{leaq} to convert the function name (a label
  14519. in x86) to an address in a register. Thus, we create a new pass that
  14520. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14521. $n$ is the arity of the function.\python{\footnote{The arity is not
  14522. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14523. This pass is named \code{reveal\_functions} and the output language
  14524. is \LangFunRef{}\index{subject}{Lfunref@\LangFunRef{}}.
  14525. %is defined in figure~\ref{fig:f1-syntax}.
  14526. %% The concrete syntax for a
  14527. %% function reference is $\CFUNREF{f}$.
  14528. %% \begin{figure}[tp]
  14529. %% \centering
  14530. %% \fbox{
  14531. %% \begin{minipage}{0.96\textwidth}
  14532. %% {\if\edition\racketEd
  14533. %% \[
  14534. %% \begin{array}{lcl}
  14535. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14536. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14537. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14538. %% \end{array}
  14539. %% \]
  14540. %% \fi}
  14541. %% {\if\edition\pythonEd\pythonColor
  14542. %% \[
  14543. %% \begin{array}{lcl}
  14544. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14545. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14546. %% \end{array}
  14547. %% \]
  14548. %% \fi}
  14549. %% \end{minipage}
  14550. %% }
  14551. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14552. %% (figure~\ref{fig:Lfun-syntax}).}
  14553. %% \label{fig:f1-syntax}
  14554. %% \end{figure}
  14555. %% Distinguishing between calls in tail position and non-tail position
  14556. %% requires the pass to have some notion of context. We recommend using
  14557. %% two mutually recursive functions, one for processing expressions in
  14558. %% tail position and another for the rest.
  14559. \racket{Placing this pass after \code{uniquify} will make sure that
  14560. there are no local variables and functions that share the same
  14561. name.}
  14562. %
  14563. The \code{reveal\_functions} pass should come before the
  14564. \code{remove\_complex\_operands} pass because function references
  14565. should be categorized as complex expressions.
  14566. \section{Limit Functions}
  14567. \label{sec:limit-functions-r4}
  14568. Recall that we wish to limit the number of function parameters to six
  14569. so that we do not need to use the stack for argument passing, which
  14570. makes it easier to implement efficient tail calls. However, because
  14571. the input language \LangFun{} supports arbitrary numbers of function
  14572. arguments, we have some work to do! The \code{limit\_functions} pass
  14573. transforms functions and function calls that involve more than six
  14574. arguments to pass the first five arguments as usual, but it packs the
  14575. rest of the arguments into a tuple and passes it as the sixth
  14576. argument.\footnote{The implementation this pass can be postponed to
  14577. last because you can test the rest of the passes on functions with
  14578. six or fewer parameters.}
  14579. Each function definition with seven or more parameters is transformed as
  14580. follows:
  14581. {\if\edition\racketEd
  14582. \begin{lstlisting}
  14583. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14584. |$\Rightarrow$|
  14585. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14586. \end{lstlisting}
  14587. \fi}
  14588. {\if\edition\pythonEd\pythonColor
  14589. \begin{lstlisting}
  14590. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14591. |$\Rightarrow$|
  14592. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14593. |$T_r$|, None, |$\itm{body}'$|, None)
  14594. \end{lstlisting}
  14595. \fi}
  14596. %
  14597. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14598. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14599. the $k$th element of the tuple, where $k = i - 6$.
  14600. %
  14601. {\if\edition\racketEd
  14602. \begin{lstlisting}
  14603. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14604. \end{lstlisting}
  14605. \fi}
  14606. {\if\edition\pythonEd\pythonColor
  14607. \begin{lstlisting}
  14608. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14609. \end{lstlisting}
  14610. \fi}
  14611. For function calls with too many arguments, the \code{limit\_functions}
  14612. pass transforms them in the following way:
  14613. \begin{tabular}{lll}
  14614. \begin{minipage}{0.3\textwidth}
  14615. {\if\edition\racketEd
  14616. \begin{lstlisting}
  14617. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14618. \end{lstlisting}
  14619. \fi}
  14620. {\if\edition\pythonEd\pythonColor
  14621. \begin{lstlisting}
  14622. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14623. \end{lstlisting}
  14624. \fi}
  14625. \end{minipage}
  14626. &
  14627. $\Rightarrow$
  14628. &
  14629. \begin{minipage}{0.5\textwidth}
  14630. {\if\edition\racketEd
  14631. \begin{lstlisting}
  14632. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14633. \end{lstlisting}
  14634. \fi}
  14635. {\if\edition\pythonEd\pythonColor
  14636. \begin{lstlisting}
  14637. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14638. \end{lstlisting}
  14639. \fi}
  14640. \end{minipage}
  14641. \end{tabular}
  14642. \section{Remove Complex Operands}
  14643. \label{sec:rco-r4}
  14644. The primary decisions to make for this pass are whether to classify
  14645. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14646. atomic or complex expressions. Recall that an atomic expression
  14647. ends up as an immediate argument of an x86 instruction. Function
  14648. application translates to a sequence of instructions, so
  14649. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14650. a complex expression. On the other hand, the arguments of
  14651. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14652. expressions.
  14653. %
  14654. Regarding \code{FunRef}, as discussed previously, the function label
  14655. needs to be converted to an address using the \code{leaq}
  14656. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14657. needs to be classified as a complex expression so that we generate an
  14658. assignment statement with a left-hand side that can serve as the
  14659. target of the \code{leaq}.
  14660. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14661. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14662. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14663. and augments programs to include a list of function definitions.
  14664. %
  14665. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14666. \newcommand{\LfunMonadASTRacket}{
  14667. \begin{array}{lcl}
  14668. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14669. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14670. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14671. \end{array}
  14672. }
  14673. \newcommand{\LfunMonadASTPython}{
  14674. \begin{array}{lcl}
  14675. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14676. \MID \key{TupleType}\LS\Type^+\RS\\
  14677. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14678. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14679. \Stmt &::=& \RETURN{\Exp} \\
  14680. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14681. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14682. \end{array}
  14683. }
  14684. \begin{figure}[tp]
  14685. \centering
  14686. \begin{tcolorbox}[colback=white]
  14687. \footnotesize
  14688. {\if\edition\racketEd
  14689. \[
  14690. \begin{array}{l}
  14691. \gray{\LvarMonadASTRacket} \\ \hline
  14692. \gray{\LifMonadASTRacket} \\ \hline
  14693. \gray{\LwhileMonadASTRacket} \\ \hline
  14694. \gray{\LtupMonadASTRacket} \\ \hline
  14695. \LfunMonadASTRacket \\
  14696. \begin{array}{rcl}
  14697. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14698. \end{array}
  14699. \end{array}
  14700. \]
  14701. \fi}
  14702. {\if\edition\pythonEd\pythonColor
  14703. \[
  14704. \begin{array}{l}
  14705. \gray{\LvarMonadASTPython} \\ \hline
  14706. \gray{\LifMonadASTPython} \\ \hline
  14707. \gray{\LwhileMonadASTPython} \\ \hline
  14708. \gray{\LtupMonadASTPython} \\ \hline
  14709. \LfunMonadASTPython \\
  14710. \begin{array}{rcl}
  14711. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14712. \end{array}
  14713. \end{array}
  14714. \]
  14715. \fi}
  14716. \end{tcolorbox}
  14717. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14718. \label{fig:Lfun-anf-syntax}
  14719. \index{subject}{Lfunmon@\LangFunANF{} abstract syntax}
  14720. \end{figure}
  14721. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14722. %% \LangFunANF{} of this pass.
  14723. %% \begin{figure}[tp]
  14724. %% \centering
  14725. %% \fbox{
  14726. %% \begin{minipage}{0.96\textwidth}
  14727. %% \small
  14728. %% \[
  14729. %% \begin{array}{rcl}
  14730. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14731. %% \MID \VOID{} } \\
  14732. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14733. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14734. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14735. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14736. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14737. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14738. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14739. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14740. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14741. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14742. %% \end{array}
  14743. %% \]
  14744. %% \end{minipage}
  14745. %% }
  14746. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14747. %% \label{fig:Lfun-anf-syntax}
  14748. %% \end{figure}
  14749. \section{Explicate Control and the \LangCFun{} Language}
  14750. \label{sec:explicate-control-r4}
  14751. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14752. output of \code{explicate\_control}.
  14753. %
  14754. %% \racket{(The concrete syntax is given in
  14755. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14756. %
  14757. \racket{The auxiliary functions for assignment and tail contexts should
  14758. be updated with cases for \code{Apply} and \code{FunRef}.}
  14759. The auxiliary function for predicate context should be updated for
  14760. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14761. \code{FunRef} cannot be a Boolean.)
  14762. %
  14763. \racket{In assignment and predicate contexts,
  14764. \code{Apply} becomes \code{Call}, whereas
  14765. in tail position \code{Apply} becomes \code{TailCall}.}
  14766. %
  14767. We recommend defining a new auxiliary function for processing function
  14768. definitions. This code is similar to the case for \code{Program} in
  14769. \LangVecANF{}. The top-level \code{explicate\_control} function that
  14770. handles the \code{ProgramDefs} form of \LangFunANF{} can apply this
  14771. new function to all function definitions.
  14772. {\if\edition\pythonEd\pythonColor
  14773. The translation of \code{Return} statements requires a new auxiliary
  14774. function to handle expressions in tail context, called
  14775. \code{explicate\_tail}. The function should take an expression and the
  14776. dictionary of basic blocks and produce a list of statements in the
  14777. \LangCFun{} language. The \code{explicate\_tail} function should
  14778. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14779. and a default case for other kinds of expressions. The default case
  14780. should produce a \code{Return} statement. The case for \code{Call}
  14781. should change it into \code{TailCall}. The other cases should
  14782. recursively process their subexpressions and statements, choosing the
  14783. appropriate explicate functions for the various contexts.
  14784. \fi}
  14785. \newcommand{\CfunASTRacket}{
  14786. \begin{array}{lcl}
  14787. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14788. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14789. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14790. \end{array}
  14791. }
  14792. \newcommand{\CfunASTPython}{
  14793. \begin{array}{lcl}
  14794. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14795. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14796. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14797. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14798. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14799. \end{array}
  14800. }
  14801. \begin{figure}[tp]
  14802. \begin{tcolorbox}[colback=white]
  14803. \footnotesize
  14804. {\if\edition\racketEd
  14805. \[
  14806. \begin{array}{l}
  14807. \gray{\CvarASTRacket} \\ \hline
  14808. \gray{\CifASTRacket} \\ \hline
  14809. \gray{\CloopASTRacket} \\ \hline
  14810. \gray{\CtupASTRacket} \\ \hline
  14811. \CfunASTRacket \\
  14812. \begin{array}{lcl}
  14813. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14814. \end{array}
  14815. \end{array}
  14816. \]
  14817. \fi}
  14818. {\if\edition\pythonEd\pythonColor
  14819. \[
  14820. \begin{array}{l}
  14821. \gray{\CifASTPython} \\ \hline
  14822. \gray{\CtupASTPython} \\ \hline
  14823. \CfunASTPython \\
  14824. \begin{array}{lcl}
  14825. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14826. \end{array}
  14827. \end{array}
  14828. \]
  14829. \fi}
  14830. \end{tcolorbox}
  14831. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14832. \label{fig:c3-syntax}
  14833. \index{subject}{Cfun@\LangCFun{} abstract syntax}
  14834. \end{figure}
  14835. \clearpage
  14836. \section{Select Instructions and the \LangXIndCall{} Language}
  14837. \label{sec:select-r4}
  14838. \index{subject}{select instructions}
  14839. The output of select instructions is a program in the \LangXIndCall{}
  14840. language; the definition of its concrete syntax is shown in
  14841. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14842. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14843. directive on the labels of function definitions to make sure the
  14844. bottom three bits are zero, which we put to use in
  14845. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14846. this section. \index{subject}{x86}
  14847. \newcommand{\GrammarXIndCall}{
  14848. \begin{array}{lcl}
  14849. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14850. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14851. \Block &::= & \Instr^{+} \\
  14852. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14853. \end{array}
  14854. }
  14855. \newcommand{\ASTXIndCallRacket}{
  14856. \begin{array}{lcl}
  14857. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14858. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14859. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14860. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14861. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14862. \end{array}
  14863. }
  14864. \begin{figure}[tp]
  14865. \begin{tcolorbox}[colback=white]
  14866. \small
  14867. {\if\edition\racketEd
  14868. \[
  14869. \begin{array}{l}
  14870. \gray{\GrammarXIntRacket} \\ \hline
  14871. \gray{\GrammarXIfRacket} \\ \hline
  14872. \gray{\GrammarXGlobal} \\ \hline
  14873. \GrammarXIndCall \\
  14874. \begin{array}{lcl}
  14875. \LangXIndCallM{} &::= & \Def^{*}
  14876. \end{array}
  14877. \end{array}
  14878. \]
  14879. \fi}
  14880. {\if\edition\pythonEd
  14881. \[
  14882. \begin{array}{l}
  14883. \gray{\GrammarXIntPython} \\ \hline
  14884. \gray{\GrammarXIfPython} \\ \hline
  14885. \gray{\GrammarXGlobal} \\ \hline
  14886. \GrammarXIndCall \\
  14887. \begin{array}{lcl}
  14888. \LangXIndCallM{} &::= & \Def^{*}
  14889. \end{array}
  14890. \end{array}
  14891. \]
  14892. \fi}
  14893. \end{tcolorbox}
  14894. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14895. \label{fig:x86-3-concrete}
  14896. \end{figure}
  14897. \begin{figure}[tp]
  14898. \begin{tcolorbox}[colback=white]
  14899. \small
  14900. {\if\edition\racketEd
  14901. \[\arraycolsep=3pt
  14902. \begin{array}{l}
  14903. \gray{\ASTXIntRacket} \\ \hline
  14904. \gray{\ASTXIfRacket} \\ \hline
  14905. \gray{\ASTXGlobalRacket} \\ \hline
  14906. \ASTXIndCallRacket \\
  14907. \begin{array}{lcl}
  14908. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14909. \end{array}
  14910. \end{array}
  14911. \]
  14912. \fi}
  14913. {\if\edition\pythonEd\pythonColor
  14914. \[
  14915. \begin{array}{lcl}
  14916. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14917. \MID \BYTEREG{\Reg} } \\
  14918. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14919. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14920. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14921. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14922. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14923. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14924. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14925. \end{array}
  14926. \]
  14927. \fi}
  14928. \end{tcolorbox}
  14929. \caption{The abstract syntax of \LangXIndCall{} (extends
  14930. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14931. \label{fig:x86-3}
  14932. \end{figure}
  14933. An assignment of a function reference to a variable becomes a
  14934. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14935. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14936. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14937. node, whose concrete syntax is instruction-pointer-relative
  14938. addressing.
  14939. \begin{center}
  14940. \begin{tabular}{lcl}
  14941. \begin{minipage}{0.35\textwidth}
  14942. {\if\edition\racketEd
  14943. \begin{lstlisting}
  14944. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14945. \end{lstlisting}
  14946. \fi}
  14947. {\if\edition\pythonEd\pythonColor
  14948. \begin{lstlisting}
  14949. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14950. \end{lstlisting}
  14951. \fi}
  14952. \end{minipage}
  14953. &
  14954. $\Rightarrow$\qquad\qquad
  14955. &
  14956. \begin{minipage}{0.3\textwidth}
  14957. \begin{lstlisting}
  14958. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14959. \end{lstlisting}
  14960. \end{minipage}
  14961. \end{tabular}
  14962. \end{center}
  14963. Regarding function definitions, we need to remove the parameters and
  14964. instead perform parameter passing using the conventions discussed in
  14965. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14966. registers. We recommend turning the parameters into local variables
  14967. and generating instructions at the beginning of the function to move
  14968. from the argument-passing registers
  14969. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14970. {\if\edition\racketEd
  14971. \begin{lstlisting}
  14972. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14973. |$\Rightarrow$|
  14974. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14975. \end{lstlisting}
  14976. \fi}
  14977. {\if\edition\pythonEd\pythonColor
  14978. \begin{lstlisting}
  14979. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14980. |$\Rightarrow$|
  14981. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14982. \end{lstlisting}
  14983. \fi}
  14984. The basic blocks $B'$ are the same as $B$ except that the
  14985. \code{start} block is modified to add the instructions for moving from
  14986. the argument registers to the parameter variables. So the \code{start}
  14987. block of $B$ shown on the left of the following is changed to the code
  14988. on the right:
  14989. \begin{center}
  14990. \begin{minipage}{0.3\textwidth}
  14991. \begin{lstlisting}
  14992. start:
  14993. |$\itm{instr}_1$|
  14994. |$\cdots$|
  14995. |$\itm{instr}_n$|
  14996. \end{lstlisting}
  14997. \end{minipage}
  14998. $\Rightarrow$
  14999. \begin{minipage}{0.3\textwidth}
  15000. \begin{lstlisting}
  15001. |$f$|start:
  15002. movq %rdi, |$x_1$|
  15003. movq %rsi, |$x_2$|
  15004. |$\cdots$|
  15005. |$\itm{instr}_1$|
  15006. |$\cdots$|
  15007. |$\itm{instr}_n$|
  15008. \end{lstlisting}
  15009. \end{minipage}
  15010. \end{center}
  15011. Recall that we use the label \code{start} for the initial block of a
  15012. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  15013. the conclusion of the program with \code{conclusion}, so that
  15014. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  15015. by a jump to \code{conclusion}. With the addition of function
  15016. definitions, there is a start block and conclusion for each function,
  15017. but their labels need to be unique. We recommend prepending the
  15018. function's name to \code{start} and \code{conclusion}, respectively,
  15019. to obtain unique labels.
  15020. \racket{The interpreter for \LangXIndCall{} needs to be given the
  15021. number of parameters the function expects, but the parameters are no
  15022. longer in the syntax of function definitions. Instead, add an entry
  15023. to $\itm{info}$ that maps \code{num-params} to the number of
  15024. parameters to construct $\itm{info}'$.}
  15025. By changing the parameters to local variables, we are giving the
  15026. register allocator control over which registers or stack locations to
  15027. use for them. If you implement the move-biasing challenge
  15028. (section~\ref{sec:move-biasing}), the register allocator will try to
  15029. assign the parameter variables to the corresponding argument register,
  15030. in which case the \code{patch\_instructions} pass will remove the
  15031. \code{movq} instruction. This happens in the example translation given
  15032. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  15033. the \code{add} function.
  15034. %
  15035. Also, note that the register allocator will perform liveness analysis
  15036. on this sequence of move instructions and build the interference
  15037. graph. So, for example, $x_1$ will be marked as interfering with
  15038. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  15039. which is good because otherwise the first \code{movq} would overwrite
  15040. the argument in \code{rsi} that is needed for $x_2$.
  15041. Next, consider the compilation of function calls. In the mirror image
  15042. of the handling of parameters in function definitions, the arguments
  15043. are moved to the argument-passing registers. Note that the function
  15044. is not given as a label, but its address is produced by the argument
  15045. $\itm{arg}_0$. So, we translate the call into an indirect function
  15046. call. The return value from the function is stored in \code{rax}, so
  15047. it needs to be moved into the \itm{lhs}.
  15048. \begin{lstlisting}
  15049. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  15050. |$\Rightarrow$|
  15051. movq |$\itm{arg}_1$|, %rdi
  15052. movq |$\itm{arg}_2$|, %rsi
  15053. |$\vdots$|
  15054. callq *|$\itm{arg}_0$|
  15055. movq %rax, |$\itm{lhs}$|
  15056. \end{lstlisting}
  15057. The \code{IndirectCallq} AST node includes an integer for the arity of
  15058. the function, that is, the number of parameters. That information is
  15059. useful in the \code{uncover\_live} pass for determining which
  15060. argument-passing registers are potentially read during the call.
  15061. For tail calls, the parameter passing is the same as non-tail calls:
  15062. generate instructions to move the arguments into the argument-passing
  15063. registers. After that we need to pop the frame from the procedure
  15064. call stack. However, we do not yet know how big the frame is; that
  15065. gets determined during register allocation. So, instead of generating
  15066. those instructions here, we invent a new instruction that means ``pop
  15067. the frame and then do an indirect jump,'' which we name
  15068. \code{TailJmp}. The abstract syntax for this instruction includes an
  15069. argument that specifies where to jump and an integer that represents
  15070. the arity of the function being called.
  15071. \section{Register Allocation}
  15072. \label{sec:register-allocation-r4}
  15073. The addition of functions requires some changes to all three aspects
  15074. of register allocation, which we discuss in the following subsections.
  15075. \subsection{Liveness Analysis}
  15076. \label{sec:liveness-analysis-r4}
  15077. \index{subject}{liveness analysis}
  15078. %% The rest of the passes need only minor modifications to handle the new
  15079. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  15080. %% \code{leaq}.
  15081. The \code{IndirectCallq} instruction should be treated like
  15082. \code{Callq} regarding its written locations $W$, in that they should
  15083. include all the caller-saved registers. Recall that the reason for
  15084. that is to force variables that are live across a function call to be assigned to callee-saved
  15085. registers or to be spilled to the stack.
  15086. Regarding the set of read locations $R$, the arity fields of
  15087. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  15088. argument-passing registers should be considered as read by those
  15089. instructions. Also, the target field of \code{TailJmp} and
  15090. \code{IndirectCallq} should be included in the set of read locations
  15091. $R$.
  15092. \subsection{Build Interference Graph}
  15093. \label{sec:build-interference-r4}
  15094. With the addition of function definitions, we compute a separate interference
  15095. graph for each function (not just one for the whole program).
  15096. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  15097. spill tuple-typed variables that are live during a call to
  15098. \code{collect}, the garbage collector. With the addition of functions
  15099. to our language, we need to revisit this issue. Functions that perform
  15100. allocation contain calls to the collector. Thus, we should not only
  15101. spill a tuple-typed variable when it is live during a call to
  15102. \code{collect}, but we should spill the variable if it is live during
  15103. a call to any user-defined function. Thus, in the
  15104. \code{build\_interference} pass, we recommend adding interference
  15105. edges between call-live tuple-typed variables and the callee-saved
  15106. registers (in addition to creating edges between
  15107. call-live variables and the caller-saved registers).
  15108. \subsection{Allocate Registers}
  15109. The primary change to the \code{allocate\_registers} pass is adding an
  15110. auxiliary function for handling definitions (the \Def{} nonterminal
  15111. shown in figure~\ref{fig:x86-3}) with one case for function
  15112. definitions. The logic is the same as described in
  15113. chapter~\ref{ch:register-allocation-Lvar} except that now register
  15114. allocation is performed many times, once for each function definition,
  15115. instead of just once for the whole program.
  15116. \section{Patch Instructions}
  15117. In \code{patch\_instructions}, you should deal with the x86
  15118. idiosyncrasy that the destination argument of \code{leaq} must be a
  15119. register. Additionally, you should ensure that the argument of
  15120. \code{TailJmp} is \itm{rax}, our reserved register---because we
  15121. trample many other registers before the tail call, as explained in the
  15122. next section.
  15123. \section{Generate Prelude and Conclusion}
  15124. Now that register allocation is complete, we can translate the
  15125. \code{TailJmp} into a sequence of instructions. A naive translation of
  15126. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  15127. before the jump we need to pop the current frame to achieve efficient
  15128. tail calls. This sequence of instructions is the same as the code for
  15129. the conclusion of a function, except that the \code{retq} is replaced with
  15130. \code{jmp *$\itm{arg}$}.
  15131. Regarding function definitions, we generate a prelude and conclusion
  15132. for each one. This code is similar to the prelude and conclusion
  15133. generated for the \code{main} function presented in
  15134. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  15135. carry out the following steps:
  15136. % TODO: .align the functions!
  15137. \begin{enumerate}
  15138. %% \item Start with \code{.global} and \code{.align} directives followed
  15139. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  15140. %% example.)
  15141. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  15142. pointer.
  15143. \item Push to the stack all the callee-saved registers that were
  15144. used for register allocation.
  15145. \item Move the stack pointer \code{rsp} down to make room for the
  15146. regular spills (aligned to 16 bytes).
  15147. \item Move the root stack pointer \code{r15} up by the size of the
  15148. root-stack frame for this function, which depends on the number of
  15149. spilled tuple-typed variables. \label{root-stack-init}
  15150. \item Initialize to zero all new entries in the root-stack frame.
  15151. \item Jump to the start block.
  15152. \end{enumerate}
  15153. The prelude of the \code{main} function has an additional task: call
  15154. the \code{initialize} function to set up the garbage collector, and
  15155. then move the value of the global \code{rootstack\_begin} in
  15156. \code{r15}. This initialization should happen before step
  15157. \ref{root-stack-init}, which depends on \code{r15}.
  15158. The conclusion of every function should do the following:
  15159. \begin{enumerate}
  15160. \item Move the stack pointer back up past the regular spills.
  15161. \item Restore the callee-saved registers by popping them from the
  15162. stack.
  15163. \item Move the root stack pointer back down by the size of the
  15164. root-stack frame for this function.
  15165. \item Restore \code{rbp} by popping it from the stack.
  15166. \item Return to the caller with the \code{retq} instruction.
  15167. \end{enumerate}
  15168. The output of this pass is \LangXIndCallFlat{}, which differs from
  15169. \LangXIndCall{} in that there is no longer an AST node for function
  15170. definitions. Instead, a program is just
  15171. \racket{an association list}\python{a dictionary}
  15172. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15173. {\if\edition\racketEd
  15174. \[
  15175. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15176. \]
  15177. \fi}
  15178. {\if\edition\pythonEd
  15179. \[
  15180. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15181. \]
  15182. \fi}
  15183. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15184. compiling \LangFun{} to x86.
  15185. \begin{exercise}\normalfont\normalsize
  15186. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15187. Create eight new programs that use functions including examples that
  15188. pass functions and return functions from other functions, recursive
  15189. functions, functions that create tuples, and functions that make tail
  15190. calls. Test your compiler on these new programs and all your
  15191. previously created test programs.
  15192. \end{exercise}
  15193. \begin{figure}[tbp]
  15194. \begin{tcolorbox}[colback=white]
  15195. {\if\edition\racketEd
  15196. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15197. \node (Lfun) at (0,2) {\large \LangFun{}};
  15198. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15199. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15200. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15201. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15202. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15203. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15204. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15205. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15206. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15207. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15208. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15209. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15210. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15211. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15212. \path[->,bend left=15] (Lfun) edge [above] node
  15213. {\ttfamily\footnotesize shrink} (Lfun-1);
  15214. \path[->,bend left=15] (Lfun-1) edge [above] node
  15215. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15216. \path[->,bend left=15] (Lfun-2) edge [above] node
  15217. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15218. \path[->,bend left=15] (F1-1) edge [left] node
  15219. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15220. \path[->,bend left=15] (F1-2) edge [below] node
  15221. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15222. \path[->,bend left=15] (F1-3) edge [below] node
  15223. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15224. \path[->,bend right=15] (F1-4) edge [above] node
  15225. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15226. \path[->,bend right=15] (F1-5) edge [right] node
  15227. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15228. \path[->,bend right=15] (C3-2) edge [right] node
  15229. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15230. \path[->,bend left=15] (x86-2) edge [right] node
  15231. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15232. \path[->,bend right=15] (x86-2-1) edge [below] node
  15233. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15234. \path[->,bend right=15] (x86-2-2) edge [right] node
  15235. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15236. \path[->,bend left=15] (x86-3) edge [above] node
  15237. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15238. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15239. \end{tikzpicture}
  15240. \fi}
  15241. {\if\edition\pythonEd\pythonColor
  15242. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15243. \node (Lfun) at (0,2) {\large \LangFun{}};
  15244. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15245. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15246. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15247. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15248. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15249. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15250. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15251. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15252. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15253. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15254. \path[->,bend left=15] (Lfun) edge [above] node
  15255. {\ttfamily\footnotesize shrink} (Lfun-2);
  15256. \path[->,bend left=15] (Lfun-2) edge [above] node
  15257. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15258. \path[->,bend left=15] (F1-1) edge [above] node
  15259. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15260. \path[->,bend left=15] (F1-2) edge [right] node
  15261. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15262. \path[->,bend right=15] (F1-4) edge [above] node
  15263. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15264. \path[->,bend right=15] (F1-5) edge [right] node
  15265. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15266. \path[->,bend left=15] (C3-2) edge [right] node
  15267. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15268. \path[->,bend right=15] (x86-2) edge [below] node
  15269. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15270. \path[->,bend left=15] (x86-3) edge [above] node
  15271. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15272. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15273. \end{tikzpicture}
  15274. \fi}
  15275. \end{tcolorbox}
  15276. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15277. \label{fig:Lfun-passes}
  15278. \end{figure}
  15279. \section{An Example Translation}
  15280. \label{sec:functions-example}
  15281. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15282. function in \LangFun{} to x86. The figure includes the results of
  15283. \code{explicate\_control} and \code{select\_instructions}.
  15284. \begin{figure}[hbtp]
  15285. \begin{tcolorbox}[colback=white]
  15286. \begin{tabular}{ll}
  15287. \begin{minipage}{0.4\textwidth}
  15288. % s3_2.rkt
  15289. {\if\edition\racketEd
  15290. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15291. (define (add [x : Integer]
  15292. [y : Integer])
  15293. : Integer
  15294. (+ x y))
  15295. (add 40 2)
  15296. \end{lstlisting}
  15297. \fi}
  15298. {\if\edition\pythonEd\pythonColor
  15299. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15300. def add(x:int, y:int) -> int:
  15301. return x + y
  15302. print(add(40, 2))
  15303. \end{lstlisting}
  15304. \fi}
  15305. $\Downarrow$
  15306. {\if\edition\racketEd
  15307. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15308. (define (add86 [x87 : Integer]
  15309. [y88 : Integer])
  15310. : Integer
  15311. add86start:
  15312. return (+ x87 y88);
  15313. )
  15314. (define (main) : Integer ()
  15315. mainstart:
  15316. tmp89 = (fun-ref add86 2);
  15317. (tail-call tmp89 40 2)
  15318. )
  15319. \end{lstlisting}
  15320. \fi}
  15321. {\if\edition\pythonEd\pythonColor
  15322. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15323. def add(x:int, y:int) -> int:
  15324. addstart:
  15325. return x + y
  15326. def main() -> int:
  15327. mainstart:
  15328. fun.0 = add
  15329. tmp.1 = fun.0(40, 2)
  15330. print(tmp.1)
  15331. return 0
  15332. \end{lstlisting}
  15333. \fi}
  15334. \end{minipage}
  15335. &
  15336. $\Rightarrow$
  15337. \begin{minipage}{0.5\textwidth}
  15338. {\if\edition\racketEd
  15339. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15340. (define (add86) : Integer
  15341. add86start:
  15342. movq %rdi, x87
  15343. movq %rsi, y88
  15344. movq x87, %rax
  15345. addq y88, %rax
  15346. jmp inc1389conclusion
  15347. )
  15348. (define (main) : Integer
  15349. mainstart:
  15350. leaq (fun-ref add86 2), tmp89
  15351. movq $40, %rdi
  15352. movq $2, %rsi
  15353. tail-jmp tmp89
  15354. )
  15355. \end{lstlisting}
  15356. \fi}
  15357. {\if\edition\pythonEd\pythonColor
  15358. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15359. def add() -> int:
  15360. addstart:
  15361. movq %rdi, x
  15362. movq %rsi, y
  15363. movq x, %rax
  15364. addq y, %rax
  15365. jmp addconclusion
  15366. def main() -> int:
  15367. mainstart:
  15368. leaq add, fun.0
  15369. movq $40, %rdi
  15370. movq $2, %rsi
  15371. callq *fun.0
  15372. movq %rax, tmp.1
  15373. movq tmp.1, %rdi
  15374. callq print_int
  15375. movq $0, %rax
  15376. jmp mainconclusion
  15377. \end{lstlisting}
  15378. \fi}
  15379. $\Downarrow$
  15380. \end{minipage}
  15381. \end{tabular}
  15382. \begin{tabular}{ll}
  15383. \begin{minipage}{0.3\textwidth}
  15384. {\if\edition\racketEd
  15385. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15386. .globl add86
  15387. .align 8
  15388. add86:
  15389. pushq %rbp
  15390. movq %rsp, %rbp
  15391. jmp add86start
  15392. add86start:
  15393. movq %rdi, %rax
  15394. addq %rsi, %rax
  15395. jmp add86conclusion
  15396. add86conclusion:
  15397. popq %rbp
  15398. retq
  15399. \end{lstlisting}
  15400. \fi}
  15401. {\if\edition\pythonEd\pythonColor
  15402. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15403. .align 8
  15404. add:
  15405. pushq %rbp
  15406. movq %rsp, %rbp
  15407. subq $0, %rsp
  15408. jmp addstart
  15409. addstart:
  15410. movq %rdi, %rdx
  15411. movq %rsi, %rcx
  15412. movq %rdx, %rax
  15413. addq %rcx, %rax
  15414. jmp addconclusion
  15415. addconclusion:
  15416. subq $0, %r15
  15417. addq $0, %rsp
  15418. popq %rbp
  15419. retq
  15420. \end{lstlisting}
  15421. \fi}
  15422. \end{minipage}
  15423. &
  15424. \begin{minipage}{0.5\textwidth}
  15425. {\if\edition\racketEd
  15426. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15427. .globl main
  15428. .align 8
  15429. main:
  15430. pushq %rbp
  15431. movq %rsp, %rbp
  15432. movq $16384, %rdi
  15433. movq $16384, %rsi
  15434. callq initialize
  15435. movq rootstack_begin(%rip), %r15
  15436. jmp mainstart
  15437. mainstart:
  15438. leaq add86(%rip), %rcx
  15439. movq $40, %rdi
  15440. movq $2, %rsi
  15441. movq %rcx, %rax
  15442. popq %rbp
  15443. jmp *%rax
  15444. mainconclusion:
  15445. popq %rbp
  15446. retq
  15447. \end{lstlisting}
  15448. \fi}
  15449. {\if\edition\pythonEd\pythonColor
  15450. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15451. .globl main
  15452. .align 8
  15453. main:
  15454. pushq %rbp
  15455. movq %rsp, %rbp
  15456. subq $0, %rsp
  15457. movq $65536, %rdi
  15458. movq $65536, %rsi
  15459. callq initialize
  15460. movq rootstack_begin(%rip), %r15
  15461. jmp mainstart
  15462. mainstart:
  15463. leaq add(%rip), %rcx
  15464. movq $40, %rdi
  15465. movq $2, %rsi
  15466. callq *%rcx
  15467. movq %rax, %rcx
  15468. movq %rcx, %rdi
  15469. callq print_int
  15470. movq $0, %rax
  15471. jmp mainconclusion
  15472. mainconclusion:
  15473. subq $0, %r15
  15474. addq $0, %rsp
  15475. popq %rbp
  15476. retq
  15477. \end{lstlisting}
  15478. \fi}
  15479. \end{minipage}
  15480. \end{tabular}
  15481. \end{tcolorbox}
  15482. \caption{Example compilation of a simple function to x86.}
  15483. \label{fig:add-fun}
  15484. \end{figure}
  15485. % Challenge idea: inlining! (simple version)
  15486. % Further Reading
  15487. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15488. \chapter{Lexically Scoped Functions}
  15489. \label{ch:Llambda}
  15490. \setcounter{footnote}{0}
  15491. This chapter studies lexically scoped functions. Lexical
  15492. scoping\index{subject}{lexical scoping} means that a function's body
  15493. may refer to variables whose binding site is outside of the function,
  15494. in an enclosing scope.
  15495. %
  15496. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15497. in \LangLam{}, which extends \LangFun{} with the
  15498. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15499. functions. The body of the \key{lambda} refers to three variables:
  15500. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15501. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15502. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15503. function \code{f}}, and \code{x} is a parameter of function
  15504. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15505. result value. The main expression of the program includes two calls to
  15506. \code{f} with different arguments for \code{x}: first \code{5} and
  15507. then \code{3}. The functions returned from \code{f} are bound to
  15508. variables \code{g} and \code{h}. Even though these two functions were
  15509. created by the same \code{lambda}, they are really different functions
  15510. because they use different values for \code{x}. Applying \code{g} to
  15511. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15512. produces \code{22}, so the result of the program is \code{42}.
  15513. \begin{figure}[btp]
  15514. \begin{tcolorbox}[colback=white]
  15515. {\if\edition\racketEd
  15516. % lambda_test_21.rkt
  15517. \begin{lstlisting}
  15518. (define (f [x : Integer]) : (Integer -> Integer)
  15519. (let ([y 4])
  15520. (lambda: ([z : Integer]) : Integer
  15521. (+ x (+ y z)))))
  15522. (let ([g (f 5)])
  15523. (let ([h (f 3)])
  15524. (+ (g 11) (h 15))))
  15525. \end{lstlisting}
  15526. \fi}
  15527. {\if\edition\pythonEd\pythonColor
  15528. \begin{lstlisting}
  15529. def f(x : int) -> Callable[[int], int]:
  15530. y = 4
  15531. return lambda z: x + y + z
  15532. g = f(5)
  15533. h = f(3)
  15534. print(g(11) + h(15))
  15535. \end{lstlisting}
  15536. \fi}
  15537. \end{tcolorbox}
  15538. \caption{Example of a lexically scoped function.}
  15539. \label{fig:lexical-scoping}
  15540. \end{figure}
  15541. The approach that we take for implementing lexically scoped functions
  15542. is to compile them into top-level function definitions, translating
  15543. from \LangLam{} into \LangFun{}. However, the compiler must give
  15544. special treatment to variable occurrences such as \code{x} and
  15545. \code{y} in the body of the \code{lambda} shown in
  15546. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15547. may not refer to variables defined outside of it. To identify such
  15548. variable occurrences, we review the standard notion of free variable.
  15549. \begin{definition}\normalfont
  15550. A variable is \emph{free in expression} $e$ if the variable occurs
  15551. inside $e$ but does not have an enclosing definition that is also in
  15552. $e$.\index{subject}{free variable}
  15553. \end{definition}
  15554. For example, in the expression
  15555. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15556. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15557. only \code{x} and \code{y} are free in the following expression,
  15558. because \code{z} is defined by the \code{lambda}
  15559. {\if\edition\racketEd
  15560. \begin{lstlisting}
  15561. (lambda: ([z : Integer]) : Integer
  15562. (+ x (+ y z)))
  15563. \end{lstlisting}
  15564. \fi}
  15565. {\if\edition\pythonEd\pythonColor
  15566. \begin{lstlisting}
  15567. lambda z: x + y + z
  15568. \end{lstlisting}
  15569. \fi}
  15570. %
  15571. \noindent Thus the free variables of a \code{lambda} are the ones that
  15572. need special treatment. We need to transport at runtime the values
  15573. of those variables from the point where the \code{lambda} was created
  15574. to the point where the \code{lambda} is applied. An efficient solution
  15575. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15576. values of the free variables together with a function pointer into a
  15577. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15578. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15579. closure}
  15580. %
  15581. By design, we have all the ingredients to make closures:
  15582. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15583. function pointers. The function pointer resides at index $0$, and the
  15584. values for the free variables fill in the rest of the tuple.
  15585. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15586. to see how closures work. It is a three-step dance. The program calls
  15587. function \code{f}, which creates a closure for the \code{lambda}. The
  15588. closure is a tuple whose first element is a pointer to the top-level
  15589. function that we will generate for the \code{lambda}; the second
  15590. element is the value of \code{x}, which is \code{5}; and the third
  15591. element is \code{4}, the value of \code{y}. The closure does not
  15592. contain an element for \code{z} because \code{z} is not a free
  15593. variable of the \code{lambda}. Creating the closure is step 1 of the
  15594. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15595. shown in figure~\ref{fig:closures}.
  15596. %
  15597. The second call to \code{f} creates another closure, this time with
  15598. \code{3} in the second slot (for \code{x}). This closure is also
  15599. returned from \code{f} but bound to \code{h}, which is also shown in
  15600. figure~\ref{fig:closures}.
  15601. \begin{figure}[tbp]
  15602. \centering
  15603. \begin{minipage}{0.65\textwidth}
  15604. \begin{tcolorbox}[colback=white]
  15605. \includegraphics[width=\textwidth]{figs/closures}
  15606. \end{tcolorbox}
  15607. \end{minipage}
  15608. \caption{Flat closure representations for the two functions
  15609. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15610. \label{fig:closures}
  15611. \end{figure}
  15612. Continuing with the example, consider the application of \code{g} to
  15613. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15614. closure, we obtain the function pointer from the first element of the
  15615. closure and call it, passing in the closure itself and then the
  15616. regular arguments, in this case \code{11}. This technique for applying
  15617. a closure is step 2 of the dance.
  15618. %
  15619. But doesn't this \code{lambda} take only one argument, for parameter
  15620. \code{z}? The third and final step of the dance is generating a
  15621. top-level function for a \code{lambda}. We add an additional
  15622. parameter for the closure and insert an initialization at the beginning
  15623. of the function for each free variable, to bind those variables to the
  15624. appropriate elements from the closure parameter.
  15625. %
  15626. This three-step dance is known as \emph{closure
  15627. conversion}\index{subject}{closure conversion}. We discuss the
  15628. details of closure conversion in section~\ref{sec:closure-conversion}
  15629. and show the code generated from the example in
  15630. section~\ref{sec:example-lambda}. First, we define the syntax and
  15631. semantics of \LangLam{} in section~\ref{sec:r5}.
  15632. \section{The \LangLam{} Language}
  15633. \label{sec:r5}
  15634. The definitions of the concrete syntax and abstract syntax for
  15635. \LangLam{}, a language with anonymous functions and lexical scoping,
  15636. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15637. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15638. for \LangFun{}, which already has syntax for function application.
  15639. %
  15640. \python{The syntax also includes an assignment statement that includes
  15641. a type annotation for the variable on the left-hand side, which
  15642. facilitates the type checking of \code{lambda} expressions that we
  15643. discuss later in this section.}
  15644. %
  15645. \racket{The \code{procedure-arity} operation returns the number of parameters
  15646. of a given function, an operation that we need for the translation
  15647. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15648. %
  15649. \python{The \code{arity} operation returns the number of parameters of
  15650. a given function, an operation that we need for the translation
  15651. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15652. The \code{arity} operation is not in Python, but the same functionality
  15653. is available in a more complex form. We include \code{arity} in the
  15654. \LangLam{} source language to enable testing.}
  15655. \newcommand{\LlambdaGrammarRacket}{
  15656. \begin{array}{lcl}
  15657. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15658. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15659. \end{array}
  15660. }
  15661. \newcommand{\LlambdaASTRacket}{
  15662. \begin{array}{lcl}
  15663. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15664. \itm{op} &::=& \code{procedure-arity}
  15665. \end{array}
  15666. }
  15667. \newcommand{\LlambdaGrammarPython}{
  15668. \begin{array}{lcl}
  15669. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15670. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15671. \end{array}
  15672. }
  15673. \newcommand{\LlambdaASTPython}{
  15674. \begin{array}{lcl}
  15675. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15676. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15677. \end{array}
  15678. }
  15679. % include AnnAssign in ASTPython
  15680. \begin{figure}[tp]
  15681. \centering
  15682. \begin{tcolorbox}[colback=white]
  15683. \small
  15684. {\if\edition\racketEd
  15685. \[
  15686. \begin{array}{l}
  15687. \gray{\LintGrammarRacket{}} \\ \hline
  15688. \gray{\LvarGrammarRacket{}} \\ \hline
  15689. \gray{\LifGrammarRacket{}} \\ \hline
  15690. \gray{\LwhileGrammarRacket} \\ \hline
  15691. \gray{\LtupGrammarRacket} \\ \hline
  15692. \gray{\LfunGrammarRacket} \\ \hline
  15693. \LlambdaGrammarRacket \\
  15694. \begin{array}{lcl}
  15695. \LangLamM{} &::=& \Def\ldots \; \Exp
  15696. \end{array}
  15697. \end{array}
  15698. \]
  15699. \fi}
  15700. {\if\edition\pythonEd\pythonColor
  15701. \[
  15702. \begin{array}{l}
  15703. \gray{\LintGrammarPython{}} \\ \hline
  15704. \gray{\LvarGrammarPython{}} \\ \hline
  15705. \gray{\LifGrammarPython{}} \\ \hline
  15706. \gray{\LwhileGrammarPython} \\ \hline
  15707. \gray{\LtupGrammarPython} \\ \hline
  15708. \gray{\LfunGrammarPython} \\ \hline
  15709. \LlambdaGrammarPython \\
  15710. \begin{array}{lcl}
  15711. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15712. \end{array}
  15713. \end{array}
  15714. \]
  15715. \fi}
  15716. \end{tcolorbox}
  15717. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15718. with \key{lambda}.}
  15719. \label{fig:Llam-concrete-syntax}
  15720. \index{subject}{Llambda@\LangLam{} concrete syntax}
  15721. \end{figure}
  15722. \begin{figure}[tp]
  15723. \centering
  15724. \begin{tcolorbox}[colback=white]
  15725. \small
  15726. {\if\edition\racketEd
  15727. \[\arraycolsep=3pt
  15728. \begin{array}{l}
  15729. \gray{\LintOpAST} \\ \hline
  15730. \gray{\LvarASTRacket{}} \\ \hline
  15731. \gray{\LifASTRacket{}} \\ \hline
  15732. \gray{\LwhileASTRacket{}} \\ \hline
  15733. \gray{\LtupASTRacket{}} \\ \hline
  15734. \gray{\LfunASTRacket} \\ \hline
  15735. \LlambdaASTRacket \\
  15736. \begin{array}{lcl}
  15737. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15738. \end{array}
  15739. \end{array}
  15740. \]
  15741. \fi}
  15742. {\if\edition\pythonEd\pythonColor
  15743. \[
  15744. \begin{array}{l}
  15745. \gray{\LintASTPython} \\ \hline
  15746. \gray{\LvarASTPython{}} \\ \hline
  15747. \gray{\LifASTPython{}} \\ \hline
  15748. \gray{\LwhileASTPython{}} \\ \hline
  15749. \gray{\LtupASTPython{}} \\ \hline
  15750. \gray{\LfunASTPython} \\ \hline
  15751. \LlambdaASTPython \\
  15752. \begin{array}{lcl}
  15753. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15754. \end{array}
  15755. \end{array}
  15756. \]
  15757. \fi}
  15758. \end{tcolorbox}
  15759. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15760. \label{fig:Llam-syntax}
  15761. \index{subject}{Llambda@\LangLam{} abstract syntax}
  15762. \end{figure}
  15763. Figure~\ref{fig:interp-Llambda} shows the definitional
  15764. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15765. \key{Lambda} saves the current environment inside the returned
  15766. function value. Recall that during function application, the
  15767. environment stored in the function value, extended with the mapping of
  15768. parameters to argument values, is used to interpret the body of the
  15769. function.
  15770. \begin{figure}[tbp]
  15771. \begin{tcolorbox}[colback=white]
  15772. {\if\edition\racketEd
  15773. \begin{lstlisting}
  15774. (define interp-Llambda-class
  15775. (class interp-Lfun-class
  15776. (super-new)
  15777. (define/override (interp-op op)
  15778. (match op
  15779. ['procedure-arity
  15780. (lambda (v)
  15781. (match v
  15782. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15783. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15784. [else (super interp-op op)]))
  15785. (define/override ((interp-exp env) e)
  15786. (define recur (interp-exp env))
  15787. (match e
  15788. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15789. `(function ,xs ,body ,env)]
  15790. [else ((super interp-exp env) e)]))
  15791. ))
  15792. (define (interp-Llambda p)
  15793. (send (new interp-Llambda-class) interp-program p))
  15794. \end{lstlisting}
  15795. \fi}
  15796. {\if\edition\pythonEd\pythonColor
  15797. \begin{lstlisting}
  15798. class InterpLlambda(InterpLfun):
  15799. def arity(self, v):
  15800. match v:
  15801. case Function(name, params, body, env):
  15802. return len(params)
  15803. case _:
  15804. raise Exception('Llambda arity unexpected ' + repr(v))
  15805. def interp_exp(self, e, env):
  15806. match e:
  15807. case Call(Name('arity'), [fun]):
  15808. f = self.interp_exp(fun, env)
  15809. return self.arity(f)
  15810. case Lambda(params, body):
  15811. return Function('lambda', params, [Return(body)], env)
  15812. case _:
  15813. return super().interp_exp(e, env)
  15814. def interp_stmt(self, s, env, cont):
  15815. match s:
  15816. case AnnAssign(lhs, typ, value, simple):
  15817. env[lhs.id] = self.interp_exp(value, env)
  15818. return self.interp_stmts(cont, env)
  15819. case Pass():
  15820. return self.interp_stmts(cont, env)
  15821. case _:
  15822. return super().interp_stmt(s, env, cont)
  15823. \end{lstlisting}
  15824. \fi}
  15825. \end{tcolorbox}
  15826. \caption{Interpreter for \LangLam{}.}
  15827. \label{fig:interp-Llambda}
  15828. \end{figure}
  15829. {\if\edition\racketEd
  15830. %
  15831. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15832. \key{lambda} form. The body of the \key{lambda} is checked in an
  15833. environment that includes the current environment (because it is
  15834. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15835. require the body's type to match the declared return type.
  15836. %
  15837. \fi}
  15838. {\if\edition\pythonEd\pythonColor
  15839. %
  15840. Figures~\ref{fig:type-check-Llambda} and
  15841. \ref{fig:type-check-Llambda-part2} define the type checker for
  15842. \LangLam{}, which is more complex than one might expect. The reason
  15843. for the added complexity is that the syntax of \key{lambda} does not
  15844. include type annotations for the parameters or return type. Instead
  15845. they must be inferred. There are many approaches to type inference
  15846. from which to choose, of varying degrees of complexity. We choose one
  15847. of the simpler approaches, bidirectional type
  15848. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15849. book is compilation, not type inference.
  15850. The main idea of bidirectional type inference is to add an auxiliary
  15851. function, here named \code{check\_exp}, that takes an expected type
  15852. and checks whether the given expression is of that type. Thus, in
  15853. \code{check\_exp}, type information flows in a top-down manner with
  15854. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15855. function, where type information flows in a primarily bottom-up
  15856. manner.
  15857. %
  15858. The idea then is to use \code{check\_exp} in all the places where we
  15859. already know what the type of an expression should be, such as in the
  15860. \code{return} statement of a top-level function definition or on the
  15861. right-hand side of an annotated assignment statement.
  15862. With regard to \code{lambda}, it is straightforward to check a
  15863. \code{lambda} inside \code{check\_exp} because the expected type
  15864. provides the parameter types and the return type. On the other hand,
  15865. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15866. that we do not allow \code{lambda} in contexts in which we don't already
  15867. know its type. This restriction does not incur a loss of
  15868. expressiveness for \LangLam{} because it is straightforward to modify
  15869. a program to sidestep the restriction, for example, by using an
  15870. annotated assignment statement to assign the \code{lambda} to a
  15871. temporary variable.
  15872. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15873. checker records their type in a \code{has\_type} field. This type
  15874. information is used further on in this chapter.
  15875. %
  15876. \fi}
  15877. \begin{figure}[tbp]
  15878. \begin{tcolorbox}[colback=white]
  15879. {\if\edition\racketEd
  15880. \begin{lstlisting}
  15881. (define (type-check-Llambda env)
  15882. (lambda (e)
  15883. (match e
  15884. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15885. (define-values (new-body bodyT)
  15886. ((type-check-exp (append (map cons xs Ts) env)) body))
  15887. (define ty `(,@Ts -> ,rT))
  15888. (cond
  15889. [(equal? rT bodyT)
  15890. (values (HasType (Lambda params rT new-body) ty) ty)]
  15891. [else
  15892. (error "mismatch in return type" bodyT rT)])]
  15893. ...
  15894. )))
  15895. \end{lstlisting}
  15896. \fi}
  15897. {\if\edition\pythonEd\pythonColor
  15898. \begin{lstlisting}
  15899. class TypeCheckLlambda(TypeCheckLfun):
  15900. def type_check_exp(self, e, env):
  15901. match e:
  15902. case Name(id):
  15903. e.has_type = env[id]
  15904. return env[id]
  15905. case Lambda(params, body):
  15906. raise Exception('cannot synthesize a type for a lambda')
  15907. case Call(Name('arity'), [func]):
  15908. func_t = self.type_check_exp(func, env)
  15909. match func_t:
  15910. case FunctionType(params_t, return_t):
  15911. return IntType()
  15912. case _:
  15913. raise Exception('in arity, unexpected ' + repr(func_t))
  15914. case _:
  15915. return super().type_check_exp(e, env)
  15916. def check_exp(self, e, ty, env):
  15917. match e:
  15918. case Lambda(params, body):
  15919. e.has_type = ty
  15920. match ty:
  15921. case FunctionType(params_t, return_t):
  15922. new_env = env.copy().update(zip(params, params_t))
  15923. self.check_exp(body, return_t, new_env)
  15924. case _:
  15925. raise Exception('lambda does not have type ' + str(ty))
  15926. case Call(func, args):
  15927. func_t = self.type_check_exp(func, env)
  15928. match func_t:
  15929. case FunctionType(params_t, return_t):
  15930. for (arg, param_t) in zip(args, params_t):
  15931. self.check_exp(arg, param_t, env)
  15932. self.check_type_equal(return_t, ty, e)
  15933. case _:
  15934. raise Exception('type_check_exp: in call, unexpected ' + \
  15935. repr(func_t))
  15936. case _:
  15937. t = self.type_check_exp(e, env)
  15938. self.check_type_equal(t, ty, e)
  15939. \end{lstlisting}
  15940. \fi}
  15941. \end{tcolorbox}
  15942. \caption{Type checking \LangLam{}\python{, part 1}.}
  15943. \label{fig:type-check-Llambda}
  15944. \end{figure}
  15945. {\if\edition\pythonEd\pythonColor
  15946. \begin{figure}[tbp]
  15947. \begin{tcolorbox}[colback=white]
  15948. \begin{lstlisting}
  15949. def check_stmts(self, ss, return_ty, env):
  15950. if len(ss) == 0:
  15951. return
  15952. match ss[0]:
  15953. case FunctionDef(name, params, body, dl, returns, comment):
  15954. new_env = env.copy().update(params)
  15955. rt = self.check_stmts(body, returns, new_env)
  15956. self.check_stmts(ss[1:], return_ty, env)
  15957. case Return(value):
  15958. self.check_exp(value, return_ty, env)
  15959. case Assign([Name(id)], value):
  15960. if id in env:
  15961. self.check_exp(value, env[id], env)
  15962. else:
  15963. env[id] = self.type_check_exp(value, env)
  15964. self.check_stmts(ss[1:], return_ty, env)
  15965. case Assign([Subscript(tup, Constant(index), Store())], value):
  15966. tup_t = self.type_check_exp(tup, env)
  15967. match tup_t:
  15968. case TupleType(ts):
  15969. self.check_exp(value, ts[index], env)
  15970. case _:
  15971. raise Exception('expected a tuple, not ' + repr(tup_t))
  15972. self.check_stmts(ss[1:], return_ty, env)
  15973. case AnnAssign(Name(id), ty_annot, value, simple):
  15974. ss[0].annotation = ty_annot
  15975. if id in env:
  15976. self.check_type_equal(env[id], ty_annot)
  15977. else:
  15978. env[id] = ty_annot
  15979. self.check_exp(value, ty_annot, env)
  15980. self.check_stmts(ss[1:], return_ty, env)
  15981. case _:
  15982. self.type_check_stmts(ss, env)
  15983. def type_check(self, p):
  15984. match p:
  15985. case Module(body):
  15986. env = {}
  15987. for s in body:
  15988. match s:
  15989. case FunctionDef(name, params, bod, dl, returns, comment):
  15990. params_t = [t for (x,t) in params]
  15991. env[name] = FunctionType(params_t, returns)
  15992. self.check_stmts(body, int, env)
  15993. \end{lstlisting}
  15994. \end{tcolorbox}
  15995. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15996. \label{fig:type-check-Llambda-part2}
  15997. \end{figure}
  15998. \fi}
  15999. \clearpage
  16000. \section{Assignment and Lexically Scoped Functions}
  16001. \label{sec:assignment-scoping}
  16002. The combination of lexically scoped functions and assignment to
  16003. variables raises a challenge with the flat-closure approach to
  16004. implementing lexically scoped functions. Consider the following
  16005. example in which function \code{f} has a free variable \code{x} that
  16006. is changed after \code{f} is created but before the call to \code{f}.
  16007. % loop_test_11.rkt
  16008. {\if\edition\racketEd
  16009. \begin{lstlisting}
  16010. (let ([x 0])
  16011. (let ([y 0])
  16012. (let ([z 20])
  16013. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16014. (begin
  16015. (set! x 10)
  16016. (set! y 12)
  16017. (f y))))))
  16018. \end{lstlisting}
  16019. \fi}
  16020. {\if\edition\pythonEd\pythonColor
  16021. % box_free_assign.py
  16022. \begin{lstlisting}
  16023. def g(z : int) -> int:
  16024. x = 0
  16025. y = 0
  16026. f : Callable[[int],int] = lambda a: a + x + z
  16027. x = 10
  16028. y = 12
  16029. return f(y)
  16030. print(g(20))
  16031. \end{lstlisting}
  16032. \fi} The correct output for this example is \code{42} because the call
  16033. to \code{f} is required to use the current value of \code{x} (which is
  16034. \code{10}). Unfortunately, the closure conversion pass
  16035. (section~\ref{sec:closure-conversion}) generates code for the
  16036. \code{lambda} that copies the old value of \code{x} into a
  16037. closure. Thus, if we naively applied closure conversion, the output of
  16038. this program would be \code{32}.
  16039. A first attempt at solving this problem would be to save a pointer to
  16040. \code{x} in the closure and change the occurrences of \code{x} inside
  16041. the lambda to dereference the pointer. Of course, this would require
  16042. assigning \code{x} to the stack and not to a register. However, the
  16043. problem goes a bit deeper.
  16044. Consider the following example that returns a function that refers to
  16045. a local variable of the enclosing function:
  16046. \begin{center}
  16047. \begin{minipage}{\textwidth}
  16048. {\if\edition\racketEd
  16049. \begin{lstlisting}
  16050. (define (f) : ( -> Integer)
  16051. (let ([x 0])
  16052. (let ([g (lambda: () : Integer x)])
  16053. (begin
  16054. (set! x 42)
  16055. g))))
  16056. ((f))
  16057. \end{lstlisting}
  16058. \fi}
  16059. {\if\edition\pythonEd\pythonColor
  16060. % counter.py
  16061. \begin{lstlisting}
  16062. def f():
  16063. x = 0
  16064. g = lambda: x
  16065. x = 42
  16066. return g
  16067. print(f()())
  16068. \end{lstlisting}
  16069. \fi}
  16070. \end{minipage}
  16071. \end{center}
  16072. In this example, the lifetime of \code{x} extends beyond the lifetime
  16073. of the call to \code{f}. Thus, if we were to store \code{x} on the
  16074. stack frame for the call to \code{f}, it would be gone by the time we
  16075. called \code{g}, leaving us with dangling pointers for
  16076. \code{x}. This example demonstrates that when a variable occurs free
  16077. inside a function, its lifetime becomes indefinite. Thus, the value of
  16078. the variable needs to live on the heap. The verb
  16079. \emph{box}\index{subject}{box} is often used for allocating a single
  16080. value on the heap, producing a pointer, and
  16081. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  16082. %
  16083. We introduce a new pass named \code{convert\_assignments} to address
  16084. this challenge.
  16085. %
  16086. \python{But before diving into that, we have one more
  16087. problem to discuss.}
  16088. {\if\edition\pythonEd\pythonColor
  16089. \section{Uniquify Variables}
  16090. \label{sec:uniquify-lambda}
  16091. With the addition of \code{lambda} we have a complication to deal
  16092. with: name shadowing. Consider the following program with a function
  16093. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  16094. \code{lambda} expressions. The first \code{lambda} has a parameter
  16095. that is also named \code{x}.
  16096. \begin{lstlisting}
  16097. def f(x:int, y:int) -> Callable[[int], int]:
  16098. g : Callable[[int],int] = (lambda x: x + y)
  16099. h : Callable[[int],int] = (lambda y: x + y)
  16100. x = input_int()
  16101. return g
  16102. print(f(0, 10)(32))
  16103. \end{lstlisting}
  16104. Many of our compiler passes rely on being able to connect variable
  16105. uses with their definitions using just the name of the
  16106. variable. However, in the example above, the name of the variable does
  16107. not uniquely determine its definition. To solve this problem we
  16108. recommend implementing a pass named \code{uniquify} that renames every
  16109. variable in the program to make sure that they are all unique.
  16110. The following shows the result of \code{uniquify} for the example
  16111. above. The \code{x} parameter of function \code{f} is renamed to
  16112. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  16113. renamed to \code{x\_4}.
  16114. \begin{lstlisting}
  16115. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  16116. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  16117. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  16118. x_0 = input_int()
  16119. return g_2
  16120. def main() -> int :
  16121. print(f(0, 10)(32))
  16122. return 0
  16123. \end{lstlisting}
  16124. \fi} % pythonEd
  16125. %% \section{Reveal Functions}
  16126. %% \label{sec:reveal-functions-r5}
  16127. %% \racket{To support the \code{procedure-arity} operator we need to
  16128. %% communicate the arity of a function to the point of closure
  16129. %% creation.}
  16130. %% %
  16131. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  16132. %% function at runtime. Thus, we need to communicate the arity of a
  16133. %% function to the point of closure creation.}
  16134. %% %
  16135. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  16136. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  16137. %% \[
  16138. %% \begin{array}{lcl}
  16139. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  16140. %% \end{array}
  16141. %% \]
  16142. \section{Assignment Conversion}
  16143. \label{sec:convert-assignments}
  16144. The purpose of the \code{convert\_assignments} pass is to address the
  16145. challenge regarding the interaction between variable assignments and
  16146. closure conversion. First we identify which variables need to be
  16147. boxed, and then we transform the program to box those variables. In
  16148. general, boxing introduces runtime overhead that we would like to
  16149. avoid, so we should box as few variables as possible. We recommend
  16150. boxing the variables in the intersection of the following two sets of
  16151. variables:
  16152. \begin{enumerate}
  16153. \item The variables that are free in a \code{lambda}.
  16154. \item The variables that appear on the left-hand side of an
  16155. assignment.
  16156. \end{enumerate}
  16157. The first condition is a must but the second condition is
  16158. conservative. It is possible to develop a more liberal condition using
  16159. static program analysis.
  16160. Consider again the first example from
  16161. section~\ref{sec:assignment-scoping}:
  16162. %
  16163. {\if\edition\racketEd
  16164. \begin{lstlisting}
  16165. (let ([x 0])
  16166. (let ([y 0])
  16167. (let ([z 20])
  16168. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16169. (begin
  16170. (set! x 10)
  16171. (set! y 12)
  16172. (f y))))))
  16173. \end{lstlisting}
  16174. \fi}
  16175. {\if\edition\pythonEd\pythonColor
  16176. \begin{lstlisting}
  16177. def g(z : int) -> int:
  16178. x = 0
  16179. y = 0
  16180. f : Callable[[int],int] = lambda a: a + x + z
  16181. x = 10
  16182. y = 12
  16183. return f(y)
  16184. print(g(20))
  16185. \end{lstlisting}
  16186. \fi}
  16187. %
  16188. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16189. side of assignments. The variables \code{x} and \code{z} occur free
  16190. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16191. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16192. three transformations: initialize \code{x} with a tuple whose element
  16193. is uninitialized, replace reads from \code{x} with tuple reads, and
  16194. replace each assignment to \code{x} with a tuple write. The output of
  16195. \code{convert\_assignments} for this example is as follows:
  16196. %
  16197. {\if\edition\racketEd
  16198. \begin{lstlisting}
  16199. (define (main) : Integer
  16200. (let ([x0 (vector 0)])
  16201. (let ([y1 0])
  16202. (let ([z2 20])
  16203. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16204. (+ a3 (+ (vector-ref x0 0) z2)))])
  16205. (begin
  16206. (vector-set! x0 0 10)
  16207. (set! y1 12)
  16208. (f4 y1)))))))
  16209. \end{lstlisting}
  16210. \fi}
  16211. %
  16212. {\if\edition\pythonEd\pythonColor
  16213. \begin{lstlisting}
  16214. def g(z : int)-> int:
  16215. x = (uninitialized(int),)
  16216. x[0] = 0
  16217. y = 0
  16218. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16219. x[0] = 10
  16220. y = 12
  16221. return f(y)
  16222. def main() -> int:
  16223. print(g(20))
  16224. return 0
  16225. \end{lstlisting}
  16226. \fi}
  16227. To compute the free variables of all the \code{lambda} expressions, we
  16228. recommend defining the following two auxiliary functions:
  16229. \begin{enumerate}
  16230. \item \code{free\_variables} computes the free variables of an expression, and
  16231. \item \code{free\_in\_lambda} collects all the variables that are
  16232. free in any of the \code{lambda} expressions, using
  16233. \code{free\_variables} in the case for each \code{lambda}.
  16234. \end{enumerate}
  16235. {\if\edition\racketEd
  16236. %
  16237. To compute the variables that are assigned to, we recommend updating
  16238. the \code{collect-set!} function that we introduced in
  16239. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16240. as \code{Lambda}.
  16241. %
  16242. \fi}
  16243. {\if\edition\pythonEd\pythonColor
  16244. %
  16245. To compute the variables that are assigned to, we recommend defining
  16246. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16247. the set of variables that occur in the left-hand side of an assignment
  16248. statement and otherwise returns the empty set.
  16249. %
  16250. \fi}
  16251. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16252. free in a \code{lambda} and that are assigned to in the enclosing
  16253. function definition.
  16254. Next we discuss the \code{convert\_assignments} pass. In the case for
  16255. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16256. $\VAR{x}$ to a tuple read.
  16257. %
  16258. {\if\edition\racketEd
  16259. \begin{lstlisting}
  16260. (Var |$x$|)
  16261. |$\Rightarrow$|
  16262. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16263. \end{lstlisting}
  16264. \fi}
  16265. %
  16266. {\if\edition\pythonEd\pythonColor
  16267. \begin{lstlisting}
  16268. Name(|$x$|)
  16269. |$\Rightarrow$|
  16270. Subscript(Name(|$x$|), Constant(0), Load())
  16271. \end{lstlisting}
  16272. \fi}
  16273. %
  16274. \noindent In the case for assignment, recursively process the
  16275. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16276. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16277. as follows:
  16278. %
  16279. {\if\edition\racketEd
  16280. \begin{lstlisting}
  16281. (SetBang |$x$| |$\itm{rhs}$|)
  16282. |$\Rightarrow$|
  16283. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16284. \end{lstlisting}
  16285. \fi}
  16286. {\if\edition\pythonEd\pythonColor
  16287. \begin{lstlisting}
  16288. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16289. |$\Rightarrow$|
  16290. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16291. \end{lstlisting}
  16292. \fi}
  16293. %
  16294. {\if\edition\racketEd
  16295. The case for \code{Lambda} is nontrivial, but it is similar to the
  16296. case for function definitions, which we discuss next.
  16297. \fi}
  16298. %
  16299. To translate a function definition, we first compute $\mathit{AF}$,
  16300. the intersection of the variables that are free in a \code{lambda} and
  16301. that are assigned to. We then apply assignment conversion to the body
  16302. of the function definition. Finally, we box the parameters of this
  16303. function definition that are in $\mathit{AF}$. For example,
  16304. the parameter \code{x} of the following function \code{g}
  16305. needs to be boxed:
  16306. {\if\edition\racketEd
  16307. \begin{lstlisting}
  16308. (define (g [x : Integer]) : Integer
  16309. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16310. (begin
  16311. (set! x 10)
  16312. (f 32))))
  16313. \end{lstlisting}
  16314. \fi}
  16315. %
  16316. {\if\edition\pythonEd\pythonColor
  16317. \begin{lstlisting}
  16318. def g(x : int) -> int:
  16319. f : Callable[[int],int] = lambda a: a + x
  16320. x = 10
  16321. return f(32)
  16322. \end{lstlisting}
  16323. \fi}
  16324. %
  16325. \noindent We box parameter \code{x} by creating a local variable named
  16326. \code{x} that is initialized to a tuple whose contents is the value of
  16327. the parameter, which is renamed to \code{x\_0}.
  16328. %
  16329. {\if\edition\racketEd
  16330. \begin{lstlisting}
  16331. (define (g [x_0 : Integer]) : Integer
  16332. (let ([x (vector x_0)])
  16333. (let ([f (lambda: ([a : Integer]) : Integer
  16334. (+ a (vector-ref x 0)))])
  16335. (begin
  16336. (vector-set! x 0 10)
  16337. (f 32)))))
  16338. \end{lstlisting}
  16339. \fi}
  16340. %
  16341. {\if\edition\pythonEd\pythonColor
  16342. \begin{lstlisting}
  16343. def g(x_0 : int)-> int:
  16344. x = (x_0,)
  16345. f : Callable[[int], int] = (lambda a: a + x[0])
  16346. x[0] = 10
  16347. return f(32)
  16348. \end{lstlisting}
  16349. \fi}
  16350. \section{Closure Conversion}
  16351. \label{sec:closure-conversion}
  16352. \index{subject}{closure conversion}
  16353. The compiling of lexically scoped functions into top-level function
  16354. definitions and flat closures is accomplished in the pass
  16355. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16356. and before \code{limit\_functions}.
  16357. As usual, we implement the pass as a recursive function over the
  16358. AST. The interesting cases are for \key{lambda} and function
  16359. application. We transform a \key{lambda} expression into an expression
  16360. that creates a closure, that is, a tuple for which the first element
  16361. is a function pointer and the rest of the elements are the values of
  16362. the free variables of the \key{lambda}.
  16363. %
  16364. However, we use the \code{Closure} AST node instead of using a tuple
  16365. so that we can record the arity.
  16366. %
  16367. In the generated code that follows, \itm{fvs} is the list of free
  16368. variables of the lambda and \itm{name} is a unique symbol generated to
  16369. identify the lambda.
  16370. %
  16371. \racket{The \itm{arity} is the number of parameters (the length of
  16372. \itm{ps}).}
  16373. %
  16374. {\if\edition\racketEd
  16375. \begin{lstlisting}
  16376. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16377. |$\Rightarrow$|
  16378. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16379. \end{lstlisting}
  16380. \fi}
  16381. %
  16382. {\if\edition\pythonEd\pythonColor
  16383. \begin{lstlisting}
  16384. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16385. |$\Rightarrow$|
  16386. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16387. \end{lstlisting}
  16388. \fi}
  16389. %
  16390. In addition to transforming each \key{Lambda} AST node into a
  16391. tuple, we create a top-level function definition for each
  16392. \key{Lambda}, as shown next.\\
  16393. \begin{minipage}{0.8\textwidth}
  16394. {\if\edition\racketEd
  16395. \begin{lstlisting}
  16396. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16397. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16398. ...
  16399. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16400. |\itm{body'}|)...))
  16401. \end{lstlisting}
  16402. \fi}
  16403. {\if\edition\pythonEd\pythonColor
  16404. \begin{lstlisting}
  16405. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16406. |$\itm{fvs}_1$| = clos[1]
  16407. |$\ldots$|
  16408. |$\itm{fvs}_m$| = clos[|$m$|]
  16409. |\itm{body'}|
  16410. \end{lstlisting}
  16411. \fi}
  16412. \end{minipage}\\
  16413. %
  16414. The \code{clos} parameter refers to the closure. The type
  16415. \itm{closTy} is a tuple type for which the first element type is
  16416. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16417. rest of the element types are the types of the free variables in the
  16418. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16419. is nontrivial to give a type to the function in the closure's
  16420. type.\footnote{To give an accurate type to a closure, we would need to
  16421. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16422. %
  16423. \racket{Translate the type
  16424. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16425. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16426. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16427. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16428. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16429. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16430. %% The dummy type is considered to be equal to any other type during type
  16431. %% checking.
  16432. The free variables become local variables that are initialized with
  16433. their values in the closure.
  16434. Closure conversion turns every function into a tuple, so the type
  16435. annotations in the program must also be translated. We recommend
  16436. defining an auxiliary recursive function for this purpose. Function
  16437. types should be translated as follows:
  16438. %
  16439. {\if\edition\racketEd
  16440. \begin{lstlisting}
  16441. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16442. |$\Rightarrow$|
  16443. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16444. \end{lstlisting}
  16445. \fi}
  16446. {\if\edition\pythonEd\pythonColor
  16447. \begin{lstlisting}
  16448. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16449. |$\Rightarrow$|
  16450. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16451. \end{lstlisting}
  16452. \fi}
  16453. %
  16454. This type indicates that the first thing in the tuple is a
  16455. function. The first parameter of the function is a tuple (a closure)
  16456. and the rest of the parameters are the ones from the original
  16457. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16458. omits the types of the free variables because (1) those types are not
  16459. available in this context, and (2) we do not need them in the code that
  16460. is generated for function application. So this type describes only the
  16461. first component of the closure tuple. At runtime the tuple may have
  16462. more components, but we ignore them at this point.
  16463. We transform function application into code that retrieves the
  16464. function from the closure and then calls the function, passing the
  16465. closure as the first argument. We place $e'$ in a temporary variable
  16466. to avoid code duplication.
  16467. \begin{center}
  16468. \begin{minipage}{\textwidth}
  16469. {\if\edition\racketEd
  16470. \begin{lstlisting}
  16471. (Apply |$e$| |$\itm{es}$|)
  16472. |$\Rightarrow$|
  16473. (Let |$\itm{tmp}$| |$e'$|
  16474. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16475. \end{lstlisting}
  16476. \fi}
  16477. %
  16478. {\if\edition\pythonEd\pythonColor
  16479. \begin{lstlisting}
  16480. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16481. |$\Rightarrow$|
  16482. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16483. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16484. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16485. \end{lstlisting}
  16486. \fi}
  16487. \end{minipage}
  16488. \end{center}
  16489. There is also the question of what to do with references to top-level
  16490. function definitions. To maintain a uniform translation of function
  16491. application, we turn function references into closures.
  16492. \begin{tabular}{lll}
  16493. \begin{minipage}{0.2\textwidth}
  16494. {\if\edition\racketEd
  16495. \begin{lstlisting}
  16496. (FunRef |$f$| |$n$|)
  16497. \end{lstlisting}
  16498. \fi}
  16499. {\if\edition\pythonEd\pythonColor
  16500. \begin{lstlisting}
  16501. FunRef(|$f$|, |$n$|)
  16502. \end{lstlisting}
  16503. \fi}
  16504. \end{minipage}
  16505. &
  16506. $\Rightarrow\qquad$
  16507. &
  16508. \begin{minipage}{0.5\textwidth}
  16509. {\if\edition\racketEd
  16510. \begin{lstlisting}
  16511. (Closure |$n$| (list (FunRef |$f$| |$n$|)))
  16512. \end{lstlisting}
  16513. \fi}
  16514. {\if\edition\pythonEd\pythonColor
  16515. \begin{lstlisting}
  16516. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16517. \end{lstlisting}
  16518. \fi}
  16519. \end{minipage}
  16520. \end{tabular} \\
  16521. We no longer need the annotated assignment statement \code{AnnAssign}
  16522. to support the type checking of \code{lambda} expressions, so we
  16523. translate it to a regular \code{Assign} statement.
  16524. The top-level function definitions need to be updated to take an extra
  16525. closure parameter, but that parameter is ignored in the body of those
  16526. functions.
  16527. \subsection{An Example Translation}
  16528. \label{sec:example-lambda}
  16529. Figure~\ref{fig:lexical-functions-example} shows the result of
  16530. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16531. program demonstrating lexical scoping that we discussed at the
  16532. beginning of this chapter.
  16533. \begin{figure}[tbp]
  16534. \begin{tcolorbox}[colback=white]
  16535. \begin{minipage}{0.8\textwidth}
  16536. {\if\edition\racketEd
  16537. % tests/lambda_test_6.rkt
  16538. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16539. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16540. (let ([y8 4])
  16541. (lambda: ([z9 : Integer]) : Integer
  16542. (+ x7 (+ y8 z9)))))
  16543. (define (main) : Integer
  16544. (let ([g0 ((fun-ref f6 1) 5)])
  16545. (let ([h1 ((fun-ref f6 1) 3)])
  16546. (+ (g0 11) (h1 15)))))
  16547. \end{lstlisting}
  16548. $\Rightarrow$
  16549. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16550. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16551. (let ([y8 4])
  16552. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16553. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16554. (let ([x7 (vector-ref fvs3 1)])
  16555. (let ([y8 (vector-ref fvs3 2)])
  16556. (+ x7 (+ y8 z9)))))
  16557. (define (main) : Integer
  16558. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16559. ((vector-ref clos5 0) clos5 5))])
  16560. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16561. ((vector-ref clos6 0) clos6 3))])
  16562. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16563. \end{lstlisting}
  16564. \fi}
  16565. %
  16566. {\if\edition\pythonEd\pythonColor
  16567. % free_var.py
  16568. \begin{lstlisting}
  16569. def f(x: int) -> Callable[[int],int]:
  16570. y = 4
  16571. return lambda z: x + y + z
  16572. g = f(5)
  16573. h = f(3)
  16574. print(g(11) + h(15))
  16575. \end{lstlisting}
  16576. $\Rightarrow$
  16577. \begin{lstlisting}
  16578. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16579. x = fvs_1[1]
  16580. y = fvs_1[2]
  16581. return (x + y[0] + z)
  16582. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16583. y = (uninitialized(int),)
  16584. y[0] = 4
  16585. return closure{1}({lambda_0}, x, y)
  16586. def main() -> int:
  16587. g = (begin: clos_3 = closure{1}({f})
  16588. clos_3[0](clos_3, 5))
  16589. h = (begin: clos_4 = closure{1}({f})
  16590. clos_4[0](clos_4, 3))
  16591. print((begin: clos_5 = g
  16592. clos_5[0](clos_5, 11))
  16593. + (begin: clos_6 = h
  16594. clos_6[0](clos_6, 15)))
  16595. return 0
  16596. \end{lstlisting}
  16597. \fi}
  16598. \end{minipage}
  16599. \end{tcolorbox}
  16600. \caption{Example of closure conversion.}
  16601. \label{fig:lexical-functions-example}
  16602. \end{figure}
  16603. \begin{exercise}\normalfont\normalsize
  16604. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16605. Create five new programs that use \key{lambda} functions and make use of
  16606. lexical scoping. Test your compiler on these new programs and all
  16607. your previously created test programs.
  16608. \end{exercise}
  16609. \section{Expose Allocation}
  16610. \label{sec:expose-allocation-r5}
  16611. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code that
  16612. allocates and initializes a tuple, similar to the translation of the
  16613. tuple creation in section~\ref{sec:expose-allocation}. The main
  16614. difference is replacing the use of \ALLOC{\itm{len}}{\itm{type}} with
  16615. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}. The result type of
  16616. the translation of $\CLOSURE{\itm{arity}}{\Exp^{*}}$ should be a tuple
  16617. type, but only a single element tuple type. The types of the tuple
  16618. elements that correspond to the free variables of the closure should
  16619. not appear in the tuple type. The new AST class \code{UncheckedCast}
  16620. can be used to adjust the result type.
  16621. \section{Explicate Control and \LangCLam{}}
  16622. \label{sec:explicate-r5}
  16623. The output language of \code{explicate\_control} is \LangCLam{}; the
  16624. definition of its abstract syntax is shown in
  16625. figure~\ref{fig:Clam-syntax}.
  16626. %
  16627. \racket{The only differences with respect to \LangCFun{} are the
  16628. addition of the \code{AllocateClosure} form to the grammar for
  16629. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16630. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16631. similar to the handling of other expressions such as primitive
  16632. operators.}
  16633. %
  16634. \python{The differences with respect to \LangCFun{} are the
  16635. additions of \code{Uninitialized}, \code{AllocateClosure},
  16636. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16637. \code{explicate\_control} pass is similar to the handling of other
  16638. expressions such as primitive operators.}
  16639. \newcommand{\ClambdaASTRacket}{
  16640. \begin{array}{lcl}
  16641. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16642. \itm{op} &::= & \code{procedure-arity}
  16643. \end{array}
  16644. }
  16645. \newcommand{\ClambdaASTPython}{
  16646. \begin{array}{lcl}
  16647. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16648. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16649. &\MID& \ARITY{\Atm}
  16650. \MID \key{UncheckedCast}\LP\Exp,\Type\RP
  16651. \end{array}
  16652. }
  16653. \begin{figure}[tp]
  16654. \begin{tcolorbox}[colback=white]
  16655. \small
  16656. {\if\edition\racketEd
  16657. \[
  16658. \begin{array}{l}
  16659. \gray{\CvarASTRacket} \\ \hline
  16660. \gray{\CifASTRacket} \\ \hline
  16661. \gray{\CloopASTRacket} \\ \hline
  16662. \gray{\CtupASTRacket} \\ \hline
  16663. \gray{\CfunASTRacket} \\ \hline
  16664. \ClambdaASTRacket \\
  16665. \begin{array}{lcl}
  16666. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16667. \end{array}
  16668. \end{array}
  16669. \]
  16670. \fi}
  16671. {\if\edition\pythonEd\pythonColor
  16672. \[
  16673. \begin{array}{l}
  16674. \gray{\CifASTPython} \\ \hline
  16675. \gray{\CtupASTPython} \\ \hline
  16676. \gray{\CfunASTPython} \\ \hline
  16677. \ClambdaASTPython \\
  16678. \begin{array}{lcl}
  16679. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16680. \end{array}
  16681. \end{array}
  16682. \]
  16683. \fi}
  16684. \end{tcolorbox}
  16685. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16686. \label{fig:Clam-syntax}
  16687. \index{subject}{Clambda@\LangCLam{} abstract syntax}
  16688. \end{figure}
  16689. \section{Select Instructions}
  16690. \label{sec:select-instructions-Llambda}
  16691. \index{subject}{select instructions}
  16692. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16693. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16694. (section~\ref{sec:select-instructions-gc}). The only difference is
  16695. that you should place the \itm{arity} in the tag that is stored at
  16696. position $0$ of the tuple. Recall that in
  16697. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16698. was not used. We store the arity in the $5$ bits starting at position
  16699. $57$.
  16700. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16701. instructions that access the tag from position $0$ of the vector and
  16702. extract the $5$ bits starting at position $57$ from the tag.}
  16703. %
  16704. \python{Compile a call to the \code{arity} operator to a sequence of
  16705. instructions that access the tag from position $0$ of the tuple
  16706. (representing a closure) and extract the $5$ bits starting at position
  16707. $57$ from the tag.}
  16708. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16709. needed for the compilation of \LangLam{}.
  16710. \begin{figure}[bthp]
  16711. \begin{tcolorbox}[colback=white]
  16712. {\if\edition\racketEd
  16713. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16714. \node (Lfun) at (0,2) {\large \LangLam{}};
  16715. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16716. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16717. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16718. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16719. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16720. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16721. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16722. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16723. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16724. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16725. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16726. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16727. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16728. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16729. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16730. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16731. \path[->,bend left=15] (Lfun) edge [above] node
  16732. {\ttfamily\footnotesize shrink} (Lfun-2);
  16733. \path[->,bend left=15] (Lfun-2) edge [above] node
  16734. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16735. \path[->,bend left=15] (Lfun-3) edge [above] node
  16736. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16737. \path[->,bend left=15] (F1-0) edge [left] node
  16738. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16739. \path[->,bend left=15] (F1-1) edge [below] node
  16740. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16741. \path[->,bend right=15] (F1-2) edge [above] node
  16742. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16743. \path[->,bend right=15] (F1-3) edge [above] node
  16744. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16745. \path[->,bend left=15] (F1-4) edge [right] node
  16746. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16747. \path[->,bend right=15] (F1-5) edge [below] node
  16748. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16749. \path[->,bend left=15] (F1-6) edge [above] node
  16750. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16751. \path[->] (C3-2) edge [right] node
  16752. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16753. \path[->,bend right=15] (x86-2) edge [right] node
  16754. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16755. \path[->,bend right=15] (x86-2-1) edge [below] node
  16756. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16757. \path[->,bend right=15] (x86-2-2) edge [right] node
  16758. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16759. \path[->,bend left=15] (x86-3) edge [above] node
  16760. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16761. \path[->,bend left=15] (x86-4) edge [right] node
  16762. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16763. \end{tikzpicture}
  16764. \fi}
  16765. {\if\edition\pythonEd\pythonColor
  16766. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16767. \node (Lfun) at (0,2) {\large \LangLam{}};
  16768. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16769. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16770. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16771. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16772. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16773. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16774. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16775. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16776. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16777. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16778. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16779. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16780. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16781. \path[->,bend left=15] (Lfun) edge [above] node
  16782. {\ttfamily\footnotesize shrink} (Lfun-2);
  16783. \path[->,bend left=15] (Lfun-2) edge [above] node
  16784. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16785. \path[->,bend left=15] (Lfun-3) edge [above] node
  16786. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16787. \path[->,bend left=15] (F1-0) edge [left] node
  16788. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16789. \path[->,bend left=15] (F1-1) edge [below] node
  16790. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16791. \path[->,bend left=15] (F1-2) edge [below] node
  16792. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16793. \path[->,bend right=15] (F1-3) edge [above] node
  16794. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16795. \path[->,bend right=15] (F1-5) edge [right] node
  16796. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16797. \path[->,bend left=15] (F1-6) edge [right] node
  16798. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16799. \path[->,bend right=15] (C3-2) edge [right] node
  16800. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16801. \path[->,bend right=15] (x86-2) edge [below] node
  16802. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16803. \path[->,bend right=15] (x86-3) edge [below] node
  16804. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16805. \path[->,bend left=15] (x86-4) edge [above] node
  16806. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16807. \end{tikzpicture}
  16808. \fi}
  16809. \end{tcolorbox}
  16810. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16811. functions.}
  16812. \label{fig:Llambda-passes}
  16813. \end{figure}
  16814. \clearpage
  16815. \section{Challenge: Optimize Closures}
  16816. \label{sec:optimize-closures}
  16817. In this chapter we compile lexically scoped functions into a
  16818. relatively efficient representation: flat closures. However, even this
  16819. representation comes with some overhead. For example, consider the
  16820. following program with a function \code{tail\_sum} that does not have
  16821. any free variables and where all the uses of \code{tail\_sum} are in
  16822. applications in which we know that only \code{tail\_sum} is being applied
  16823. (and not any other functions):
  16824. \begin{center}
  16825. \begin{minipage}{0.95\textwidth}
  16826. {\if\edition\racketEd
  16827. \begin{lstlisting}
  16828. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16829. (if (eq? n 0)
  16830. s
  16831. (tail_sum (- n 1) (+ n s))))
  16832. (+ (tail_sum 3 0) 36)
  16833. \end{lstlisting}
  16834. \fi}
  16835. {\if\edition\pythonEd\pythonColor
  16836. \begin{lstlisting}
  16837. def tail_sum(n : int, s : int) -> int:
  16838. if n == 0:
  16839. return s
  16840. else:
  16841. return tail_sum(n - 1, n + s)
  16842. print(tail_sum(3, 0) + 36)
  16843. \end{lstlisting}
  16844. \fi}
  16845. \end{minipage}
  16846. \end{center}
  16847. As described in this chapter, we uniformly apply closure conversion to
  16848. all functions, obtaining the following output for this program:
  16849. \begin{center}
  16850. \begin{minipage}{0.95\textwidth}
  16851. {\if\edition\racketEd
  16852. \begin{lstlisting}
  16853. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16854. (if (eq? n2 0)
  16855. s3
  16856. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16857. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16858. (define (main) : Integer
  16859. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16860. ((vector-ref clos6 0) clos6 3 0)) 27))
  16861. \end{lstlisting}
  16862. \fi}
  16863. {\if\edition\pythonEd\pythonColor
  16864. \begin{lstlisting}
  16865. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16866. if n_0 == 0:
  16867. return s_1
  16868. else:
  16869. return (begin: clos_2 = (tail_sum,)
  16870. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16871. def main() -> int :
  16872. print((begin: clos_4 = (tail_sum,)
  16873. clos_4[0](clos_4, 3, 0)) + 36)
  16874. return 0
  16875. \end{lstlisting}
  16876. \fi}
  16877. \end{minipage}
  16878. \end{center}
  16879. If this program were compiled according to the previous chapter, there
  16880. would be no allocation and the calls to \code{tail\_sum} would be
  16881. direct calls. In contrast, the program presented here allocates memory
  16882. for each closure and the calls to \code{tail\_sum} are indirect. These
  16883. two differences incur considerable overhead in a program such as this,
  16884. in which the allocations and indirect calls occur inside a tight loop.
  16885. One might think that this problem is trivial to solve: can't we just
  16886. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16887. and compile them to direct calls instead of treating it like a call to
  16888. a closure? We would also drop the new \code{fvs} parameter of
  16889. \code{tail\_sum}.
  16890. %
  16891. However, this problem is not so trivial, because a global function may
  16892. \emph{escape} and become involved in applications that also involve
  16893. closures. Consider the following example in which the application
  16894. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16895. application because the \code{lambda} may flow into \code{f}, but the
  16896. \code{inc} function might also flow into \code{f}:
  16897. \begin{center}
  16898. \begin{minipage}{\textwidth}
  16899. % lambda_test_30.rkt
  16900. {\if\edition\racketEd
  16901. \begin{lstlisting}
  16902. (define (inc [x : Integer]) : Integer
  16903. (+ x 1))
  16904. (let ([y (read)])
  16905. (let ([f (if (eq? (read) 0)
  16906. inc
  16907. (lambda: ([x : Integer]) : Integer (- x y)))])
  16908. (f 41)))
  16909. \end{lstlisting}
  16910. \fi}
  16911. {\if\edition\pythonEd\pythonColor
  16912. \begin{lstlisting}
  16913. def add1(x : int) -> int:
  16914. return x + 1
  16915. y = input_int()
  16916. g : Callable[[int], int] = lambda x: x - y
  16917. f = add1 if input_int() == 0 else g
  16918. print(f(41))
  16919. \end{lstlisting}
  16920. \fi}
  16921. \end{minipage}
  16922. \end{center}
  16923. If a global function name is used in any way other than as the
  16924. operator in a direct call, then we say that the function
  16925. \emph{escapes}. If a global function does not escape, then we do not
  16926. need to perform closure conversion on the function.
  16927. \begin{exercise}\normalfont\normalsize
  16928. Implement an auxiliary function for detecting which global
  16929. functions escape. Using that function, implement an improved version
  16930. of closure conversion that does not apply closure conversion to
  16931. global functions that do not escape but instead compiles them as
  16932. regular functions. Create several new test cases that check whether
  16933. your compiler properly detects whether global functions escape or not.
  16934. \end{exercise}
  16935. So far we have reduced the overhead of calling global functions, but
  16936. it would also be nice to reduce the overhead of calling a
  16937. \code{lambda} when we can determine at compile time which
  16938. \code{lambda} will be called. We refer to such calls as \emph{known
  16939. calls}. Consider the following example in which a \code{lambda} is
  16940. bound to \code{f} and then applied.
  16941. {\if\edition\racketEd
  16942. % lambda_test_9.rkt
  16943. \begin{lstlisting}
  16944. (let ([y (read)])
  16945. (let ([f (lambda: ([x : Integer]) : Integer
  16946. (+ x y))])
  16947. (f 21)))
  16948. \end{lstlisting}
  16949. \fi}
  16950. {\if\edition\pythonEd\pythonColor
  16951. \begin{lstlisting}
  16952. y = input_int()
  16953. f : Callable[[int],int] = lambda x: x + y
  16954. print(f(21))
  16955. \end{lstlisting}
  16956. \fi}
  16957. %
  16958. \noindent Closure conversion compiles the application
  16959. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16960. %
  16961. {\if\edition\racketEd
  16962. \begin{lstlisting}
  16963. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16964. (let ([y2 (vector-ref fvs6 1)])
  16965. (+ x3 y2)))
  16966. (define (main) : Integer
  16967. (let ([y2 (read)])
  16968. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16969. ((vector-ref f4 0) f4 21))))
  16970. \end{lstlisting}
  16971. \fi}
  16972. {\if\edition\pythonEd\pythonColor
  16973. \begin{lstlisting}
  16974. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16975. y_1 = fvs_4[1]
  16976. return x_2 + y_1[0]
  16977. def main() -> int:
  16978. y_1 = (777,)
  16979. y_1[0] = input_int()
  16980. f_0 = (lambda_3, y_1)
  16981. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16982. return 0
  16983. \end{lstlisting}
  16984. \fi}
  16985. %
  16986. \noindent However, we can instead compile the application
  16987. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16988. %
  16989. {\if\edition\racketEd
  16990. \begin{lstlisting}
  16991. (define (main) : Integer
  16992. (let ([y2 (read)])
  16993. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16994. ((fun-ref lambda5 1) f4 21))))
  16995. \end{lstlisting}
  16996. \fi}
  16997. {\if\edition\pythonEd\pythonColor
  16998. \begin{lstlisting}
  16999. def main() -> int:
  17000. y_1 = (777,)
  17001. y_1[0] = input_int()
  17002. f_0 = (lambda_3, y_1)
  17003. print(lambda_3(f_0, 21))
  17004. return 0
  17005. \end{lstlisting}
  17006. \fi}
  17007. The problem of determining which \code{lambda} will be called from a
  17008. particular application is quite challenging in general and the topic
  17009. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  17010. following exercise we recommend that you compile an application to a
  17011. direct call when the operator is a variable and \racket{the variable
  17012. is \code{let}-bound to a closure}\python{the previous assignment to
  17013. the variable is a closure}. This can be accomplished by maintaining
  17014. an environment that maps variables to function names. Extend the
  17015. environment whenever you encounter a closure on the right-hand side of
  17016. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  17017. name of the global function for the closure. This pass should come
  17018. after closure conversion.
  17019. \begin{exercise}\normalfont\normalsize
  17020. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  17021. compiles known calls into direct calls. Verify that your compiler is
  17022. successful in this regard on several example programs.
  17023. \end{exercise}
  17024. These exercises only scratch the surface of closure optimization. A
  17025. good next step for the interested reader is to look at the work of
  17026. \citet{Keep:2012ab}.
  17027. \section{Further Reading}
  17028. The notion of lexically scoped functions predates modern computers by
  17029. about a decade. They were invented by \citet{Church:1932aa}, who
  17030. proposed the lambda calculus as a foundation for logic. Anonymous
  17031. functions were included in the LISP~\citep{McCarthy:1960dz}
  17032. programming language but were initially dynamically scoped. The Scheme
  17033. dialect of LISP adopted lexical scoping, and
  17034. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  17035. Scheme programs. However, environments were represented as linked
  17036. lists, so variable look-up was linear in the size of the
  17037. environment. \citet{Appel91} gives a detailed description of several
  17038. closure representations. In this chapter we represent environments
  17039. using flat closures, which were invented by
  17040. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  17041. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  17042. closures, variable look-up is constant time but the time to create a
  17043. closure is proportional to the number of its free variables. Flat
  17044. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  17045. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  17046. % todo: related work on assignment conversion (e.g. orbit and rabbit
  17047. % compilers)
  17048. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17049. \chapter{Dynamic Typing}
  17050. \label{ch:Ldyn}
  17051. \index{subject}{dynamic typing}
  17052. \setcounter{footnote}{0}
  17053. In this chapter we learn how to compile \LangDyn{}, a dynamically
  17054. typed language that is a subset of \racket{Racket}\python{Python}. The
  17055. focus on dynamic typing is in contrast to the previous chapters, which
  17056. have studied the compilation of statically typed languages. In
  17057. dynamically typed languages such as \LangDyn{}, a particular
  17058. expression may produce a value of a different type each time it is
  17059. executed. Consider the following example with a conditional \code{if}
  17060. expression that may return a Boolean or an integer depending on the
  17061. input to the program:
  17062. % part of dynamic_test_25.rkt
  17063. {\if\edition\racketEd
  17064. \begin{lstlisting}
  17065. (not (if (eq? (read) 1) #f 0))
  17066. \end{lstlisting}
  17067. \fi}
  17068. {\if\edition\pythonEd\pythonColor
  17069. \begin{lstlisting}
  17070. not (False if input_int() == 1 else 0)
  17071. \end{lstlisting}
  17072. \fi}
  17073. Languages that allow expressions to produce different kinds of values
  17074. are called \emph{polymorphic}, a word composed of the Greek roots
  17075. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  17076. There are several kinds of polymorphism in programming languages, such as
  17077. subtype polymorphism\index{subject}{subtype polymorphism} and
  17078. parametric polymorphism\index{subject}{parametric polymorphism}
  17079. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  17080. study in this chapter does not have a special name; it is the kind
  17081. that arises in dynamically typed languages.
  17082. Another characteristic of dynamically typed languages is that
  17083. their primitive operations, such as \code{not}, are often defined to operate
  17084. on many different types of values. In fact, in
  17085. \racket{Racket}\python{Python}, the \code{not} operator produces a
  17086. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  17087. given anything else it returns \FALSE{}.
  17088. Furthermore, even when primitive operations restrict their inputs to
  17089. values of a certain type, this restriction is enforced at runtime
  17090. instead of during compilation. For example, the tuple read
  17091. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  17092. results in a runtime error because the first argument must
  17093. be a tuple, not a Boolean.
  17094. \section{The \LangDyn{} Language}
  17095. \newcommand{\LdynGrammarRacket}{
  17096. \begin{array}{rcl}
  17097. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  17098. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  17099. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  17100. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  17101. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  17102. \end{array}
  17103. }
  17104. \newcommand{\LdynASTRacket}{
  17105. \begin{array}{lcl}
  17106. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17107. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  17108. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  17109. \end{array}
  17110. }
  17111. \begin{figure}[tp]
  17112. \centering
  17113. \begin{tcolorbox}[colback=white]
  17114. \small
  17115. {\if\edition\racketEd
  17116. \[
  17117. \begin{array}{l}
  17118. \gray{\LintGrammarRacket{}} \\ \hline
  17119. \gray{\LvarGrammarRacket{}} \\ \hline
  17120. \gray{\LifGrammarRacket{}} \\ \hline
  17121. \gray{\LwhileGrammarRacket} \\ \hline
  17122. \gray{\LtupGrammarRacket} \\ \hline
  17123. \LdynGrammarRacket \\
  17124. \begin{array}{rcl}
  17125. \LangDynM{} &::=& \Def\ldots\; \Exp
  17126. \end{array}
  17127. \end{array}
  17128. \]
  17129. \fi}
  17130. {\if\edition\pythonEd\pythonColor
  17131. \[
  17132. \begin{array}{rcl}
  17133. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  17134. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  17135. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  17136. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  17137. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  17138. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  17139. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  17140. \MID \CLEN{\Exp} \\
  17141. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17142. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  17143. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  17144. \MID \Var\mathop{\key{=}}\Exp \\
  17145. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  17146. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  17147. &\MID& \CRETURN{\Exp} \\
  17148. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  17149. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  17150. \end{array}
  17151. \]
  17152. \fi}
  17153. \end{tcolorbox}
  17154. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17155. \label{fig:r7-concrete-syntax}
  17156. \index{subject}{Ldyn@\LangDyn{} concrete syntax}
  17157. \end{figure}
  17158. \begin{figure}[tp]
  17159. \centering
  17160. \begin{tcolorbox}[colback=white]
  17161. \small
  17162. {\if\edition\racketEd
  17163. \[
  17164. \begin{array}{l}
  17165. \gray{\LintASTRacket{}} \\ \hline
  17166. \gray{\LvarASTRacket{}} \\ \hline
  17167. \gray{\LifASTRacket{}} \\ \hline
  17168. \gray{\LwhileASTRacket} \\ \hline
  17169. \gray{\LtupASTRacket} \\ \hline
  17170. \LdynASTRacket \\
  17171. \begin{array}{lcl}
  17172. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17173. \end{array}
  17174. \end{array}
  17175. \]
  17176. \fi}
  17177. {\if\edition\pythonEd\pythonColor
  17178. \[
  17179. \begin{array}{rcl}
  17180. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17181. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17182. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17183. \MID \code{Is()} \\
  17184. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17185. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17186. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17187. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17188. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17189. &\MID& \VAR{\Var{}}
  17190. \MID \BOOL{\itm{bool}}
  17191. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17192. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17193. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17194. &\MID& \LEN{\Exp} \\
  17195. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17196. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17197. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17198. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17199. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17200. &\MID& \RETURN{\Exp} \\
  17201. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17202. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17203. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17204. \end{array}
  17205. \]
  17206. \fi}
  17207. \end{tcolorbox}
  17208. \caption{The abstract syntax of \LangDyn{}.}
  17209. \label{fig:r7-syntax}
  17210. \index{subject}{Ldyn@\LangDyn{} abstract syntax}
  17211. \end{figure}
  17212. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17213. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17214. %
  17215. There is no type checker for \LangDyn{} because it checks types only
  17216. at runtime.
  17217. The definitional interpreter for \LangDyn{} is presented in
  17218. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17219. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17220. \INT{n}. Instead of simply returning the integer \code{n} (as
  17221. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17222. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17223. value} that combines an underlying value with a tag that identifies
  17224. what kind of value it is. We define the following \racket{struct}\python{class}
  17225. to represent tagged values:
  17226. %
  17227. {\if\edition\racketEd
  17228. \begin{lstlisting}
  17229. (struct Tagged (value tag) #:transparent)
  17230. \end{lstlisting}
  17231. \fi}
  17232. {\if\edition\pythonEd\pythonColor
  17233. \begin{minipage}{\textwidth}
  17234. \begin{lstlisting}
  17235. @dataclass(eq=True)
  17236. class Tagged(Value):
  17237. value : Value
  17238. tag : str
  17239. def __str__(self):
  17240. return str(self.value)
  17241. \end{lstlisting}
  17242. \end{minipage}
  17243. \fi}
  17244. %
  17245. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17246. \code{Vector}, and \code{Procedure}.}
  17247. %
  17248. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17249. \skey{tuple}, and \skey{function}.}
  17250. %
  17251. Tags are closely related to types but do not always capture all the
  17252. information that a type does.
  17253. %
  17254. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17255. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17256. Any)} is tagged with \code{Procedure}.}
  17257. %
  17258. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17259. is tagged with \skey{tuple} and a function of type
  17260. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17261. is tagged with \skey{function}.}
  17262. Next consider the match case for accessing the element of a tuple.
  17263. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17264. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17265. argument is a tuple and the second is an integer.
  17266. \racket{
  17267. If they are not, a \code{trapped-error} is raised. Recall from
  17268. section~\ref{sec:interp_Lint} that when a definition interpreter
  17269. raises a \code{trapped-error} error, the compiled code must also
  17270. signal an error by exiting with return code \code{255}. A
  17271. \code{trapped-error} is also raised if the index is not less than the
  17272. length of the vector.
  17273. }
  17274. %
  17275. \python{If they are not, an exception is raised. The compiled code
  17276. must also signal an error by exiting with return code \code{255}. A
  17277. exception is also raised if the index is not less than the length of the
  17278. tuple or if it is negative.}
  17279. \begin{figure}[tbp]
  17280. \begin{tcolorbox}[colback=white]
  17281. {\if\edition\racketEd
  17282. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17283. (define ((interp-Ldyn-exp env) ast)
  17284. (define recur (interp-Ldyn-exp env))
  17285. (match ast
  17286. [(Var x) (unbox (lookup x env)]
  17287. [(Int n) (Tagged n 'Integer)]
  17288. [(Bool b) (Tagged b 'Boolean)]
  17289. [(Lambda xs rt body)
  17290. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17291. [(Prim 'vector es)
  17292. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17293. [(Prim 'vector-ref (list e1 e2))
  17294. (define vec (recur e1)) (define i (recur e2))
  17295. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17296. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17297. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17298. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17299. [(Prim 'vector-set! (list e1 e2 e3))
  17300. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17301. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17302. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17303. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17304. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17305. (Tagged (void) 'Void)]
  17306. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17307. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17308. [(Prim 'or (list e1 e2))
  17309. (define v1 (recur e1))
  17310. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17311. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17312. [(Prim op (list e1))
  17313. #:when (set-member? type-predicates op)
  17314. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17315. [(Prim op es)
  17316. (define args (map recur es))
  17317. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17318. (unless (for/or ([expected-tags (op-tags op)])
  17319. (equal? expected-tags tags))
  17320. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17321. (tag-value
  17322. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17323. [(If q t f)
  17324. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17325. [(Apply f es)
  17326. (define new-f (recur f)) (define args (map recur es))
  17327. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17328. (match f-val
  17329. [`(function ,xs ,body ,lam-env)
  17330. (unless (eq? (length xs) (length args))
  17331. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17332. (define new-env (append (map cons xs args) lam-env))
  17333. ((interp-Ldyn-exp new-env) body)]
  17334. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17335. \end{lstlisting}
  17336. \fi}
  17337. {\if\edition\pythonEd\pythonColor
  17338. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17339. class InterpLdyn(InterpLlambda):
  17340. def interp_exp(self, e, env):
  17341. match e:
  17342. case Constant(n):
  17343. return self.tag(super().interp_exp(e, env))
  17344. case Tuple(es, Load()):
  17345. return self.tag(super().interp_exp(e, env))
  17346. case Lambda(params, body):
  17347. return self.tag(super().interp_exp(e, env))
  17348. case Call(Name('input_int'), []):
  17349. return self.tag(super().interp_exp(e, env))
  17350. case BinOp(left, Add(), right):
  17351. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17352. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17353. case BinOp(left, Sub(), right):
  17354. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17355. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17356. case UnaryOp(USub(), e1):
  17357. v = self.interp_exp(e1, env)
  17358. return self.tag(- self.untag(v, 'int', e))
  17359. case IfExp(test, body, orelse):
  17360. v = self.interp_exp(test, env)
  17361. if self.untag(v, 'bool', e):
  17362. return self.interp_exp(body, env)
  17363. else:
  17364. return self.interp_exp(orelse, env)
  17365. case UnaryOp(Not(), e1):
  17366. v = self.interp_exp(e1, env)
  17367. return self.tag(not self.untag(v, 'bool', e))
  17368. case BoolOp(And(), values):
  17369. left = values[0]; right = values[1]
  17370. l = self.interp_exp(left, env)
  17371. if self.untag(l, 'bool', e):
  17372. return self.interp_exp(right, env)
  17373. else:
  17374. return self.tag(False)
  17375. case BoolOp(Or(), values):
  17376. left = values[0]; right = values[1]
  17377. l = self.interp_exp(left, env)
  17378. if self.untag(l, 'bool', e):
  17379. return self.tag(True)
  17380. else:
  17381. return self.interp_exp(right, env)
  17382. \end{lstlisting}
  17383. \fi}
  17384. \end{tcolorbox}
  17385. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17386. \label{fig:interp-Ldyn}
  17387. \end{figure}
  17388. {\if\edition\pythonEd\pythonColor
  17389. \begin{figure}[tbp]
  17390. \begin{tcolorbox}[colback=white]
  17391. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17392. # interp_exp continued
  17393. case Compare(left, [cmp], [right]):
  17394. l = self.interp_exp(left, env)
  17395. r = self.interp_exp(right, env)
  17396. if l.tag == r.tag:
  17397. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17398. else:
  17399. raise Exception('interp Compare unexpected '
  17400. + repr(l) + ' ' + repr(r))
  17401. case Subscript(tup, index, Load()):
  17402. t = self.interp_exp(tup, env)
  17403. n = self.interp_exp(index, env)
  17404. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17405. case Call(Name('len'), [tup]):
  17406. t = self.interp_exp(tup, env)
  17407. return self.tag(len(self.untag(t, 'tuple', e)))
  17408. case _:
  17409. return self.tag(super().interp_exp(e, env))
  17410. def interp_stmt(self, s, env, cont):
  17411. match s:
  17412. case If(test, body, orelse):
  17413. v = self.interp_exp(test, env)
  17414. match self.untag(v, 'bool', s):
  17415. case True:
  17416. return self.interp_stmts(body + cont, env)
  17417. case False:
  17418. return self.interp_stmts(orelse + cont, env)
  17419. case While(test, body, []):
  17420. v = self.interp_exp(test, env)
  17421. if self.untag(v, 'bool', test):
  17422. self.interp_stmts(body + [s] + cont, env)
  17423. else:
  17424. return self.interp_stmts(cont, env)
  17425. case Assign([Subscript(tup, index)], value):
  17426. tup = self.interp_exp(tup, env)
  17427. index = self.interp_exp(index, env)
  17428. tup_v = self.untag(tup, 'tuple', s)
  17429. index_v = self.untag(index, 'int', s)
  17430. tup_v[index_v] = self.interp_exp(value, env)
  17431. return self.interp_stmts(cont, env)
  17432. case FunctionDef(name, params, bod, dl, returns, comment):
  17433. if isinstance(params, ast.arguments):
  17434. ps = [p.arg for p in params.args]
  17435. else:
  17436. ps = [x for (x,t) in params]
  17437. env[name] = self.tag(Function(name, ps, bod, env))
  17438. return self.interp_stmts(cont, env)
  17439. case _:
  17440. return super().interp_stmt(s, env, cont)
  17441. \end{lstlisting}
  17442. \end{tcolorbox}
  17443. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17444. \label{fig:interp-Ldyn-2}
  17445. \end{figure}
  17446. \fi}
  17447. \begin{figure}[tbp]
  17448. \begin{tcolorbox}[colback=white]
  17449. {\if\edition\racketEd
  17450. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17451. (define (interp-op op)
  17452. (match op
  17453. ['+ fx+]
  17454. ['- fx-]
  17455. ['read read-fixnum]
  17456. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17457. ['< (lambda (v1 v2)
  17458. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17459. ['<= (lambda (v1 v2)
  17460. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17461. ['> (lambda (v1 v2)
  17462. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17463. ['>= (lambda (v1 v2)
  17464. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17465. ['boolean? boolean?]
  17466. ['integer? fixnum?]
  17467. ['void? void?]
  17468. ['vector? vector?]
  17469. ['vector-length vector-length]
  17470. ['procedure? (match-lambda
  17471. [`(functions ,xs ,body ,env) #t] [else #f])]
  17472. [else (error 'interp-op "unknown operator" op)]))
  17473. (define (op-tags op)
  17474. (match op
  17475. ['+ '((Integer Integer))]
  17476. ['- '((Integer Integer) (Integer))]
  17477. ['read '(())]
  17478. ['not '((Boolean))]
  17479. ['< '((Integer Integer))]
  17480. ['<= '((Integer Integer))]
  17481. ['> '((Integer Integer))]
  17482. ['>= '((Integer Integer))]
  17483. ['vector-length '((Vector))]))
  17484. (define type-predicates
  17485. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17486. (define (tag-value v)
  17487. (cond [(boolean? v) (Tagged v 'Boolean)]
  17488. [(fixnum? v) (Tagged v 'Integer)]
  17489. [(procedure? v) (Tagged v 'Procedure)]
  17490. [(vector? v) (Tagged v 'Vector)]
  17491. [(void? v) (Tagged v 'Void)]
  17492. [else (error 'tag-value "unidentified value ~a" v)]))
  17493. (define (check-tag val expected ast)
  17494. (define tag (Tagged-tag val))
  17495. (unless (eq? tag expected)
  17496. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17497. \end{lstlisting}
  17498. \fi}
  17499. {\if\edition\pythonEd\pythonColor
  17500. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17501. class InterpLdyn(InterpLlambda):
  17502. def tag(self, v):
  17503. if v is True or v is False:
  17504. return Tagged(v, 'bool')
  17505. elif isinstance(v, int):
  17506. return Tagged(v, 'int')
  17507. elif isinstance(v, Function):
  17508. return Tagged(v, 'function')
  17509. elif isinstance(v, tuple):
  17510. return Tagged(v, 'tuple')
  17511. elif isinstance(v, type(None)):
  17512. return Tagged(v, 'none')
  17513. else:
  17514. raise Exception('tag: unexpected ' + repr(v))
  17515. def untag(self, v, expected_tag, ast):
  17516. match v:
  17517. case Tagged(val, tag) if tag == expected_tag:
  17518. return val
  17519. case _:
  17520. raise TrappedError('expected Tagged value with '
  17521. + expected_tag + ', not ' + ' ' + repr(v))
  17522. def apply_fun(self, fun, args, e):
  17523. f = self.untag(fun, 'function', e)
  17524. return super().apply_fun(f, args, e)
  17525. \end{lstlisting}
  17526. \fi}
  17527. \end{tcolorbox}
  17528. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17529. \label{fig:interp-Ldyn-aux}
  17530. \end{figure}
  17531. %\clearpage
  17532. \section{Representation of Tagged Values}
  17533. The interpreter for \LangDyn{} introduced a new kind of value: the
  17534. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17535. represent tagged values at the bit level. Because almost every
  17536. operation in \LangDyn{} involves manipulating tagged values, the
  17537. representation must be efficient. Recall that all our values are 64
  17538. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17539. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17540. $011$ for procedures, and $101$ for the void value\python{,
  17541. \key{None}}. We define the following auxiliary function for mapping
  17542. types to tag codes:
  17543. %
  17544. {\if\edition\racketEd
  17545. \begin{align*}
  17546. \itm{tagof}(\key{Integer}) &= 001 \\
  17547. \itm{tagof}(\key{Boolean}) &= 100 \\
  17548. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17549. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17550. \itm{tagof}(\key{Void}) &= 101
  17551. \end{align*}
  17552. \fi}
  17553. {\if\edition\pythonEd\pythonColor
  17554. \begin{align*}
  17555. \itm{tagof}(\key{IntType()}) &= 001 \\
  17556. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17557. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17558. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17559. \itm{tagof}(\key{type(None)}) &= 101
  17560. \end{align*}
  17561. \fi}
  17562. %
  17563. This stealing of 3 bits comes at some price: integers are now restricted
  17564. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17565. affect tuples and procedures because those values are addresses, and
  17566. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17567. they are always $000$. Thus, we do not lose information by overwriting
  17568. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17569. to recover the original address.
  17570. To make tagged values into first-class entities, we can give them a
  17571. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17572. operations such as \code{Inject} and \code{Project} for creating and
  17573. using them, yielding the statically typed \LangAny{} intermediate
  17574. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17575. section~\ref{sec:compile-r7}; in the next section we describe the
  17576. \LangAny{} language in greater detail.
  17577. \section{The \LangAny{} Language}
  17578. \label{sec:Rany-lang}
  17579. \newcommand{\LanyASTRacket}{
  17580. \begin{array}{lcl}
  17581. \Type &::= & \ANYTY \\
  17582. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17583. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17584. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17585. \itm{op} &::= & \code{any-vector-length}
  17586. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17587. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17588. \MID \code{procedure?} \MID \code{void?} \\
  17589. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17590. \end{array}
  17591. }
  17592. \newcommand{\LanyASTPython}{
  17593. \begin{array}{lcl}
  17594. \Type &::= & \key{AnyType()} \\
  17595. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17596. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17597. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17598. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17599. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17600. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17601. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17602. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17603. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17604. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17605. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17606. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17607. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17608. \end{array}
  17609. }
  17610. \begin{figure}[tp]
  17611. \centering
  17612. \begin{tcolorbox}[colback=white]
  17613. \small
  17614. {\if\edition\racketEd
  17615. \[
  17616. \begin{array}{l}
  17617. \gray{\LintOpAST} \\ \hline
  17618. \gray{\LvarASTRacket{}} \\ \hline
  17619. \gray{\LifASTRacket{}} \\ \hline
  17620. \gray{\LwhileASTRacket{}} \\ \hline
  17621. \gray{\LtupASTRacket{}} \\ \hline
  17622. \gray{\LfunASTRacket} \\ \hline
  17623. \gray{\LlambdaASTRacket} \\ \hline
  17624. \LanyASTRacket \\
  17625. \begin{array}{lcl}
  17626. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17627. \end{array}
  17628. \end{array}
  17629. \]
  17630. \fi}
  17631. {\if\edition\pythonEd\pythonColor
  17632. \[
  17633. \begin{array}{l}
  17634. \gray{\LintASTPython} \\ \hline
  17635. \gray{\LvarASTPython{}} \\ \hline
  17636. \gray{\LifASTPython{}} \\ \hline
  17637. \gray{\LwhileASTPython{}} \\ \hline
  17638. \gray{\LtupASTPython{}} \\ \hline
  17639. \gray{\LfunASTPython} \\ \hline
  17640. \gray{\LlambdaASTPython} \\ \hline
  17641. \LanyASTPython \\
  17642. \begin{array}{lcl}
  17643. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17644. \end{array}
  17645. \end{array}
  17646. \]
  17647. \fi}
  17648. \end{tcolorbox}
  17649. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17650. \label{fig:Lany-syntax}
  17651. \index{subject}{Lany@\LangAny{} abstract syntax}
  17652. \end{figure}
  17653. The definition of the abstract syntax of \LangAny{} is given in
  17654. figure~\ref{fig:Lany-syntax}.
  17655. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17656. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17657. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17658. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17659. converts the tagged value produced by expression $e$ into a value of
  17660. type $T$ or halts the program if the type tag does not match $T$.
  17661. %
  17662. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17663. restricted to be a flat type (the nonterminal $\FType$) which
  17664. simplifies the implementation and complies with the needs for
  17665. compiling \LangDyn{}.
  17666. The \racket{\code{any-vector}} operators
  17667. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17668. operations so that they can be applied to a value of type
  17669. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17670. tuple operations in that the index is not restricted to a literal
  17671. integer in the grammar but is allowed to be any expression.
  17672. \racket{The type predicates such as
  17673. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17674. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17675. the predicate and return {\FALSE} otherwise.}
  17676. \racket{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}
  17677. and it uses the auxiliary functions presented in figure~\ref{fig:type-check-Lany-aux}.}
  17678. \python{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}.}
  17679. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17680. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17681. \begin{figure}[btp]
  17682. \begin{tcolorbox}[colback=white]
  17683. {\if\edition\racketEd
  17684. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17685. (define type-check-Lany-class
  17686. (class type-check-Llambda-class
  17687. (super-new)
  17688. (inherit check-type-equal?)
  17689. (define/override (type-check-exp env)
  17690. (lambda (e)
  17691. (define recur (type-check-exp env))
  17692. (match e
  17693. [(Inject e1 ty)
  17694. (unless (flat-ty? ty)
  17695. (error 'type-check "may only inject from flat type, not ~a" ty))
  17696. (define-values (new-e1 e-ty) (recur e1))
  17697. (check-type-equal? e-ty ty e)
  17698. (values (Inject new-e1 ty) 'Any)]
  17699. [(Project e1 ty)
  17700. (unless (flat-ty? ty)
  17701. (error 'type-check "may only project to flat type, not ~a" ty))
  17702. (define-values (new-e1 e-ty) (recur e1))
  17703. (check-type-equal? e-ty 'Any e)
  17704. (values (Project new-e1 ty) ty)]
  17705. [(Prim 'any-vector-length (list e1))
  17706. (define-values (e1^ t1) (recur e1))
  17707. (check-type-equal? t1 'Any e)
  17708. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17709. [(Prim 'any-vector-ref (list e1 e2))
  17710. (define-values (e1^ t1) (recur e1))
  17711. (define-values (e2^ t2) (recur e2))
  17712. (check-type-equal? t1 'Any e)
  17713. (check-type-equal? t2 'Integer e)
  17714. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17715. [(Prim 'any-vector-set! (list e1 e2 e3))
  17716. (define-values (e1^ t1) (recur e1))
  17717. (define-values (e2^ t2) (recur e2))
  17718. (define-values (e3^ t3) (recur e3))
  17719. (check-type-equal? t1 'Any e)
  17720. (check-type-equal? t2 'Integer e)
  17721. (check-type-equal? t3 'Any e)
  17722. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17723. [(Prim pred (list e1))
  17724. #:when (set-member? (type-predicates) pred)
  17725. (define-values (new-e1 e-ty) (recur e1))
  17726. (check-type-equal? e-ty 'Any e)
  17727. (values (Prim pred (list new-e1)) 'Boolean)]
  17728. [(Prim 'eq? (list arg1 arg2))
  17729. (define-values (e1 t1) (recur arg1))
  17730. (define-values (e2 t2) (recur arg2))
  17731. (match* (t1 t2)
  17732. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17733. [(other wise) (check-type-equal? t1 t2 e)])
  17734. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17735. [else ((super type-check-exp env) e)])))
  17736. ))
  17737. \end{lstlisting}
  17738. \fi}
  17739. {\if\edition\pythonEd\pythonColor
  17740. \begin{lstlisting}
  17741. class TypeCheckLany(TypeCheckLlambda):
  17742. def type_check_exp(self, e, env):
  17743. match e:
  17744. case Inject(value, typ):
  17745. self.check_exp(value, typ, env)
  17746. return AnyType()
  17747. case Project(value, typ):
  17748. self.check_exp(value, AnyType(), env)
  17749. return typ
  17750. case Call(Name('any_tuple_load'), [tup, index]):
  17751. self.check_exp(tup, AnyType(), env)
  17752. self.check_exp(index, IntType(), env)
  17753. return AnyType()
  17754. case Call(Name('any_len'), [tup]):
  17755. self.check_exp(tup, AnyType(), env)
  17756. return IntType()
  17757. case Call(Name('arity'), [fun]):
  17758. ty = self.type_check_exp(fun, env)
  17759. match ty:
  17760. case FunctionType(ps, rt):
  17761. return IntType()
  17762. case TupleType([FunctionType(ps,rs)]):
  17763. return IntType()
  17764. case _:
  17765. raise Exception('type check arity unexpected ' + repr(ty))
  17766. case Call(Name('make_any'), [value, tag]):
  17767. self.type_check_exp(value, env)
  17768. self.check_exp(tag, IntType(), env)
  17769. return AnyType()
  17770. case AnnLambda(params, returns, body):
  17771. new_env = {x:t for (x,t) in env.items()}
  17772. for (x,t) in params:
  17773. new_env[x] = t
  17774. return_t = self.type_check_exp(body, new_env)
  17775. self.check_type_equal(returns, return_t, e)
  17776. return FunctionType([t for (x,t) in params], return_t)
  17777. case _:
  17778. return super().type_check_exp(e, env)
  17779. \end{lstlisting}
  17780. \fi}
  17781. \end{tcolorbox}
  17782. \caption{Type checker for the \LangAny{} language.}
  17783. \label{fig:type-check-Lany}
  17784. \end{figure}
  17785. {\if\edition\racketEd
  17786. \begin{figure}[tbp]
  17787. \begin{tcolorbox}[colback=white]
  17788. \begin{lstlisting}
  17789. (define/override (operator-types)
  17790. (append
  17791. '((integer? . ((Any) . Boolean))
  17792. (vector? . ((Any) . Boolean))
  17793. (procedure? . ((Any) . Boolean))
  17794. (void? . ((Any) . Boolean)))
  17795. (super operator-types)))
  17796. (define/public (type-predicates)
  17797. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17798. (define/public (flat-ty? ty)
  17799. (match ty
  17800. [(or `Integer `Boolean `Void) #t]
  17801. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17802. [`(,ts ... -> ,rt)
  17803. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17804. [else #f]))
  17805. \end{lstlisting}
  17806. \end{tcolorbox}
  17807. \caption{Auxiliary methods for type checking \LangAny{}.}
  17808. \label{fig:type-check-Lany-aux}
  17809. \end{figure}
  17810. \fi}
  17811. \begin{figure}[tbp]
  17812. \begin{tcolorbox}[colback=white]
  17813. {\if\edition\racketEd
  17814. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17815. (define interp-Lany-class
  17816. (class interp-Llambda-class
  17817. (super-new)
  17818. (define/override (interp-op op)
  17819. (match op
  17820. ['boolean? (match-lambda
  17821. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17822. [else #f])]
  17823. ['integer? (match-lambda
  17824. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17825. [else #f])]
  17826. ['vector? (match-lambda
  17827. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17828. [else #f])]
  17829. ['procedure? (match-lambda
  17830. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17831. [else #f])]
  17832. ['eq? (match-lambda*
  17833. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17834. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17835. [ls (apply (super interp-op op) ls)])]
  17836. ['any-vector-ref (lambda (v i)
  17837. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17838. ['any-vector-set! (lambda (v i a)
  17839. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17840. ['any-vector-length (lambda (v)
  17841. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17842. [else (super interp-op op)]))
  17843. (define/override ((interp-exp env) e)
  17844. (define recur (interp-exp env))
  17845. (match e
  17846. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17847. [(Project e ty2) (apply-project (recur e) ty2)]
  17848. [else ((super interp-exp env) e)]))
  17849. ))
  17850. (define (interp-Lany p)
  17851. (send (new interp-Lany-class) interp-program p))
  17852. \end{lstlisting}
  17853. \fi}
  17854. {\if\edition\pythonEd\pythonColor
  17855. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17856. class InterpLany(InterpLlambda):
  17857. def interp_exp(self, e, env):
  17858. match e:
  17859. case Inject(value, typ):
  17860. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17861. case Project(value, typ):
  17862. match self.interp_exp(value, env):
  17863. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17864. return val
  17865. case _:
  17866. raise Exception('failed project to ' + self.type_to_tag(typ))
  17867. case Call(Name('any_tuple_load'), [tup, index]):
  17868. match self.interp_exp(tup, env):
  17869. case Tagged(v, tag):
  17870. return v[self.interp_exp(index, env)]
  17871. case _:
  17872. raise Exception('in any_tuple_load untagged value')
  17873. case Call(Name('any_len'), [value]):
  17874. match self.interp_exp(value, env):
  17875. case Tagged(value, tag):
  17876. return len(value)
  17877. case _:
  17878. raise Exception('interp any_len untagged value')
  17879. case Call(Name('arity'), [fun]):
  17880. return self.arity(self.interp_exp(fun, env))
  17881. case _:
  17882. return super().interp_exp(e, env)
  17883. \end{lstlisting}
  17884. \fi}
  17885. \end{tcolorbox}
  17886. \caption{Interpreter for \LangAny{}.}
  17887. \label{fig:interp-Lany}
  17888. \end{figure}
  17889. \begin{figure}[btp]
  17890. \begin{tcolorbox}[colback=white]
  17891. {\if\edition\racketEd
  17892. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17893. (define/public (apply-inject v tg) (Tagged v tg))
  17894. (define/public (apply-project v ty2)
  17895. (define tag2 (any-tag ty2))
  17896. (match v
  17897. [(Tagged v1 tag1)
  17898. (cond
  17899. [(eq? tag1 tag2)
  17900. (match ty2
  17901. [`(Vector ,ts ...)
  17902. (define l1 ((interp-op 'vector-length) v1))
  17903. (cond
  17904. [(eq? l1 (length ts)) v1]
  17905. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17906. l1 (length ts))])]
  17907. [`(,ts ... -> ,rt)
  17908. (match v1
  17909. [`(function ,xs ,body ,env)
  17910. (cond [(eq? (length xs) (length ts)) v1]
  17911. [else
  17912. (error 'apply-project "arity mismatch ~a != ~a"
  17913. (length xs) (length ts))])]
  17914. [else (error 'apply-project "expected function not ~a" v1)])]
  17915. [else v1])]
  17916. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17917. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17918. \end{lstlisting}
  17919. \fi}
  17920. {\if\edition\pythonEd\pythonColor
  17921. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17922. class InterpLany(InterpLlambda):
  17923. def type_to_tag(self, typ):
  17924. match typ:
  17925. case FunctionType(params, rt):
  17926. return 'function'
  17927. case TupleType(fields):
  17928. return 'tuple'
  17929. case IntType():
  17930. return 'int'
  17931. case BoolType():
  17932. return 'bool'
  17933. case _:
  17934. raise Exception('type_to_tag unexpected ' + repr(typ))
  17935. def arity(self, v):
  17936. match v:
  17937. case Function(name, params, body, env):
  17938. return len(params)
  17939. case _:
  17940. raise Exception('Lany arity unexpected ' + repr(v))
  17941. \end{lstlisting}
  17942. \fi}
  17943. \end{tcolorbox}
  17944. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17945. \label{fig:interp-Lany-aux}
  17946. \end{figure}
  17947. \clearpage
  17948. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17949. \label{sec:compile-r7}
  17950. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17951. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17952. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17953. is that given any subexpression $e$ in the \LangDyn{} program, the
  17954. pass will produce an expression $e'$ in \LangAny{} that has type
  17955. \ANYTY{}. For example, the first row in
  17956. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17957. \TRUE{}, which must be injected to produce an expression of type
  17958. \ANYTY{}.
  17959. %
  17960. The compilation of addition is shown in the second row of
  17961. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17962. representative of many primitive operations: the arguments have type
  17963. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17964. be performed.
  17965. The compilation of \key{lambda} (third row of
  17966. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17967. produce type annotations: we simply use \ANYTY{}.
  17968. %
  17969. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17970. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17971. this pass has to account for some differences in behavior between
  17972. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17973. permissive than \LangAny{} regarding what kind of values can be used
  17974. in various places. For example, the condition of an \key{if} does
  17975. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17976. of the same type (in that case the result is \code{\#f}).}
  17977. \begin{figure}[btp]
  17978. \centering
  17979. \begin{tcolorbox}[colback=white]
  17980. {\if\edition\racketEd
  17981. \begin{tabular}{lll}
  17982. \begin{minipage}{0.27\textwidth}
  17983. \begin{lstlisting}
  17984. #t
  17985. \end{lstlisting}
  17986. \end{minipage}
  17987. &
  17988. $\Rightarrow$
  17989. &
  17990. \begin{minipage}{0.65\textwidth}
  17991. \begin{lstlisting}
  17992. (inject #t Boolean)
  17993. \end{lstlisting}
  17994. \end{minipage}
  17995. \\[2ex]\hline
  17996. \begin{minipage}{0.27\textwidth}
  17997. \begin{lstlisting}
  17998. (+ |$e_1$| |$e_2$|)
  17999. \end{lstlisting}
  18000. \end{minipage}
  18001. &
  18002. $\Rightarrow$
  18003. &
  18004. \begin{minipage}{0.65\textwidth}
  18005. \begin{lstlisting}
  18006. (inject
  18007. (+ (project |$e'_1$| Integer)
  18008. (project |$e'_2$| Integer))
  18009. Integer)
  18010. \end{lstlisting}
  18011. \end{minipage}
  18012. \\[2ex]\hline
  18013. \begin{minipage}{0.27\textwidth}
  18014. \begin{lstlisting}
  18015. (lambda (|$x_1 \ldots$|) |$e$|)
  18016. \end{lstlisting}
  18017. \end{minipage}
  18018. &
  18019. $\Rightarrow$
  18020. &
  18021. \begin{minipage}{0.65\textwidth}
  18022. \begin{lstlisting}
  18023. (inject
  18024. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  18025. (Any|$\ldots$|Any -> Any))
  18026. \end{lstlisting}
  18027. \end{minipage}
  18028. \\[2ex]\hline
  18029. \begin{minipage}{0.27\textwidth}
  18030. \begin{lstlisting}
  18031. (|$e_0$| |$e_1 \ldots e_n$|)
  18032. \end{lstlisting}
  18033. \end{minipage}
  18034. &
  18035. $\Rightarrow$
  18036. &
  18037. \begin{minipage}{0.65\textwidth}
  18038. \begin{lstlisting}
  18039. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  18040. \end{lstlisting}
  18041. \end{minipage}
  18042. \\[2ex]\hline
  18043. \begin{minipage}{0.27\textwidth}
  18044. \begin{lstlisting}
  18045. (vector-ref |$e_1$| |$e_2$|)
  18046. \end{lstlisting}
  18047. \end{minipage}
  18048. &
  18049. $\Rightarrow$
  18050. &
  18051. \begin{minipage}{0.65\textwidth}
  18052. \begin{lstlisting}
  18053. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  18054. \end{lstlisting}
  18055. \end{minipage}
  18056. \\[2ex]\hline
  18057. \begin{minipage}{0.27\textwidth}
  18058. \begin{lstlisting}
  18059. (if |$e_1$| |$e_2$| |$e_3$|)
  18060. \end{lstlisting}
  18061. \end{minipage}
  18062. &
  18063. $\Rightarrow$
  18064. &
  18065. \begin{minipage}{0.65\textwidth}
  18066. \begin{lstlisting}
  18067. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18068. \end{lstlisting}
  18069. \end{minipage}
  18070. \\[2ex]\hline
  18071. \begin{minipage}{0.27\textwidth}
  18072. \begin{lstlisting}
  18073. (eq? |$e_1$| |$e_2$|)
  18074. \end{lstlisting}
  18075. \end{minipage}
  18076. &
  18077. $\Rightarrow$
  18078. &
  18079. \begin{minipage}{0.65\textwidth}
  18080. \begin{lstlisting}
  18081. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18082. \end{lstlisting}
  18083. \end{minipage}
  18084. \\[2ex]\hline
  18085. \begin{minipage}{0.27\textwidth}
  18086. \begin{lstlisting}
  18087. (not |$e_1$|)
  18088. \end{lstlisting}
  18089. \end{minipage}
  18090. &
  18091. $\Rightarrow$
  18092. &
  18093. \begin{minipage}{0.65\textwidth}
  18094. \begin{lstlisting}
  18095. (if (eq? |$e'_1$| (inject #f Boolean))
  18096. (inject #t Boolean) (inject #f Boolean))
  18097. \end{lstlisting}
  18098. \end{minipage}
  18099. \end{tabular}
  18100. \fi}
  18101. {\if\edition\pythonEd\pythonColor
  18102. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  18103. \begin{minipage}{0.23\textwidth}
  18104. \begin{lstlisting}
  18105. True
  18106. \end{lstlisting}
  18107. \end{minipage}
  18108. &
  18109. $\Rightarrow$
  18110. &
  18111. \begin{minipage}{0.7\textwidth}
  18112. \begin{lstlisting}
  18113. Inject(True, BoolType())
  18114. \end{lstlisting}
  18115. \end{minipage}
  18116. \\[2ex]\hline
  18117. \begin{minipage}{0.23\textwidth}
  18118. \begin{lstlisting}
  18119. |$e_1$| + |$e_2$|
  18120. \end{lstlisting}
  18121. \end{minipage}
  18122. &
  18123. $\Rightarrow$
  18124. &
  18125. \begin{minipage}{0.7\textwidth}
  18126. \begin{lstlisting}
  18127. Inject(Project(|$e'_1$|, IntType())
  18128. + Project(|$e'_2$|, IntType()),
  18129. IntType())
  18130. \end{lstlisting}
  18131. \end{minipage}
  18132. \\[2ex]\hline
  18133. \begin{minipage}{0.23\textwidth}
  18134. \begin{lstlisting}
  18135. lambda |$x_1 \ldots$|: |$e$|
  18136. \end{lstlisting}
  18137. \end{minipage}
  18138. &
  18139. $\Rightarrow$
  18140. &
  18141. \begin{minipage}{0.7\textwidth}
  18142. \begin{lstlisting}
  18143. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  18144. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  18145. \end{lstlisting}
  18146. \end{minipage}
  18147. \\[2ex]\hline
  18148. \begin{minipage}{0.23\textwidth}
  18149. \begin{lstlisting}
  18150. |$e_0$|(|$e_1 \ldots e_n$|)
  18151. \end{lstlisting}
  18152. \end{minipage}
  18153. &
  18154. $\Rightarrow$
  18155. &
  18156. \begin{minipage}{0.7\textwidth}
  18157. \begin{lstlisting}
  18158. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18159. AnyType())), |$e'_1, \ldots, e'_n$|)
  18160. \end{lstlisting}
  18161. \end{minipage}
  18162. \\[2ex]\hline
  18163. \begin{minipage}{0.23\textwidth}
  18164. \begin{lstlisting}
  18165. |$e_1$|[|$e_2$|]
  18166. \end{lstlisting}
  18167. \end{minipage}
  18168. &
  18169. $\Rightarrow$
  18170. &
  18171. \begin{minipage}{0.7\textwidth}
  18172. \begin{lstlisting}
  18173. Call(Name('any_tuple_load'),
  18174. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18175. \end{lstlisting}
  18176. \end{minipage}
  18177. %% \begin{minipage}{0.23\textwidth}
  18178. %% \begin{lstlisting}
  18179. %% |$e_2$| if |$e_1$| else |$e_3$|
  18180. %% \end{lstlisting}
  18181. %% \end{minipage}
  18182. %% &
  18183. %% $\Rightarrow$
  18184. %% &
  18185. %% \begin{minipage}{0.7\textwidth}
  18186. %% \begin{lstlisting}
  18187. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18188. %% \end{lstlisting}
  18189. %% \end{minipage}
  18190. %% \\[2ex]\hline
  18191. %% \begin{minipage}{0.23\textwidth}
  18192. %% \begin{lstlisting}
  18193. %% (eq? |$e_1$| |$e_2$|)
  18194. %% \end{lstlisting}
  18195. %% \end{minipage}
  18196. %% &
  18197. %% $\Rightarrow$
  18198. %% &
  18199. %% \begin{minipage}{0.7\textwidth}
  18200. %% \begin{lstlisting}
  18201. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18202. %% \end{lstlisting}
  18203. %% \end{minipage}
  18204. %% \\[2ex]\hline
  18205. %% \begin{minipage}{0.23\textwidth}
  18206. %% \begin{lstlisting}
  18207. %% (not |$e_1$|)
  18208. %% \end{lstlisting}
  18209. %% \end{minipage}
  18210. %% &
  18211. %% $\Rightarrow$
  18212. %% &
  18213. %% \begin{minipage}{0.7\textwidth}
  18214. %% \begin{lstlisting}
  18215. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18216. %% (inject #t Boolean) (inject #f Boolean))
  18217. %% \end{lstlisting}
  18218. %% \end{minipage}
  18219. %% \\[2ex]\hline
  18220. \\\hline
  18221. \end{tabular}
  18222. \fi}
  18223. \end{tcolorbox}
  18224. \caption{Cast insertion.}
  18225. \label{fig:compile-r7-Lany}
  18226. \end{figure}
  18227. \section{Reveal Casts}
  18228. \label{sec:reveal-casts-Lany}
  18229. % TODO: define R'_6
  18230. In the \code{reveal\_casts} pass, we recommend compiling
  18231. \code{Project} into a conditional expression that checks whether the
  18232. value's tag matches the target type; if it does, the value is
  18233. converted to a value of the target type by removing the tag; if it
  18234. does not, the program exits.
  18235. %
  18236. {\if\edition\racketEd
  18237. %
  18238. To perform these actions we need a new primitive operation,
  18239. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18240. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18241. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18242. underlying value from a tagged value. The \code{ValueOf} form
  18243. includes the type for the underlying value that is used by the type
  18244. checker.
  18245. %
  18246. \fi}
  18247. %
  18248. {\if\edition\pythonEd\pythonColor
  18249. %
  18250. To perform these actions we need two new AST classes: \code{TagOf} and
  18251. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18252. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18253. the underlying value from a tagged value. The \code{ValueOf}
  18254. operation includes the type for the underlying value that is used by
  18255. the type checker.
  18256. %
  18257. \fi}
  18258. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18259. \code{Project} can be translated as follows:
  18260. \begin{center}
  18261. \begin{minipage}{1.0\textwidth}
  18262. {\if\edition\racketEd
  18263. \begin{lstlisting}
  18264. (Project |$e$| |$\FType$|)
  18265. |$\Rightarrow$|
  18266. (Let |$\itm{tmp}$| |$e'$|
  18267. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18268. (Int |$\itm{tagof}(\FType)$|)))
  18269. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18270. (Exit)))
  18271. \end{lstlisting}
  18272. \fi}
  18273. {\if\edition\pythonEd\pythonColor
  18274. \begin{lstlisting}
  18275. Project(|$e$|, |$\FType$|)
  18276. |$\Rightarrow$|
  18277. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18278. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18279. [Constant(|$\itm{tagof}(\FType)$|)]),
  18280. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18281. Call(Name('exit'), [])))
  18282. \end{lstlisting}
  18283. \fi}
  18284. \end{minipage}
  18285. \end{center}
  18286. If the target type of the projection is a tuple or function type, then
  18287. there is a bit more work to do. For tuples, check that the length of
  18288. the tuple type matches the length of the tuple. For functions, check
  18289. that the number of parameters in the function type matches the
  18290. function's arity.
  18291. Regarding \code{Inject}, we recommend compiling it to a slightly
  18292. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18293. takes a tag instead of a type.
  18294. \begin{center}
  18295. \begin{minipage}{1.0\textwidth}
  18296. {\if\edition\racketEd
  18297. \begin{lstlisting}
  18298. (Inject |$e$| |$\FType$|)
  18299. |$\Rightarrow$|
  18300. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18301. \end{lstlisting}
  18302. \fi}
  18303. {\if\edition\pythonEd\pythonColor
  18304. \begin{lstlisting}
  18305. Inject(|$e$|, |$\FType$|)
  18306. |$\Rightarrow$|
  18307. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18308. \end{lstlisting}
  18309. \fi}
  18310. \end{minipage}
  18311. \end{center}
  18312. {\if\edition\pythonEd\pythonColor
  18313. %
  18314. The introduction of \code{make\_any} makes it difficult to use
  18315. bidirectional type checking because we no longer have an expected type
  18316. to use for type checking the expression $e'$. Thus, we run into
  18317. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18318. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18319. annotated lambda) that contains its return type and the types of its
  18320. parameters.
  18321. %
  18322. \fi}
  18323. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18324. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18325. translation of \code{Project}.}
  18326. {\if\edition\racketEd
  18327. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18328. combine the projection action with the vector operation. Also, the
  18329. read and write operations allow arbitrary expressions for the index, so
  18330. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18331. cannot guarantee that the index is within bounds. Thus, we insert code
  18332. to perform bounds checking at runtime. The translation for
  18333. \code{any-vector-ref} is as follows, and the other two operations are
  18334. translated in a similar way:
  18335. \begin{center}
  18336. \begin{minipage}{0.95\textwidth}
  18337. \begin{lstlisting}
  18338. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18339. |$\Rightarrow$|
  18340. (Let |$v$| |$e'_1$|
  18341. (Let |$i$| |$e'_2$|
  18342. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18343. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18344. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18345. (Exit))
  18346. (Exit))))
  18347. \end{lstlisting}
  18348. \end{minipage}
  18349. \end{center}
  18350. \fi}
  18351. %
  18352. {\if\edition\pythonEd\pythonColor
  18353. %
  18354. The \code{any\_tuple\_load} operation combines the projection action
  18355. with the load operation. Also, the load operation allows arbitrary
  18356. expressions for the index, so the type checker for \LangAny{}
  18357. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18358. within bounds. Thus, we insert code to perform bounds checking at
  18359. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18360. \begin{lstlisting}
  18361. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18362. |$\Rightarrow$|
  18363. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18364. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18365. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18366. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18367. Call(Name('exit'), [])),
  18368. Call(Name('exit'), [])))
  18369. \end{lstlisting}
  18370. \fi}
  18371. {\if\edition\pythonEd\pythonColor
  18372. \section{Assignment Conversion}
  18373. \label{sec:convert-assignments-Lany}
  18374. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18375. \code{AnnLambda} AST classes.
  18376. \section{Closure Conversion}
  18377. \label{sec:closure-conversion-Lany}
  18378. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18379. \code{AnnLambda} AST classes.
  18380. \fi}
  18381. \section{Remove Complex Operands}
  18382. \label{sec:rco-Lany}
  18383. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18384. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18385. %
  18386. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18387. complex expressions. Their subexpressions must be atomic.}
  18388. \section{Explicate Control and \LangCAny{}}
  18389. \label{sec:explicate-Lany}
  18390. The output of \code{explicate\_control} is the \LangCAny{} language,
  18391. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18392. %
  18393. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18394. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18395. note that the index argument of \code{vector-ref} and
  18396. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18397. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18398. %
  18399. \python{Update the auxiliary functions \code{explicate\_tail},
  18400. \code{explicate\_effect}, and \code{explicate\_pred} as
  18401. appropriate to handle the new expressions in \LangCAny{}. }
  18402. \newcommand{\CanyASTPython}{
  18403. \begin{array}{lcl}
  18404. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18405. &\MID& \key{TagOf}\LP \Atm \RP
  18406. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18407. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18408. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18409. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18410. \end{array}
  18411. }
  18412. \newcommand{\CanyASTRacket}{
  18413. \begin{array}{lcl}
  18414. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18415. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18416. &\MID& \VALUEOF{\Atm}{\FType} \\
  18417. \Tail &::= & \LP\key{Exit}\RP
  18418. \end{array}
  18419. }
  18420. \begin{figure}[tp]
  18421. \begin{tcolorbox}[colback=white]
  18422. \small
  18423. {\if\edition\racketEd
  18424. \[
  18425. \begin{array}{l}
  18426. \gray{\CvarASTRacket} \\ \hline
  18427. \gray{\CifASTRacket} \\ \hline
  18428. \gray{\CloopASTRacket} \\ \hline
  18429. \gray{\CtupASTRacket} \\ \hline
  18430. \gray{\CfunASTRacket} \\ \hline
  18431. \gray{\ClambdaASTRacket} \\ \hline
  18432. \CanyASTRacket \\
  18433. \begin{array}{lcl}
  18434. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18435. \end{array}
  18436. \end{array}
  18437. \]
  18438. \fi}
  18439. {\if\edition\pythonEd\pythonColor
  18440. \[
  18441. \begin{array}{l}
  18442. \gray{\CifASTPython} \\ \hline
  18443. \gray{\CtupASTPython} \\ \hline
  18444. \gray{\CfunASTPython} \\ \hline
  18445. \gray{\ClambdaASTPython} \\ \hline
  18446. \CanyASTPython \\
  18447. \begin{array}{lcl}
  18448. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18449. \end{array}
  18450. \end{array}
  18451. \]
  18452. \fi}
  18453. \end{tcolorbox}
  18454. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18455. \label{fig:c5-syntax}
  18456. \index{subject}{Cany@\LangCAny{} abstract syntax}
  18457. \end{figure}
  18458. \section{Select Instructions}
  18459. \label{sec:select-Lany}
  18460. \index{subject}{select instructions}
  18461. In the \code{select\_instructions} pass, we translate the primitive
  18462. operations on the \ANYTY{} type to x86 instructions that manipulate
  18463. the three tag bits of the tagged value. In the following descriptions,
  18464. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18465. of translating $e$ into an x86 argument:
  18466. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18467. We recommend compiling the
  18468. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18469. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18470. shifts the destination to the left by the number of bits specified by its
  18471. source argument (in this case three, the length of the tag), and it
  18472. preserves the sign of the integer. We use the \key{orq} instruction to
  18473. combine the tag and the value to form the tagged value.
  18474. {\if\edition\racketEd
  18475. \begin{lstlisting}
  18476. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18477. |$\Rightarrow$|
  18478. movq |$e'$|, |\itm{lhs'}|
  18479. salq $3, |\itm{lhs'}|
  18480. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18481. \end{lstlisting}
  18482. \fi}
  18483. %
  18484. {\if\edition\pythonEd\pythonColor
  18485. \begin{lstlisting}
  18486. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18487. |$\Rightarrow$|
  18488. movq |$e'$|, |\itm{lhs'}|
  18489. salq $3, |\itm{lhs'}|
  18490. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18491. \end{lstlisting}
  18492. \fi}
  18493. %
  18494. The instruction selection\index{subject}{instruction selection} for
  18495. tuples and procedures is different because there is no need to shift
  18496. them to the left. The rightmost 3 bits are already zeros, so we simply
  18497. combine the value and the tag using \key{orq}. \\
  18498. %
  18499. {\if\edition\racketEd
  18500. \begin{center}
  18501. \begin{minipage}{\textwidth}
  18502. \begin{lstlisting}
  18503. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18504. |$\Rightarrow$|
  18505. movq |$e'$|, |\itm{lhs'}|
  18506. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18507. \end{lstlisting}
  18508. \end{minipage}
  18509. \end{center}
  18510. \fi}
  18511. %
  18512. {\if\edition\pythonEd\pythonColor
  18513. \begin{lstlisting}
  18514. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18515. |$\Rightarrow$|
  18516. movq |$e'$|, |\itm{lhs'}|
  18517. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18518. \end{lstlisting}
  18519. \fi}
  18520. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18521. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18522. operation extracts the type tag from a value of type \ANYTY{}. The
  18523. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18524. bitwise-and of the value with $111$ ($7$ decimal).
  18525. %
  18526. {\if\edition\racketEd
  18527. \begin{lstlisting}
  18528. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18529. |$\Rightarrow$|
  18530. movq |$e'$|, |\itm{lhs'}|
  18531. andq $7, |\itm{lhs'}|
  18532. \end{lstlisting}
  18533. \fi}
  18534. %
  18535. {\if\edition\pythonEd\pythonColor
  18536. \begin{lstlisting}
  18537. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18538. |$\Rightarrow$|
  18539. movq |$e'$|, |\itm{lhs'}|
  18540. andq $7, |\itm{lhs'}|
  18541. \end{lstlisting}
  18542. \fi}
  18543. \paragraph{\code{ValueOf}}
  18544. The instructions for \key{ValueOf} also differ, depending on whether
  18545. the type $T$ is a pointer (tuple or function) or not (integer or
  18546. Boolean). The following shows the instruction
  18547. selection for integers and
  18548. Booleans, in which we produce an untagged value by shifting it to the
  18549. right by 3 bits:
  18550. %
  18551. {\if\edition\racketEd
  18552. \begin{lstlisting}
  18553. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18554. |$\Rightarrow$|
  18555. movq |$e'$|, |\itm{lhs'}|
  18556. sarq $3, |\itm{lhs'}|
  18557. \end{lstlisting}
  18558. \fi}
  18559. %
  18560. {\if\edition\pythonEd\pythonColor
  18561. \begin{lstlisting}
  18562. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18563. |$\Rightarrow$|
  18564. movq |$e'$|, |\itm{lhs'}|
  18565. sarq $3, |\itm{lhs'}|
  18566. \end{lstlisting}
  18567. \fi}
  18568. %
  18569. In the case for tuples and procedures, we zero out the rightmost 3
  18570. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18571. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18572. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18573. Finally, we apply \code{andq} with the tagged value to get the desired
  18574. result.
  18575. %
  18576. {\if\edition\racketEd
  18577. \begin{lstlisting}
  18578. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18579. |$\Rightarrow$|
  18580. movq $|$-8$|, |\itm{lhs'}|
  18581. andq |$e'$|, |\itm{lhs'}|
  18582. \end{lstlisting}
  18583. \fi}
  18584. %
  18585. {\if\edition\pythonEd\pythonColor
  18586. \begin{lstlisting}
  18587. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18588. |$\Rightarrow$|
  18589. movq $|$-8$|, |\itm{lhs'}|
  18590. andq |$e'$|, |\itm{lhs'}|
  18591. \end{lstlisting}
  18592. \fi}
  18593. %% \paragraph{Type Predicates} We leave it to the reader to
  18594. %% devise a sequence of instructions to implement the type predicates
  18595. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18596. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18597. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18598. operation combines the effect of \code{ValueOf} with accessing the
  18599. length of a tuple from the tag stored at the zero index of the tuple.
  18600. {\if\edition\racketEd
  18601. \begin{lstlisting}
  18602. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18603. |$\Longrightarrow$|
  18604. movq $|$-8$|, %r11
  18605. andq |$e_1'$|, %r11
  18606. movq 0(%r11), %r11
  18607. andq $126, %r11
  18608. sarq $1, %r11
  18609. movq %r11, |$\itm{lhs'}$|
  18610. \end{lstlisting}
  18611. \fi}
  18612. {\if\edition\pythonEd\pythonColor
  18613. \begin{lstlisting}
  18614. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18615. |$\Longrightarrow$|
  18616. movq $|$-8$|, %r11
  18617. andq |$e_1'$|, %r11
  18618. movq 0(%r11), %r11
  18619. andq $126, %r11
  18620. sarq $1, %r11
  18621. movq %r11, |$\itm{lhs'}$|
  18622. \end{lstlisting}
  18623. \fi}
  18624. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18625. This operation combines the effect of \code{ValueOf} with reading an
  18626. element of the tuple (see
  18627. section~\ref{sec:select-instructions-gc}). However, the index may be
  18628. an arbitrary atom, so instead of computing the offset at compile time,
  18629. we must generate instructions to compute the offset at runtime as
  18630. follows. Note the use of the new instruction \code{imulq}.
  18631. \begin{center}
  18632. \begin{minipage}{0.96\textwidth}
  18633. {\if\edition\racketEd
  18634. \begin{lstlisting}
  18635. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18636. |$\Longrightarrow$|
  18637. movq |$\neg 111$|, %r11
  18638. andq |$e_1'$|, %r11
  18639. movq |$e_2'$|, %rax
  18640. addq $1, %rax
  18641. imulq $8, %rax
  18642. addq %rax, %r11
  18643. movq 0(%r11) |$\itm{lhs'}$|
  18644. \end{lstlisting}
  18645. \fi}
  18646. %
  18647. {\if\edition\pythonEd\pythonColor
  18648. \begin{lstlisting}
  18649. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18650. |$\Longrightarrow$|
  18651. movq $|$-8$|, %r11
  18652. andq |$e_1'$|, %r11
  18653. movq |$e_2'$|, %rax
  18654. addq $1, %rax
  18655. imulq $8, %rax
  18656. addq %rax, %r11
  18657. movq 0(%r11) |$\itm{lhs'}$|
  18658. \end{lstlisting}
  18659. \fi}
  18660. \end{minipage}
  18661. \end{center}
  18662. % $ pacify font lock
  18663. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18664. %% The code generation for
  18665. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18666. %% analogous to the above translation for reading from a tuple.
  18667. \section{Register Allocation for \LangAny{} }
  18668. \label{sec:register-allocation-Lany}
  18669. \index{subject}{register allocation}
  18670. There is an interesting interaction between tagged values and garbage
  18671. collection that has an impact on register allocation. A variable of
  18672. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18673. that needs to be inspected and copied during garbage collection. Thus,
  18674. we need to treat variables of type \ANYTY{} in a similar way to
  18675. variables of tuple type for purposes of register allocation,
  18676. with particular attention to the following:
  18677. \begin{itemize}
  18678. \item If a variable of type \ANYTY{} is live during a function call,
  18679. then it must be spilled. This can be accomplished by changing
  18680. \code{build\_interference} to mark all variables of type \ANYTY{}
  18681. that are live after a \code{callq} to be interfering with all the
  18682. registers.
  18683. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18684. the root stack instead of the normal procedure call stack.
  18685. \end{itemize}
  18686. Another concern regarding the root stack is that the garbage collector
  18687. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18688. tagged value that points to a tuple, and (3) a tagged value that is
  18689. not a tuple. We enable this differentiation by choosing not to use the
  18690. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18691. reserved for identifying plain old pointers to tuples. That way, if
  18692. one of the first three bits is set, then we have a tagged value and
  18693. inspecting the tag can differentiate between tuples ($010$) and the
  18694. other kinds of values.
  18695. %% \begin{exercise}\normalfont
  18696. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18697. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18698. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18699. %% compiler on these new programs and all of your previously created test
  18700. %% programs.
  18701. %% \end{exercise}
  18702. \begin{exercise}\normalfont\normalsize
  18703. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18704. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18705. by removing type annotations. Add five more test programs that
  18706. specifically rely on the language being dynamically typed. That is,
  18707. they should not be legal programs in a statically typed language, but
  18708. nevertheless they should be valid \LangDyn{} programs that run to
  18709. completion without error.
  18710. \end{exercise}
  18711. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18712. for the compilation of \LangDyn{}.
  18713. \begin{figure}[bthp]
  18714. \begin{tcolorbox}[colback=white]
  18715. {\if\edition\racketEd
  18716. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18717. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18718. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18719. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18720. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18721. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18722. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18723. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18724. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18725. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18726. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18727. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18728. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18729. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18730. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18731. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18732. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18733. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18734. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18735. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18736. \path[->,bend left=15] (Lfun) edge [above] node
  18737. {\ttfamily\footnotesize shrink} (Lfun-2);
  18738. \path[->,bend left=15] (Lfun-2) edge [above] node
  18739. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18740. \path[->,bend left=15] (Lfun-3) edge [above] node
  18741. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18742. \path[->,bend left=15] (Lfun-4) edge [left] node
  18743. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18744. \path[->,bend left=15] (Lfun-5) edge [below] node
  18745. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18746. \path[->,bend left=15] (Lfun-6) edge [below] node
  18747. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18748. \path[->,bend right=15] (Lfun-7) edge [above] node
  18749. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18750. \path[->,bend right=15] (F1-2) edge [right] node
  18751. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18752. \path[->,bend right=15] (F1-3) edge [below] node
  18753. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18754. \path[->,bend right=15] (F1-4) edge [below] node
  18755. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18756. \path[->,bend left=15] (F1-5) edge [above] node
  18757. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18758. \path[->,bend left=10] (F1-6) edge [below] node
  18759. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18760. \path[->,bend left=15] (C3-2) edge [right] node
  18761. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18762. \path[->,bend right=15] (x86-2) edge [right] node
  18763. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18764. \path[->,bend right=15] (x86-2-1) edge [below] node
  18765. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18766. \path[->,bend right=15] (x86-2-2) edge [right] node
  18767. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18768. \path[->,bend left=15] (x86-3) edge [above] node
  18769. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18770. \path[->,bend left=15] (x86-4) edge [right] node
  18771. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18772. \end{tikzpicture}
  18773. \fi}
  18774. {\if\edition\pythonEd\pythonColor
  18775. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18776. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18777. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18778. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18779. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18780. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18781. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18782. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18783. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18784. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18785. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18786. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18787. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18788. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18789. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18790. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18791. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18792. \path[->,bend left=15] (Lfun) edge [above] node
  18793. {\ttfamily\footnotesize shrink} (Lfun-2);
  18794. \path[->,bend left=15] (Lfun-2) edge [above] node
  18795. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18796. \path[->,bend left=15] (Lfun-3) edge [above] node
  18797. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18798. \path[->,bend left=15] (Lfun-4) edge [left] node
  18799. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18800. \path[->,bend left=15] (Lfun-5) edge [below] node
  18801. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18802. \path[->,bend right=15] (Lfun-6) edge [above] node
  18803. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18804. \path[->,bend right=15] (Lfun-7) edge [above] node
  18805. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18806. \path[->,bend right=15] (F1-2) edge [right] node
  18807. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18808. \path[->,bend right=15] (F1-3) edge [below] node
  18809. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18810. \path[->,bend left=15] (F1-5) edge [above] node
  18811. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18812. \path[->,bend left=10] (F1-6) edge [below] node
  18813. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18814. \path[->,bend right=15] (C3-2) edge [right] node
  18815. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18816. \path[->,bend right=15] (x86-2) edge [below] node
  18817. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18818. \path[->,bend right=15] (x86-3) edge [below] node
  18819. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18820. \path[->,bend left=15] (x86-4) edge [above] node
  18821. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18822. \end{tikzpicture}
  18823. \fi}
  18824. \end{tcolorbox}
  18825. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18826. \label{fig:Ldyn-passes}
  18827. \end{figure}
  18828. % Further Reading
  18829. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18830. %% {\if\edition\pythonEd\pythonColor
  18831. %% \chapter{Objects}
  18832. %% \label{ch:Lobject}
  18833. %% \index{subject}{objects}
  18834. %% \index{subject}{classes}
  18835. %% \setcounter{footnote}{0}
  18836. %% \fi}
  18837. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18838. \chapter{Gradual Typing}
  18839. \label{ch:Lgrad}
  18840. \index{subject}{gradual typing}
  18841. \setcounter{footnote}{0}
  18842. This chapter studies the language \LangGrad{}, in which the programmer
  18843. can choose between static and dynamic type checking in different parts
  18844. of a program, thereby mixing the statically typed \LangLam{} language
  18845. with the dynamically typed \LangDyn{}. There are several approaches to
  18846. mixing static and dynamic typing, including multilanguage
  18847. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18848. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18849. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18850. programmer controls the amount of static versus dynamic checking by
  18851. adding or removing type annotations on parameters and
  18852. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18853. The definition of the concrete syntax of \LangGrad{} is shown in
  18854. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18855. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18856. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18857. annotations are optional, which is specified in the grammar using the
  18858. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18859. annotations are not optional, but we use the \CANYTY{} type when a type
  18860. annotation is absent.
  18861. %
  18862. Both the type checker and the interpreter for \LangGrad{} require some
  18863. interesting changes to enable gradual typing, which we discuss in the
  18864. next two sections.
  18865. \newcommand{\LgradGrammarRacket}{
  18866. \begin{array}{lcl}
  18867. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18868. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18869. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18870. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18871. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18872. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18873. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18874. \end{array}
  18875. }
  18876. \newcommand{\LgradASTRacket}{
  18877. \begin{array}{lcl}
  18878. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18879. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18880. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18881. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18882. \itm{op} &::=& \code{procedure-arity} \\
  18883. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18884. \end{array}
  18885. }
  18886. \newcommand{\LgradGrammarPython}{
  18887. \begin{array}{lcl}
  18888. \Type &::=& \key{Any}
  18889. \MID \key{int}
  18890. \MID \key{bool}
  18891. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18892. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18893. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18894. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18895. \MID \CARITY{\Exp} \\
  18896. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18897. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18898. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18899. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18900. \end{array}
  18901. }
  18902. \newcommand{\LgradASTPython}{
  18903. \begin{array}{lcl}
  18904. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18905. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18906. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18907. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18908. &\MID& \ARITY{\Exp} \\
  18909. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18910. \MID \RETURN{\Exp} \\
  18911. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18912. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18913. \end{array}
  18914. }
  18915. \begin{figure}[tbp]
  18916. \centering
  18917. \begin{tcolorbox}[colback=white]
  18918. \vspace{-5pt}
  18919. \small
  18920. {\if\edition\racketEd
  18921. \[
  18922. \begin{array}{l}
  18923. \gray{\LintGrammarRacket{}} \\ \hline
  18924. \gray{\LvarGrammarRacket{}} \\ \hline
  18925. \gray{\LifGrammarRacket{}} \\ \hline
  18926. \gray{\LwhileGrammarRacket} \\ \hline
  18927. \gray{\LtupGrammarRacket} \\ \hline
  18928. \LgradGrammarRacket \\
  18929. \begin{array}{lcl}
  18930. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18931. \end{array}
  18932. \end{array}
  18933. \]
  18934. \fi}
  18935. {\if\edition\pythonEd\pythonColor
  18936. \[
  18937. \begin{array}{l}
  18938. \gray{\LintGrammarPython{}} \\ \hline
  18939. \gray{\LvarGrammarPython{}} \\ \hline
  18940. \gray{\LifGrammarPython{}} \\ \hline
  18941. \gray{\LwhileGrammarPython} \\ \hline
  18942. \gray{\LtupGrammarPython} \\ \hline
  18943. \LgradGrammarPython \\
  18944. \begin{array}{lcl}
  18945. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18946. \end{array}
  18947. \end{array}
  18948. \]
  18949. \fi}
  18950. \end{tcolorbox}
  18951. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18952. \label{fig:Lgrad-concrete-syntax}
  18953. \index{subject}{L?@\LangGrad{} concrete syntax}
  18954. \end{figure}
  18955. \begin{figure}[tbp]
  18956. \centering
  18957. \begin{tcolorbox}[colback=white]
  18958. \small
  18959. {\if\edition\racketEd
  18960. \[
  18961. \begin{array}{l}
  18962. \gray{\LintOpAST} \\ \hline
  18963. \gray{\LvarASTRacket{}} \\ \hline
  18964. \gray{\LifASTRacket{}} \\ \hline
  18965. \gray{\LwhileASTRacket{}} \\ \hline
  18966. \gray{\LtupASTRacket{}} \\ \hline
  18967. \LgradASTRacket \\
  18968. \begin{array}{lcl}
  18969. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18970. \end{array}
  18971. \end{array}
  18972. \]
  18973. \fi}
  18974. {\if\edition\pythonEd\pythonColor
  18975. \[
  18976. \begin{array}{l}
  18977. \gray{\LintASTPython{}} \\ \hline
  18978. \gray{\LvarASTPython{}} \\ \hline
  18979. \gray{\LifASTPython{}} \\ \hline
  18980. \gray{\LwhileASTPython} \\ \hline
  18981. \gray{\LtupASTPython} \\ \hline
  18982. \LgradASTPython \\
  18983. \begin{array}{lcl}
  18984. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18985. \end{array}
  18986. \end{array}
  18987. \]
  18988. \fi}
  18989. \end{tcolorbox}
  18990. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18991. \label{fig:Lgrad-syntax}
  18992. \index{subject}{L?@\LangGrad{} abstract syntax}
  18993. \end{figure}
  18994. % TODO: more road map -Jeremy
  18995. %\clearpage
  18996. \section{Type Checking \LangGrad{}}
  18997. \label{sec:gradual-type-check}
  18998. We begin by discussing the type checking of a partially typed variant
  18999. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  19000. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  19001. statically typed, so there is nothing special happening there with
  19002. respect to type checking. On the other hand, the \code{inc} function
  19003. does not have type annotations, so the type checker assigns the type
  19004. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  19005. \code{+} operator inside \code{inc}. It expects both arguments to have
  19006. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  19007. a gradually typed language, such differences are allowed so long as
  19008. the types are \emph{consistent}; that is, they are equal except in
  19009. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  19010. is consistent with every other type. Figure~\ref{fig:consistent}
  19011. shows the definition of the
  19012. \racket{\code{consistent?}}\python{\code{consistent}} method.
  19013. %
  19014. So the type checker allows the \code{+} operator to be applied
  19015. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  19016. %
  19017. Next consider the call to the \code{map} function shown in
  19018. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  19019. tuple. The \code{inc} function has type
  19020. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  19021. but parameter \code{f} of \code{map} has type
  19022. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19023. The type checker for \LangGrad{} accepts this call because the two types are
  19024. consistent.
  19025. \begin{figure}[hbtp]
  19026. % gradual_test_9.rkt
  19027. \begin{tcolorbox}[colback=white]
  19028. {\if\edition\racketEd
  19029. \begin{lstlisting}
  19030. (define (map [f : (Integer -> Integer)]
  19031. [v : (Vector Integer Integer)])
  19032. : (Vector Integer Integer)
  19033. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19034. (define (inc x) (+ x 1))
  19035. (vector-ref (map inc (vector 0 41)) 1)
  19036. \end{lstlisting}
  19037. \fi}
  19038. {\if\edition\pythonEd\pythonColor
  19039. \begin{lstlisting}
  19040. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19041. return f(v[0]), f(v[1])
  19042. def inc(x):
  19043. return x + 1
  19044. t = map(inc, (0, 41))
  19045. print(t[1])
  19046. \end{lstlisting}
  19047. \fi}
  19048. \end{tcolorbox}
  19049. \caption{A partially typed version of the \code{map} example.}
  19050. \label{fig:gradual-map}
  19051. \end{figure}
  19052. \begin{figure}[tbp]
  19053. \begin{tcolorbox}[colback=white]
  19054. {\if\edition\racketEd
  19055. \begin{lstlisting}
  19056. (define/public (consistent? t1 t2)
  19057. (match* (t1 t2)
  19058. [('Integer 'Integer) #t]
  19059. [('Boolean 'Boolean) #t]
  19060. [('Void 'Void) #t]
  19061. [('Any t2) #t]
  19062. [(t1 'Any) #t]
  19063. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19064. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  19065. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19066. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  19067. (consistent? rt1 rt2))]
  19068. [(other wise) #f]))
  19069. \end{lstlisting}
  19070. \fi}
  19071. {\if\edition\pythonEd\pythonColor
  19072. \begin{lstlisting}
  19073. def consistent(self, t1, t2):
  19074. match (t1, t2):
  19075. case (AnyType(), _):
  19076. return True
  19077. case (_, AnyType()):
  19078. return True
  19079. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19080. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  19081. case (TupleType(ts1), TupleType(ts2)):
  19082. return all(map(self.consistent, ts1, ts2))
  19083. case (_, _):
  19084. return t1 == t2
  19085. \end{lstlisting}
  19086. \fi}
  19087. \vspace{-5pt}
  19088. \end{tcolorbox}
  19089. \caption{The consistency method on types.}
  19090. \label{fig:consistent}
  19091. \end{figure}
  19092. It is also helpful to consider how gradual typing handles programs with an
  19093. error, such as applying \code{map} to a function that sometimes
  19094. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  19095. type checker for \LangGrad{} accepts this program because the type of
  19096. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  19097. \code{map}; that is,
  19098. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  19099. is consistent with
  19100. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19101. One might say that a gradual type checker is optimistic in that it
  19102. accepts programs that might execute without a runtime type error.
  19103. %
  19104. The definition of the type checker for \LangGrad{} is shown in
  19105. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  19106. and \ref{fig:type-check-Lgradual-3}.
  19107. %% \begin{figure}[tp]
  19108. %% \centering
  19109. %% \fbox{
  19110. %% \begin{minipage}{0.96\textwidth}
  19111. %% \small
  19112. %% \[
  19113. %% \begin{array}{lcl}
  19114. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  19115. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  19116. %% \end{array}
  19117. %% \]
  19118. %% \end{minipage}
  19119. %% }
  19120. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  19121. %% \label{fig:Lgrad-prime-syntax}
  19122. %% \end{figure}
  19123. \begin{figure}[tbp]
  19124. \begin{tcolorbox}[colback=white]
  19125. {\if\edition\racketEd
  19126. \begin{lstlisting}
  19127. (define (map [f : (Integer -> Integer)]
  19128. [v : (Vector Integer Integer)])
  19129. : (Vector Integer Integer)
  19130. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19131. (define (inc x) (+ x 1))
  19132. (define (true) #t)
  19133. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  19134. (vector-ref (map maybe_inc (vector 0 41)) 0)
  19135. \end{lstlisting}
  19136. \fi}
  19137. {\if\edition\pythonEd\pythonColor
  19138. \begin{lstlisting}
  19139. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19140. return f(v[0]), f(v[1])
  19141. def inc(x):
  19142. return x + 1
  19143. def true():
  19144. return True
  19145. def maybe_inc(x):
  19146. return inc(x) if input_int() == 0 else true()
  19147. t = map(maybe_inc, (0, 41))
  19148. print(t[1])
  19149. \end{lstlisting}
  19150. \fi}
  19151. \vspace{-5pt}
  19152. \end{tcolorbox}
  19153. \caption{A variant of the \code{map} example with an error.}
  19154. \label{fig:map-maybe_inc}
  19155. \end{figure}
  19156. Running this program with input \code{1} triggers an
  19157. error when the \code{maybe\_inc} function returns
  19158. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19159. performs checking at runtime to ensure the integrity of the static
  19160. types, such as the
  19161. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19162. annotation on
  19163. parameter \code{f} of \code{map}.
  19164. Here we give a preview of how the runtime checking is accomplished;
  19165. the following sections provide the details.
  19166. The runtime checking is carried out by a new \code{Cast} AST node that
  19167. is generated in a new pass named \code{cast\_insert}. The output of
  19168. \code{cast\_insert} is a program in the \LangCast{} language, which
  19169. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19170. %
  19171. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19172. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19173. inserted every time the type checker encounters two types that are
  19174. consistent but not equal. In the \code{inc} function, \code{x} is
  19175. cast to \INTTY{} and the result of the \code{+} is cast to
  19176. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19177. is cast from
  19178. \racket{\code{(Any -> Any)}}
  19179. \python{\code{Callable[[Any], Any]}}
  19180. to
  19181. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19182. %
  19183. In the next section we see how to interpret the \code{Cast} node.
  19184. \begin{figure}[btp]
  19185. \begin{tcolorbox}[colback=white]
  19186. {\if\edition\racketEd
  19187. \begin{lstlisting}
  19188. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19189. : (Vector Integer Integer)
  19190. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19191. (define (inc [x : Any]) : Any
  19192. (cast (+ (cast x Any Integer) 1) Integer Any))
  19193. (define (true) : Any (cast #t Boolean Any))
  19194. (define (maybe_inc [x : Any]) : Any
  19195. (if (eq? 0 (read)) (inc x) (true)))
  19196. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19197. (vector 0 41)) 0)
  19198. \end{lstlisting}
  19199. \fi}
  19200. {\if\edition\pythonEd\pythonColor
  19201. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19202. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19203. return f(v[0]), f(v[1])
  19204. def inc(x : Any) -> Any:
  19205. return Cast(Cast(x, Any, int) + 1, int, Any)
  19206. def true() -> Any:
  19207. return Cast(True, bool, Any)
  19208. def maybe_inc(x : Any) -> Any:
  19209. return inc(x) if input_int() == 0 else true()
  19210. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19211. (0, 41))
  19212. print(t[1])
  19213. \end{lstlisting}
  19214. \fi}
  19215. \vspace{-5pt}
  19216. \end{tcolorbox}
  19217. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19218. and \code{maybe\_inc} example.}
  19219. \label{fig:map-cast}
  19220. \end{figure}
  19221. {\if\edition\pythonEd\pythonColor
  19222. \begin{figure}[tbp]
  19223. \begin{tcolorbox}[colback=white]
  19224. \begin{lstlisting}
  19225. class TypeCheckLgrad(TypeCheckLlambda):
  19226. def type_check_exp(self, e, env) -> Type:
  19227. match e:
  19228. case Name(id):
  19229. return env[id]
  19230. case Constant(value) if isinstance(value, bool):
  19231. return BoolType()
  19232. case Constant(value) if isinstance(value, int):
  19233. return IntType()
  19234. case Call(Name('input_int'), []):
  19235. return IntType()
  19236. case BinOp(left, op, right):
  19237. left_type = self.type_check_exp(left, env)
  19238. self.check_consistent(left_type, IntType(), left)
  19239. right_type = self.type_check_exp(right, env)
  19240. self.check_consistent(right_type, IntType(), right)
  19241. return IntType()
  19242. case IfExp(test, body, orelse):
  19243. test_t = self.type_check_exp(test, env)
  19244. self.check_consistent(test_t, BoolType(), test)
  19245. body_t = self.type_check_exp(body, env)
  19246. orelse_t = self.type_check_exp(orelse, env)
  19247. self.check_consistent(body_t, orelse_t, e)
  19248. return self.join_types(body_t, orelse_t)
  19249. case Call(func, args):
  19250. func_t = self.type_check_exp(func, env)
  19251. args_t = [self.type_check_exp(arg, env) for arg in args]
  19252. match func_t:
  19253. case FunctionType(params_t, return_t) \
  19254. if len(params_t) == len(args_t):
  19255. for (arg_t, param_t) in zip(args_t, params_t):
  19256. self.check_consistent(param_t, arg_t, e)
  19257. return return_t
  19258. case AnyType():
  19259. return AnyType()
  19260. case _:
  19261. raise Exception('type_check_exp: in call, unexpected '
  19262. + repr(func_t))
  19263. ...
  19264. case _:
  19265. raise Exception('type_check_exp: unexpected ' + repr(e))
  19266. \end{lstlisting}
  19267. \end{tcolorbox}
  19268. \caption{Type checking expressions in the \LangGrad{} language.}
  19269. \label{fig:type-check-Lgradual-1}
  19270. \end{figure}
  19271. \begin{figure}[tbp]
  19272. \begin{tcolorbox}[colback=white]
  19273. \begin{lstlisting}
  19274. def check_exp(self, e, expected_ty, env):
  19275. match e:
  19276. case Lambda(params, body):
  19277. match expected_ty:
  19278. case FunctionType(params_t, return_t):
  19279. new_env = env.copy().update(zip(params, params_t))
  19280. e.has_type = expected_ty
  19281. body_ty = self.type_check_exp(body, new_env)
  19282. self.check_consistent(body_ty, return_t)
  19283. case AnyType():
  19284. new_env = env.copy().update((p, AnyType()) for p in params)
  19285. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19286. body_ty = self.type_check_exp(body, new_env)
  19287. case _:
  19288. raise Exception('lambda is not of type ' + str(expected_ty))
  19289. case _:
  19290. e_ty = self.type_check_exp(e, env)
  19291. self.check_consistent(e_ty, expected_ty, e)
  19292. \end{lstlisting}
  19293. \end{tcolorbox}
  19294. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19295. \label{fig:type-check-Lgradual-2}
  19296. \end{figure}
  19297. \begin{figure}[tbp]
  19298. \begin{tcolorbox}[colback=white]
  19299. \begin{lstlisting}
  19300. def type_check_stmt(self, s, env, return_type):
  19301. match s:
  19302. case Assign([Name(id)], value):
  19303. value_ty = self.type_check_exp(value, env)
  19304. if id in env:
  19305. self.check_consistent(env[id], value_ty, value)
  19306. else:
  19307. env[id] = value_ty
  19308. ...
  19309. case _:
  19310. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19311. def type_check_stmts(self, ss, env, return_type):
  19312. for s in ss:
  19313. self.type_check_stmt(s, env, return_type)
  19314. \end{lstlisting}
  19315. \end{tcolorbox}
  19316. \caption{Type checking statements in the \LangGrad{} language.}
  19317. \label{fig:type-check-Lgradual-3}
  19318. \end{figure}
  19319. \clearpage
  19320. \begin{figure}[tbp]
  19321. \begin{tcolorbox}[colback=white]
  19322. \begin{lstlisting}
  19323. def join_types(self, t1, t2):
  19324. match (t1, t2):
  19325. case (AnyType(), _):
  19326. return t2
  19327. case (_, AnyType()):
  19328. return t1
  19329. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19330. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19331. self.join_types(rt1,rt2))
  19332. case (TupleType(ts1), TupleType(ts2)):
  19333. return TupleType(list(map(self.join_types, ts1, ts2)))
  19334. case (_, _):
  19335. return t1
  19336. def check_consistent(self, t1, t2, e):
  19337. if not self.consistent(t1, t2):
  19338. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19339. + repr(t2) + ' in ' + repr(e))
  19340. \end{lstlisting}
  19341. \end{tcolorbox}
  19342. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19343. \label{fig:type-check-Lgradual-aux}
  19344. \end{figure}
  19345. \fi}
  19346. {\if\edition\racketEd
  19347. \begin{figure}[tbp]
  19348. \begin{tcolorbox}[colback=white]
  19349. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19350. (define/override (type-check-exp env)
  19351. (lambda (e)
  19352. (define recur (type-check-exp env))
  19353. (match e
  19354. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19355. (define-values (new-es ts)
  19356. (for/lists (exprs types) ([e es])
  19357. (recur e)))
  19358. (define t-ret (type-check-op op ts e))
  19359. (values (Prim op new-es) t-ret)]
  19360. [(Prim 'eq? (list e1 e2))
  19361. (define-values (e1^ t1) (recur e1))
  19362. (define-values (e2^ t2) (recur e2))
  19363. (check-consistent? t1 t2 e)
  19364. (define T (meet t1 t2))
  19365. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19366. [(Prim 'and (list e1 e2))
  19367. (recur (If e1 e2 (Bool #f)))]
  19368. [(Prim 'or (list e1 e2))
  19369. (define tmp (gensym 'tmp))
  19370. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19371. [(If e1 e2 e3)
  19372. (define-values (e1^ T1) (recur e1))
  19373. (define-values (e2^ T2) (recur e2))
  19374. (define-values (e3^ T3) (recur e3))
  19375. (check-consistent? T1 'Boolean e)
  19376. (check-consistent? T2 T3 e)
  19377. (define Tif (meet T2 T3))
  19378. (values (If e1^ e2^ e3^) Tif)]
  19379. [(SetBang x e1)
  19380. (define-values (e1^ T1) (recur e1))
  19381. (define varT (dict-ref env x))
  19382. (check-consistent? T1 varT e)
  19383. (values (SetBang x e1^) 'Void)]
  19384. [(WhileLoop e1 e2)
  19385. (define-values (e1^ T1) (recur e1))
  19386. (check-consistent? T1 'Boolean e)
  19387. (define-values (e2^ T2) ((type-check-exp env) e2))
  19388. (values (WhileLoop e1^ e2^) 'Void)]
  19389. [(Prim 'vector-length (list e1))
  19390. (define-values (e1^ t) (recur e1))
  19391. (match t
  19392. [`(Vector ,ts ...)
  19393. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19394. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19395. \end{lstlisting}
  19396. \end{tcolorbox}
  19397. \caption{Type checker for the \LangGrad{} language, part 1.}
  19398. \label{fig:type-check-Lgradual-1}
  19399. \end{figure}
  19400. \begin{figure}[tbp]
  19401. \begin{tcolorbox}[colback=white]
  19402. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19403. [(Prim 'vector-ref (list e1 e2))
  19404. (define-values (e1^ t1) (recur e1))
  19405. (define-values (e2^ t2) (recur e2))
  19406. (check-consistent? t2 'Integer e)
  19407. (match t1
  19408. [`(Vector ,ts ...)
  19409. (match e2^
  19410. [(Int i)
  19411. (unless (and (0 . <= . i) (i . < . (length ts)))
  19412. (error 'type-check "invalid index ~a in ~a" i e))
  19413. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19414. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19415. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19416. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19417. [(Prim 'vector-set! (list e1 e2 e3) )
  19418. (define-values (e1^ t1) (recur e1))
  19419. (define-values (e2^ t2) (recur e2))
  19420. (define-values (e3^ t3) (recur e3))
  19421. (check-consistent? t2 'Integer e)
  19422. (match t1
  19423. [`(Vector ,ts ...)
  19424. (match e2^
  19425. [(Int i)
  19426. (unless (and (0 . <= . i) (i . < . (length ts)))
  19427. (error 'type-check "invalid index ~a in ~a" i e))
  19428. (check-consistent? (list-ref ts i) t3 e)
  19429. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19430. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19431. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19432. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19433. [(Apply e1 e2s)
  19434. (define-values (e1^ T1) (recur e1))
  19435. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19436. (match T1
  19437. [`(,T1ps ... -> ,T1rt)
  19438. (for ([T2 T2s] [Tp T1ps])
  19439. (check-consistent? T2 Tp e))
  19440. (values (Apply e1^ e2s^) T1rt)]
  19441. [`Any (values (Apply e1^ e2s^) 'Any)]
  19442. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19443. [(Lambda params Tr e1)
  19444. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19445. (match p
  19446. [`[,x : ,T] (values x T)]
  19447. [(? symbol? x) (values x 'Any)])))
  19448. (define-values (e1^ T1)
  19449. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19450. (check-consistent? Tr T1 e)
  19451. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19452. `(,@Ts -> ,Tr))]
  19453. [else ((super type-check-exp env) e)]
  19454. )))
  19455. \end{lstlisting}
  19456. \end{tcolorbox}
  19457. \caption{Type checker for the \LangGrad{} language, part 2.}
  19458. \label{fig:type-check-Lgradual-2}
  19459. \end{figure}
  19460. \begin{figure}[tbp]
  19461. \begin{tcolorbox}[colback=white]
  19462. \begin{lstlisting}
  19463. (define/override (type-check-def env)
  19464. (lambda (e)
  19465. (match e
  19466. [(Def f params rt info body)
  19467. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19468. (match p
  19469. [`[,x : ,T] (values x T)]
  19470. [(? symbol? x) (values x 'Any)])))
  19471. (define new-env (append (map cons xs ps) env))
  19472. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19473. (check-consistent? ty^ rt e)
  19474. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19475. [else (error 'type-check "ill-formed function definition ~a" e)]
  19476. )))
  19477. (define/override (type-check-program e)
  19478. (match e
  19479. [(Program info body)
  19480. (define-values (body^ ty) ((type-check-exp '()) body))
  19481. (check-consistent? ty 'Integer e)
  19482. (ProgramDefsExp info '() body^)]
  19483. [(ProgramDefsExp info ds body)
  19484. (define new-env (for/list ([d ds])
  19485. (cons (Def-name d) (fun-def-type d))))
  19486. (define ds^ (for/list ([d ds])
  19487. ((type-check-def new-env) d)))
  19488. (define-values (body^ ty) ((type-check-exp new-env) body))
  19489. (check-consistent? ty 'Integer e)
  19490. (ProgramDefsExp info ds^ body^)]
  19491. [else (super type-check-program e)]))
  19492. \end{lstlisting}
  19493. \end{tcolorbox}
  19494. \caption{Type checker for the \LangGrad{} language, part 3.}
  19495. \label{fig:type-check-Lgradual-3}
  19496. \end{figure}
  19497. \begin{figure}[tbp]
  19498. \begin{tcolorbox}[colback=white]
  19499. \begin{lstlisting}
  19500. (define/public (join t1 t2)
  19501. (match* (t1 t2)
  19502. [('Integer 'Integer) 'Integer]
  19503. [('Boolean 'Boolean) 'Boolean]
  19504. [('Void 'Void) 'Void]
  19505. [('Any t2) t2]
  19506. [(t1 'Any) t1]
  19507. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19508. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19509. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19510. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19511. -> ,(join rt1 rt2))]))
  19512. (define/public (meet t1 t2)
  19513. (match* (t1 t2)
  19514. [('Integer 'Integer) 'Integer]
  19515. [('Boolean 'Boolean) 'Boolean]
  19516. [('Void 'Void) 'Void]
  19517. [('Any t2) 'Any]
  19518. [(t1 'Any) 'Any]
  19519. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19520. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19521. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19522. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19523. -> ,(meet rt1 rt2))]))
  19524. (define/public (check-consistent? t1 t2 e)
  19525. (unless (consistent? t1 t2)
  19526. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19527. (define explicit-prim-ops
  19528. (set-union
  19529. (type-predicates)
  19530. (set 'procedure-arity 'eq? 'not 'and 'or
  19531. 'vector 'vector-length 'vector-ref 'vector-set!
  19532. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19533. (define/override (fun-def-type d)
  19534. (match d
  19535. [(Def f params rt info body)
  19536. (define ps
  19537. (for/list ([p params])
  19538. (match p
  19539. [`[,x : ,T] T]
  19540. [(? symbol?) 'Any]
  19541. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19542. `(,@ps -> ,rt)]
  19543. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19544. \end{lstlisting}
  19545. \end{tcolorbox}
  19546. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19547. \label{fig:type-check-Lgradual-aux}
  19548. \end{figure}
  19549. \fi}
  19550. \section{Interpreting \LangCast{} }
  19551. \label{sec:interp-casts}
  19552. The runtime behavior of casts involving simple types such as
  19553. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19554. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19555. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19556. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19557. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19558. operator, by checking the value's tag and either retrieving
  19559. the underlying integer or signaling an error if the tag is not the
  19560. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19561. %
  19562. Things get more interesting with casts involving
  19563. \racket{function and tuple types}\python{function, tuple, and array types}.
  19564. Consider the cast of the function \code{maybe\_inc} from
  19565. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19566. to
  19567. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19568. shown in figure~\ref{fig:map-maybe_inc}.
  19569. When the \code{maybe\_inc} function flows through
  19570. this cast at runtime, we don't know whether it will return
  19571. an integer, because that depends on the input from the user.
  19572. The \LangCast{} interpreter therefore delays the checking
  19573. of the cast until the function is applied. To do so it
  19574. wraps \code{maybe\_inc} in a new function that casts its parameter
  19575. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19576. casts the return value from \CANYTY{} to \INTTY{}.
  19577. {\if\edition\pythonEd\pythonColor
  19578. %
  19579. There are further complications regarding casts on mutable data,
  19580. such as the \code{list} type introduced in
  19581. the challenge assignment of section~\ref{sec:arrays}.
  19582. %
  19583. \fi}
  19584. %
  19585. Consider the example presented in figure~\ref{fig:map-bang} that
  19586. defines a partially typed version of \code{map} whose parameter
  19587. \code{v} has type
  19588. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19589. and that updates \code{v} in place
  19590. instead of returning a new tuple. We name this function
  19591. \code{map\_inplace}. We apply \code{map\_inplace} to
  19592. \racket{a tuple}\python{an array} of integers, so the type checker
  19593. inserts a cast from
  19594. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19595. to
  19596. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19597. A naive way for the \LangCast{} interpreter to cast between
  19598. \racket{tuple}\python{array} types would be to build a new
  19599. \racket{tuple}\python{array} whose elements are the result
  19600. of casting each of the original elements to the target
  19601. type. However, this approach is not valid for mutable data structures.
  19602. In the example of figure~\ref{fig:map-bang},
  19603. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19604. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19605. the original one.
  19606. Instead the interpreter needs to create a new kind of value, a
  19607. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19608. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19609. and then applies a
  19610. cast to the resulting value. On a write, the proxy casts the argument
  19611. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19612. \racket{
  19613. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19614. \code{0} from \INTTY{} to \CANYTY{}.
  19615. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19616. from \CANYTY{} to \INTTY{}.
  19617. }
  19618. \python{
  19619. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19620. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19621. For the subscript on the left of the assignment,
  19622. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19623. }
  19624. Finally we consider casts between the \CANYTY{} type and higher-order types
  19625. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19626. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19627. have a type annotation, so it is given type \CANYTY{}. In the call to
  19628. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19629. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19630. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19631. \code{Inject}, but that doesn't work because
  19632. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19633. a flat type. Instead, we must first cast to
  19634. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19635. and then inject to \CANYTY{}.
  19636. \begin{figure}[tbp]
  19637. \begin{tcolorbox}[colback=white]
  19638. % gradual_test_11.rkt
  19639. {\if\edition\racketEd
  19640. \begin{lstlisting}
  19641. (define (map_inplace [f : (Any -> Any)]
  19642. [v : (Vector Any Any)]) : Void
  19643. (begin
  19644. (vector-set! v 0 (f (vector-ref v 0)))
  19645. (vector-set! v 1 (f (vector-ref v 1)))))
  19646. (define (inc x) (+ x 1))
  19647. (let ([v (vector 0 41)])
  19648. (begin (map_inplace inc v) (vector-ref v 1)))
  19649. \end{lstlisting}
  19650. \fi}
  19651. {\if\edition\pythonEd\pythonColor
  19652. \begin{lstlisting}
  19653. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19654. i = 0
  19655. while i != len(v):
  19656. v[i] = f(v[i])
  19657. i = i + 1
  19658. def inc(x : int) -> int:
  19659. return x + 1
  19660. v = [0, 41]
  19661. map_inplace(inc, v)
  19662. print(v[1])
  19663. \end{lstlisting}
  19664. \fi}
  19665. \end{tcolorbox}
  19666. \caption{An example involving casts on arrays.}
  19667. \label{fig:map-bang}
  19668. \end{figure}
  19669. \begin{figure}[btp]
  19670. \begin{tcolorbox}[colback=white]
  19671. {\if\edition\racketEd
  19672. \begin{lstlisting}
  19673. (define (map_inplace [f : (Any -> Any)] v) : Void
  19674. (begin
  19675. (vector-set! v 0 (f (vector-ref v 0)))
  19676. (vector-set! v 1 (f (vector-ref v 1)))))
  19677. (define (inc x) (+ x 1))
  19678. (let ([v (vector 0 41)])
  19679. (begin (map_inplace inc v) (vector-ref v 1)))
  19680. \end{lstlisting}
  19681. \fi}
  19682. {\if\edition\pythonEd\pythonColor
  19683. \begin{lstlisting}
  19684. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19685. i = 0
  19686. while i != len(v):
  19687. v[i] = f(v[i])
  19688. i = i + 1
  19689. def inc(x):
  19690. return x + 1
  19691. v = [0, 41]
  19692. map_inplace(inc, v)
  19693. print(v[1])
  19694. \end{lstlisting}
  19695. \fi}
  19696. \end{tcolorbox}
  19697. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19698. \label{fig:map-any}
  19699. \end{figure}
  19700. \begin{figure}[tbp]
  19701. \begin{tcolorbox}[colback=white]
  19702. {\if\edition\racketEd
  19703. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19704. (define/public (apply_cast v s t)
  19705. (match* (s t)
  19706. [(t1 t2) #:when (equal? t1 t2) v]
  19707. [('Any t2)
  19708. (match t2
  19709. [`(,ts ... -> ,rt)
  19710. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19711. (define v^ (apply-project v any->any))
  19712. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19713. [`(Vector ,ts ...)
  19714. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19715. (define v^ (apply-project v vec-any))
  19716. (apply_cast v^ vec-any `(Vector ,@ts))]
  19717. [else (apply-project v t2)])]
  19718. [(t1 'Any)
  19719. (match t1
  19720. [`(,ts ... -> ,rt)
  19721. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19722. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19723. (apply-inject v^ (any-tag any->any))]
  19724. [`(Vector ,ts ...)
  19725. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19726. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19727. (apply-inject v^ (any-tag vec-any))]
  19728. [else (apply-inject v (any-tag t1))])]
  19729. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19730. (define x (gensym 'x))
  19731. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19732. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19733. (define cast-writes
  19734. (for/list ([t1 ts1] [t2 ts2])
  19735. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19736. `(vector-proxy ,(vector v (apply vector cast-reads)
  19737. (apply vector cast-writes)))]
  19738. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19739. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19740. `(function ,xs ,(Cast
  19741. (Apply (Value v)
  19742. (for/list ([x xs][t1 ts1][t2 ts2])
  19743. (Cast (Var x) t2 t1)))
  19744. rt1 rt2) ())]
  19745. ))
  19746. \end{lstlisting}
  19747. \fi}
  19748. {\if\edition\pythonEd\pythonColor
  19749. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19750. def apply_cast(self, value, src, tgt):
  19751. match (src, tgt):
  19752. case (AnyType(), FunctionType(ps2, rt2)):
  19753. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19754. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19755. case (AnyType(), TupleType(ts2)):
  19756. anytup = TupleType([AnyType() for t1 in ts2])
  19757. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19758. case (AnyType(), ListType(t2)):
  19759. anylist = ListType([AnyType() for t1 in ts2])
  19760. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19761. case (AnyType(), AnyType()):
  19762. return value
  19763. case (AnyType(), _):
  19764. return self.apply_project(value, tgt)
  19765. case (FunctionType(ps1,rt1), AnyType()):
  19766. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19767. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19768. case (TupleType(ts1), AnyType()):
  19769. anytup = TupleType([AnyType() for t1 in ts1])
  19770. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19771. case (ListType(t1), AnyType()):
  19772. anylist = ListType(AnyType())
  19773. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19774. case (_, AnyType()):
  19775. return self.apply_inject(value, src)
  19776. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19777. params = [generate_name('x') for p in ps2]
  19778. args = [Cast(Name(x), t2, t1)
  19779. for (x,t1,t2) in zip(params, ps1, ps2)]
  19780. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19781. return Function('cast', params, [Return(body)], {})
  19782. case (TupleType(ts1), TupleType(ts2)):
  19783. x = generate_name('x')
  19784. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19785. for (t1,t2) in zip(ts1,ts2)]
  19786. return ProxiedTuple(value, reads)
  19787. case (ListType(t1), ListType(t2)):
  19788. x = generate_name('x')
  19789. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19790. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19791. return ProxiedList(value, read, write)
  19792. case (t1, t2) if t1 == t2:
  19793. return value
  19794. case (t1, t2):
  19795. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19796. def apply_inject(self, value, src):
  19797. return Tagged(value, self.type_to_tag(src))
  19798. def apply_project(self, value, tgt):
  19799. match value:
  19800. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19801. return val
  19802. case _:
  19803. raise Exception('apply_project, unexpected ' + repr(value))
  19804. \end{lstlisting}
  19805. \fi}
  19806. \end{tcolorbox}
  19807. \caption{The \code{apply\_cast} auxiliary method.}
  19808. \label{fig:apply_cast}
  19809. \end{figure}
  19810. The \LangCast{} interpreter uses an auxiliary function named
  19811. \code{apply\_cast} to cast a value from a source type to a target type,
  19812. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19813. the kinds of casts that we've discussed in this section.
  19814. %
  19815. The definition of the interpreter for \LangCast{} is shown in
  19816. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19817. dispatching to \code{apply\_cast}.
  19818. \racket{To handle the addition of tuple
  19819. proxies, we update the tuple primitives in \code{interp-op} using the
  19820. functions given in figure~\ref{fig:guarded-tuple}.}
  19821. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19822. \begin{figure}[tbp]
  19823. \begin{tcolorbox}[colback=white]
  19824. {\if\edition\racketEd
  19825. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19826. (define interp-Lcast-class
  19827. (class interp-Llambda-class
  19828. (super-new)
  19829. (inherit apply-fun apply-inject apply-project)
  19830. (define/override (interp-op op)
  19831. (match op
  19832. ['vector-length guarded-vector-length]
  19833. ['vector-ref guarded-vector-ref]
  19834. ['vector-set! guarded-vector-set!]
  19835. ['any-vector-ref (lambda (v i)
  19836. (match v [`(tagged ,v^ ,tg)
  19837. (guarded-vector-ref v^ i)]))]
  19838. ['any-vector-set! (lambda (v i a)
  19839. (match v [`(tagged ,v^ ,tg)
  19840. (guarded-vector-set! v^ i a)]))]
  19841. ['any-vector-length (lambda (v)
  19842. (match v [`(tagged ,v^ ,tg)
  19843. (guarded-vector-length v^)]))]
  19844. [else (super interp-op op)]
  19845. ))
  19846. (define/override ((interp-exp env) e)
  19847. (define (recur e) ((interp-exp env) e))
  19848. (match e
  19849. [(Value v) v]
  19850. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19851. [else ((super interp-exp env) e)]))
  19852. ))
  19853. (define (interp-Lcast p)
  19854. (send (new interp-Lcast-class) interp-program p))
  19855. \end{lstlisting}
  19856. \fi}
  19857. {\if\edition\pythonEd\pythonColor
  19858. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19859. class InterpLcast(InterpLany):
  19860. def interp_exp(self, e, env):
  19861. match e:
  19862. case Cast(value, src, tgt):
  19863. v = self.interp_exp(value, env)
  19864. return self.apply_cast(v, src, tgt)
  19865. case ValueExp(value):
  19866. return value
  19867. ...
  19868. case _:
  19869. return super().interp_exp(e, env)
  19870. \end{lstlisting}
  19871. \fi}
  19872. \end{tcolorbox}
  19873. \caption{The interpreter for \LangCast{}.}
  19874. \label{fig:interp-Lcast}
  19875. \end{figure}
  19876. {\if\edition\racketEd
  19877. \begin{figure}[tbp]
  19878. \begin{tcolorbox}[colback=white]
  19879. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19880. (define (guarded-vector-ref vec i)
  19881. (match vec
  19882. [`(vector-proxy ,proxy)
  19883. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19884. (define rd (vector-ref (vector-ref proxy 1) i))
  19885. (apply-fun rd (list val) 'guarded-vector-ref)]
  19886. [else (vector-ref vec i)]))
  19887. (define (guarded-vector-set! vec i arg)
  19888. (match vec
  19889. [`(vector-proxy ,proxy)
  19890. (define wr (vector-ref (vector-ref proxy 2) i))
  19891. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19892. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19893. [else (vector-set! vec i arg)]))
  19894. (define (guarded-vector-length vec)
  19895. (match vec
  19896. [`(vector-proxy ,proxy)
  19897. (guarded-vector-length (vector-ref proxy 0))]
  19898. [else (vector-length vec)]))
  19899. \end{lstlisting}
  19900. %% {\if\edition\pythonEd\pythonColor
  19901. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19902. %% UNDER CONSTRUCTION
  19903. %% \end{lstlisting}
  19904. %% \fi}
  19905. \end{tcolorbox}
  19906. \caption{The \code{guarded-vector} auxiliary functions.}
  19907. \label{fig:guarded-tuple}
  19908. \end{figure}
  19909. \fi}
  19910. {\if\edition\pythonEd\pythonColor
  19911. \section{Overload Resolution }
  19912. \label{sec:gradual-resolution}
  19913. Recall that when we added support for arrays in
  19914. section~\ref{sec:arrays}, the syntax for the array operations were the
  19915. same as for tuple operations (for example, accessing an element and
  19916. getting the length). So we performed overload resolution, with a pass
  19917. named \code{resolve}, to separate the array and tuple operations. In
  19918. particular, we introduced the primitives \code{array\_load},
  19919. \code{array\_store}, and \code{array\_len}.
  19920. For gradual typing, we further overload these operators to work on
  19921. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19922. updated with new cases for the \CANYTY{} type, translating the element
  19923. access and length operations to the primitives \code{any\_load},
  19924. \code{any\_store}, and \code{any\_len}.
  19925. \fi}
  19926. \section{Cast Insertion }
  19927. \label{sec:gradual-insert-casts}
  19928. In our discussion of type checking of \LangGrad{}, we mentioned how
  19929. the runtime aspect of type checking is carried out by the \code{Cast}
  19930. AST node, which is added to the program by a new pass named
  19931. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19932. language. We now discuss the details of this pass.
  19933. The \code{cast\_insert} pass is closely related to the type checker
  19934. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19935. In particular, the type checker allows implicit casts between
  19936. consistent types. The job of the \code{cast\_insert} pass is to make
  19937. those casts explicit. It does so by inserting
  19938. \code{Cast} nodes into the AST.
  19939. %
  19940. For the most part, the implicit casts occur in places where the type
  19941. checker checks two types for consistency. Consider the case for
  19942. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19943. checker requires that the type of the left operand is consistent with
  19944. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19945. \code{Cast} around the left operand, converting from its type to
  19946. \INTTY{}. The story is similar for the right operand. It is not always
  19947. necessary to insert a cast, for example, if the left operand already has type
  19948. \INTTY{} then there is no need for a \code{Cast}.
  19949. Some of the implicit casts are not as straightforward. One such case
  19950. arises with the
  19951. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19952. see that the type checker requires that the two branches have
  19953. consistent types and that type of the conditional expression is the
  19954. meet of the branches' types. In the target language \LangCast{}, both
  19955. branches will need to have the same type, and that type
  19956. will be the type of the conditional expression. Thus, each branch requires
  19957. a \code{Cast} to convert from its type to the meet of the branches' types.
  19958. The case for the function call exhibits another interesting situation. If
  19959. the function expression is of type \CANYTY{}, then it needs to be cast
  19960. to a function type so that it can be used in a function call in
  19961. \LangCast{}. Which function type should it be cast to? The parameter
  19962. and return types are unknown, so we can simply use \CANYTY{} for all
  19963. of them. Furthermore, in \LangCast{} the argument types will need to
  19964. exactly match the parameter types, so we must cast all the arguments
  19965. to type \CANYTY{} (if they are not already of that type).
  19966. {\if\edition\racketEd
  19967. %
  19968. Likewise, the cases for the tuple operators \code{vector-length},
  19969. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19970. where the tuple expression is of type \CANYTY{}. Instead of
  19971. handling these situations with casts, we recommend translating
  19972. the special-purpose variants of the tuple operators that handle
  19973. tuples of type \CANYTY{}: \code{any-vector-length},
  19974. \code{any-vector-ref}, and \code{any-vector-set!}.
  19975. %
  19976. \fi}
  19977. \section{Lower Casts }
  19978. \label{sec:lower_casts}
  19979. The next step in the journey toward x86 is the \code{lower\_casts}
  19980. pass that translates the casts in \LangCast{} to the lower-level
  19981. \code{Inject} and \code{Project} operators and new operators for
  19982. proxies, extending the \LangLam{} language to \LangProxy{}.
  19983. The \LangProxy{} language can also be described as an extension of
  19984. \LangAny{}, with the addition of proxies. We recommend creating an
  19985. auxiliary function named \code{lower\_cast} that takes an expression
  19986. (in \LangCast{}), a source type, and a target type and translates it
  19987. to an expression in \LangProxy{}.
  19988. The \code{lower\_cast} function can follow a code structure similar to
  19989. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19990. the interpreter for \LangCast{}, because it must handle the same cases
  19991. as \code{apply\_cast} and it needs to mimic the behavior of
  19992. \code{apply\_cast}. The most interesting cases concern
  19993. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19994. {\if\edition\racketEd
  19995. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19996. type to another tuple type is accomplished by creating a proxy that
  19997. intercepts the operations on the underlying tuple. Here we make the
  19998. creation of the proxy explicit with the \code{vector-proxy} AST
  19999. node. It takes three arguments: the first is an expression for the
  20000. tuple, the second is a tuple of functions for casting an element that is
  20001. being read from the tuple, and the third is a tuple of functions for
  20002. casting an element that is being written to the array. You can create
  20003. the functions for reading and writing using lambda expressions. Also,
  20004. as we show in the next section, we need to differentiate these tuples
  20005. of functions from the user-created ones, so we recommend using a new
  20006. AST node named \code{raw-vector} instead of \code{vector}.
  20007. %
  20008. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  20009. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  20010. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  20011. \fi}
  20012. {\if\edition\pythonEd\pythonColor
  20013. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  20014. type to another array type is accomplished by creating a proxy that
  20015. intercepts the operations on the underlying array. Here we make the
  20016. creation of the proxy explicit with the \code{ListProxy} AST node. It
  20017. takes fives arguments: the first is an expression for the array, the
  20018. second is a function for casting an element that is being read from
  20019. the array, the third is a function for casting an element that is
  20020. being written to the array, the fourth is the type of the underlying
  20021. array, and the fifth is the type of the proxied array. You can create
  20022. the functions for reading and writing using lambda expressions.
  20023. A cast between two tuple types can be handled in a similar manner. We
  20024. create a proxy with the \code{TupleProxy} AST node. Tuples are
  20025. immutable, so there is no need for a function to cast the value during
  20026. a write. Because there is a separate element type for each slot in
  20027. the tuple, we need more than one function for casting during a read:
  20028. we need a tuple of functions.
  20029. %
  20030. Also, as we show in the next section, we need to differentiate these
  20031. tuples from the user-created ones, so we recommend using a new AST
  20032. node named \code{RawTuple} instead of \code{Tuple} to create the
  20033. tuples of functions.
  20034. %
  20035. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  20036. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  20037. that involves casting an array of integers to an array of \CANYTY{}.
  20038. \fi}
  20039. \begin{figure}[tbp]
  20040. \begin{tcolorbox}[colback=white]
  20041. {\if\edition\racketEd
  20042. \begin{lstlisting}
  20043. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  20044. (begin
  20045. (vector-set! v 0 (f (vector-ref v 0)))
  20046. (vector-set! v 1 (f (vector-ref v 1)))))
  20047. (define (inc [x : Any]) : Any
  20048. (inject (+ (project x Integer) 1) Integer))
  20049. (let ([v (vector 0 41)])
  20050. (begin
  20051. (map_inplace inc (vector-proxy v
  20052. (raw-vector (lambda: ([x9 : Integer]) : Any
  20053. (inject x9 Integer))
  20054. (lambda: ([x9 : Integer]) : Any
  20055. (inject x9 Integer)))
  20056. (raw-vector (lambda: ([x9 : Any]) : Integer
  20057. (project x9 Integer))
  20058. (lambda: ([x9 : Any]) : Integer
  20059. (project x9 Integer)))))
  20060. (vector-ref v 1)))
  20061. \end{lstlisting}
  20062. \fi}
  20063. {\if\edition\pythonEd\pythonColor
  20064. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20065. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  20066. i = 0
  20067. while i != array_len(v):
  20068. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  20069. i = (i + 1)
  20070. def inc(x : int) -> int:
  20071. return (x + 1)
  20072. def main() -> int:
  20073. v = [0, 41]
  20074. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  20075. print(array_load(v, 1))
  20076. return 0
  20077. \end{lstlisting}
  20078. \fi}
  20079. \end{tcolorbox}
  20080. \caption{Output of \code{lower\_casts} on the example shown in
  20081. figure~\ref{fig:map-bang}.}
  20082. \label{fig:map-bang-lower-cast}
  20083. \end{figure}
  20084. A cast from one function type to another function type is accomplished
  20085. by generating a \code{lambda} whose parameter and return types match
  20086. the target function type. The body of the \code{lambda} should cast
  20087. the parameters from the target type to the source type. (Yes,
  20088. backward! Functions are contravariant\index{subject}{contravariant}
  20089. in the parameters.) Afterward, call the underlying function and then
  20090. cast the result from the source return type to the target return type.
  20091. Figure~\ref{fig:map-lower-cast} shows the output of the
  20092. \code{lower\_casts} pass on the \code{map} example given in
  20093. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  20094. call to \code{map} is wrapped in a \code{lambda}.
  20095. \begin{figure}[tbp]
  20096. \begin{tcolorbox}[colback=white]
  20097. {\if\edition\racketEd
  20098. \begin{lstlisting}
  20099. (define (map [f : (Integer -> Integer)]
  20100. [v : (Vector Integer Integer)])
  20101. : (Vector Integer Integer)
  20102. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20103. (define (inc [x : Any]) : Any
  20104. (inject (+ (project x Integer) 1) Integer))
  20105. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  20106. (project (inc (inject x9 Integer)) Integer))
  20107. (vector 0 41)) 1)
  20108. \end{lstlisting}
  20109. \fi}
  20110. {\if\edition\pythonEd\pythonColor
  20111. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20112. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  20113. return (f(v[0]), f(v[1]),)
  20114. def inc(x : any) -> any:
  20115. return inject((project(x, int) + 1), int)
  20116. def main() -> int:
  20117. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  20118. print(t[1])
  20119. return 0
  20120. \end{lstlisting}
  20121. \fi}
  20122. \end{tcolorbox}
  20123. \caption{Output of \code{lower\_casts} on the example shown in
  20124. figure~\ref{fig:gradual-map}.}
  20125. \label{fig:map-lower-cast}
  20126. \end{figure}
  20127. %\pagebreak
  20128. \section{Differentiate Proxies }
  20129. \label{sec:differentiate-proxies}
  20130. So far, the responsibility of differentiating tuples and tuple proxies
  20131. has been the job of the interpreter.
  20132. %
  20133. \racket{For example, the interpreter for \LangCast{} implements
  20134. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  20135. figure~\ref{fig:guarded-tuple}.}
  20136. %
  20137. In the \code{differentiate\_proxies} pass we shift this responsibility
  20138. to the generated code.
  20139. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  20140. we used the type \TUPLETYPENAME{} for both
  20141. real tuples and tuple proxies.
  20142. \python{Similarly, we use the type \code{list} for both arrays and
  20143. array proxies.}
  20144. In \LangPVec{} we return the
  20145. \TUPLETYPENAME{} type to its original
  20146. meaning, as the type of just tuples, and we introduce a new type,
  20147. \PTUPLETYNAME{}, whose values
  20148. can be either real tuples or tuple
  20149. proxies.
  20150. %
  20151. {\if\edition\pythonEd\pythonColor
  20152. Likewise, we return the
  20153. \ARRAYTYPENAME{} type to its original
  20154. meaning, as the type of arrays, and we introduce a new type,
  20155. \PARRAYTYNAME{}, whose values
  20156. can be either arrays or array proxies.
  20157. These new types come with a suite of new primitive operations.
  20158. \fi}
  20159. {\if\edition\racketEd
  20160. A tuple proxy is represented by a tuple containing three things: (1) the
  20161. underlying tuple, (2) a tuple of functions for casting elements that
  20162. are read from the tuple, and (3) a tuple of functions for casting
  20163. values to be written to the tuple. So, we define the following
  20164. abbreviation for the type of a tuple proxy:
  20165. \[
  20166. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20167. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20168. \]
  20169. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20170. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20171. %
  20172. Next we describe each of the new primitive operations.
  20173. \begin{description}
  20174. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20175. (\key{PVector} $T \ldots$)]\ \\
  20176. %
  20177. This operation brands a vector as a value of the \code{PVector} type.
  20178. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20179. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20180. %
  20181. This operation brands a vector proxy as value of the \code{PVector} type.
  20182. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20183. \BOOLTY{}] \ \\
  20184. %
  20185. This returns true if the value is a tuple proxy and false if it is a
  20186. real tuple.
  20187. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20188. (\key{Vector} $T \ldots$)]\ \\
  20189. %
  20190. Assuming that the input is a tuple, this operation returns the
  20191. tuple.
  20192. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20193. $\to$ \INTTY{}]\ \\
  20194. %
  20195. Given a tuple proxy, this operation returns the length of the tuple.
  20196. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20197. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20198. %
  20199. Given a tuple proxy, this operation returns the $i$th element of the
  20200. tuple.
  20201. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20202. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20203. Given a tuple proxy, this operation writes a value to the $i$th element
  20204. of the tuple.
  20205. \end{description}
  20206. \fi}
  20207. {\if\edition\pythonEd\pythonColor
  20208. %
  20209. A tuple proxy is represented by a tuple containing (1) the underlying
  20210. tuple and (2) a tuple of functions for casting elements that are read
  20211. from the tuple. The \LangPVec{} language includes the following AST
  20212. classes and primitive functions.
  20213. \begin{description}
  20214. \item[\code{InjectTuple}] \ \\
  20215. %
  20216. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20217. \item[\code{InjectTupleProxy}]\ \\
  20218. %
  20219. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20220. \item[\code{is\_tuple\_proxy}]\ \\
  20221. %
  20222. This primitive returns true if the value is a tuple proxy and false
  20223. if it is a tuple.
  20224. \item[\code{project\_tuple}]\ \\
  20225. %
  20226. Converts a tuple that is branded as \PTUPLETYNAME{}
  20227. back to a tuple.
  20228. \item[\code{proxy\_tuple\_len}]\ \\
  20229. %
  20230. Given a tuple proxy, returns the length of the underlying tuple.
  20231. \item[\code{proxy\_tuple\_load}]\ \\
  20232. %
  20233. Given a tuple proxy, returns the $i$th element of the underlying
  20234. tuple.
  20235. \end{description}
  20236. An array proxy is represented by a tuple containing (1) the underlying
  20237. array, (2) a function for casting elements that are read from the
  20238. array, and (3) a function for casting elements that are written to the
  20239. array. The \LangPVec{} language includes the following AST classes
  20240. and primitive functions.
  20241. \begin{description}
  20242. \item[\code{InjectList}]\ \\
  20243. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20244. \item[\code{InjectListProxy}]\ \\
  20245. %
  20246. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20247. \item[\code{is\_array\_proxy}]\ \\
  20248. %
  20249. Returns true if the value is an array proxy and false if it is an
  20250. array.
  20251. \item[\code{project\_array}]\ \\
  20252. %
  20253. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20254. array.
  20255. \item[\code{proxy\_array\_len}]\ \\
  20256. %
  20257. Given an array proxy, returns the length of the underlying array.
  20258. \item[\code{proxy\_array\_load}]\ \\
  20259. %
  20260. Given an array proxy, returns the $i$th element of the underlying
  20261. array.
  20262. \item[\code{proxy\_array\_store}]\ \\
  20263. %
  20264. Given an array proxy, writes a value to the $i$th element of the
  20265. underlying array.
  20266. \end{description}
  20267. \fi}
  20268. Now we discuss the translation that differentiates tuples and arrays
  20269. from proxies. First, every type annotation in the program is
  20270. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20271. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20272. places. For example, we wrap every tuple creation with an
  20273. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20274. %
  20275. {\if\edition\racketEd
  20276. \begin{minipage}{0.96\textwidth}
  20277. \begin{lstlisting}
  20278. (vector |$e_1 \ldots e_n$|)
  20279. |$\Rightarrow$|
  20280. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20281. \end{lstlisting}
  20282. \end{minipage}
  20283. \fi}
  20284. {\if\edition\pythonEd\pythonColor
  20285. \begin{lstlisting}
  20286. Tuple(|$e_1, \ldots, e_n$|)
  20287. |$\Rightarrow$|
  20288. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20289. \end{lstlisting}
  20290. \fi}
  20291. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20292. AST node that we introduced in the previous
  20293. section does not get injected.
  20294. {\if\edition\racketEd
  20295. \begin{lstlisting}
  20296. (raw-vector |$e_1 \ldots e_n$|)
  20297. |$\Rightarrow$|
  20298. (vector |$e'_1 \ldots e'_n$|)
  20299. \end{lstlisting}
  20300. \fi}
  20301. {\if\edition\pythonEd\pythonColor
  20302. \begin{lstlisting}
  20303. RawTuple(|$e_1, \ldots, e_n$|)
  20304. |$\Rightarrow$|
  20305. Tuple(|$e'_1, \ldots, e'_n$|)
  20306. \end{lstlisting}
  20307. \fi}
  20308. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20309. translates as follows:
  20310. %
  20311. {\if\edition\racketEd
  20312. \begin{lstlisting}
  20313. (vector-proxy |$e_1~e_2~e_3$|)
  20314. |$\Rightarrow$|
  20315. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20316. \end{lstlisting}
  20317. \fi}
  20318. {\if\edition\pythonEd\pythonColor
  20319. \begin{lstlisting}
  20320. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20321. |$\Rightarrow$|
  20322. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20323. \end{lstlisting}
  20324. \fi}
  20325. We translate the element access operations into conditional
  20326. expressions that check whether the value is a proxy and then dispatch
  20327. to either the appropriate proxy tuple operation or the regular tuple
  20328. operation.
  20329. {\if\edition\racketEd
  20330. \begin{lstlisting}
  20331. (vector-ref |$e_1$| |$i$|)
  20332. |$\Rightarrow$|
  20333. (let ([|$v~e_1$|])
  20334. (if (proxy? |$v$|)
  20335. (proxy-vector-ref |$v$| |$i$|)
  20336. (vector-ref (project-vector |$v$|) |$i$|)
  20337. \end{lstlisting}
  20338. \fi}
  20339. %
  20340. Note that in the branch for a tuple, we must apply
  20341. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20342. from the tuple.
  20343. The translation of array operations is similar to the ones for tuples.
  20344. \section{Reveal Casts }
  20345. \label{sec:reveal-casts-gradual}
  20346. {\if\edition\racketEd
  20347. Recall that the \code{reveal\_casts} pass
  20348. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20349. \code{Inject} and \code{Project} into lower-level operations.
  20350. %
  20351. In particular, \code{Project} turns into a conditional expression that
  20352. inspects the tag and retrieves the underlying value. Here we need to
  20353. augment the translation of \code{Project} to handle the situation in which
  20354. the target type is \code{PVector}. Instead of using
  20355. \code{vector-length} we need to use \code{proxy-vector-length}.
  20356. \begin{lstlisting}
  20357. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20358. |$\Rightarrow$|
  20359. (let |$\itm{tmp}$| |$e'$|
  20360. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20361. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20362. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20363. (exit)))
  20364. \end{lstlisting}
  20365. \fi}
  20366. %
  20367. {\if\edition\pythonEd\pythonColor
  20368. Recall that the $\itm{tagof}$ function determines the bits used to
  20369. identify values of different types, and it is used in the \code{reveal\_casts}
  20370. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20371. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20372. decimal), just like the tuple and array types.
  20373. \fi}
  20374. %
  20375. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20376. \pagebreak
  20377. \section{Closure Conversion }
  20378. \label{sec:closure-conversion-gradual}
  20379. The auxiliary function that translates type annotations needs to be
  20380. updated to handle the \PTUPLETYNAME{}
  20381. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20382. %
  20383. Otherwise, the only other changes are adding cases that copy the new
  20384. AST nodes.
  20385. \section{Select Instructions }
  20386. \label{sec:select-instructions-gradual}
  20387. \index{subject}{select instructions}
  20388. Recall that the \code{select\_instructions} pass is responsible for
  20389. lowering the primitive operations into x86 instructions. So, we need
  20390. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20391. to x86. To do so, the first question we need to answer is how to
  20392. differentiate between tuple and tuple proxies\python{, and likewise for
  20393. arrays and array proxies}. We need just one bit to accomplish this;
  20394. we use the bit in position $63$ of the 64-bit tag at the front of
  20395. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20396. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20397. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20398. it that way.
  20399. {\if\edition\racketEd
  20400. \begin{lstlisting}
  20401. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20402. |$\Rightarrow$|
  20403. movq |$e'_1$|, |$\itm{lhs'}$|
  20404. \end{lstlisting}
  20405. \fi}
  20406. {\if\edition\pythonEd\pythonColor
  20407. \begin{lstlisting}
  20408. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20409. |$\Rightarrow$|
  20410. movq |$e'_1$|, |$\itm{lhs'}$|
  20411. \end{lstlisting}
  20412. \fi}
  20413. \python{The translation for \code{InjectList} is also a move instruction.}
  20414. \noindent On the other hand,
  20415. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20416. $63$ to $1$.
  20417. %
  20418. {\if\edition\racketEd
  20419. \begin{lstlisting}
  20420. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20421. |$\Rightarrow$|
  20422. movq |$e'_1$|, %r11
  20423. movq |$(1 << 63)$|, %rax
  20424. orq 0(%r11), %rax
  20425. movq %rax, 0(%r11)
  20426. movq %r11, |$\itm{lhs'}$|
  20427. \end{lstlisting}
  20428. \fi}
  20429. {\if\edition\pythonEd\pythonColor
  20430. \begin{lstlisting}
  20431. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20432. |$\Rightarrow$|
  20433. movq |$e'_1$|, %r11
  20434. movq |$(1 << 63)$|, %rax
  20435. orq 0(%r11), %rax
  20436. movq %rax, 0(%r11)
  20437. movq %r11, |$\itm{lhs'}$|
  20438. \end{lstlisting}
  20439. \fi}
  20440. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20441. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20442. The \racket{\code{proxy?} operation consumes}%
  20443. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20444. consume}
  20445. the information so carefully stashed away by the injections. It
  20446. isolates bit $63$ to tell whether the value is a proxy.
  20447. %
  20448. {\if\edition\racketEd
  20449. \begin{lstlisting}
  20450. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20451. |$\Rightarrow$|
  20452. movq |$e_1'$|, %r11
  20453. movq 0(%r11), %rax
  20454. sarq $63, %rax
  20455. andq $1, %rax
  20456. movq %rax, |$\itm{lhs'}$|
  20457. \end{lstlisting}
  20458. \fi}%
  20459. %
  20460. {\if\edition\pythonEd\pythonColor
  20461. \begin{lstlisting}
  20462. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20463. |$\Rightarrow$|
  20464. movq |$e_1'$|, %r11
  20465. movq 0(%r11), %rax
  20466. sarq $63, %rax
  20467. andq $1, %rax
  20468. movq %rax, |$\itm{lhs'}$|
  20469. \end{lstlisting}
  20470. \fi}%
  20471. %
  20472. The \racket{\code{project-vector} operation is}
  20473. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20474. straightforward to translate, so we leave that to the reader.
  20475. Regarding the element access operations for tuples\python{ and arrays}, the
  20476. runtime provides procedures that implement them (they are recursive
  20477. functions!), so here we simply need to translate these tuple
  20478. operations into the appropriate function call. For example, here is
  20479. the translation for
  20480. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20481. {\if\edition\racketEd
  20482. \begin{minipage}{0.96\textwidth}
  20483. \begin{lstlisting}
  20484. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20485. |$\Rightarrow$|
  20486. movq |$e_1'$|, %rdi
  20487. movq |$e_2'$|, %rsi
  20488. callq proxy_vector_ref
  20489. movq %rax, |$\itm{lhs'}$|
  20490. \end{lstlisting}
  20491. \end{minipage}
  20492. \fi}
  20493. {\if\edition\pythonEd\pythonColor
  20494. \begin{lstlisting}
  20495. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20496. |$\Rightarrow$|
  20497. movq |$e_1'$|, %rdi
  20498. movq |$e_2'$|, %rsi
  20499. callq proxy_vector_ref
  20500. movq %rax, |$\itm{lhs'}$|
  20501. \end{lstlisting}
  20502. \fi}
  20503. {\if\edition\pythonEd\pythonColor
  20504. % TODO: revisit the names vecof for python -Jeremy
  20505. We translate
  20506. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20507. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20508. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20509. \fi}
  20510. We have another batch of operations to deal with: those for the
  20511. \CANYTY{} type. Recall that we generate an
  20512. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20513. there is a element access on something of type \CANYTY{}, and
  20514. similarly for
  20515. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20516. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20517. section~\ref{sec:select-Lany} we selected instructions for these
  20518. operations on the basis of the idea that the underlying value was a tuple or
  20519. array. But in the current setting, the underlying value is of type
  20520. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20521. functions to deal with this:
  20522. \code{proxy\_vector\_ref},
  20523. \code{proxy\_vector\_set}, and
  20524. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20525. to determine whether the value is a proxy, and then
  20526. dispatches to the the appropriate code.
  20527. %
  20528. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20529. can be translated as follows.
  20530. We begin by projecting the underlying value out of the tagged value and
  20531. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20532. {\if\edition\racketEd
  20533. \begin{lstlisting}
  20534. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20535. |$\Rightarrow$|
  20536. movq |$\neg 111$|, %rdi
  20537. andq |$e_1'$|, %rdi
  20538. movq |$e_2'$|, %rsi
  20539. callq proxy_vector_ref
  20540. movq %rax, |$\itm{lhs'}$|
  20541. \end{lstlisting}
  20542. \fi}
  20543. {\if\edition\pythonEd\pythonColor
  20544. \begin{lstlisting}
  20545. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20546. |$\Rightarrow$|
  20547. movq |$\neg 111$|, %rdi
  20548. andq |$e_1'$|, %rdi
  20549. movq |$e_2'$|, %rsi
  20550. callq proxy_vector_ref
  20551. movq %rax, |$\itm{lhs'}$|
  20552. \end{lstlisting}
  20553. \fi}
  20554. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20555. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20556. are translated in a similar way. Alternatively, you could generate
  20557. instructions to open-code
  20558. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20559. and \code{proxy\_vector\_length} functions.
  20560. \begin{exercise}\normalfont\normalsize
  20561. Implement a compiler for the gradually typed \LangGrad{} language by
  20562. extending and adapting your compiler for \LangLam{}. Create ten new
  20563. partially typed test programs. In addition to testing with these
  20564. new programs, test your compiler on all the tests for \LangLam{}
  20565. and for \LangDyn{}.
  20566. %
  20567. \racket{Sometimes you may get a type-checking error on the
  20568. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20569. the \CANYTY{} type around each subexpression that has caused a type
  20570. error. Although \LangDyn{} does not have explicit casts, you can
  20571. induce one by wrapping the subexpression \code{e} with a call to
  20572. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20573. %
  20574. \python{Sometimes you may get a type-checking error on the
  20575. \LangDyn{} programs, but you can adapt them by inserting a
  20576. temporary variable of type \CANYTY{} that is initialized with the
  20577. troublesome expression.}
  20578. \end{exercise}
  20579. \begin{figure}[t]
  20580. \begin{tcolorbox}[colback=white]
  20581. {\if\edition\racketEd
  20582. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20583. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20584. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20585. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20586. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20587. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20588. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20589. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20590. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20591. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20592. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20593. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20594. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20595. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20596. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20597. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20598. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20599. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20600. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20601. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20602. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20603. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20604. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20605. \path[->,bend left=15] (Lgradual) edge [above] node
  20606. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20607. \path[->,bend left=15] (Lgradual2) edge [above] node
  20608. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20609. \path[->,bend left=15] (Lgradual3) edge [above] node
  20610. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20611. \path[->,bend left=15] (Lgradual4) edge [left] node
  20612. {\ttfamily\footnotesize shrink} (Lgradualr);
  20613. \path[->,bend left=15] (Lgradualr) edge [above] node
  20614. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20615. \path[->,bend right=15] (Lgradualp) edge [above] node
  20616. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20617. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20618. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20619. \path[->,bend right=15] (Llambdapp) edge [above] node
  20620. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20621. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20622. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20623. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20624. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20625. \path[->,bend left=15] (F1-2) edge [above] node
  20626. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20627. \path[->,bend left=15] (F1-3) edge [left] node
  20628. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20629. \path[->,bend left=15] (F1-4) edge [below] node
  20630. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20631. \path[->,bend right=15] (F1-5) edge [above] node
  20632. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20633. \path[->,bend right=15] (F1-6) edge [above] node
  20634. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20635. \path[->,bend right=15] (C3-2) edge [right] node
  20636. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20637. \path[->,bend right=15] (x86-2) edge [right] node
  20638. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20639. \path[->,bend right=15] (x86-2-1) edge [below] node
  20640. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20641. \path[->,bend right=15] (x86-2-2) edge [right] node
  20642. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20643. \path[->,bend left=15] (x86-3) edge [above] node
  20644. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20645. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20646. \end{tikzpicture}
  20647. \fi}
  20648. {\if\edition\pythonEd\pythonColor
  20649. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20650. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20651. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20652. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20653. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20654. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20655. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20656. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20657. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20658. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20659. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20660. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20661. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20662. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20663. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20664. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20665. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20666. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20667. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20668. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20669. \path[->,bend left=15] (Lgradual) edge [above] node
  20670. {\ttfamily\footnotesize shrink} (Lgradual2);
  20671. \path[->,bend left=15] (Lgradual2) edge [above] node
  20672. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20673. \path[->,bend left=15] (Lgradual3) edge [above] node
  20674. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20675. \path[->,bend left=15] (Lgradual4) edge [left] node
  20676. {\ttfamily\footnotesize resolve} (Lgradualr);
  20677. \path[->,bend left=15] (Lgradualr) edge [below] node
  20678. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20679. \path[->,bend right=15] (Lgradualp) edge [above] node
  20680. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20681. \path[->,bend right=15] (Llambdapp) edge [above] node
  20682. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20683. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20684. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20685. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20686. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20687. \path[->,bend left=15] (F1-1) edge [above] node
  20688. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20689. \path[->,bend left=15] (F1-2) edge [above] node
  20690. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20691. \path[->,bend left=15] (F1-3) edge [right] node
  20692. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20693. \path[->,bend right=15] (F1-5) edge [above] node
  20694. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20695. \path[->,bend right=15] (F1-6) edge [above] node
  20696. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20697. \path[->,bend right=15] (C3-2) edge [right] node
  20698. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20699. \path[->,bend right=15] (x86-2) edge [below] node
  20700. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20701. \path[->,bend right=15] (x86-3) edge [below] node
  20702. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20703. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20704. \end{tikzpicture}
  20705. \fi}
  20706. \end{tcolorbox}
  20707. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20708. \label{fig:Lgradual-passes}
  20709. \end{figure}
  20710. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20711. needed for the compilation of \LangGrad{}.
  20712. \section{Further Reading}
  20713. This chapter just scratches the surface of gradual typing. The basic
  20714. approach described here is missing two key ingredients that one would
  20715. want in an implementation of gradual typing: blame
  20716. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20717. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20718. problem addressed by blame tracking is that when a cast on a
  20719. higher-order value fails, it often does so at a point in the program
  20720. that is far removed from the original cast. Blame tracking is a
  20721. technique for propagating extra information through casts and proxies
  20722. so that when a cast fails, the error message can point back to the
  20723. original location of the cast in the source program.
  20724. The problem addressed by space-efficient casts also relates to
  20725. higher-order casts. It turns out that in partially typed programs, a
  20726. function or tuple can flow through a great many casts at runtime. With
  20727. the approach described in this chapter, each cast adds another
  20728. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20729. considerable space, but it also makes the function calls and tuple
  20730. operations slow. For example, a partially typed version of quicksort
  20731. could, in the worst case, build a chain of proxies of length $O(n)$
  20732. around the tuple, changing the overall time complexity of the
  20733. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20734. solution to this problem by representing casts using the coercion
  20735. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20736. long chains of proxies by compressing them into a concise normal
  20737. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20738. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20739. the Grift compiler:
  20740. \begin{center}
  20741. \url{https://github.com/Gradual-Typing/Grift}
  20742. \end{center}
  20743. There are also interesting interactions between gradual typing and
  20744. other language features, such as generics, information-flow types, and
  20745. type inference, to name a few. We recommend to the reader the
  20746. online gradual typing bibliography for more material:
  20747. \begin{center}
  20748. \url{http://samth.github.io/gradual-typing-bib/}
  20749. \end{center}
  20750. % TODO: challenge problem:
  20751. % type analysis and type specialization?
  20752. % coercions?
  20753. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20754. \chapter{Generics}
  20755. \label{ch:Lpoly}
  20756. \setcounter{footnote}{0}
  20757. This chapter studies the compilation of
  20758. generics\index{subject}{generics} (aka parametric
  20759. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20760. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20761. enable programmers to make code more reusable by parameterizing
  20762. functions and data structures with respect to the types on which they
  20763. operate. For example, figure~\ref{fig:map-poly} revisits the
  20764. \code{map} example and this time gives it a more fitting type. This
  20765. \code{map} function is parameterized with respect to the element type
  20766. of the tuple. The type of \code{map} is the following generic type
  20767. specified by the \code{All} type with parameter \code{T}:
  20768. {\if\edition\racketEd
  20769. \begin{lstlisting}
  20770. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20771. \end{lstlisting}
  20772. \fi}
  20773. {\if\edition\pythonEd\pythonColor
  20774. \begin{lstlisting}
  20775. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20776. \end{lstlisting}
  20777. \fi}
  20778. %
  20779. The idea is that \code{map} can be used at \emph{all} choices of a
  20780. type for parameter \code{T}. In the example shown in
  20781. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20782. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20783. \code{T}, but we could have just as well applied \code{map} to a tuple
  20784. of Booleans.
  20785. %
  20786. A \emph{monomorphic} function is simply one that is not generic.
  20787. %
  20788. We use the term \emph{instantiation} for the process (within the
  20789. language implementation) of turning a generic function into a
  20790. monomorphic one, where the type parameters have been replaced by
  20791. types.
  20792. {\if\edition\pythonEd\pythonColor
  20793. %
  20794. In Python, when writing a generic function such as \code{map}, one
  20795. does not explicitly write its generic type (using \code{All}).
  20796. Instead, that the function is generic is implied by the use of type
  20797. variables (such as \code{T}) in the type annotations of its
  20798. parameters.
  20799. %
  20800. \fi}
  20801. \begin{figure}[tbp]
  20802. % poly_test_2.rkt
  20803. \begin{tcolorbox}[colback=white]
  20804. {\if\edition\racketEd
  20805. \begin{lstlisting}
  20806. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20807. (define (map f v)
  20808. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20809. (define (inc [x : Integer]) : Integer (+ x 1))
  20810. (vector-ref (map inc (vector 0 41)) 1)
  20811. \end{lstlisting}
  20812. \fi}
  20813. {\if\edition\pythonEd\pythonColor
  20814. \begin{lstlisting}
  20815. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20816. return (f(tup[0]), f(tup[1]))
  20817. def add1(x : int) -> int:
  20818. return x + 1
  20819. t = map(add1, (0, 41))
  20820. print(t[1])
  20821. \end{lstlisting}
  20822. \fi}
  20823. \end{tcolorbox}
  20824. \caption{A generic version of the \code{map} function.}
  20825. \label{fig:map-poly}
  20826. \end{figure}
  20827. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20828. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20829. shows the definition of the abstract syntax.
  20830. %
  20831. {\if\edition\racketEd
  20832. We add a second form for function definitions in which a type
  20833. declaration comes before the \code{define}. In the abstract syntax,
  20834. the return type in the \code{Def} is \CANYTY{}, but that should be
  20835. ignored in favor of the return type in the type declaration. (The
  20836. \CANYTY{} comes from using the same parser as discussed in
  20837. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20838. enables the use of an \code{All} type for a function, thereby making
  20839. it generic.
  20840. \fi}
  20841. %
  20842. The grammar for types is extended to include the type of a generic
  20843. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20844. abstract syntax)}.
  20845. \newcommand{\LpolyGrammarRacket}{
  20846. \begin{array}{lcl}
  20847. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20848. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20849. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20850. \end{array}
  20851. }
  20852. \newcommand{\LpolyASTRacket}{
  20853. \begin{array}{lcl}
  20854. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20855. \Def &::=& \DECL{\Var}{\Type} \\
  20856. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20857. \end{array}
  20858. }
  20859. \newcommand{\LpolyGrammarPython}{
  20860. \begin{array}{lcl}
  20861. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20862. \end{array}
  20863. }
  20864. \newcommand{\LpolyASTPython}{
  20865. \begin{array}{lcl}
  20866. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20867. \MID \key{GenericVar}\LP\Var\RP
  20868. \end{array}
  20869. }
  20870. \begin{figure}[tp]
  20871. \centering
  20872. \begin{tcolorbox}[colback=white]
  20873. \footnotesize
  20874. {\if\edition\racketEd
  20875. \[
  20876. \begin{array}{l}
  20877. \gray{\LintGrammarRacket{}} \\ \hline
  20878. \gray{\LvarGrammarRacket{}} \\ \hline
  20879. \gray{\LifGrammarRacket{}} \\ \hline
  20880. \gray{\LwhileGrammarRacket} \\ \hline
  20881. \gray{\LtupGrammarRacket} \\ \hline
  20882. \gray{\LfunGrammarRacket} \\ \hline
  20883. \gray{\LlambdaGrammarRacket} \\ \hline
  20884. \LpolyGrammarRacket \\
  20885. \begin{array}{lcl}
  20886. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20887. \end{array}
  20888. \end{array}
  20889. \]
  20890. \fi}
  20891. {\if\edition\pythonEd\pythonColor
  20892. \[
  20893. \begin{array}{l}
  20894. \gray{\LintGrammarPython{}} \\ \hline
  20895. \gray{\LvarGrammarPython{}} \\ \hline
  20896. \gray{\LifGrammarPython{}} \\ \hline
  20897. \gray{\LwhileGrammarPython} \\ \hline
  20898. \gray{\LtupGrammarPython} \\ \hline
  20899. \gray{\LfunGrammarPython} \\ \hline
  20900. \gray{\LlambdaGrammarPython} \\\hline
  20901. \LpolyGrammarPython \\
  20902. \begin{array}{lcl}
  20903. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20904. \end{array}
  20905. \end{array}
  20906. \]
  20907. \fi}
  20908. \end{tcolorbox}
  20909. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20910. (figure~\ref{fig:Llam-concrete-syntax}).}
  20911. \label{fig:Lpoly-concrete-syntax}
  20912. \index{subject}{Lgen@\LangPoly{} concrete syntax}
  20913. \end{figure}
  20914. \begin{figure}[tp]
  20915. \centering
  20916. \begin{tcolorbox}[colback=white]
  20917. \footnotesize
  20918. {\if\edition\racketEd
  20919. \[
  20920. \begin{array}{l}
  20921. \gray{\LintOpAST} \\ \hline
  20922. \gray{\LvarASTRacket{}} \\ \hline
  20923. \gray{\LifASTRacket{}} \\ \hline
  20924. \gray{\LwhileASTRacket{}} \\ \hline
  20925. \gray{\LtupASTRacket{}} \\ \hline
  20926. \gray{\LfunASTRacket} \\ \hline
  20927. \gray{\LlambdaASTRacket} \\ \hline
  20928. \LpolyASTRacket \\
  20929. \begin{array}{lcl}
  20930. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20931. \end{array}
  20932. \end{array}
  20933. \]
  20934. \fi}
  20935. {\if\edition\pythonEd\pythonColor
  20936. \[
  20937. \begin{array}{l}
  20938. \gray{\LintASTPython} \\ \hline
  20939. \gray{\LvarASTPython{}} \\ \hline
  20940. \gray{\LifASTPython{}} \\ \hline
  20941. \gray{\LwhileASTPython{}} \\ \hline
  20942. \gray{\LtupASTPython{}} \\ \hline
  20943. \gray{\LfunASTPython} \\ \hline
  20944. \gray{\LlambdaASTPython} \\ \hline
  20945. \LpolyASTPython \\
  20946. \begin{array}{lcl}
  20947. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20948. \end{array}
  20949. \end{array}
  20950. \]
  20951. \fi}
  20952. \end{tcolorbox}
  20953. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20954. (figure~\ref{fig:Llam-syntax}).}
  20955. \label{fig:Lpoly-syntax}
  20956. \index{subject}{Lgen@\LangPoly{} abstract syntax}
  20957. \end{figure}
  20958. By including the \code{All} type in the $\Type$ nonterminal of the
  20959. grammar we choose to make generics first class, which has interesting
  20960. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20961. not include syntax for the \code{All} type. It is inferred for functions whose
  20962. type annotations contain type variables.} Many languages with generics, such as
  20963. C++~\citep{stroustrup88:_param_types} and Standard
  20964. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20965. may be helpful to see an example of first-class generics in action. In
  20966. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20967. whose parameter is a generic function. Indeed, because the grammar for
  20968. $\Type$ includes the \code{All} type, a generic function may also be
  20969. returned from a function or stored inside a tuple. The body of
  20970. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20971. and also to an integer, which would not be possible if \code{f} were
  20972. not generic.
  20973. \begin{figure}[tbp]
  20974. \begin{tcolorbox}[colback=white]
  20975. {\if\edition\racketEd
  20976. \begin{lstlisting}
  20977. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20978. (define (apply_twice f)
  20979. (if (f #t) (f 42) (f 777)))
  20980. (: id (All (T) (T -> T)))
  20981. (define (id x) x)
  20982. (apply_twice id)
  20983. \end{lstlisting}
  20984. \fi}
  20985. {\if\edition\pythonEd\pythonColor
  20986. \begin{lstlisting}
  20987. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20988. if f(True):
  20989. return f(42)
  20990. else:
  20991. return f(777)
  20992. def id(x: T) -> T:
  20993. return x
  20994. print(apply_twice(id))
  20995. \end{lstlisting}
  20996. \fi}
  20997. \end{tcolorbox}
  20998. \caption{An example illustrating first-class generics.}
  20999. \label{fig:apply-twice}
  21000. \end{figure}
  21001. The type checker for \LangPoly{} shown in
  21002. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  21003. (compared to \LangLam{}) which we discuss in the following paragraphs.
  21004. {\if\edition\pythonEd\pythonColor
  21005. %
  21006. Regarding function definitions, if the type annotations on its
  21007. parameters contain generic variables, then the function is generic and
  21008. therefore its type is an \code{All} type wrapped around a function
  21009. type. Otherwise the function is monomorphic and its type is simply
  21010. a function type.
  21011. %
  21012. \fi}
  21013. The type checking of a function application is extended to handle the
  21014. case in which the operator expression is a generic function. In that case
  21015. the type arguments are deduced by matching the types of the parameters
  21016. with the types of the arguments.
  21017. %
  21018. The \code{match\_types} auxiliary function
  21019. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  21020. recursively descending through a parameter type \code{param\_ty} and
  21021. the corresponding argument type \code{arg\_ty}, making sure that they
  21022. are equal except when there is a type parameter in the parameter
  21023. type. Upon encountering a type parameter for the first time, the
  21024. algorithm deduces an association of the type parameter to the
  21025. corresponding part of the argument type. If it is not the first time
  21026. that the type parameter has been encountered, the algorithm looks up
  21027. its deduced type and makes sure that it is equal to the corresponding
  21028. part of the argument type. The return type of the application is the
  21029. return type of the generic function with the type parameters
  21030. replaced by the deduced type arguments, using the
  21031. \code{substitute\_type} auxiliary function, which is also listed in
  21032. figure~\ref{fig:type-check-Lpoly-aux}.
  21033. The type checker extends type equality to handle the \code{All} type.
  21034. This is not quite as simple as for other types, such as function and
  21035. tuple types, because two \code{All} types can be syntactically
  21036. different even though they are equivalent. For example,
  21037. \begin{center}
  21038. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  21039. \end{center}
  21040. is equivalent to
  21041. \begin{center}
  21042. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  21043. \end{center}
  21044. Two generic types are equal if they differ only in
  21045. the choice of the names of the type parameters. The definition of type
  21046. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  21047. parameters in one type to match the type parameters of the other type.
  21048. {\if\edition\racketEd
  21049. %
  21050. The type checker also ensures that only defined type variables appear
  21051. in type annotations. The \code{check\_well\_formed} function for which
  21052. the definition is shown in figure~\ref{fig:well-formed-types}
  21053. recursively inspects a type, making sure that each type variable has
  21054. been defined.
  21055. %
  21056. \fi}
  21057. \begin{figure}[tbp]
  21058. \begin{tcolorbox}[colback=white]
  21059. {\if\edition\racketEd
  21060. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21061. (define type-check-poly-class
  21062. (class type-check-Llambda-class
  21063. (super-new)
  21064. (inherit check-type-equal?)
  21065. (define/override (type-check-apply env e1 es)
  21066. (define-values (e^ ty) ((type-check-exp env) e1))
  21067. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  21068. ((type-check-exp env) e)))
  21069. (match ty
  21070. [`(,ty^* ... -> ,rt)
  21071. (for ([arg-ty ty*] [param-ty ty^*])
  21072. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  21073. (values e^ es^ rt)]
  21074. [`(All ,xs (,tys ... -> ,rt))
  21075. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21076. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  21077. (match_types env^^ param-ty arg-ty)))
  21078. (define targs
  21079. (for/list ([x xs])
  21080. (match (dict-ref env^^ x (lambda () #f))
  21081. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  21082. x (Apply e1 es))]
  21083. [ty ty])))
  21084. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  21085. [else (error 'type-check "expected a function, not ~a" ty)]))
  21086. (define/override ((type-check-exp env) e)
  21087. (match e
  21088. [(Lambda `([,xs : ,Ts] ...) rT body)
  21089. (for ([T Ts]) ((check_well_formed env) T))
  21090. ((check_well_formed env) rT)
  21091. ((super type-check-exp env) e)]
  21092. [(HasType e1 ty)
  21093. ((check_well_formed env) ty)
  21094. ((super type-check-exp env) e)]
  21095. [else ((super type-check-exp env) e)]))
  21096. (define/override ((type-check-def env) d)
  21097. (verbose 'type-check "poly/def" d)
  21098. (match d
  21099. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  21100. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  21101. (for ([p ps]) ((check_well_formed ts-env) p))
  21102. ((check_well_formed ts-env) rt)
  21103. (define new-env (append ts-env (map cons xs ps) env))
  21104. (define-values (body^ ty^) ((type-check-exp new-env) body))
  21105. (check-type-equal? ty^ rt body)
  21106. (Generic ts (Def f p:t* rt info body^))]
  21107. [else ((super type-check-def env) d)]))
  21108. (define/override (type-check-program p)
  21109. (match p
  21110. [(Program info body)
  21111. (type-check-program (ProgramDefsExp info '() body))]
  21112. [(ProgramDefsExp info ds body)
  21113. (define ds^ (combine-decls-defs ds))
  21114. (define new-env (for/list ([d ds^])
  21115. (cons (def-name d) (fun-def-type d))))
  21116. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  21117. (define-values (body^ ty) ((type-check-exp new-env) body))
  21118. (check-type-equal? ty 'Integer body)
  21119. (ProgramDefsExp info ds^^ body^)]))
  21120. ))
  21121. \end{lstlisting}
  21122. \fi}
  21123. {\if\edition\pythonEd\pythonColor
  21124. \begin{lstlisting}[basicstyle=\ttfamily\small]
  21125. def type_check_exp(self, e, env):
  21126. match e:
  21127. case Call(Name(f), args) if f in builtin_functions:
  21128. return super().type_check_exp(e, env)
  21129. case Call(func, args):
  21130. func_t = self.type_check_exp(func, env)
  21131. func.has_type = func_t
  21132. match func_t:
  21133. case AllType(ps, FunctionType(p_tys, rt)):
  21134. for arg in args:
  21135. arg.has_type = self.type_check_exp(arg, env)
  21136. arg_tys = [arg.has_type for arg in args]
  21137. deduced = {}
  21138. for (p, a) in zip(p_tys, arg_tys):
  21139. self.match_types(p, a, deduced, e)
  21140. return self.substitute_type(rt, deduced)
  21141. case _:
  21142. return super().type_check_exp(e, env)
  21143. case _:
  21144. return super().type_check_exp(e, env)
  21145. def type_check(self, p):
  21146. match p:
  21147. case Module(body):
  21148. env = {}
  21149. for s in body:
  21150. match s:
  21151. case FunctionDef(name, params, bod, dl, returns, comment):
  21152. params_t = [t for (x,t) in params]
  21153. ty_params = set()
  21154. for t in params_t:
  21155. ty_params |$\mid$|= self.generic_variables(t)
  21156. ty = FunctionType(params_t, returns)
  21157. if len(ty_params) > 0:
  21158. ty = AllType(list(ty_params), ty)
  21159. env[name] = ty
  21160. self.check_stmts(body, IntType(), env)
  21161. case _:
  21162. raise Exception('type_check: unexpected ' + repr(p))
  21163. \end{lstlisting}
  21164. \fi}
  21165. \end{tcolorbox}
  21166. \caption{Type checker for the \LangPoly{} language.}
  21167. \label{fig:type-check-Lpoly}
  21168. \end{figure}
  21169. \begin{figure}[tbp]
  21170. \begin{tcolorbox}[colback=white]
  21171. {\if\edition\racketEd
  21172. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21173. (define/override (type-equal? t1 t2)
  21174. (match* (t1 t2)
  21175. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21176. (define env (map cons xs ys))
  21177. (type-equal? (substitute_type env T1) T2)]
  21178. [(other wise)
  21179. (super type-equal? t1 t2)]))
  21180. (define/public (match_types env pt at)
  21181. (match* (pt at)
  21182. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21183. [('Void 'Void) env] [('Any 'Any) env]
  21184. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21185. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21186. (match_types env^ pt1 at1))]
  21187. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21188. (define env^ (match_types env prt art))
  21189. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21190. (match_types env^^ pt1 at1))]
  21191. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21192. (define env^ (append (map cons pxs axs) env))
  21193. (match_types env^ pt1 at1)]
  21194. [((? symbol? x) at)
  21195. (match (dict-ref env x (lambda () #f))
  21196. [#f (error 'type-check "undefined type variable ~a" x)]
  21197. ['Type (cons (cons x at) env)]
  21198. [t^ (check-type-equal? at t^ 'matching) env])]
  21199. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21200. (define/public (substitute_type env pt)
  21201. (match pt
  21202. ['Integer 'Integer] ['Boolean 'Boolean]
  21203. ['Void 'Void] ['Any 'Any]
  21204. [`(Vector ,ts ...)
  21205. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21206. [`(,ts ... -> ,rt)
  21207. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21208. [`(All ,xs ,t)
  21209. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21210. [(? symbol? x) (dict-ref env x)]
  21211. [else (error 'type-check "expected a type not ~a" pt)]))
  21212. (define/public (combine-decls-defs ds)
  21213. (match ds
  21214. ['() '()]
  21215. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21216. (unless (equal? name f)
  21217. (error 'type-check "name mismatch, ~a != ~a" name f))
  21218. (match type
  21219. [`(All ,xs (,ps ... -> ,rt))
  21220. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21221. (cons (Generic xs (Def name params^ rt info body))
  21222. (combine-decls-defs ds^))]
  21223. [`(,ps ... -> ,rt)
  21224. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21225. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21226. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21227. [`(,(Def f params rt info body) . ,ds^)
  21228. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21229. \end{lstlisting}
  21230. \fi}
  21231. {\if\edition\pythonEd\pythonColor
  21232. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21233. def match_types(self, param_ty, arg_ty, deduced, e):
  21234. match (param_ty, arg_ty):
  21235. case (GenericVar(id), _):
  21236. if id in deduced:
  21237. self.check_type_equal(arg_ty, deduced[id], e)
  21238. else:
  21239. deduced[id] = arg_ty
  21240. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21241. rename = {ap: GenericVar(p) for (ap,p) in zip(arg_ps, ps)}
  21242. new_arg_ty = self.substitute_type(arg_ty, rename)
  21243. self.match_types(ty, new_arg_ty, deduced, e)
  21244. case (TupleType(ps), TupleType(ts)):
  21245. for (p, a) in zip(ps, ts):
  21246. self.match_types(p, a, deduced, e)
  21247. case (ListType(p), ListType(a)):
  21248. self.match_types(p, a, deduced, e)
  21249. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21250. for (pp, ap) in zip(pps, aps):
  21251. self.match_types(pp, ap, deduced, e)
  21252. self.match_types(prt, art, deduced, e)
  21253. case (IntType(), IntType()):
  21254. pass
  21255. case (BoolType(), BoolType()):
  21256. pass
  21257. case _:
  21258. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21259. def substitute_type(self, ty, var_map):
  21260. match ty:
  21261. case GenericVar(id):
  21262. return var_map[id]
  21263. case AllType(ps, ty):
  21264. new_map = copy.deepcopy(var_map)
  21265. for p in ps:
  21266. new_map[p] = GenericVar(p)
  21267. return AllType(ps, self.substitute_type(ty, new_map))
  21268. case TupleType(ts):
  21269. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21270. case ListType(ty):
  21271. return ListType(self.substitute_type(ty, var_map))
  21272. case FunctionType(pts, rt):
  21273. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21274. self.substitute_type(rt, var_map))
  21275. case IntType():
  21276. return IntType()
  21277. case BoolType():
  21278. return BoolType()
  21279. case _:
  21280. raise Exception('substitute_type: unexpected ' + repr(ty))
  21281. def check_type_equal(self, t1, t2, e):
  21282. match (t1, t2):
  21283. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21284. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21285. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21286. case (_, _):
  21287. return super().check_type_equal(t1, t2, e)
  21288. \end{lstlisting}
  21289. \fi}
  21290. \end{tcolorbox}
  21291. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21292. \label{fig:type-check-Lpoly-aux}
  21293. \end{figure}
  21294. {\if\edition\racketEd
  21295. \begin{figure}[tbp]
  21296. \begin{tcolorbox}[colback=white]
  21297. \begin{lstlisting}
  21298. (define/public ((check_well_formed env) ty)
  21299. (match ty
  21300. ['Integer (void)]
  21301. ['Boolean (void)]
  21302. ['Void (void)]
  21303. [(? symbol? a)
  21304. (match (dict-ref env a (lambda () #f))
  21305. ['Type (void)]
  21306. [else (error 'type-check "undefined type variable ~a" a)])]
  21307. [`(Vector ,ts ...)
  21308. (for ([t ts]) ((check_well_formed env) t))]
  21309. [`(,ts ... -> ,t)
  21310. (for ([t ts]) ((check_well_formed env) t))
  21311. ((check_well_formed env) t)]
  21312. [`(All ,xs ,t)
  21313. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21314. ((check_well_formed env^) t)]
  21315. [else (error 'type-check "unrecognized type ~a" ty)]))
  21316. \end{lstlisting}
  21317. \end{tcolorbox}
  21318. \caption{Well-formed types.}
  21319. \label{fig:well-formed-types}
  21320. \end{figure}
  21321. \fi}
  21322. % TODO: interpreter for R'_10
  21323. \clearpage
  21324. \section{Compiling Generics}
  21325. \label{sec:compiling-poly}
  21326. Broadly speaking, there are four approaches to compiling generics, as
  21327. follows:
  21328. \begin{description}
  21329. \item[Monomorphization] generates a different version of a generic
  21330. function for each set of type arguments with which it is used,
  21331. producing type-specialized code. This approach results in the most
  21332. efficient code but requires whole-program compilation (no separate
  21333. compilation) and may increase code size. Unfortunately,
  21334. monomorphization is incompatible with first-class generics because
  21335. it is not always possible to determine which generic functions are
  21336. used with which type arguments during compilation. (It can be done
  21337. at runtime with just-in-time compilation.) Monomorphization is
  21338. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21339. generic functions in NESL~\citep{Blelloch:1993aa} and
  21340. ML~\citep{Weeks:2006aa}.
  21341. \item[Uniform representation] generates one version of each generic
  21342. function and requires all values to have a common \emph{boxed} format,
  21343. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21344. generic and monomorphic code is compiled similarly to code in a
  21345. dynamically typed language (like \LangDyn{}), in which primitive
  21346. operators require their arguments to be projected from \CANYTY{} and
  21347. their results to be injected into \CANYTY{}. (In object-oriented
  21348. languages, the projection is accomplished via virtual method
  21349. dispatch.) The uniform representation approach is compatible with
  21350. separate compilation and with first-class generics. However, it
  21351. produces the least efficient code because it introduces overhead in
  21352. the entire program. This approach is used in
  21353. Java~\citep{Bracha:1998fk},
  21354. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21355. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21356. \item[Mixed representation] generates one version of each generic
  21357. function, using a boxed representation for type variables. However,
  21358. monomorphic code is compiled as usual (as in \LangLam{}), and
  21359. conversions are performed at the boundaries between monomorphic code
  21360. and polymorphic code (for example, when a generic function is instantiated
  21361. and called). This approach is compatible with separate compilation
  21362. and first-class generics and maintains efficiency in monomorphic
  21363. code. The trade-off is increased overhead at the boundary between
  21364. monomorphic and generic code. This approach is used in
  21365. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21366. Java 5 with the addition of autoboxing.
  21367. \item[Type passing] uses the unboxed representation in both
  21368. monomorphic and generic code. Each generic function is compiled to a
  21369. single function with extra parameters that describe the type
  21370. arguments. The type information is used by the generated code to
  21371. determine how to access the unboxed values at runtime. This approach is
  21372. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21373. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21374. compilation and first-class generics and maintains the
  21375. efficiency for monomorphic code. There is runtime overhead in
  21376. polymorphic code from dispatching on type information.
  21377. \end{description}
  21378. In this chapter we use the mixed representation approach, partly
  21379. because of its favorable attributes and partly because it is
  21380. straightforward to implement using the tools that we have already
  21381. built to support gradual typing. The work of compiling generic
  21382. functions is performed in two passes, \code{resolve} and
  21383. \code{erase\_types}, that we discuss next. The output of
  21384. \code{erase\_types} is \LangCast{}
  21385. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21386. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21387. \section{Resolve Instantiation}
  21388. \label{sec:generic-resolve}
  21389. Recall that the type checker for \LangPoly{} deduces the type
  21390. arguments at call sites to a generic function. The purpose of the
  21391. \code{resolve} pass is to turn this implicit instantiation into an
  21392. explicit one, by adding \code{inst} nodes to the syntax of the
  21393. intermediate language. An \code{inst} node records the mapping of
  21394. type parameters to type arguments. The semantics of the \code{inst}
  21395. node is to instantiate the result of its first argument, a generic
  21396. function, to produce a monomorphic function. However, because the
  21397. interpreter never analyzes type annotations, instantiation can be a
  21398. no-op and simply return the generic function.
  21399. %
  21400. The output language of the \code{resolve} pass is \LangInst{},
  21401. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21402. {\if\edition\racketEd
  21403. The \code{resolve} pass combines the type declaration and polymorphic
  21404. function into a single definition, using the \code{Poly} form, to make
  21405. polymorphic functions more convenient to process in the next pass of the
  21406. compiler.
  21407. \fi}
  21408. \newcommand{\LinstASTRacket}{
  21409. \begin{array}{lcl}
  21410. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21411. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21412. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21413. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21414. \end{array}
  21415. }
  21416. \newcommand{\LinstASTPython}{
  21417. \begin{array}{lcl}
  21418. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21419. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21420. \end{array}
  21421. }
  21422. \begin{figure}[tp]
  21423. \centering
  21424. \begin{tcolorbox}[colback=white]
  21425. \small
  21426. {\if\edition\racketEd
  21427. \[
  21428. \begin{array}{l}
  21429. \gray{\LintOpAST} \\ \hline
  21430. \gray{\LvarASTRacket{}} \\ \hline
  21431. \gray{\LifASTRacket{}} \\ \hline
  21432. \gray{\LwhileASTRacket{}} \\ \hline
  21433. \gray{\LtupASTRacket{}} \\ \hline
  21434. \gray{\LfunASTRacket} \\ \hline
  21435. \gray{\LlambdaASTRacket} \\ \hline
  21436. \LinstASTRacket \\
  21437. \begin{array}{lcl}
  21438. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21439. \end{array}
  21440. \end{array}
  21441. \]
  21442. \fi}
  21443. {\if\edition\pythonEd\pythonColor
  21444. \[
  21445. \begin{array}{l}
  21446. \gray{\LintASTPython} \\ \hline
  21447. \gray{\LvarASTPython{}} \\ \hline
  21448. \gray{\LifASTPython{}} \\ \hline
  21449. \gray{\LwhileASTPython{}} \\ \hline
  21450. \gray{\LtupASTPython{}} \\ \hline
  21451. \gray{\LfunASTPython} \\ \hline
  21452. \gray{\LlambdaASTPython} \\ \hline
  21453. \LinstASTPython \\
  21454. \begin{array}{lcl}
  21455. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21456. \end{array}
  21457. \end{array}
  21458. \]
  21459. \fi}
  21460. \end{tcolorbox}
  21461. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21462. (figure~\ref{fig:Llam-syntax}).}
  21463. \label{fig:Lpoly-prime-syntax}
  21464. \index{subject}{Linst@\LangInst{} abstract syntax}
  21465. \end{figure}
  21466. The output of the \code{resolve} pass on the generic \code{map}
  21467. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21468. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21469. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21470. \begin{figure}[tbp]
  21471. % poly_test_2.rkt
  21472. \begin{tcolorbox}[colback=white]
  21473. {\if\edition\racketEd
  21474. \begin{lstlisting}
  21475. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21476. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21477. (define (inc [x : Integer]) : Integer (+ x 1))
  21478. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21479. (Integer))
  21480. inc (vector 0 41)) 1)
  21481. \end{lstlisting}
  21482. \fi}
  21483. {\if\edition\pythonEd\pythonColor
  21484. \begin{lstlisting}
  21485. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21486. return (f(tup[0]), f(tup[1]))
  21487. def add1(x : int) -> int:
  21488. return x + 1
  21489. t = inst(map, {T: int})(add1, (0, 41))
  21490. print(t[1])
  21491. \end{lstlisting}
  21492. \fi}
  21493. \end{tcolorbox}
  21494. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21495. \label{fig:map-resolve}
  21496. \end{figure}
  21497. \section{Erase Generic Types}
  21498. \label{sec:erase_types}
  21499. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21500. represent type variables. For example, figure~\ref{fig:map-erase}
  21501. shows the output of the \code{erase\_types} pass on the generic
  21502. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21503. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21504. \code{All} types are removed from the type of \code{map}.
  21505. \begin{figure}[tbp]
  21506. \begin{tcolorbox}[colback=white]
  21507. {\if\edition\racketEd
  21508. \begin{lstlisting}
  21509. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21510. : (Vector Any Any)
  21511. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21512. (define (inc [x : Integer]) : Integer (+ x 1))
  21513. (vector-ref ((cast map
  21514. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21515. ((Integer -> Integer) (Vector Integer Integer)
  21516. -> (Vector Integer Integer)))
  21517. inc (vector 0 41)) 1)
  21518. \end{lstlisting}
  21519. \fi}
  21520. {\if\edition\pythonEd\pythonColor
  21521. \begin{lstlisting}
  21522. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21523. return (f(tup[0]), f(tup[1]))
  21524. def add1(x : int) -> int:
  21525. return (x + 1)
  21526. def main() -> int:
  21527. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21528. print(t[1])
  21529. return 0
  21530. \end{lstlisting}
  21531. {\small
  21532. where\\
  21533. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21534. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21535. }
  21536. \fi}
  21537. \end{tcolorbox}
  21538. \caption{The generic \code{map} example after type erasure.}
  21539. \label{fig:map-erase}
  21540. \end{figure}
  21541. This process of type erasure creates a challenge at points of
  21542. instantiation. For example, consider the instantiation of
  21543. \code{map} shown in figure~\ref{fig:map-resolve}.
  21544. The type of \code{map} is
  21545. %
  21546. {\if\edition\racketEd
  21547. \begin{lstlisting}
  21548. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21549. \end{lstlisting}
  21550. \fi}
  21551. {\if\edition\pythonEd\pythonColor
  21552. \begin{lstlisting}
  21553. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21554. \end{lstlisting}
  21555. \fi}
  21556. %
  21557. \noindent and it is instantiated to
  21558. %
  21559. {\if\edition\racketEd
  21560. \begin{lstlisting}
  21561. ((Integer -> Integer) (Vector Integer Integer)
  21562. -> (Vector Integer Integer))
  21563. \end{lstlisting}
  21564. \fi}
  21565. {\if\edition\pythonEd\pythonColor
  21566. \begin{lstlisting}
  21567. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21568. \end{lstlisting}
  21569. \fi}
  21570. %
  21571. \noindent After erasure, the type of \code{map} is
  21572. %
  21573. {\if\edition\racketEd
  21574. \begin{lstlisting}
  21575. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21576. \end{lstlisting}
  21577. \fi}
  21578. {\if\edition\pythonEd\pythonColor
  21579. \begin{lstlisting}
  21580. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21581. \end{lstlisting}
  21582. \fi}
  21583. %
  21584. \noindent but we need to convert it to the instantiated type. This is
  21585. easy to do in the language \LangCast{} with a single \code{cast}. In
  21586. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21587. \code{map} has been compiled to a \code{cast} from the type of
  21588. \code{map} to the instantiated type. The source and the target type of
  21589. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21590. is the case because both the source and target are obtained from the
  21591. same generic type of \code{map}, replacing the type parameters with
  21592. \CANYTY{} in the former and with the deduced type arguments in the
  21593. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21594. To implement the \code{erase\_types} pass, we first recommend defining
  21595. a recursive function that translates types, named
  21596. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21597. follows.
  21598. %
  21599. {\if\edition\racketEd
  21600. \begin{lstlisting}
  21601. |$T$|
  21602. |$\Rightarrow$|
  21603. Any
  21604. \end{lstlisting}
  21605. \fi}
  21606. {\if\edition\pythonEd\pythonColor
  21607. \begin{lstlisting}
  21608. GenericVar(|$T$|)
  21609. |$\Rightarrow$|
  21610. Any
  21611. \end{lstlisting}
  21612. \fi}
  21613. %
  21614. \noindent The \code{erase\_type} function also removes the generic
  21615. \code{All} types.
  21616. %
  21617. {\if\edition\racketEd
  21618. \begin{lstlisting}
  21619. (All |$xs$| |$T_1$|)
  21620. |$\Rightarrow$|
  21621. |$T'_1$|
  21622. \end{lstlisting}
  21623. \fi}
  21624. {\if\edition\pythonEd\pythonColor
  21625. \begin{lstlisting}
  21626. AllType(|$xs$|, |$T_1$|)
  21627. |$\Rightarrow$|
  21628. |$T'_1$|
  21629. \end{lstlisting}
  21630. \fi}
  21631. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21632. $T_1$.
  21633. %
  21634. In this compiler pass, apply the \code{erase\_type} function to all
  21635. the type annotations in the program.
  21636. Regarding the translation of expressions, the case for \code{Inst} is
  21637. the interesting one. We translate it into a \code{Cast}, as shown
  21638. next.
  21639. The type of the subexpression $e$ is a generic type of the form
  21640. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21641. The source type of the cast is the erasure of $T$, the type $T_s$.
  21642. %
  21643. {\if\edition\racketEd
  21644. %
  21645. The target type $T_t$ is the result of substituting the argument types
  21646. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21647. erasure.
  21648. %
  21649. \begin{lstlisting}
  21650. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21651. |$\Rightarrow$|
  21652. (Cast |$e'$| |$T_s$| |$T_t$|)
  21653. \end{lstlisting}
  21654. %
  21655. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21656. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21657. \fi}
  21658. {\if\edition\pythonEd\pythonColor
  21659. %
  21660. The target type $T_t$ is the result of substituting the deduced
  21661. argument types $d$ in $T$ and then performing type erasure.
  21662. %
  21663. \begin{lstlisting}
  21664. Inst(|$e$|, |$d$|)
  21665. |$\Rightarrow$|
  21666. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21667. \end{lstlisting}
  21668. %
  21669. where
  21670. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21671. \fi}
  21672. Finally, each generic function is translated to a regular
  21673. function in which type erasure has been applied to all the type
  21674. annotations and the body.
  21675. %% \begin{lstlisting}
  21676. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21677. %% |$\Rightarrow$|
  21678. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21679. %% \end{lstlisting}
  21680. \begin{exercise}\normalfont\normalsize
  21681. Implement a compiler for the polymorphic language \LangPoly{} by
  21682. extending and adapting your compiler for \LangGrad{}. Create six new
  21683. test programs that use polymorphic functions. Some of them should
  21684. make use of first-class generics.
  21685. \end{exercise}
  21686. \begin{figure}[tbp]
  21687. \begin{tcolorbox}[colback=white]
  21688. {\if\edition\racketEd
  21689. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21690. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21691. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21692. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21693. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21694. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21695. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21696. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21697. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21698. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21699. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21700. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21701. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21702. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21703. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21704. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21705. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21706. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21707. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21708. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21709. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21710. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21711. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21712. \path[->,bend left=15] (Lpoly) edge [above] node
  21713. {\ttfamily\footnotesize resolve} (Lpolyp);
  21714. \path[->,bend left=15] (Lpolyp) edge [above] node
  21715. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21716. \path[->,bend left=15] (Lgradualp) edge [above] node
  21717. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21718. \path[->,bend left=15] (Llambdapp) edge [left] node
  21719. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21720. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21721. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21722. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21723. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21724. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21725. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21726. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21727. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21728. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21729. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21730. \path[->,bend left=15] (F1-1) edge [above] node
  21731. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21732. \path[->,bend left=15] (F1-2) edge [above] node
  21733. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21734. \path[->,bend left=15] (F1-3) edge [left] node
  21735. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21736. \path[->,bend left=15] (F1-4) edge [below] node
  21737. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21738. \path[->,bend right=15] (F1-5) edge [above] node
  21739. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21740. \path[->,bend right=15] (F1-6) edge [above] node
  21741. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21742. \path[->,bend right=15] (C3-2) edge [right] node
  21743. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21744. \path[->,bend right=15] (x86-2) edge [right] node
  21745. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21746. \path[->,bend right=15] (x86-2-1) edge [below] node
  21747. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21748. \path[->,bend right=15] (x86-2-2) edge [right] node
  21749. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21750. \path[->,bend left=15] (x86-3) edge [above] node
  21751. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21752. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21753. \end{tikzpicture}
  21754. \fi}
  21755. {\if\edition\pythonEd\pythonColor
  21756. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21757. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21758. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21759. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21760. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21761. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21762. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21763. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21764. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21765. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21766. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21767. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21768. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21769. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21770. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21771. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21772. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21773. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21774. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21775. \path[->,bend left=15] (Lgradual) edge [above] node
  21776. {\ttfamily\footnotesize shrink} (Lgradual2);
  21777. \path[->,bend left=15] (Lgradual2) edge [above] node
  21778. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21779. \path[->,bend left=15] (Lgradual3) edge [above] node
  21780. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21781. \path[->,bend left=15] (Lgradual4) edge [left] node
  21782. {\ttfamily\footnotesize resolve} (Lgradualr);
  21783. \path[->,bend left=15] (Lgradualr) edge [below] node
  21784. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21785. \path[->,bend right=15] (Llambdapp) edge [above] node
  21786. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21787. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21788. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21789. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21790. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21791. \path[->,bend right=15] (F1-1) edge [below] node
  21792. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21793. \path[->,bend right=15] (F1-2) edge [below] node
  21794. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21795. \path[->,bend left=15] (F1-3) edge [above] node
  21796. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21797. \path[->,bend left=15] (F1-5) edge [left] node
  21798. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21799. \path[->,bend left=5] (F1-6) edge [below] node
  21800. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21801. \path[->,bend right=15] (C3-2) edge [right] node
  21802. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21803. \path[->,bend right=15] (x86-2) edge [below] node
  21804. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21805. \path[->,bend right=15] (x86-3) edge [below] node
  21806. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21807. \path[->,bend left=15] (x86-4) edge [above] node
  21808. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21809. \end{tikzpicture}
  21810. \fi}
  21811. \end{tcolorbox}
  21812. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21813. \label{fig:Lpoly-passes}
  21814. \end{figure}
  21815. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21816. needed to compile \LangPoly{}.
  21817. % TODO: challenge problem: specialization of instantiations
  21818. % Further Reading
  21819. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21820. \clearpage
  21821. \appendix
  21822. \chapter{Appendix}
  21823. \setcounter{footnote}{0}
  21824. {\if\edition\racketEd
  21825. \section{Interpreters}
  21826. \label{appendix:interp}
  21827. \index{subject}{interpreter}
  21828. We provide interpreters for each of the source languages \LangInt{},
  21829. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21830. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21831. intermediate languages \LangCVar{} and \LangCIf{} are in
  21832. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21833. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21834. \key{interp.rkt} file.
  21835. \section{Utility Functions}
  21836. \label{appendix:utilities}
  21837. The utility functions described in this section are in the
  21838. \key{utilities.rkt} file of the support code.
  21839. \paragraph{\code{interp-tests}}
  21840. This function runs the compiler passes and the interpreters on each of
  21841. the specified tests to check whether each pass is correct. The
  21842. \key{interp-tests} function has the following parameters:
  21843. \begin{description}
  21844. \item[name (a string)] A name to identify the compiler.
  21845. \item[typechecker] A function of exactly one argument that either
  21846. raises an error using the \code{error} function when it encounters a
  21847. type error, or returns \code{\#f} when it encounters a type
  21848. error. If there is no type error, the type checker returns the
  21849. program.
  21850. \item[passes] A list with one entry per pass. An entry is a list
  21851. consisting of four things:
  21852. \begin{enumerate}
  21853. \item a string giving the name of the pass;
  21854. \item the function that implements the pass (a translator from AST
  21855. to AST);
  21856. \item a function that implements the interpreter (a function from
  21857. AST to result value) for the output language; and,
  21858. \item a type checker for the output language. Type checkers for
  21859. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21860. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21861. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21862. type checker entry is optional. The support code does not provide
  21863. type checkers for the x86 languages.
  21864. \end{enumerate}
  21865. \item[source-interp] An interpreter for the source language. The
  21866. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21867. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21868. \item[tests] A list of test numbers that specifies which tests to
  21869. run (explained next).
  21870. \end{description}
  21871. %
  21872. The \key{interp-tests} function assumes that the subdirectory
  21873. \key{tests} has a collection of Racket programs whose names all start
  21874. with the family name, followed by an underscore and then the test
  21875. number, and ending with the file extension \key{.rkt}. Also, for each test
  21876. program that calls \code{read} one or more times, there is a file with
  21877. the same name except that the file extension is \key{.in}, which
  21878. provides the input for the Racket program. If the test program is
  21879. expected to fail type checking, then there should be an empty file of
  21880. the same name with extension \key{.tyerr}.
  21881. \paragraph{\code{compiler-tests}}
  21882. This function runs the compiler passes to generate x86 (a \key{.s}
  21883. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21884. It runs the machine code and checks that the output is $42$. The
  21885. parameters to the \code{compiler-tests} function are similar to those
  21886. of the \code{interp-tests} function, and they consist of
  21887. \begin{itemize}
  21888. \item a compiler name (a string),
  21889. \item a type checker,
  21890. \item description of the passes,
  21891. \item name of a test-family, and
  21892. \item a list of test numbers.
  21893. \end{itemize}
  21894. \paragraph{\code{compile-file}}
  21895. This function takes a description of the compiler passes (see the
  21896. comment for \key{interp-tests}) and returns a function that, given a
  21897. program file name (a string ending in \key{.rkt}), applies all the
  21898. passes and writes the output to a file whose name is the same as the
  21899. program file name with extension \key{.rkt} replaced by \key{.s}.
  21900. \paragraph{\code{read-program}}
  21901. This function takes a file path and parses that file (it must be a
  21902. Racket program) into an abstract syntax tree.
  21903. \paragraph{\code{parse-program}}
  21904. This function takes an S-expression representation of an abstract
  21905. syntax tree and converts it into the struct-based representation.
  21906. \paragraph{\code{assert}}
  21907. This function takes two parameters, a string (\code{msg}) and Boolean
  21908. (\code{bool}), and displays the message \key{msg} if the Boolean
  21909. \key{bool} is false.
  21910. \paragraph{\code{lookup}}
  21911. % remove discussion of lookup? -Jeremy
  21912. This function takes a key and an alist and returns the first value that is
  21913. associated with the given key, if there is one. If not, an error is
  21914. triggered. The alist may contain both immutable pairs (built with
  21915. \key{cons}) and mutable pairs (built with \key{mcons}).
  21916. %The \key{map2} function ...
  21917. \fi} %\racketEd
  21918. \section{x86 Instruction Set Quick Reference}
  21919. \label{sec:x86-quick-reference}
  21920. \index{subject}{x86}
  21921. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21922. do. We write $A \to B$ to mean that the value of $A$ is written into
  21923. location $B$. Address offsets are given in bytes. The instruction
  21924. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21925. registers (such as \code{\%rax}), or memory references (such as
  21926. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21927. reference per instruction. Other operands must be immediates or
  21928. registers.
  21929. \begin{table}[tbp]
  21930. \captionabove{Quick reference for the x86 instructions used in this book.}
  21931. \label{tab:x86-instr}
  21932. \centering
  21933. \begin{tabular}{l|l}
  21934. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21935. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21936. \texttt{negq} $A$ & $- A \to A$ \\
  21937. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21938. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21939. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21940. \texttt{callq} \texttt{*}$A$ & Pushes the return address and jumps to the address in $A$. \\
  21941. \texttt{retq} & Pops the return address and jumps to it. \\
  21942. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21943. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21944. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21945. \texttt{cmpq} $A$, $B$ & \multirow{2}{3.7in}{Compare $A$ and $B$ and set the flag register ($B$ must not be an immediate).} \\
  21946. & \\
  21947. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21948. matches the condition code of the instruction; otherwise go to the
  21949. next instructions. The condition codes are \key{e} for \emph{equal},
  21950. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21951. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21952. \texttt{jl} $L$ & \\
  21953. \texttt{jle} $L$ & \\
  21954. \texttt{jg} $L$ & \\
  21955. \texttt{jge} $L$ & \\
  21956. \texttt{jmp} $L$ & Jump to label $L$. \\
  21957. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21958. \texttt{movzbq} $A$, $B$ &
  21959. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21960. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21961. and the extra bytes of $B$ are set to zero.} \\
  21962. & \\
  21963. & \\
  21964. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21965. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21966. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21967. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21968. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21969. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21970. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21971. description of the condition codes. $A$ must be a single byte register
  21972. (e.g., \texttt{al} or \texttt{cl}).} \\
  21973. \texttt{setl} $A$ & \\
  21974. \texttt{setle} $A$ & \\
  21975. \texttt{setg} $A$ & \\
  21976. \texttt{setge} $A$ &
  21977. \end{tabular}
  21978. \end{table}
  21979. \backmatter
  21980. \addtocontents{toc}{\vspace{11pt}}
  21981. \cleardoublepage % needed for right page number in TOC for References
  21982. %% \nocite{*} is a way to get all the entries in the .bib file to
  21983. %% print in the bibliography:
  21984. \nocite{*}\let\bibname\refname
  21985. \addcontentsline{toc}{fmbm}{\refname}
  21986. \printbibliography
  21987. %\printindex{authors}{Author Index}
  21988. \printindex{subject}{Index}
  21989. \end{document}
  21990. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21991. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21992. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21993. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21994. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21995. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21996. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21997. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21998. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21999. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  22000. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  22001. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  22002. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  22003. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  22004. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  22005. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  22006. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  22007. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  22008. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  22009. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  22010. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  22011. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  22012. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  22013. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  22014. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  22015. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  22016. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  22017. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  22018. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  22019. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  22020. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  22021. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  22022. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  22023. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  22024. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  22025. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  22026. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  22027. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  22028. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  22029. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  22030. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  22031. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  22032. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  22033. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  22034. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  22035. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  22036. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  22037. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  22038. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  22039. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  22040. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  22041. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  22042. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  22043. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  22044. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  22045. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  22046. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  22047. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  22048. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  22049. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  22050. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  22051. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  22052. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  22053. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  22054. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  22055. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  22056. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  22057. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  22058. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  22059. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  22060. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  22061. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  22062. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  22063. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  22064. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  22065. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  22066. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  22067. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  22068. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  22069. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  22070. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  22071. % LocalWords: pseudocode underapproximation underapproximations LALR
  22072. % LocalWords: semilattices overapproximate incrementing Earley docs
  22073. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  22074. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  22075. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  22076. % LocalWords: LC partialevaluation pythonEd TOC TrappedError